-
[Codewars] Array.diffAlgorithm 2021. 3. 20. 17:58
www.codewars.com/kata/523f5d21c841566fde000009/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
더보기배열 a에서 b 값과 같은 요소를 제거하고 리턴하는 문제
Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.
It should remove all values from list a, which are present in list b.
arrayDiff([1,2],[1]) == [2]
If a value is present in b, all of its occurrences must be removed from the other:
arrayDiff([1,2,2,2,3],[2]) == [1,3]
배열 a에서 b 값과 같은 요소를 제거하고 리턴하는 문제
Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.
It should remove all values from list a, which are present in list b.
arrayDiff([1,2],[1]) == [2]
If a value is present in b, all of its occurrences must be removed from the other:
arrayDiff([1,2,2,2,3],[2]) == [1,3]
풀이
- 배열 a에서 b의 i번째 요소와 똑같은 숫자가 있다면
- splice를 사용하여 삭제한다(while 사용하여 존재하지 않을 때까지 반복)
- a 리턴
function arrayDiff(a, b) { for(let i = 0; i < b.length; i++) { while(a.indexOf(b[i]) !== -1) { a.splice(a.indexOf(b[i]), 1); } } return a; }
'Algorithm' 카테고리의 다른 글
[Codewars] RGB To Hex Conversion (0) 2021.03.23 [Codewars] Dubstep (0) 2021.03.22 [프로그래머스] 소수 만들기 (0) 2021.03.18 [Codewars] Sum of Digits / Digital Root (0) 2021.03.17 [Codewars] Which are in? (0) 2021.03.15