코플릿/재귀

13_findMatryoshka

테오구 2021. 10. 31. 10:15
728x90

문제

러시아 전통인형 마트료시카에 대한 정보를 담은 객체와 수를 입력받아 조건에 맞는 인형이 있는지 여부를 리턴해야 합니다.

입력

const matryoshka = {
  size: 10,
  matryoshka: {
    size: 9,
    matryoshka: null,
  },
};

let output = findMatryoshka(matryoshka, 10);
console.log(output); // --> true

output = findMatryoshka(matryoshka, 8);
console.log(output); // --> false

 

 

 

function findMatryoshka(matryoshka, size) {
  // TODO: 여기에 코드를 작성합니다.
  // 가장 밖에 있는 마트료시카가 가장크다
  if(Object.keys(matryoshka).length === 0){
    return false
  }
  else if(matryoshka.size === size){
    return true;
  }
  else if(matryoshka.matryoshka === null){
    return false
  }
  return findMatryoshka(matryoshka.matryoshka, size)
}

 

 

 

 

function findMatryoshka(matryoshka, size) {
  // recursive case
  if (matryoshka.size === size) {
    return true;
  } else if (matryoshka.matryoshka && matryoshka.size > size) {
    return findMatryoshka(matryoshka.matryoshka, size);
  }

  // base case
  return false;
}
728x90

'코플릿 > 재귀' 카테고리의 다른 글

11_or  (0) 2021.10.31
12_reverseArr  (0) 2021.10.31
14_unpackGiftbox  (0) 2021.10.31
15_flattenArr  (0) 2021.10.31
10_and  (0) 2021.10.30