2

一个面试题 岗位是 FreeLancer 自己写了下

 2 years ago
source link: https://www.v2ex.com/t/807896
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  JavaScript

一个面试题 岗位是 FreeLancer 自己写了下

  KomiSans · 9 小时 20 分钟前 · 512 次点击

我的个人解法->

// 判断迁移数组的总和是否为 15
function filcheck(ar) {
    return ar.reduce((x, k) => {
        return x + k
    }, 0) === 15;
}

function entrance() {
    // 定义原数据数组
    var constArr = [3, 5, 7];
    // 定义初始迁移数据数组
    var arrReserver = [0, 0, 0];
    // 奇偶数定义 回合制玩家判断
    var odvar = 0;
    // 循环判断条件
    while (!filcheck(arrReserver)) {
        // 当数组中的所有元素已被移除后直接跳出循环
        if (arrReserver.length === 1) break;
        // 生成数组中的随机下标
        var arrIdx = Math.floor(Math.random() * (constArr.length));
        // 两数组同位置上元素的偏差 代表还剩多少物件
        var bxa = constArr[arrIdx] - arrReserver[arrIdx];
        // 当剩余数量为 0 时 移除该行
        if (bxa === 0) {
            constArr.splice(arrIdx, 1);
            arrReserver.splice(arrIdx, 1);
            continue;
        }
        // 迁移数据数组对应行数量添加
        arrReserver[arrIdx] += Math.floor((Math.random() * (bxa)) + 1);
        // 代表玩家本身
        odvar++;
    }
    // 利用回合制进行判断是哪位玩家失败
    return odvar % 2 === 0 ? "player1" : "player2";
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK