문제풀이_알고리즘

future·2021년 1월 5일
0

문제풀이

목록 보기
6/6

#unpackGiftbox

선물 상자에 대한 정보를 담은 배열과 문자열을 입력받아 조건에 맞는 선물이 있는지 여부를 리턴해야 한다.

주의사항

  • boolean 타입을 리턴
  • 함수 unpackGiftbox는 재귀함수의 형태로 작성
  • 반복문(for, while) 사용이 가능
  • 입력받은 배열은 함수의 호출 뒤에도 처음 상태를 유지 (immutability)
  • 빈 배열 또는 빈 문자열을 입력받은 경우 false를 리턴

입출력 예시

const giftBox = ['macbook', 'mugcup', ['eyephone', 'postcard'], 'money'];

let output = unpackGiftbox(giftBox, 'iphone');
console.log(output); // --> false

풀이방법

  1. 빈 배열(binarr)을 선언
  2. for문을 돌려 giftBox의 요소들을 순회
    2-1. 만약 giftBox의 요소가 wish와 같을 경우 → return true
    2-2. 만약 giftBox의 요소가 배열일 경우 → 빈 배열에 해당 요소를 합쳐줌
  3. 반복문을 빠져나옴
  4. 배열 binarr의 길이가 0보다 클 경우 → 재귀함수를 리턴
  5. 위의 조건 모두 해당하지 않는 경우 → return false
function unpackGiftbox(giftBox, wish) { 
  
  if (giftBox.length === 0 || wish === '') {
    return false;
  }
  
  let binarr = [];
  for (let i = 0; i < giftBox.length; i++) {
    if (giftBox[i] === wish) {
      return true;
    } else if (Array.isArray(giftBox[i])) {
      binarr = binarr.concat(giftBox[i]);
    }
  }

  if (binarr.length > 0) {
    return unpackGiftbox(binarr, wish);
  }

  return false;
}
profile
get, set, go!

0개의 댓글