猴子问题:
写一个环形队列,问题就迎刃而解了。
class RingQueue
{
protected $items = [];
public function __construct($items = [])
{
$this->items = array_values($items);
}
public function current()
{
return current($this->items);
}
public function key()
{
return key($this->items);
}
public function next()
{
$next = next($this->items);
if ($next === false) {
reset($this->items);
return current($this->items);
}
return $next;
}
public function nextByStep($step)
{
$i = 0;
for ($i; $i < $step; $i++) {
$this->next();
}
return current($this->items);
}
public function count()
{
return count($this->items);
}
public function add($item)
{
$this->items[] = $itme;
return $this;
}
public function remove($index)
{
unset($this->items[$index]);
if (current($this->items) === false) {
reset($this->items);
}
return $this;
}
public function print()
{
return implode(',', $this->items);
}
}
function game(ringQueue $monkeys, $round)
{
$count = $monkeys->count();
if ($count === 1) {
echo 'Game Over.' . PHP_EOL;
echo 'Winner: ' . $monkeys->current() . PHP_EOL;
return;
}
echo 'Round: ' . $round . PHP_EOL;
echo 'Monkeys: ' . $monkeys->print() . PHP_EOL;
echo 'Current Monkey: ' . $monkeys->current() . PHP_EOL;
$step = rand(0, $count - 1);
echo 'Step: ' . ($step + 1) . PHP_EOL;
$outMonkey = $monkeys->nextByStep($step);
$monkeys->remove($monkeys->key());
echo 'Out Monkey: ' . $outMonkey . PHP_EOL;
echo '--------------------------' . PHP_EOL;
game($monkeys, $round + 1);
}
$ringQueue = new ringQueue(['A', 'B', 'C', 'D']);
game($ringQueue, 1);
结果:
Round: 1
Monkeys: A,B,C,D
Current Monkey: A
Step: 2
Out Monkey: B
--------------------------
Round: 2
Monkeys: A,C,D
Current Monkey: C
Step: 1
Out Monkey: C
--------------------------
Round: 3
Monkeys: A,D
Current Monkey: D
Step: 2
Out Monkey: A
--------------------------
Game Over.
Winner: D