|
15 | 15 | # [0,3,2,1,4]. |
16 | 16 | # We can swap 1 with 0 in the initial array to get [0,2,3,1,4] and so on. |
17 | 17 | # Each step swap with 0 only. |
18 | | -#Edited by cyberking-saga |
| 18 | +# Edited by cyberking-saga |
19 | 19 |
|
20 | | -def garage(beg, end): |
| 20 | +def garage(initial, final): |
21 | 21 | 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 |
35 | 33 | 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 |
43 | 39 |
|
44 | 40 | if __name__ == "__main__": |
45 | 41 | initial = [1,2,3,0,4] |
|
0 commit comments