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:
JavaScript
x
4
1
quadruples([3,2,2,4,8,5], 'even') // 1
2
quadruples([2,4,6,8,10,5], 'even') // 2
3
quadruples([2,4,6,8,10,5], 'odd') // 0
4
so far this is where I am at:
JavaScript
1
7
1
function quadruples(givenArray, evenOrOdd) {
2
let arr = []
3
if(evenOrOdd == 'even') {
4
if( i = 0; i < givenArray.length; i++) {
5
6
}
7
};
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
JavaScript
1
45
45
1
const quadruples = (givenArray, evenOrOdd) => {
2
// never hardcode `magic numbers`, create constants for them
3
const sequenceLength = 4
4
5
// based on evenOrOdd calculating what the division by 2
6
// will be if it is even, then 0, if it is odd, then 1
7
const rest = evenOrOdd === 'even' ? 0 : 1
8
9
// this will hold the total count of quadruples
10
let totalCount = 0
11
12
// this is the local count of contiguous elements
13
let count = 0
14
15
// looping over the array
16
for (let i = 0; i <= givenArray.length; i += 1) {
17
const el = givenArray[i]
18
19
// if the element is not what we want
20
if (i === givenArray.length || el % 2 !== rest) {
21
// if the count is 4 or more, we add to totalCount the count
22
// minus 4 and plus 1, meaning that if we have 4, it's 1 quadruple,
23
// if it is 5, then it's 2 quadruples, etc.
24
// Otherwise (count is less than 4) we add 0 (nothing)
25
totalCount += count >= sequenceLength ? count - sequenceLength + 1 : 0
26
27
// resetting the count to zero as we encountered the opposite
28
// of what we are looking for (even/odd)
29
count = 0
30
31
// if the element is what we need (even or odd)
32
} else {
33
// increasing the count of how many we've seen by far
34
count += 1
35
}
36
}
37
38
// returning totalCount of quadruples
39
return totalCount
40
}
41
42
console.log(quadruples([1, 3, 5, 7, 9, 11], 'odd')) // 3
43
console.log(quadruples([3, 2, 2, 4, 8, 5], 'even')) // 1
44
console.log(quadruples([2, 4, 6, 8, 10, 5], 'even')) // 2
45
console.log(quadruples([2, 4, 6, 8, 10, 5], 'odd')) // 0