我希望我的数组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>
答案 0 :(得分:2)
我们可以将counting sorting
概念用于此目的。所以我们可以先计算每个元素的数量。然后获取计数等于2的元素。
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));
如果需要仅按序列获取数字,那么我们有两种可能的情况:
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 ] ]