Last active
March 22, 2021 12:20
-
-
Save izharaazmi/69365ce306114f1539e75465bc1767da to your computer and use it in GitHub Desktop.
N number of people are standing in a circle with person 1 having a gun. He kills the next person and handovers the gun to next alive person. This continues until only one person survives. Find out the survivor.
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
<?php | |
class CircleOfDeath | |
{ | |
protected $size; | |
protected $list; | |
protected $current; | |
public function __construct($size) | |
{ | |
$this->size = $size; | |
$this->list = array_fill(1, $this->size, true); | |
} | |
public function massKill() | |
{ | |
$this->current = 1; | |
while (true) | |
{ | |
$kill = $this->getNext(); | |
if ($kill) | |
{ | |
$this->list[$kill] = false; | |
$next = $this->getNext(); | |
if ($next) | |
{ | |
$this->current = $next; | |
} | |
else | |
{ | |
break; | |
} | |
} | |
else | |
{ | |
break; | |
} | |
} | |
return $this->current; | |
} | |
public function getNext() | |
{ | |
for ($i = $this->current + 1; $i <= $this->size; $i++) | |
{ | |
if ($this->list[$i]) | |
{ | |
return $i; | |
} | |
} | |
for ($i = 1; $i < $this->current; $i++) | |
{ | |
if ($this->list[$i]) | |
{ | |
return $i; | |
} | |
} | |
return 0; | |
} | |
} | |
$opts = getopt('s:'); | |
if (isset($opts['s']) || !is_numeric($opts['s'])) | |
{ | |
$circle = new CircleOfDeath($opts['s']); | |
echo 'The survivor is: ' . $circle->massKill(); | |
echo PHP_EOL; | |
} | |
else | |
{ | |
echo "\nUSAGE: \n\nphp ./circle-of-death.php -s 100\n\n"; | |
} | |
/** | |
* Command: php ./circle-of-death.php -s 100 | |
* | |
* Output: The survivor is 73. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment