Calculating Josephus Permutations efficiently in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

This problem takes its name by arguably the most important event in the life of the ancient historian Josephus − according to his tale, he and his 40 soldiers were trapped in a cave by the Romans during a siege.

Refusing to surrender to the enemy, they instead opted for mass suicide, with a twist − they formed a circle and proceeded to kill one man every three, until one last man was left (and that it was supposed to kill himself to end the act).

Josephus and another man were the last two and, as we now know every detail of the story, you may have correctly guessed that they didn't exactly follow through the original idea.

We are required to write a JavaScript function that returns a Josephus permutation.

Taking as parameters the initial array/list of items to be permuted as if they were in a circle and counted out every k places until none remained.

For example, with n=7 and k=3 josephus(7,3) should act this way.

[1,2,3,4,5,6,7] − initial sequence
[1,2,4,5,6,7] => 3 is counted out and goes into the result [3]
[1,2,4,5,7] => 6 is counted out and goes into the result [3,6]
[1,4,5,7] => 2 is counted out and goes into the result [3,6,2]
[1,4,5] => 7 is counted out and goes into the result [3,6,2,7]
[1,4] => 5 is counted out and goes into the result [3,6,2,7,5]
[4] => 1 is counted out and goes into the result [3,6,2,7,5,1]
[] => 4 is counted out and goes into the result [3,6,2,7,5,1,4]

Therefore, our final result is −

josephus([1,2,3,4,5,6,7],3)==[3,6,2,7,5,1,4];

Example

The code for this will be −

const arr = [1, 2, 3, 4, 5, 6, 7];
const num = 3;
const helper = (n, k, i, map) => {
   if (map.hasOwnProperty([n, k, i]))
   return map[[n, k, i]];
   if (i === 1)
   return map[[n, k, i]] = (k − 1) % n;
   return map[[n, k, i]] =
   (k + helper(n − 1, k, i − 1, map)) % n;
}
const josephus = (arr, k) => {
   let n = arr.length;
   let result = new Array(n);
   let map = {};
   for (let i=1; i<=n; i++)
   result[i − 1] = arr[ helper(n, k, i, map) ];
   return result;
};
console.log(josephus(arr, num));

Output

And the output in the console will be −

[
   3, 6, 2, 7,
   5, 1, 4
]
raja
Published on 21-Nov-2020 10:13:55
Advertisements