Javascript Array Puzzle: People with Sword Around a Circle
I want to solve one of the popular mathematical puzzles Josephus problem aka "100 people with a sword standing around a circle" using Javascript array methods for programmers.
Using basic Javascript coding and Array object with Array methods, it is easy to build an algoritm to solve this popular question for computer programmers.
Here is the puzzle also known as Josephus problem:
100 people are standing in a circle in an order from 1 to 100.
Number 1 has a sword. He kills the next person and then gives the sword to next.
Let's summarize like this. First person in order around the circle kills the next persons who is number 2 and passes the sword to person number 3
All of the people around the circle do the same until only 1 of them survives.
Which number survives at the last?
Javascript Code to Find Which Number Survives
In order to solve this mathematical puzzle, I preferred to code and simulate the case in Javascript.
Web programmers can easily read the below Javascript code.
The first part of the Javascript code block creates an array and populates it with numbers from 1 to 100 in a Javascript For Loop.
// populate the array for 100 people
var team = new Array();
for (var i = 1; i <= 100; i++) {
team[i  1] = i;
}
var current;
var next;
var j = 0.
while (team.length > 1) { // loop until only 1 exists
current = team[j];
team.push(team[j]); // move current to the end
team.shift(); // remove from existing
next = team[j];
team.shift(); // delete next
document.writeln("Number " + current + " kills number " + next + "<br />");
}
document.writeln("The last one is number " + team[0]);
//alert(team[0]);
Second part of the Javascript code block does the simulation in a While loop.
The logical test for While Loop is the number of existing people which means the number of items in the array.
Programmers can get the number of array items using Array.Length property.
Within the While Loop, current person who has the sword is added to the end of the array.
To append a new item to the array, developers can use Array.Push method.
Then the current person is removed or deleted from its initial existing place using Array.Shift method.
This enables to move the current array item to the end of the array like cut&paste.
The second Array.Shift method maps to the person killed with sword.
He or she is simply removed from the array.
Below is the output of above Javascript code execution, listing which number is killed by which number.
And at the end of the game, when code execution exists Javascript While loop, we can see that the last existing person around the circle is seen as number 73
I hope Javascript developers liked this solution of the mathematical puzzle or at least the algorithm applied for the solution of Josephus problem.
An other mathematical puzzle that can be easily solved using Javascript array objects and array methods is the Morris number sequence puzzle. I hope programmers will enjoy it too
