In: Computer Science
Solve by using python function. use loop
Input; Crossing Times = { 10,15,20,25}
1.Firstly person '1' and '2' cross the path with total time about 15 min(maximum of 10, 15)
2.Now the person '1' will come back with total time of '10' minutes.
3. Now, person 1 and person 3 cross the path with total of about 20 minutes .(maximum of 10,20)
4. Now the person 1 will come back in 10 mintues
5. Lastly person 1 and person 4 will cross the path together in about 25 minutes(max of 10,25)
print the total sum of all(15+10+20+10+25)
I have written required comments along with code please go through them to understand the code.
Two basic things here to observe are
So we take two list one is persons who are left side of bridge and other list ,who are right side of the bridge.
def total_time(left_side):
""" Time calculation for crossing over bridge
"""
total_time_taken = 0
right_side = []
while True:
right_side.extend([left_side[0], left_side[1]]) # Extend new list means first two people crossed the bridge
# print("right-",right_side) # Incase you need to see how each lists are updated please uncomment the print statements
total_time_taken += max(left_side[0], left_side[1]) # Now time take to cross the brdige is maximum of two people times crossing the bridge
left_side.pop(0) # so we remove first person
left_side.pop(0) # after removing first person the second person replaces the first person we remove that person as well from the first list
if left_side == []: # when the first list gets empty means everybody crossed the bridge we exit the loop
break
# print("left-",left_side)
# the person going back to another to pick up another has minimum time so we add minum time person to arr again. means first list
left_side.insert(0, min(right_side))
# print("left-",left_side)
total_time_taken += min(right_side) # we add the time taken by person going back it will be minimum time from the second list
right_side.pop(right_side.index(min(right_side))) # so we remove the person who is crossing the bridge from second list
# print("right-",right_side)
return total_time_taken
print("Time take to everyone cross the bridge:{}".format(total_time([10,5,20,25, 1]))
Output with Print Satements with change in left and right sides:
Output without print statements :
Output with a new example :
Please leave a comment for any further queries