본문 바로가기

컴퓨터과학/Algorithm

[R] [Codewars] 8Kyu - Filter out the geese

 

Codewars: Achieve mastery through coding challenge

Codewars is a coding practice site for all programmers where you can learn various programming languages. Join the community and improve your skills in many languages!

www.codewars.com

문제

Write a function, gooseFilter / goose-filter / goose_filter / GooseFilter, that takes an array of strings as an argument and returns a filtered array containing the same elements but with the 'geese' removed.

The geese are any strings in the following array, which is pre-populated in your solution:

geese = ["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"]

For example, if this array were passed as an argument:

["Mallard", "Hook Bill", "African", "Crested", "Pilgrim", "Toulouse", "Blue Swedish"]

Your function would return the following array:

["Mallard", "Hook Bill", "Crested", "Blue Swedish"]

The elements in the returned array should be in the same order as in the initial array passed to your function, albeit with the 'geese' removed. Note that all of the strings will be in the same case as those provided, and some elements may be repeated.

 

코드

goose_filter <- function(birds){
  birds[! birds %in% c("African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher")]
}

 

설명

입력 벡터에서 geese 벡터의 원소들을 제거한 벡터를 반환하는 문제다.

 

1. 차집합으로 하면 되지 않을까 싶어 한번 풀어보았다.

goose_filter <- function(birds){
  setdiff(birds, c("African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"))
}

하지만 집합은 중복을 허용하지 않기 때문에, 입력값이 뭉개지므로 이 코드는 오답이다.

 

2. 벡터에서 특정 원소를 삭제하는 기능을 활용하여 풀었다. 자세한 방법은 링크를 참조.