Code: Select all
positions := { "apple": 0, "boy": 1, "cat":2 }
startIndex := positions[startPos]
endIndex := positions[endPos]
moves := abs(endIndex - startIndex)
direction := endIndex > startIndex ? "right" : "left"
If I am at the cat position (2) and want to go to the apple, moving left 2 is correct. But in a closed "loop", going from the cat position to the right by 1 will also lead to the apple. Both right 1 and left 2 are valid moves, but right 1 requires fewer steps. If we have a longer array, such as the cat being at position 100 and the apple at position 3, going left for 97 moves is awful. Instead, if we can move right directly to the apple in just 3 moves(or a case from apple to cat also 3 move). How to install this close loop, fewer moves logic into the existing script?