-
[Codewars] Are they the "same"?Algorithm 2020. 11. 8. 17:31
www.codewars.com/kata/550498447451fbbd7600041c/train/javascript
Codewars: Achieve mastery through challenge
Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.
www.codewars.com
더보기문제
Given two arrays a and b write a function comp(a, b) (or compSame(a, b)) 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.
예제
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]Invalid arrays
If, for example, we change the first number to something else, comp may not return true anymore:
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [132, 14641, 20736, 361, 25921, 361, 20736, 361]comp(a,b) returns false because in b 132 is not the square of any number of a.
a = [121, 144, 19, 161, 19, 144, 19, 11]
b = [121, 14641, 20736, 36100, 25921, 361, 20736, 361]comp(a,b) returns false because in b 36100 is not the square of any number of a.
풀이
- a, b 배열을 각각 오름차순으로 정렬한다.
- for문을 배열 길이만큼 사용한다.
- a 배열 요소를 제곱해서 b 배열 같은 인덱스의 값과 같으면 카운트를 늘려준다
- 카운트와 배열의 길이가 같으면 true, 아니면 false
function comp(array1, array2){ let sortA = array1.sort((a, b) => a - b); let sortB = array2.sort((a, b) => a - b); let count = 0; for(let i = 0; i < sortA.length; i++) { if(Math.pow(sortA[i], 2) === sortB[i]) { count++; } } if(count === sortA.length) return true; return false; }
'Algorithm' 카테고리의 다른 글
[프로그래머스] 약수의 합 (0) 2021.01.18 [Codewars] Valid Braces (0) 2020.11.16 [Codewars] Format a string of names like 'Bart, Lisa & Maggie' (0) 2020.11.08 [Codewars] Who likes it? (0) 2020.10.28 [Codewars] Create Phone Number (0) 2020.10.27