javascriptparity

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:

//[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. 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) {
      let x, y;
      for (let i = 0; i < arr.length; i++) {
        y = arr[i] % 2;
        if (x === y) return i;
        x = y;
      }
      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

    TypeScript Playground