javascript - 编写一个函数,该函数接受一个整数数组和一个“偶数”或“奇数”字符串
问题描述
我正在处理 javascript 中的一个问题,我应该编写一个函数,该函数接收一个整数数组和一个“偶数”或“奇数”的字符串。该函数将计算连续出现 4 个偶数或 4 个奇数的次数。
例如:
quadruples([3,2,2,4,8,5], 'even') // 1
quadruples([2,4,6,8,10,5], 'even') // 2
quadruples([2,4,6,8,10,5], 'odd') // 0
到目前为止,这是我所在的位置:
function quadruples(givenArray, evenOrOdd) {
let arr = []
if(evenOrOdd == 'even') {
if( i = 0; i < givenArray.length; i++) {
}
};
我想我需要运行一个 for 循环,然后使用 % 运算符,但我被困在从这里去哪里。
任何帮助表示赞赏!
解决方案
您需要使用局部和全局变量对此进行动态编程: [2, 4, 6, 8, 10, 5]
- 2 - 偶数,count 为 1,totalCount 为 0
- 4 - 偶数,计数为 2,totalCount 为 0
- 6 - 偶数,计数为 3,totalCount 为 0
- 8 - 偶数,count 为 4,totalCount 为 0
- 10 - 偶数,计数为 5,totalCount 为 0
- 5 - 奇数,计数为 5,将 totalCount 增加 5 - 4 + 1 = 2,将计数重置为 0
const quadruples = (givenArray, evenOrOdd) => {
// never hardcode `magic numbers`, create constants for them
const sequenceLength = 4
// based on evenOrOdd calculating what the division by 2
// will be if it is even, then 0, if it is odd, then 1
const rest = evenOrOdd === 'even' ? 0 : 1
// this will hold the total count of quadruples
let totalCount = 0
// this is the local count of contiguous elements
let count = 0
// looping over the array
for (let i = 0; i <= givenArray.length; i += 1) {
const el = givenArray[i]
// if the element is not what we want
if (i === givenArray.length || el % 2 !== rest) {
// if the count is 4 or more, we add to totalCount the count
// minus 4 and plus 1, meaning that if we have 4, it's 1 quadruple,
// if it is 5, then it's 2 quadruples, etc.
// Otherwise (count is less than 4) we add 0 (nothing)
totalCount += count >= sequenceLength ? count - sequenceLength + 1 : 0
// resetting the count to zero as we encountered the opposite
// of what we are looking for (even/odd)
count = 0
// if the element is what we need (even or odd)
} else {
// increasing the count of how many we've seen by far
count += 1
}
}
// returning totalCount of quadruples
return totalCount
}
console.log(quadruples([1, 3, 5, 7, 9, 11], 'odd')) // 3
console.log(quadruples([3, 2, 2, 4, 8, 5], 'even')) // 1
console.log(quadruples([2, 4, 6, 8, 10, 5], 'even')) // 2
console.log(quadruples([2, 4, 6, 8, 10, 5], 'odd')) // 0
推荐阅读
- php - 如何获取文件对象 laravel
- ios - 如何为 PencilKit 创建 .drawing 文件?
- java - tomcat如何调用@requestMapping注解
- r - 如何将多行列转换为长格式 R data.table
- amazon-web-services - AWS S3 对象删除问题
- mongodb - 如何使用 mongo-go-driver 编组/解组具有多态结构的 bson 数组
- python - Python BeautifulSoup:从 Google Play 商店检索评论相关信息
- cassandra - 为什么 Cassndra 被称为非结构化数据库
- javascript - 如何在映射的promise中一一修改useState数组
- php - 如何使用 PHP 删除页面 DOM 中的两个元素