본문 바로가기
알고리즘/Codewars

[Codewars] Array.diff (6 kyu) / JavaScript

by fluss 2022. 10. 9.

https://www.codewars.com/kata/523f5d21c841566fde000009

 

Codewars - Achieve mastery through coding practice and developer mentorship

Coding practice for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

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 keeping their order.

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]

 

설명:

이 kata에서 당신의 목표는 한 리스트에서 다른 리스트를 뺀 결과를 반환하는 difference 함수를 구현하는 것입니다.

순서를 유지하면서 리스트 a에서 리스트 b에 있는 모든 값을 제거해야 합니다.

arrayDiff([1,2],[1]) == [2]

If a value is present in b, all of its occurrences must be removed from the other:

값이 b에 있다면 나타나는 모든 값은 다른 리스트에서 제거되어야 합니다.

arrayDiff([1,2,2,2,3],[2]) == [1,3]

 

풀이

function arrayDiff(a, b) {
  let result = [];
  for(let i = 0; i < a.length; i++){
    result.push(a[i]);
    for(let j = 0; j < b.length; j++){
      if(a[i] === b[j]){
        result.pop();
      }
    }
  }
  return result;
}
 
 result에 a 배열의 값을 넣고 그 값이 b 배열의 갑과 같으면 넣었던 값을 빼주었다.
 

다른 사람의 좋았던 풀이

function array_diff(a, b) {
  return a.filter(e => !b.includes(e));
}

filter로 a의 원소가 b의 원소에 포함되지 않은 경우를 모은 배열을 반환한다.

댓글