数组中相同数字的序列

huangapple go评论70阅读模式
英文:

Sequence of equal numbers in array

问题

let arr = ['2', '1', '1', '2', '3', '3', '2', '2', '2', '1'].map(Number);

let maxSequence = [];

for (let i = 0; i < arr.length; i++) {
  let currentSequence = [];
  if (arr[i] === arr[i + 1]) {
    currentSequence.push(arr[i]);
  }
  if (currentSequence.length > maxSequence.length) {
    maxSequence = currentSequence;
  }
}
console.log(maxSequence.length) // 期望输出: 3
console.log(maxSequence) // 期望输出: [2, 2, 2]
英文:

I want to push the first sequence to currentSequence, then store it in maxSequence, then push the next sequence in currentSequence, check if its length is greater, if it isn't proceed further, if it is store it in maxSequence. I'd like to keep the original order of the array.

 let arr = [&#39;2&#39;,&#39;1&#39;,&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;3&#39;,&#39;2&#39;,&#39;2&#39;,&#39;2&#39;,&#39;1&#39;].map(Number)

let maxSequence = []

for(let i = 0; i&lt; arr.length; i++){
     let currentSequence = []
  if( arr[i] === arr[i+1] ){ 
    currentSequence.push(arr[i]);
  //currentSequence = arr.toSpliced(i, 1);
  }
  if(currentSequence.length &gt; maxSequence.length){
      maxSequence = currentSequence  
  }
  }
   console.log(maxSequence.length) // expected output: 3
   console.log(maxSequence) // expected output: [2, 2, 2]
 

答案1

得分: 0

以下是翻译好的部分:

let arr = ['2', '1', '1', '2', '3', '3', '2', '2', '2', '1'].map(Number)

let maxSequence = [];
let currentSequence = [];
let currentValue = -1;

for (let i = 0; i < arr.length; i++) {
  if (arr[i] === currentValue) {
    currentSequence.push(arr[i]);
  } else {
    currentValue = arr[i];
    currentSequence = [currentValue];
  }
  if (currentSequence.length > maxSequence.length) {
    maxSequence = currentSequence
  }
}
console.log(maxSequence.length) // 期望输出: 3
console.log(maxSequence) // 期望输出: [2, 2, 2]
英文:

This can be achieved like so:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let arr = [&#39;2&#39;, &#39;1&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;3&#39;, &#39;2&#39;, &#39;2&#39;, &#39;2&#39;, &#39;1&#39;].map(Number)

let maxSequence = [];
let currentSequence = [];
let currentValue = -1;

for (let i = 0; i &lt; arr.length; i++) {
  if (arr[i] === currentValue) {
    currentSequence.push(arr[i]);
  } else {
    currentValue = arr[i];
    currentSequence = [currentValue];
  }
  if (currentSequence.length &gt; maxSequence.length) {
    maxSequence = currentSequence
  }
}
console.log(maxSequence.length) // expected output: 3
console.log(maxSequence) // expected output: [2, 2, 2]

<!-- end snippet -->

答案2

得分: 0

以下是翻译好的内容:

一种实现你所需的方法是

let arr = ["2", "1", "1", "2", "3", "3", "2", "2", "2", "1"].map(Number);

let maxSequence = [];
let currentSequence = [arr[0]];

for (let i = 1; i < arr.length; i++) {
  if (arr[i] !== arr[i - 1]) { // 如果当前数字与前一个不匹配
    if (currentSequence.length > maxSequence.length) { // 这意味着当前的currentSequence已经完成,我们需要检查它是否比当前的maxSequence更长
      maxSequence = currentSequence;
    }
    currentSequence = [arr[i]]; // 然后需要重置currentSequence数组
    continue;
  }
  currentSequence.push(arr[i]); // 否则,如果数字匹配,我们将当前数字推送到currentSequence中
}
console.log(maxSequence.length); // 期望输出:3
console.log(maxSequence); // 期望输出:[2, 2, 2]
英文:

One way of doing what you need is:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let arr = [&quot;2&quot;, &quot;1&quot;, &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;3&quot;, &quot;2&quot;, &quot;2&quot;, &quot;2&quot;, &quot;1&quot;].map(Number);

let maxSequence = [];
let currentSequence = [arr[0]];

for (let i = 1; i &lt; arr.length; i++) {
  if (arr[i] !== arr[i - 1]) { // if current number does not match the one before it
    if (currentSequence.length &gt; maxSequence.length) { // it means currentSequence is complete and we need to check if it&#39;s larger than current maxSequence or not
      maxSequence = currentSequence;
    }
    currentSequence = [arr[i]]; // then need to reset the currentSequence array
    continue;
  }
  currentSequence.push(arr[i]); // else if numbers match, we push current number to the currentSequence
}
console.log(maxSequence.length); // expected output: 3
console.log(maxSequence); // expected output: [2, 2, 2]

<!-- end snippet -->

答案3

得分: 0

可以在不使用中间数组的情况下完成。

let arr = ['2','1','1','2','3','3','2','2','2','1'].map(Number);
let maxSequence;

(() => {
    let maxRunVal = arr[0], maxRun = 1;
    for (let i = 1, run = 1; i < arr.length; i++) {
        if (arr[i] == arr[i-1]) {
            run++;
            if (run > maxRun) {
                maxRun = run;
                maxRunVal = arr[i];
            }
        }
        else {
            run = 1;
        }
    }
    maxSequence = new Array(maxRun);
    maxSequence.fill(maxRunVal);
})();

console.log(maxSequence.length);
console.log(maxSequence);

如果您需要进一步的解释或有其他问题,请随时提出。

英文:

Can be done without an intermediate array.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let arr = [&#39;2&#39;,&#39;1&#39;,&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;3&#39;,&#39;2&#39;,&#39;2&#39;,&#39;2&#39;,&#39;1&#39;].map(Number);
let maxSequence;

(() =&gt; {
    let maxRunVal = arr[0], maxRun = 1;
    for (let i = 1, run = 1; i &lt; arr.length; i++) {
        if (arr[i] == arr[i-1]) {
            run++;
            if (run &gt; maxRun) {
                maxRun = run;
                maxRunVal = arr[i];
            }
        }
        else {
            run = 1;
        }
    }
    maxSequence = new Array(maxRun);
    maxSequence.fill(maxRunVal);
})();

console.log(maxSequence.length);
console.log(maxSequence);

<!-- end snippet -->

答案4

得分: 0

// ...
对于趣味性质您还可以使用正则表达式结合 [`Array.`]  `filter`  `reduce` 来过滤组请参阅 [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#instance_methods))

如果输入数组包含*多个相同长度的序列*可能会有问题因此代码片段中的函数返回了所有连续相等值的序列其长度为找到的最大长度

const arr = ['2','1','1','2','3','3','2','2','2','1','3','3','3'];
const maxSequences = longestSequencesOfEqualValues(arr);

console.log(`在 [${arr}] 中,最大序列长度为 ${
  maxSequences[0].length ?? 0}`);
console.log(`找到的序列(s):`);
maxSequences.forEach( seq => 
 console.log( `✓ [${seq}]`) 
);

function longestSequencesOfEqualValues(arr = []) {
  const groups = arr.join(``).match(/(.)*/g);
  const max = groups
    ?.filter(v => v.length > 1)
    .reduce( (a, v) => v.length > a ? v.length : a, 0 );
  return groups?.filter(el => el.length === max, 0)
    .reduce( (acc, v) => ([...acc, [...v] ]), []) ?? [];
}
// ...
英文:

For fun: you can also use a regular expression to filter the groups combined with [Array.] filter and reduce (see MDN)

It may be a problem if the input array contains multiple sequences of the same length. The function in the snippet therefore returns all sequences of consecutive equal values with a found maximum length.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const arr = [&#39;2&#39;,&#39;1&#39;,&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;3&#39;,&#39;2&#39;,&#39;2&#39;,&#39;2&#39;,&#39;1&#39;,&#39;3&#39;,&#39;3&#39;,&#39;3&#39;];
const maxSequences = longestSequencesOfEqualValues(arr);

console.log(`In [${arr}] the max sequence length is ${
  maxSequences[0].length ?? 0}`);
console.log(`found sequence(s):`);
maxSequences.forEach( seq =&gt; 
 console.log( `\u2713 [${seq}]`) 
);

function longestSequencesOfEqualValues(arr = []) {
  const groups = arr.join(``).match(/(.)*/g);
  const max = groups
    ?.filter(v =&gt; v.length &gt; 1)
    .reduce( (a, v) =&gt; v.length &gt; a ? v.length : a, 0 );
  return groups?.filter(el =&gt; el.length === max, 0)
    .reduce( (acc, v) =&gt; ([...acc, [...v] ]), []) ?? [];
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月29日 00:04:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76352381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定