[알고리즘] 과일을 찾아라.

Soozynn·2022년 7월 24일
0

알고리즘 풀이

목록 보기
4/6

면접 과제 중 코딩테스트 문제가 8개가 있었는데, 그 중 다른 문제는 쉽게 풀 수 있었으나 패턴을 파악하는데 시간이 조금 걸렸던 문제가 있어 이를 정리해보고자 한다.

테스트 케이스도 작성해놓아서 해당 링크에서 git clone을 하면 문제를 풀어볼 수 있다.


[문제]

각 자리의 숫자를 더한값을 원래 숫자에서 빼고 결과가 하단에 나열한 과일코드가 나올때까지 계산하는 코드를 작성해주세요.

**과일**


  1-kiwi
  2-pear
  3-kiwi
  4-banana
  5-melon
  6-banana
  7-melon
  8-pineapple
  9-apple
  10-pineapple
  11-cucumber
  12-pineapple
  13-cucumber
  14-orange
  15-grape
  16-orange
  17-grape
  18-apple
  19-grape
  20-cherry
  21-pear
  22-cherry
  23-pear
  24-kiwi
  25-banana
  26-kiwi
  27-apple
  28-melon
  29-banana
  30-melon
  31-pineapple
  32-melon
  33-pineapple
  34-cucumber
  35-orange
  36-apple
  37-orange
  38-grape
  39-orange
  40-grape
  41-cherry
  42-pear
  43-cherry
  44-pear
  45-apple
  46-pear
  47-kiwi
  48-banana
  49-kiwi
  50-banana
  51-melon
  52-pineapple
  53-melon
  54-apple
  55-cucumber
  56-pineapple
  57-cucumber
  58-orange
  59-cucumber
  60-orange
  61-grape
  62-cherry
  63-apple
  64-cherry
  65-pear
  66-cherry
  67-pear
  68-kiwi
  69-pear
  70-kiwi
  71-banana
  72-apple
  73-banana
  74-melon
  75-pineapple
  76-melon
  77-pineapple
  78-cucumber
  79-pineapple
  80-cucumber
  81-apple
  82-grape
  83-orange
  84-grape
  85-cherry
  86-grape
  87-cherry
  88-pear
  89-cherry
  90-apple
  91-kiwi
  92-banana
  93-kiwi
  94-banana
  95-melon
  96-banana
  97-melon
  98-pineapple
  99-apple
  100-pineapple

과연 위 코드 100개를 다 입력해야 할까요..? (다시 생각해보세요!)

**샘플코드**

const solution = (n) => {
  // ex) return "apple"
}

**예시**

- ex) 10 => apple
- ex) 325 =>
    - 325 - (3+2+5) = 315
    - 315 - (3+1+5) = 306
    - 306 - (3+0+6) = 297
    - ...

**주의할점**

- 10~10000 사이의 숫자를 입력합니다.
*/

[해석]

처음에는 위 규칙을 보면서 패턴을 이해하지 못하였는데, 예시의 코드를 자세히보니 각 자릿값을 더한 값을 계속 반복해서 빼주는 것을 알 수 있다.
이를 통해 규칙의 패턴이 무얼 뜻하는지 알게되었다. 해당 문제는 결국 한 과일만을 리턴해주는 문제이다.

예시를 해석해보자면,
처음 10의 값이 인자로 주어지면 각각의 자릿 값을 더한 1 + 0 = 1을 최종 값에서 빼주면 9가 된다. 반복되어지는 과일의 갯수는 총 10개로 내과 지정해 준 과일 값을 바탕으로 한 자릿수가 될 때까지 반복하는 것.
325가 인자로 주어지면 -> 325에서 각 자릿수를 더한 값 10을 빼고, 다시 뺀 값에서 각 자릿수를 더한 값 9를 빼준다. 이 과정을 숫자가 1의 자리수가 될 때까지 반복한다. (신기하게도 결국 한 자릿수의 숫자는 9가 되어 9번째 과일 값만 리턴하게 된다)

// 예시로 주어진 10가지의 과일을 내가 원하는 임의의 순서로 선언해준다.
const FRUITES = [
  "apple",
  "kiwi",
  "banana",
  "melon",
  "orange",
  "pineapple",
  "cherry",
  "grape",
  "pear",
  "cucumber",
];

// number 값이 일의 자리수가 될 때까지 재귀로 반복해준다.
// 아닐 경우는 자릿 값을 더한 만큼 계속 빼준다.
export default function solution(n) {
  if (n < 10) {
    return FRUITES[n];
  }

  const sumOfNumber = String(n)
    .split("")
    .map((str) => Number(str))
    .reduce((a, b) => a + b, 0);

  const number = n - sumOfNumber;

  return solution(number); // ⭐️ 재귀를 리턴해주는 것을 잊지말자. 
// 리턴을 해주지 않을 시 undefined 값을 출력하게 된다.
}

0개의 댓글