gpt4 book ai didi

javascript - 通过均匀分布值有效地合并两个数组

转载 作者:行者123 更新时间:2023-12-02 19:22:14 26 4
gpt4 key购买 nike

我见过很多问题/答案都通过交替值来合并两个数组。他们是这样工作的:

let array1 = ["a", "b", "c", "d"];
let array2 = [1, 2];

let outcome = ["a",1 ,"b", 2, "c", "d"]

但我希望根据数组大小均匀分配值以提高输出效率。

expected outcome = ["a","b", 1, "c", "d", 2] 

其他场景

let array2 = [1];
expected outcome = ["a","b", 1, "c", "d"]

实现这种合并的最佳方式应该是什么?

最佳答案

求出两个数组的长度之比,longest.length/shortest.length,然后从最长的数组中取出所有最短的数组。

let array1 = ["a", "b", "c", "d", "e"];
let array2 = [1, 2];

const evenDistribute = (array1, array2) => {
const longest = array1.length > array2.length ? array1 : array2;
const shortest = array1.length > array2.length ? array2 : array1;
const ratio = Math.floor(longest.length / shortest.length);
const results = [];
for (let i = 0; i < shortest.length; i++) {
for (let j = 0; j < ratio; j++) {
results.push(longest[i * ratio + j]);
}
results.push(shortest[i]);
}
// Grab any that are left over
for (let i = longest.length - (longest.length % shortest.length); i < longest.length; i++) {
results.push(longest[i]);
}
return results;
}

console.log(evenDistribute(array1, array2));

关于javascript - 通过均匀分布值有效地合并两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62888437/

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