The IQ test gives an array of numbers.
One of them differs from the others by parity / oddness.
The function returns its index.

function iqTest(str) { array = str.split(' '); var boolArray = []; function checkEven(num) { return +num % 2 === 0? true:false; } for (var i = 0; i < array.length; i++) { boolArray.push(checkEven(array[i])); } var differ = boolArray[0]; var index = 1; for (var j = 1; j < boolArray.length; j++) { if (boolArray[j] !== differ) { differ = boolArray[j]; index = j; } } return index; }; 

But the function returns an invalid index, when a different element is an even number.

  • where does the variable diff come from? if (boolArray[j] !== dif) - ThisMan
  • one
    Not on the question: 1. Construction ? true : false ? true : false is useless in this case. 2. No need to bet ; after for {} and function {} , but after return s and other lines inside blocks of code you need. - Regent
  • Probably globally dif == 1 here and works only with odd ones. - exvayn
  • I called it "Differed", the code correctly says - wan140
  • one
    @ wan140 because up ? and so the expression returns true or false , and this value matches what you return - Grundy

1 answer 1

How can you solve the problem without comparing the parity of each element of the array with the parity of the previous ones:

  1. We create two arrays: one for storing indices of even numbers, the other for odd ones
  2. Pass through the checked array and add the element index to the corresponding array
  3. If there is exactly one element in any of the arrays, we return it, otherwise, for example, -1

Implementation:

 function iqTest(array) { var data = [[], []]; array.forEach(function(value, index) { data[value % 2].push(index); }); if (data[0].length == 1) return data[0][0]; if (data[1].length == 1) return data[1][0]; return -1; } console.log(iqTest([1, 3, 5, 2])); 


If desired, you can extend the algorithm to check the remainder of dividing by an arbitrary (given) number:

 function iqTest(array, base) { var data = []; for (var i = 0; i < base; i++) data.push([]); array.forEach(function(value, index) { data[value % base].push(index); }); for (var i = 0; i < base; i++) { if (data[i].length == 1) return data[i][0]; } return -1; } console.log(iqTest([1, 2, 3, 4, 5], 3)); 

  • A good option. I did not think of it. Thank! - wan140
  • It is only necessary that the index starts from one. Well, I'll fix it myself, - wan140