我想在 js 中制作一個包含用戶串列的小腳本,一個用戶必須向另一個用戶贈送禮物。
通過應用以下約束:
如果“a”是圣誕老人并向“c”贈送禮物,則不能相反。所以“c”不能是“a”的圣誕老人。
它必須同時適用于偶數和奇數用戶。
在您看來,嘗試最小化比較次數的正確方法是什么,即加速腳本。
我正在考慮這樣的事情開始,但之后我不知道如何繼續:
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);
uj5u.com熱心網友回復:
您可以隨機排序陣列并將每個人分配給下一個。然后將第一個人分配給陣列中的最后一個
// 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);
uj5u.com熱心網友回復:
let players = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
players = shuffleArray(players)
// Now place the santas, players[0] is the santa of players[1], 1 of 2 ... n is santa of 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(players)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/375501.html
標籤:javascript 数组 算法 随机的
