-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjosephos-survivor.js
More file actions
52 lines (44 loc) · 1.69 KB
/
josephos-survivor.js
File metadata and controls
52 lines (44 loc) · 1.69 KB
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
50
51
52
/*
In this kata you have to correctly return who is the "survivor", ie: the last element of a Josephus permutation.
Basically you have to assume that n people are put into a circle and that they are eliminated in steps of k elements, like this:
josephus_survivor(7,3) => means 7 people in a circle;
one every 3 is eliminated until one remains
[1,2,3,4,5,6,7] - initial sequence
[1,2,4,5,6,7] => 3 is counted out
[1,2,4,5,7] => 6 is counted out
[1,4,5,7] => 2 is counted out
[1,4,5] => 7 is counted out
[1,4] => 5 is counted out
[4] => 1 counted out, 4 is the last element - the survivor!
The above link about the "base" kata description will give you a more thorough insight about the origin of this kind of permutation, but basically that's all that there is to know to solve this kata.
Notes and tips: using the solution to the other kata to check your function may be helpful, but as much larger numbers will be used, using an array/list to compute the number of the survivor may be too slow; you may assume that both n and k will always be >=1.
*/
function josephusSurvivor(n,k){
let array = []
let elIndex = k - 1
for (let i = 1; i <= n; i++){
array[i - 1] = i
}
if (elIndex > array.length){
elIndex = elIndex - (array.length * Math.floor(elIndex/array.length))
}
else if (elIndex == array.length){
elIndex = 0
}
while (array.length > 1){
if (elIndex == 0){
array.shift()
}
else{
array.splice(elIndex, 1)
}
elIndex += k - 1
if (elIndex > array.length){
elIndex = elIndex - (array.length * Math.floor(elIndex/array.length))
}
else if (elIndex == array.length){
elIndex = 0
}
}
return array[0]
}