본문 바로가기
연습장

Which are in?

by anothel 2021. 10. 13.

Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2.

 

Example 1:

a1 = ["arp", "live", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
returns ["arp", "live", "strong"]

Example 2:

a1 = ["tarp", "mice", "bull"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
returns []

 

Notes:

Arrays are written in "general" notation. See "Your Test Cases" for examples in your language. In Shell bash a1 and a2 are strings. The return is a string where words are separated by commas. Beware: r must be without duplicates.

 

Solution

class WhichAreIn {
 public:
  static std::vector<std::string> inArray(std::vector<std::string> &array1,
                                          std::vector<std::string> &array2);
};

std::vector<std::string> WhichAreIn::inArray(std::vector<std::string> &array1,
                                             std::vector<std::string> &array2) {
  std::vector<std::string> vReturn;

  for (auto x : array1) {
    for (std::string s : array2) {
      if (s.find(x) != std::string::npos) {
        vReturn.push_back(x);
        break;
      } else {
        // Do nothing
      }
    }
  }

  sort(vReturn.begin(), vReturn.end());

  return vReturn;
}

 

AustinBrunkhorst의 코드

#include <algorithm>

class WhichAreIn {
 public:
  static std::vector<std::string> inArray(std::vector<std::string> &array1,
                                          std::vector<std::string> &array2) {
    std::vector<std::string> results;

    std::copy_if(array1.begin(), array1.end(), std::back_inserter(results),
                 [&](const std::string &item1) {
                   return std::any_of(array2.begin(), array2.end(),
                                      [&](const std::string &item2) {
                                        return item2.find(item1) !=
                                               std::string::npos;
                                      });
                 });

    std::sort(results.begin(), results.end());

    return results;
  }
};

 

후기

내가 알아야 할 것들은 너무나도 많은 게 마치 심해와도 같다. 너무 깊고 또 넓다. 주어진 두 개의 벡터에는 단어들이 들어있다. 하나의 벡터에 들어가 있는 단어들 중 다른 벡터에 들어있는 단어들에 포함되어 있는지를 확인해서 포함되어 있으면 새로운 벡터에 담아서 리턴하는 형태의 문제이다. 그런데 이때, 정렬이 되어있어야 한다. 이게 포인트였다. 정렬이 되어 있어야 했다. 문제에 정렬이 되어야 한다는 말이 있었다면 좀 더 좋았을 텐데 조금은 아쉽다.

남의 코드에는 처음 보는 STL 함수들이 많았다. std::copy_if, std::back_inserter, std::any_of 그리고 [&] 람다. 딱 공부하기 좋은 코드이지만, 다른 한편으로는 과연 코드를 이렇게 알아보기 어렵게 짜야하는 이유는 무엇인가? 하는 생각이 든다. 왜냐하면 한눈에 확 들어오면 가독성이 좋을 테니까. 위에 나열한 STL의 알짜배기 함수들과 람다식은 몰라도 된다는 가정하에 말이다. 사족 필요 없이 이펙티브 STL 책을 한번 더 펼쳐봐야겠다..

 

std::any_of

주어진 조건에 일치하는 값이 하나라도 있으면 true를 리턴한다.

#include <algorithm>  // std::any_of
#include <array>      // std::array
#include <iostream>
#include <string>

int main() {
  std::array<std::string, 3> fruits = {"grape", "apple", "cherry"};

  if (std::any_of(fruits.begin(), fruits.end(),
                  [&](std::string s) { return s.compare("cherry") == 0; })) {
    std::cout << "There is cherry in the range." << std::endl;
  } else {
    std::cout << "There is not cherry in the range." << std::endl;
  }

  return 0;
}

 

std::copy_if

주어진 조건에 일치하면 해당 요소를 복사한다. 조건은 꺼내온 요소를 바탕으로 직접 만들어서 결과값을 리턴하며, true를 리턴할 경우 해당 요소를 std::back_inserter로 지정한 컨테이너에 push한다.

#include <algorithm>  // std::copy_if
#include <array>      // std::array
#include <iostream>
#include <string>
#include <vector>

int main() {
  std::array<std::string, 3> fruits = {"grape", "apple", "cherry"};
  std::vector<std::string> basket;

  std::copy(fruits.begin(), fruits.end(), std::back_inserter(basket));

  basket.clear();

  std::copy_if(fruits.begin(), fruits.end(), std::back_inserter(basket),
               [&](std::string s) { return s.compare("cherry") == 0; });

  for (auto x : basket) {
    std::cout << x << std::endl;
  }

  return 0;
}

 

(url: https://www.codewars.com/kata/550554fd08b86f84fe000a58)

 

728x90

'연습장' 카테고리의 다른 글

N과 M (2) - 15650  (0) 2021.10.18
N과 M (1) - 15649  (0) 2021.10.18
Row Weights  (0) 2021.10.13
Simple multiplication  (0) 2021.10.13
해시 > 완주하지 못한 선수  (0) 2021.10.12