Im working on a problem in javascript where I am supposed to write a function that takes in an array of integers, and a string that will be either ‘even’ or ‘odd’. The function will count how many times 4 even or 4 odd numbers show up in a row.
For example:
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
so far this is where I am at:
function quadruples(givenArray, evenOrOdd) { let arr = [] if(evenOrOdd == 'even') { if( i = 0; i < givenArray.length; i++) { } };
I figured I need to run a for loop and then use a % operator but I am stuck on where to go from here.
Any help is appreciated!
Advertisement
Answer
You need dynamic programming for this with a local and global variable: [2, 4, 6, 8, 10, 5]
- 2 – even, count is 1, totalCount is 0
- 4 – even, count is 2, totalCount is 0
- 6 – even, count is 3, totalCount is 0
- 8 – even, count is 4, totalCount is 0
- 10 – even, count is 5, totalCount is 0
- 5 – odd, count is 5, increasing totalCount by 5 – 4 + 1 = 2, resetting count to 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