iqTest.js

Codewars 알고리즘 풀이


Problem

  • Bob is preparing to pass IQ test.
    • Bob은 IQ 테스트를 준비하고 있다.
  • The most frequent task in this test is to find out which one of the given numbers differs from the others.
    • 가장 빈번한 테스트는, 주어진 숫자 중 하나가 다른 것을 찾는 것이다.
  • Bob observed that one number usually differs from the others in ‘evenness’.
    • Bob은 일반적으로 한 숫자가 다른 숫자와 균등하지 않다는 것을 관찰했다.
  • Help Bob to check his answer, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number.
    • 주어진 숫자 중에서 다른 것을 찾고, 이 숫자의 위치를 반환한다.
  • Indexes of the elements start from 1(not 0).
    • 인덱스는 0이 아닌 1부터 시작한다.



Solution 01

function iqTest(str) {
  const arr = str.split(' ').map(i => parseInt(i));
  let even = [];
  let odd = [];
  
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] % 2 === 0) {
      even.push(arr[i]);
    } else {
      odd.push(arr[i]);
    }
  }
  return even.length > odd.length ? arr.indexOf(odd[0]) + 1 : arr.indexOf(even[0]) + 1;
}

iqTest('1 2 2');       // 1 (1)
iqTest('2 4 7 8 10');  // 3 (7)
iqTest('2 4 6 9 10');  // 4 (9)


Solution 02

function iqTest(str) {
  const arr = str.split(' ').map(i => parseInt(i));
  const even = arr.filter(i => i % 2 === 0);
  const odd = arr.filter(i => i % 2 === 1);
  
  return even.length > odd.length ? arr.indexOf(odd[0]) + 1 : arr.indexOf(even[0]) + 1;
}

iqTest('1 2 2');       // 1 (1)
iqTest('2 4 7 8 10');  // 3 (7)
iqTest('2 4 6 9 10');  // 4 (9)


Solution 03

function iqTest(str) {
  const arr = str.split(' ');
  const even = arr.filter(i => i % 2 === 0);
  const odd = arr.filter(i => i % 2 === 1);
  const differ = even.length === 1 ? even[0] : odd[0];
  
  return arr.indexOf(differ) + 1;
}

iqTest('1 2 2');       // 1 (1)
iqTest('2 4 7 8 10');  // 3 (7)
iqTest('2 4 6 9 10');  // 4 (9)