gpt4 book ai didi

javascript - 在新数组中按顺序推送仅重复 2 次的数字

转载 作者:行者123 更新时间:2023-11-29 21:27:06 25 4
gpt4 key购买 nike

我希望我的数组 puma 在代码末尾包含 2,3,5,7,13,17,19,23。 (就是数字数组中按顺序重复02次的)谢谢

<!DOCTYPE html>
<html>
<head>
<title>Trial</title>
</head>
<body>
<script>
var number = [1,2,2,3,3,4,4,4,5,5,6,6,6,6,7,7,8,8,8,8,
9,9,9,10,10,10,10,10,11,12,12,12,12,12,12,
12,13,13,14,14,14,14,14,15,15,15,15,15,
16,16,16,16,16,17,17,18,18,18,18,18,18,
18,18,19,19,20,20,20,20,20,20,20,21,
21,21,21,22,22,22,22,23,23];
var puma=[];
for (k=0; k<number.length; k++)
for (i=1; i<number.length; i++)
for (j=2; j<number.length; j++)
{
if (number[k]==number[i] && number[k]!==number[j])
{
puma.push(number[k]);
}
};

document.write(puma);
</script>
</body>
</html>

最佳答案

为此,我们可以使用计数排序 概念。所以我们可以先统计每个元素的个数。然后获取计数等于二的元素。

var number = [1,2,2,3,3,4,4,4,5,5,6,6,6,6,7,7,8,8,8,8,9,9,9,10,10,10,10,10,11,12,12,12,12,12,12,12,13,13,14,14,14,14,14,15,15,15,15,15,16,16,16,16,16,17,17,18,18,18,18,18,18,18,18,19,19,20,20,20,20,20,20,20,21,21,21,21,22,22,22,22,23,23],
counts = [],
puma=[],
i;

for(i = 0; i < number.length; i++) {
counts[number[i]] = !!counts[number[i]] ? counts[number[i]] + 1 : 1;
}

function getNumbers(counts, n) {
return counts.reduce(function(a, c, i) {
if(c === n) {
a.push(i);
}
return a;
}, []);
}


document.write(getNumbers(counts, 2) + '</br>');
document.write(getNumbers(counts, 3) + '</br>');
document.write(getNumbers(counts, 4));

更新

如果只需要通过序列取数,那么我们有两种可能的情况:

  1. 当只有一个序列且长度为N时
  2. 当有多个序列且其中一个序列的长度等于N时。

var number = [0, 0, 1, 1, 2, 1, 1, 1],
counts = [],
puma=[],
prev, i, currentCount = 1;

for(i = 1, prev = number[0]; i < number.length; i++) {
var current = number[i];

if(prev === current) {
currentCount++;
}

if(prev !== current || i === number.length - 1) {
console.log(prev)
counts[prev] = (counts[prev] || []).concat([currentCount]);
prev = current;
currentCount = 1;
}
}

// (2nd situation) Get every number if it was found N times in a sequence
function getNumbers1(counts, n) {
return counts.reduce(function(a, c, i) {
if(c.indexOf(n) > -1) {
a.push(i);
}
return a;
}, []);
}

// (1st situation) Get number only if there is only one sequence of this number and it's length is equal to N
function getNumbers2(counts, n) {
return counts.reduce(function(a, c, i) {
if(c.length === 1 && c[0] === n) {
a.push(i);
}
return a;
}, []);
}

document.write(getNumbers1(counts, 2) + '</br>');
document.write(getNumbers2(counts, 2));

在这段代码中,我们首先获取每个数字的每个序列的所有长度。然后得到我们需要的序列。在最后一个例子中,counts 数组将等于 [ [ 2 ], [ 2, 3 ], [ 1 ] ] after

关于javascript - 在新数组中按顺序推送仅重复 2 次的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37233073/

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