見習村15 - Directions Reduction
15 - Directions Reduction
Don’t say so much, just coding…
Instruction
Once upon a time, on a way through the old wild mountainous west,…
… a man was given directions to go from one point to another. The directions were “NORTH”, “SOUTH”, “WEST”, “EAST”. Clearly “NORTH” and “SOUTH” are opposite, “WEST” and “EAST” too.
Going to one direction and coming back the opposite direction right away is a needless effort. Since this is the wild west, with dreadfull weather and not much water, it’s important to save yourself some energy, otherwise you might die of thirst!
How I crossed a mountain desert the smart way.
The directions given to the man are, for example, the following (depending on the language):
1 |
|
You can immediatly see that going “NORTH” and immediately “SOUTH” is not reasonable, better stay to the same place! So the task is to give to the man a simplified version of the plan. A better plan in this case is simply:
1 |
|
Other examples:
In ["NORTH", "SOUTH", "EAST", "WEST"]
, the direction “NORTH” + “SOUTH” is going north and coming back right away.
The path becomes ["EAST", "WEST"]
, now “EAST” and “WEST” annihilate each other, therefore, the final result is [] (nil in Clojure).
In [“NORTH”, “EAST”, “WEST”, “SOUTH”, “WEST”, “WEST”], “NORTH” and “SOUTH” are not directly opposite but they become directly opposite after the reduction of “EAST” and “WEST” so the whole path is reducible to [“WEST”, “WEST”].
Ruby
Init
1 |
|
Sample Testing
1 |
|
Javascript
Init
1 |
|
Sample Testing
1 |
|
Thinking
想法(1): 這邊的想法要稍微想一下,如果是南北、東西互相抵銷的時候必須不能顯示,這就會先要一開始定義然後去比比對了。
想法(2): 比對宣告的陣列中,如果進來的值對應到相同的,必須被移除在陣列中,沒有的話,則會被推進去。
圖片來源:Unsplash Aleks Marinkovic
Hint & Reference
- Ruby
- JavaScript
Solution
Ruby
1 |
|
Javascript
1 |
|