博客文章
最近发表的话题
最近发表的评论
  • 你们敲代码时都在听什么音乐 at 4个月前

    喜欢粤语歌

  • [东京][20K-30K] 日本最大的教育 SAAS 系统-招聘 PHP 工程师 at 4个月前

    正好9月想去东京玩,可以去你公司玩玩吗!!

  • 一个将会是国内最高品质的 Python 社区,大家一起来见证 at 9个月前

    @Summer 能开通邮箱注册吗。国外党没有国内手机,收不到验证码。。。

  • 来自新浪微博的面试题 at 1年前

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

    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