将数组中连续的相同项混在一起,使得输出数组没有连续的值.Javascript [英] Jumble consecutive same items in an array such that the output array has no consecutive values. Javascript
问题描述
它的想法是在具有相似值的数组中基本上没有重复的值.
The idea it to basically not have repeated values in the array with similar values.
示例数组包含值
Example array contains the values
input = [1,2,2,2,2,3,4,5,6,7,8,9]<br/>
预期的输出内容
Expected output to have something
likeoutput = [1,2,3,2,4,2,5,2,6,2,7,8,9]<br/>
我试过把它放在一个 for 循环中,它检查下一个项目,如果相同,则交换值.问题是当我有连续的相似值时.
I have tried putting this in a for loop with where it checks with the next item and if it is same, swaps the values. The problem is when I have continuous similar values.
推荐答案
这个提案的特点
- 元素计数并将其存储在适当的对象中,
- 检查是否可以传播(例如,不在这里
[1, 1, 1, 1, 3, 3]
), - 循环使用元素,所以
- 相同元素之间的最大距离.
它是如何工作的?
我以这个数组为例:[1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9]
用元素的数量构建一个对象,以元素为键存储它.
Build an object with the count of the elements, store it with the element as key.
length = {
"1": 1, "2": 4, "3": 1, "4": 1, "5": 1, "6": 1, "7": 1, "8": 1, "9": 1
}
length[2] = 4
用前一个值的长度创建一个新数组,并用空数组填充它.
length[2] = 4
Make a new array with the length of the previous value and fill it with empty arrays.
output = [[], [], [], [], []]
设置k
为属性最大值的key.
Set k
to the key of the biggest value of a property.
k = '2'
设置l
为length[k]
的值.
l = 4
l
并将 k
推送到索引为 i % outputLength
的数组的末尾.增加i
.k
.返回平面 output
数组.
l
and push k
to the end of the array with the index of i % outputLength
. Increase i
.k
.Return the flat output
array.
output first then continued
array 0: 2 1 6
array 1: 2 3 7
array 2: 2 4 8
array 3: 2 5 9
return: 2 1 6 2 3 7 2 4 8 2 5 9
distance | | | | is equal
function spread(input) {
function findMaxKey() {
var max = 0, key;
Object.keys(length).forEach(function (k) {
if (length[k] > max) {
max = length[k];
key = k;
}
});
return key;
}
var length = input.reduce(function (r, a) {
r[a] = (r[a] || 0) + 1;
return r;
}, {}),
i = 0, k = findMaxKey(), l,
outputLength = length[k],
output = Array.apply(Array, { length: outputLength }).map(function () { return []; });
if (input.length - outputLength < outputLength - 1 ) {
return; // no spread possible
}
while (k = findMaxKey()) {
l = length[k];
while (l--) {
output[i % outputLength].push(k);
i++;
}
delete length[k];
}
return output.reduce(function (r, a) { return r.concat(a) }, []);
}
console.log(spread([1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9]));
console.log(spread([1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]));
console.log(spread([1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]));
console.log(spread([1, 1, 1, 1, 3, 3]));
console.log(spread([1, 1, 3]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于将数组中连续的相同项混在一起,使得输出数组没有连续的值.Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!