【问题标题】:Js secret santa claus algoritmJs 秘密圣诞老人算法
【发布时间】:2022-01-12 15:56:35
【问题描述】:

我想用 js 制作一个小脚本,它有一个用户列表,一个用户必须给另一个用户做礼物。

通过应用以下约束:

  1. 如果“a”是圣诞老人并给“c”送了礼物,则不能反过来。 所以“c”不可能是“a”的圣诞老人。

  2. 它必须同时适用于偶数和奇数用户。

在您看来,尝试最小化比较次数的正确方法是什么,即加快脚本速度。

我想这样开始,但后来我不知道如何继续:

let name = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

let a = [...name];
let group1 = [];
let groupSanta = [];
let groupUser = [];

for (var i = 0; i < name.length / 2 - 1; i++) {
  let santaClaus = a[Math.floor(Math.random() * a.length)];
  a = a.filter(item => item !== santaClaus);
  let user = a[Math.floor(Math.random() * a.length)];
  a = a.filter(item => item !== user);
  group1.push({ santaClaus, user });
}

console.log(a, group1);

【问题讨论】:

  • 随机播放列表,每个用户都是列表中下一个用户的圣诞老人(最后折叠)。
  • 该死的我应该写代码来更快地洗牌;)你的评论比我的速度快哈哈
  • 您没有清楚地描述预期的输出。 “c”也可以从“a”以外的人那里收到礼物吗?

标签: javascript arrays algorithm random


【解决方案1】:

let players = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

players = shuffleArray(players)

const matches = players.map((name, index) => {
  return {
    santa: name,
    receiver: players[index + 1] || players[0],
  }
});

function shuffleArray(array) {
    let currentIndex = array.length, randomIndex

    while (currentIndex != 0) {
        randomIndex = Math.floor(Math.random() * currentIndex)
        currentIndex--
        [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]]
    }

    return array
}

console.log(matches)

【讨论】:

    【解决方案2】:

    您可以随机排序数组并将每个人分配给下一个。然后将第一个人分配给数组中的最后一个人

    // Define names
    const names = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
    
    // Function to shuffle array
    const shuffle = (arr) => {
        for (let i = arr.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [arr[i], arr[j]] = [arr[j], arr[i]];
        }
        return arr;
    }
    
    const randomNames = shuffle(names);
    
    // Match each person with the next one, folding over at the end
    const matches = randomNames.map((name, index) => {
      return {
        santa: name,
        receiver: randomNames[index + 1] || randomNames[0],
      }
    });
    
    console.log(matches);

    【讨论】:

      猜你喜欢
      • 2010-09-21
      • 2013-11-10
      • 2016-05-23
      • 2022-01-15
      • 1970-01-01
      • 2012-01-26
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多