… 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!
The directions given to the man are, for example, the following (depending on the language):
["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"].
or
{ "NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST" };
or
[North, South, South, East, West, North, West]
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:
["WEST"]
or
{ "WEST" }
or
[West]
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"].
Write a function dirReduc
which will take an array of strings and returns an array of strings with the needless directions removed (W<->E or S<->N side by side).
data Direction = North | East | West | South
.enum Direction {North, East, West, South}
.function dirReduc(arr){
console.log(arr);
function needless(dir1, dir2) {
dir1 = dir1.toUpperCase();
dir2 = dir2.toUpperCase();
if((dir1+dir2 == 'NORTHSOUTH') || (dir1+dir2 == 'SOUTHNORTH') || (dir1+dir2 == 'EASTWEST') || (dir1+dir2 == 'WESTEAST')) {
return true;
} else {
return false;
}
}
const result = arr.reduce(function(acc,cur){
if(acc == 0) {
acc.push(cur);
} else {
if(!needless(acc[acc.length-1], cur)) {
acc.push(cur);
} else {
acc.splice(acc.length-1,1);
}
}
return acc;
},[]);
return result;
}
function dirReduc(plan) {
var opposite = {
'NORTH': 'SOUTH', 'EAST': 'WEST', 'SOUTH': 'NORTH', 'WEST': 'EAST'};
return plan.reduce(function(dirs, dir){
if (dirs[dirs.length - 1] === opposite[dir])
dirs.pop();
else
dirs.push(dir);
return dirs;
}, []);
}
내가 string으로 체크한 반면에, 이 솔루션에서는 서로 상쇄되는 애들끼리 key,value 세트를 갖는 객체를 사용하였다. 비슷하지만, 더 간단하다.
이전 kata에도 비슷한 경우였는데, 내가 array.splice(array.length-1,1)로 사용한 것을 array.pop()으로 더 간단히 나타내였다.
나는 acc가 비었을때를 따로 케이스를 나누어서 다루었는데, 이 솔루션에서는 상쇄가 안되는 케이스와 합쳐서 한번에 다루었다.