Skip to content
Advertisement

Write a function that takes in an array of integers, and a string that will be either ‘even’ or ‘odd’

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

so far this is where I am at:

JavaScript

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
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement