Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Given an array, check that the pattern of even then odd is upheld

I’m stumped on this problem:

Given an array, check that every number switches from even to odd. All numbers in the array are positive integers.
If there is a number that breaks the pattern, return the index of that number.
If there aren’t any numbers that break the pattern, return a -1

Example arrays + solutions:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//[1, 4, 5, 7, 4] // 3

//[25, 25, 25] // 1

//[4, 5, 2, 7, 4, 9] // -1

I have solved for this problem, except when it comes to the [25, 25, 25] array. Looking for this to be solved in JS.

Really not pretty, but here’s what I have so far:

` function parity(numbers) {
   let evenIndex = []
   let oddIndex = []
   let container = []

   for (var i = 0; i < numbers.length; i+=2) {
    evenIndex.push(numbers[i])
   }

   for (var i = 1; i < numbers.length; i+=2) {
    oddIndex.push(numbers[i])
   }

   if (numbers[0] % 2 === 0) {
    for (var i = 0; i < evenIndex.length; i++) {
      if (evenIndex[i] % 2 !== 0) {
        container.push(numbers.indexOf(evenIndex[i]))
      }
    }
    for (var i = 0; i < oddIndex.length; i++) {
      if (oddIndex[i] % 2 !== 1) {
        container.push(numbers.indexOf(oddIndex[i]))
      }
    }
   }
  

   if (numbers[0] % 2 === 1) {
    for (var i = 0; i < evenIndex.length; i++) {
      if (evenIndex[i] % 2 !== 1) {
        container.push(numbers.indexOf(evenIndex[i]))
      }
    }
    for (var i = 0; i < oddIndex.length; i++) {
      if (oddIndex[i] % 2 !== 0) {
        container.push(numbers.indexOf(oddIndex[i]))
      }
    }
   }

   if (container.length === 0) {
    return -1
   }
   return Math.min(...container)
}`

>Solution :

You can simply check if the parity of each element is equal to the parity of the previous element, starting from the second element (index 1). The first index for which this is true should be returned. If the end of the array is reached, then return -1.

function solve(arr) {
  for (let i = 1; i < arr.length; i++)
    if (arr[i] % 2 === arr[i - 1] % 2) return i;
  return -1;
}
console.log(solve([1, 4, 5, 7, 4])); // 3
console.log(solve([25, 25, 25])); // 1
console.log(solve([4, 5, 2, 7, 4, 9])); // -1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading