|
| 1 | +<h1>Josephus Survivor <sup><sup>5 Kyu</sup></sup></h1> |
| 2 | + |
| 3 | +<sup> |
| 4 | + <a href="https://www.codewars.com/kata/555624b601231dc7a400017a"> |
| 5 | + <strong>LINK TO THE KATA</strong> |
| 6 | + </a> - <code>MATHEMATICS</code> <code>COMBINATORICS</code> <code>ALGORITHMS</code> <code>LISTS</code> <code>ARRAYS</code> |
| 7 | +</sup> |
| 8 | + |
| 9 | +## Description |
| 10 | + |
| 11 | +In this kata you have to correctly return who is the "survivor", ie: the last element of a [Josephus permutation](https://www.codewars.com/kata/josephus-permutation/). |
| 12 | + |
| 13 | +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: |
| 14 | + |
| 15 | +``` |
| 16 | +n=7, k=3 => means 7 people in a circle |
| 17 | +one every 3 is eliminated until one remains |
| 18 | +[1,2,3,4,5,6,7] - initial sequence |
| 19 | +[1,2,4,5,6,7] => 3 is counted out |
| 20 | +[1,2,4,5,7] => 6 is counted out |
| 21 | +[1,4,5,7] => 2 is counted out |
| 22 | +[1,4,5] => 7 is counted out |
| 23 | +[1,4] => 5 is counted out |
| 24 | +[4] => 1 counted out, 4 is the last element - the survivor! |
| 25 | +``` |
| 26 | + |
| 27 | +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. |
| 28 | + |
| 29 | +**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. |
| 30 | + |
| 31 | +## Solution |
| 32 | + |
| 33 | +```javascript |
| 34 | +const getCircleOfPersons = num => { |
| 35 | + const circle = [] |
| 36 | + for (let i = 1; i <= num; i++) { |
| 37 | + circle.push(i) |
| 38 | + } |
| 39 | + return circle |
| 40 | +} |
| 41 | + |
| 42 | +const josephusSurvivor = (n, k) => { |
| 43 | + const circleOfPersons = getCircleOfPersons(n) |
| 44 | + let index = 0 |
| 45 | + |
| 46 | + while (circleOfPersons.length > 1) { |
| 47 | + index = (index + k - 1) % circleOfPersons.length |
| 48 | + circleOfPersons.splice(index, 1) |
| 49 | + } |
| 50 | + |
| 51 | + return circleOfPersons[0] |
| 52 | +} |
| 53 | +``` |
0 commit comments