Js秘密圣诞老人算法

Js secret santa claus algoritm

我想用 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);

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)

您可以随机对数组进行排序,然后将每个人分配给下一个。然后把数组中的第一个人赋给最后一个

// 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);