Last active
July 19, 2021 13:26
-
-
Save kartikpuri95/811f75fe0233d4f3665864217af028fa to your computer and use it in GitHub Desktop.
who is left using power
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function who_is_left(n) { | |
var k = 0 | |
while (Math.pow(2,(k + 1)) < n) { | |
k=k+1 | |
if (n - (Math.pow(2,(k + 1)))!=0) { | |
console.log( (2 * (n - (Math.pow(2, k))) + 1)) | |
} else { | |
console.log( 1) | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Copied from | |
// https://www.geeksforgeeks.org/puzzle-100-people-in-a-circle-with-gun-puzzle/ | |
var person = 100; | |
// Placeholder array for person | |
var a = new Array(person); | |
// Assign placeholders from 1 to N (total person) | |
for (var i = 0; i < person; i++) { | |
a[i] = i + 1; | |
} | |
// Will start the game from 1st person (Which is at | |
// placeholder 0) | |
var pos = 0; | |
// Game will be continued till we end up with only one | |
// person left | |
while (a.length > 1) { | |
// Current person will shoot the person next to | |
// him/her. So incrementing the position. | |
pos++; | |
// As person are standing in circular manner, for | |
// person at last place has right neighbour at | |
// placeholder 0. So we are taking modulo to make it | |
// circular | |
pos = pos% (a.length); | |
// Killing the person at placeholder 'pos' | |
// To do that we simply remove that element | |
a.splice(pos,1) | |
// There is no need to increment the pos again to | |
// pass the gun Because by erasing the element at | |
// 'pos', now next person will be at 'pos'. | |
} | |
// Print Person that survive the game | |
document.write(a[0]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment