繁体   English   中英

有没有更简单的方法来计算数组中行中的相同项目?

[英]Is there more easier way to count same items that goes in row in array?

这是我的代码

function repeat(arr){
    let string = (arr.join(''))
    let start = -1
    let count = 0
    while((start = string.indexOf('hhh', start + 1)) != -1 ){
        count += 1
        start += 3
    }
    while((start = string.indexOf('ttt', start + 1)) != -1 ){
        count += 1
        start += 3
    }
    console.log(count)
}

repeat(["h", "h", "h", "t", "h", "h", "t", "t", "t", "h", "t", "h", "h", "h", "h"])

在此示例中,我尝试计算 t 或 h 连续出现 3 次的次数。

有没有办法在不制作字符串的情况下做到这一点? 或者至少将块与 while 合并为一个?

您可以迭代数组中的每个元素。

这样做时,您可以跟踪:

  • 已出现的重复组总数( total
  • 数组中前一个元素的值 ( previousElement )
  • 当前重复的元素数 ( currentCount )

以下是我上面描述的示例,包括注释:

 function countRepeats (numOfRepeated, array) { let total = 0; let currentCount = 0; // Start with an object because no object strictly equals any other value: let previousElement = {}; for (const element of array) { if (element === previousElement) { // Increment the count: currentCount += 1; if (currentCount === numOfRepeated) { // Increment the total: total += 1; // Reset the count to 1: currentCount = 1; } } else { // Reset the count to 1: currentCount = 1; } // Update the previous element: previousElement = element; } return total; } const total = countRepeats( 3, ["h", "h", "h", "t", "h", "h", "t", "t", "t", "h", "t", "h", "h", "h", "h"], // 1 2 3 1 1 2 1 2 3 1 1 1 2 3 1 // 1 2 3 ); console.log(total); // 3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM