-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelephant2.js
49 lines (38 loc) · 1.01 KB
/
elephant2.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
47
48
49
class Elf {
constructor(number) {
this.number = number;
this.previous = null;
this.next = null;
}
leave() {
this.previous.next = this.next;
this.next.previous = this.previous;
}
skip(steps) {
let elf = this;
for (let i = 0; i < steps; i++) {
elf = elf.next;
}
return elf;
}
}
module.exports = (numberOfElves) => {
const elves = Array
.from({ length: numberOfElves })
.map((_, i) => new Elf(i + 1));
for (let i = 0; i < elves.length; i++) {
elves[i].previous = i - 1 < 0 ? elves[elves.length - 1] : elves[i - 1];
elves[i].next = i + 1 === elves.length ? elves[0] : elves[i + 1];
}
let elfAcross = elves[Math.floor(elves.length / 2)];
let currentElf = elves[0];
let elvesLeft = numberOfElves;
while (currentElf.next !== currentElf) {
elfAcross.leave();
elvesLeft--;
const nextElfAcross = elfAcross.skip(elvesLeft % 2 === 0 ? 2 : 1);
elfAcross = nextElfAcross;
currentElf = currentElf.next;
}
return currentElf.number;
};