Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JiNexus/253a13ab7a88c6cd967d to your computer and use it in GitHub Desktop.
Save JiNexus/253a13ab7a88c6cd967d to your computer and use it in GitHub Desktop.
This code snippet is solely created just for fun.
function SinglyLinkedList() {
this.head = null;
}
SinglyLinkedList.prototype.push = function(val) {
var node = {
value: val,
next: null
};
if (!this.head) {
this.head = node;
} else {
current = this.head;
while(current.next) {
current = current.next;
}
current.next = node;
}
}
function CircularDoublyLinkedList()
{
this.head = null;
}
CircularDoublyLinkedList.prototype.push = function(val)
{
var head = this.head,
current = head,
node = {
person: val,
next: null,
previous: null
};
if (!head) {
node.next = node;
node.previous = node;
this.head = node;
} else {
while(current.next != head) {
current = current.next;
}
node.next = head;
node.previous = current;
head.previous = node;
current.next = node;
}
}
CircularDoublyLinkedList.prototype.remove = function(interval)
{
var position = 1;
var current = this.head;
while (current) {
if (position == interval) {
sequenceOfElimination.push(current.person);
this.head = current.next;
current.previous.next = current.next;
current.next.previous = current.previous;
position = 1;
delete current;
} else {
position++;
}
if (current.next != current) {
current = current.next;
} else {
break;
}
}
}
// Instantiate an object from Circular Doubly Linked List
var troops = new CircularDoublyLinkedList();
// Instantiate an object from Singly Linked List
var sequenceOfElimination = new SinglyLinkedList();
var josephus_problem = function(numberOfTroops, interval) {
if (numberOfTroops > 1) {
// Populate the troops
for (var i = 1; i <= numberOfTroops; i++) {
troops.push(i);
}
// Start the Josephus Problem or The elimination round!
troops.remove(interval);
} else {
console.log('No need to kill yourself. You can ride the horse now!');
}
}
var numberOfTroops = 40;
var interval = 3;
josephus_problem(numberOfTroops, interval);
console.log(sequenceOfElimination);
console.log(troops.head.person);
alert('Lone survivor ' + troops.head.person + ', you may ride the horse now!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment