문제 5

모모·2021년 12월 14일
0

문제 복기

목록 보기
5/5

배열과 문자열을 입력받아 조건에 맞는 선물이 있는지 여부를 리턴하라

조건

function unpackGiftbox(giftBox, wish) {}

인자 giftBox: 문자열, 배열을 요소로 갖는 배열
ex. const giftBox = [ipad, pillow, [candy, [macbook]], charger]

인자 wish: string 타입의 문자열

해답

function unpackGiftbox(giftBox, wish) {
  for (let i = 0; i < giftBox.length; i++) {
    if (giftBox[i] === wish) {
      return true;
    } else if (Array.isArray(giftBox[i])) {
      const result = unpackGiftbox(giftBox[i], wish);
      if (result === true) {
        return true;
      }
    }
  }

  return false;
}

나의 풀이

function unpackGiftbox(giftBox, wish) {
  for (let i = 0; i < giftBox.length; i++) {
    if (Array.isArray(giftBox[i])) {
      unpackGiftbox(giftBox[i], wish)
    } else if (giftBox[i] === wish) {
        return true
      } 
  }
  return false;
}

const giftBox = ['macbook', ['eyephone', [], ['postcard']], 'money']일 때,
unpackGiftbox(giftBox, 'postcard')를 호출했을 때의 결과는 false이다.

디버깅을 했을 때 분명 1번째 인덱스의 postcard 차례에서 return true 부분을 거치지만 그저 지나칠 뿐이다.

그 이유는 postcard 차례의 true를 저장할 곳이 없기 때문이다. return unpackGiftbox로 수정한다면 []에서 배열에 한번 더 진입한 후 평가할 요소가 없기 때문에 return false로 직행한다.

따라서 재귀함수 unpackGiftbox를 그대로 호출하지도, 바로 리턴하지도 않는 대신, 전역에 false 값을 가진 변수를 선언하여 재귀함수의 호출 결과가 true일 때 true를 리턴하도록 하자.

function unpackGiftbox(giftBox, wish) {
  let result = false;
  for (let i = 0; i < giftBox.length; i++) {
    if (Array.isArray(giftBox[i])) {
      let unboxing = unpackGiftbox(giftBox[i], wish);
      if(unboxing === true){
        result = true;
      }
    } else if (giftBox[i] === wish) {
        return true
      } 
  }
  return result;
}

0개의 댓글