Skip to content

Conversation

@KJeeu
Copy link

@KJeeu KJeeu commented Dec 10, 2023

1주차 과제 제출합니다

Copy link
Contributor

@hannut91 hannut91 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

numbers.reduce((sum, value) => sum + value, 0);

const solution = (numbers, sum = 0) => {
  if (numbers.length === 0) {
    return sum;
  }

  const value = numbers[0];
  return solution(numbers.slice(1), sum + value);
}

reduce를 사용했지만 꼬리 재귀를 구현하지 못하신 것 같아요. 꼬리 재귀로 구현한 코드는 모두 reduce를 이용해서 구현할 수 있어요.

reduce에서 기본 값에 해당하는 것은 꼬리 재귀 함수에서 sum = 0에 해당하고요.
reducer에 함수에서 계산된 값을 반환하는 것이 다음의 sum값이 되는 것은 꼬리 재귀에서 함수를 호출할 때 다음 값으로 호출하는 것과 같아요.
numbers의 길이가 0이 되면 종료하는 것은 reduce가 모든 배열을 순회하는 것과 같아요.
그래서 reduce로 구현하셨다면 꼬리재귀로 구현할 수 있으니 한 번 해보세요!

Comment on lines 2 to 4
const solution = (numbers) => {
numbers.reduce((a, b) => a + b, 0);
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여기서 작은 실수를 하나 하셨는데, 결과를 return하고 있지 않네요!

while (count <= n) {
count += 1;
const sum = list.slice(-2).reduce((a, b) => a + b, 0);
list.push(sum);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

연산할 때 마다 list가 계속 커지는데, 마지막 2개만 사용하는 것 같네요. 전전값과 바로 이전값만 유지하는 방법으로도 구현이 가능할 것 같습니다

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants