Skip to content

Commit 4eb5dcd

Browse files
authored
Merge pull request keon#67 from amrit92/master
cleanup garage.py
2 parents f3542c2 + ebbf7da commit 4eb5dcd

File tree

1 file changed

+18
-22
lines changed

1 file changed

+18
-22
lines changed

array/garage.py

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -15,31 +15,27 @@
1515
# [0,3,2,1,4].
1616
# We can swap 1 with 0 in the initial array to get [0,2,3,1,4] and so on.
1717
# Each step swap with 0 only.
18-
#Edited by cyberking-saga
18+
# Edited by cyberking-saga
1919

20-
def garage(beg, end):
20+
def garage(initial, final):
2121
i = 0
22-
moves = 0
23-
while beg != end:
24-
if beg[i] != 0 and beg[i] != end[i]:
25-
car = beg[i]
26-
empty = beg.index(0)
27-
final_pos = end.index(beg[i])
28-
if empty != final_pos:
29-
beg[final_pos], beg[empty] = beg[empty], beg[final_pos]
30-
print(beg)
31-
empty = beg.index(0)
32-
beg[beg.index(car)], beg[empty] = beg[empty], beg[beg.index(car)]
33-
print(beg)
34-
moves += 2
22+
steps = 0
23+
while initial != final:
24+
if initial[i] != 0 and initial[i] != final[i]:
25+
zero = initial.index(0)
26+
final_pos = final.index(initial[i])
27+
if zero != final_pos:
28+
# two swaps required
29+
initial[final_pos], initial[zero] = initial[zero], initial[final_pos]
30+
zero = initial.index(0)
31+
initial[i], initial[zero] = initial[zero], initial[i]
32+
steps += 2
3533
else:
36-
beg[beg.index(car)], beg[empty] = beg[empty], beg[beg.index(car)]
37-
print(beg)
38-
moves += 1
39-
i += 1
40-
if i == len(beg):
41-
i = 0
42-
return moves
34+
# one swap is enough
35+
initial[i], initial[zero] = initial[zero], initial[i]
36+
steps += 1
37+
i = (i + 1) % len(initial)
38+
return steps
4339

4440
if __name__ == "__main__":
4541
initial = [1,2,3,0,4]

0 commit comments

Comments
 (0)