Are they the "same"? ( 6 kyu )

문제

Given two arrays a and b write a function comp(a, b) (compSame(a, b) in Clojure) that checks whether the two arrays have the “same” elements, with the same multiplicities. “Same” means, here, that the elements in b are the elements in a squared, regardless of the order.

Examples

Valid arrays

a = [121, 144, 19, 161, 19, 144, 19, 11]  
b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]

comp(a, b) returns true because in b 121 is the square of 11, 14641 is the square of 121, 20736 the square of 144, 361 the square of 19, 25921 the square of 161, and so on. It gets obvious if we write b’s elements in terms of squares:

a = [121, 144, 19, 161, 19, 144, 19, 11] 
b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19]

array1 배열의 인자들을 제곱한 값이 array2에 있는지 비교하는 문제

풀이

function comp(array1, array2){
  if ( !array1 || !array2 ) return false;
  array1 = array1.map(a => { return a*a }).sort((a,b) => { return b-a });
  array2 = array2.sort((a,b) => { return b-a });
  for ( let i = 0; i < array1.length; i++ ) {
    if ( array1[i] !== array2[i] ) {
      return false;
    }
  }
  return true;
}

완전 별로인 풀이같다.

예외처리를 두개나 걸고 소트로 그냥 비교하는 방법

[1,2,3] === [1,2,3] 은 false인걸 처음알았다.. 역시난 허접

다른 사람의 풀이

function comp(array1, array2) {
  if(array1 == null || array2 == null) return false;
  array1.sort((a, b) => a - b); array2.sort((a, b) => a - b);
  return array1.map(v => v * v).every((v, i) => v == array2[i]);
}

예외처리 하나 걸고 소트로 비교


'자료구조, 알고리즘 > Codewars 문제' 카테고리의 다른 글

Find the divisors! ( 6 kyu )  (0) 2017.11.30
Array.diff ( 6 kyu )  (0) 2017.11.30
Your order, please ( 6 kyu )  (0) 2017.11.30
Greed is Good ( 5 kyu )  (0) 2017.11.30
Two Joggers ( 5 kyu )  (0) 2017.11.30

+ Recent posts