Skip to content

Commit f7fffbf

Browse files
author
Sagar Shiroya
authored
Update garage.py
Check for the case: initial = [3,1,2,0] final = [2,3,0,1] between state: [3,0,2,1] [0,3,2,1] [2,3,0,1] So only 3 moves needed while yourt program gives five moves.
1 parent 3ce776a commit f7fffbf

File tree

1 file changed

+25
-24
lines changed

1 file changed

+25
-24
lines changed

array/garage.py

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,32 +17,33 @@
1717
# Each step swap with 0 only.
1818

1919

20-
def garage(beg, end):
21-
moves = 0
20+
def count_moves(beg,end):
2221
i = 0
23-
while beg != end :
24-
if beg[i] != end[i] and beg[i] != 0:
25-
car = beg[i] #car that we will move
26-
empty = beg.index(0)
27-
beg[beg.index(car)], beg[empty] = beg[empty], beg[beg.index(car)]
28-
moves += 1
29-
## move car that's not in correct place into free space
30-
print(beg)
31-
if beg.index(car) != end.index(car):
32-
# if the recently moved car is still not in its correct place
33-
# then we want to move another car into the free space where
34-
# it will be in its correct position
35-
beg[beg.index(end[i])] = 0
36-
beg[i] = end[i]
37-
print(beg)
38-
moves += 1
39-
i += 1 #move onto the next car, check again
22+
count = 0
23+
while beg != end:
24+
if beg[i] != 0 and beg[i] != end[i]:
25+
current_car = beg[i]
26+
empty_slot = beg.index(0)
27+
final_pos = end.index(beg[i])
28+
if empty_slot != final_pos:
29+
beg[final_pos], beg[empty_slot] = beg[empty_slot], beg[final_pos]
30+
print beg
31+
empty_slot = beg.index(0)
32+
beg[beg.index(current_car)], beg[empty_slot] = beg[empty_slot], beg[beg.index(current_car)]
33+
print beg
34+
count += 2
35+
else:
36+
beg[beg.index(current_car)], beg[empty_slot] = beg[empty_slot], beg[beg.index(current_car)]
37+
print beg
38+
count += 1
39+
i += 1
4040
if i == len(beg):
4141
i = 0
42-
return moves
43-
42+
return count
43+
44+
4445
initial = [1,2,3,0,4]
4546
final = [0,3,2,1,4]
46-
print("initial:", initial)
47-
print("final:", final)
48-
print(garage(initial, final))
47+
print ('Initially:',initial)
48+
print ('Final',final)
49+
print count_moves(initial,final)

0 commit comments

Comments
 (0)