很久以前,有一條通往西部無法地帶的路......
一位年輕的牛仔,根據指示,得從一個地方前往另一個地點。指示像這樣"NORTH", "SOUTH", "WEST", "EAST"。
很明顯,"NORTH"和"SOUTH"是相反的方向, "WEST"和"EAST"也是相反的。
走一個方向,然後又往回走,無疑在做無用功。
在這人跡罕至的西部荒野,糟糕的天氣,匱乏的水源,節約點體力很重要,否則很可能死於非命!
怎樣走最明智的路線,這很重要!
給牛仔的指示,像下面這樣:
plan = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
你能一眼看出,"NORTH"和"SOUTH",這樣的路線顯然是不合理的,最好呆在原地。
所以,你的任務是,怎樣精簡路線,以節省體力。
一個更好的方案應該像這樣:
plan = ["WEST"]
另一個例子:
["NORTH", "SOUTH", "EAST", "WEST"]
"和"SOUTH"做抵消,"EAST"和"WEST"做抵消,最後返回空數組。
再看個複雜點的例子:
["NORTH", "EAST", "WEST", "SOUTH", "WEST", "WEST"]
"EAST", "WEST"]
"EAST", "WEST"EAST",作抵消,得到 ["NORTH", "SOUTH", "WEST", "WEST"]"NORTH", "SOUTH"
"NORTH", "SOUTH"作抵消,最後得到["WEST", "WESTWEST" 。
但是,請注意,下面這種情況是沒辦法抵消的:
["NORTH", "WEST", "SOUTH", "EAST"]
因為"EAST", "WEST"
或"NORTH", "SOUTH"
並非相鄰,而是隔開的。 咋們來看看怎麼寫一個這樣的減少路線函數吧。
它接受一個字串陣列作為參數,並傳回新的字串陣列。
像這樣:
dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]) // ["WEST"] dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH"]) // []
第一步,建立方向的映射關係,哪些是相反的方向:
var opposite = { "NORTH":"SOUTH", "SOUTH":"NORTH", "EAST":"WEST", "WEST":"EAST" };
然後,開始第二輪遍歷,移除,抵消,第三輪,第N輪,直到找不到相反的方向,跳出循環。
此時的陣列就是經過精簡後的最佳路線。
function dirReduc(arr){ var flag = false; while(!flag){ for(var i=arr.length-2,flag=true;i>=0;i--){ if(opposite[arr[i]] === arr[i+1]){ arr.splice(i+1,1); arr.splice(i,1); i--; flag = false; } } } return arr; }