-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
directions-reduction.js
46 lines (40 loc) · 1002 Bytes
/
directions-reduction.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const opposites = {
NORTH: 'SOUTH',
SOUTH: 'NORTH',
EAST: 'WEST',
WEST: 'EAST'
};
function dirReduc(arr) {
const stack = [];
arr.forEach(dir => {
if (stack.length) {
const prevDir = stack.pop();
if (prevDir !== opposites[dir]) {
stack.push(prevDir);
stack.push(dir);
}
} else {
stack.push(dir);
}
});
return stack;
}
console.log(
dirReduc(['NORTH', 'SOUTH', 'SOUTH', 'EAST', 'WEST', 'NORTH', 'WEST']), ['WEST']);
console.log(
dirReduc(['NORTH', 'WEST', 'SOUTH', 'EAST']), ['NORTH', 'WEST', 'SOUTH', 'EAST']);
console.log(
dirReduc(['NORTH', 'SOUTH', 'EAST', 'WEST', 'EAST', 'WEST']), []);
// function dirReduc(arr){
// const past = {};
// for (let i = arr.length - 1; i >= 0; i--) {
// const dir = arr[i];
// const oppositeDir = opposites[dir];
// past[dir] = past[dir] || [];
// past[dir].push(i);
// if (past[oppositeDir]) {
// arr.splice(i, 1);
// past[dir]--;
// }
// }
// }