javascript——队列(击鼓传花)

队列(FIFO)规则:先进先出

击鼓传花游戏规则:

所有的人围成一个圈,规定一个数字,从第一个人的名字开始数,数到谁就淘汰谁,最后剩下的人获胜。

代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>封装队列</title>
</head>

<body>
    <script>
        //封装队列类
        function Queue() {
            //属性
            this.items = [];

            //方法
            //1.将元素添加到队列中
            Queue.prototype.enQueue = function (element) {
                this.items.push(element);
            }

            //2.从队列中删除前端元素
            Queue.prototype.deQueue = function () {
                return this.items.shift();
            }

            //3.查看前端元素
            Queue.prototype.front = function () {
                return this.items[0];
            }

            //4.查看队列是否为空
            Queue.prototype.isEmpty = function () {
                return this.items.length == 0
            }

            //5.查看队列中元素的个数
            Queue.prototype.size = function () {
                return this.items.length
            }

            //6.toSting方法
            Queue.prototype.toString = function () {
                let str = ""
                for (let i = 0; i < this.items.length; i++) {
                    str += this.items[i] + " "
                }
                return str
            }

        }


        //击鼓传花
        function passGame(nameList, number) {
            let queue = new Queue();
            //将所有的名字添加进队列
            for (let i = 0; i < nameList.length; i++) {
                queue.enQueue(nameList[i])
            }
            while (queue.size() > 1) {
                // 将所有下标不是number-1的名字移到队列后面
                for (let i = 0; i < number; i++) {
                    queue.enQueue(queue.deQueue())
                }
                // 删除队列第一个名字,即下标为number-1的名字
                queue.deQueue()
            }

            // 获取最终剩下的人
            return queue.front()

        }

        let nameList = ["张三", "李四", "王五", "小红", "小明"]
        alert(passGame(nameList,5))
    </script>
</body>

</html>

结果:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值