新浪微博面试php,来自新浪微博的面试题

猴子问题:

写一个环形队列,问题就迎刃而解了。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值