gpt4 book ai didi

javascript - 如何随机化 2 个列表,使相同索引的项目不相同?

转载 作者:行者123 更新时间:2023-12-04 03:22:15 24 4
gpt4 key购买 nike

假设我有 2 个包含相同项目的列表,这些列表如下所示:

listA = [1, 3, 2];
listB = [2, 3, 1];
我想确保相同索引的列表项不匹配。所以我不希望 listA[1]listB[1] 匹配。如何随机化两个列表,以免发生这种情况?

最佳答案

可能有一种更优雅的方法来做到这一点,但下面的代码应该可以工作,即使对于不同大小的数组也是如此。它首先检查是否有可能获得您正在寻找的唯一性,如果是,则进入一个 while 循环,以连续打乱两个数组中较大的一个(就地),直到找到解决方案。

// First, set up utility functions

function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}

function smallerAndOther(arr1, arr2) {
const smallerArr = arr1.length < arr2.length ? arr1 : arr2;
const otherArr = smallerArr === arr1 ? arr2 : arr1;
return [smallerArr, otherArr];
}

function anyEqualIdx(arr1, arr2) {
const [smallerArr, otherArr] = smallerAndOther(arr1, arr2);

for (let i of smallerArr.keys()) {
if (smallerArr[i] === otherArr[i]) return true;
}
return false;
}

function getCount(array, value) {
return array.filter((v) => (v === value)).length;
}

// Now for the real stuff

function sufficientUnique(arr1, arr2) {
const [smallerArr, otherArr] = smallerAndOther(arr1, arr2);

for (let num of new Set([...smallerArr])) {
if (otherArr.length - getCount(otherArr, num) < getCount(smallerArr, num)) {
return false;
}
}
return true;
}

function shuffleUniqueIdxs(arr1, arr2) {
if (!sufficientUnique(arr1, arr2)) {
console.log("Error: Not enough unique values to meet constraint.");
return;
}
const largerArr = arr1.length > arr2.length ? arr1 : arr2;
while (anyEqualIdx(arr1, arr2)) {
shuffleArray(largerArr);
}
console.log("Success: ", arr1, arr2);
}

// Testing

let listA = [1, 3, 2];
let listB = [2, 3, 1];

shuffleUniqueIdxs(listA, listB);

listA = [7, 5, 5, 3, 9, 9, 1];
listB = [3, 5, 5];

shuffleUniqueIdxs(listA, listB);

listA = [1, 1, 1];
listB = [2, 1, 1];

shuffleUniqueIdxs(listA, listB); // shows error message

listA = [1, 1, 1, 1, 1];
listB = [2, 2, 2, 2, 2];

shuffleUniqueIdxs(listA, listB);

listB = [99, 9, 9, 9, 9, 9, 9, 9, 99, 88, 8, 8, 8, 8, 8, 7, 7, 6, 65, 5, 5, 5, 4]
listA = [9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 6];

shuffleUniqueIdxs(listA, listB);

关于javascript - 如何随机化 2 个列表,使相同索引的项目不相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68294826/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com