Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dsa-week1-assignment #1

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion problem-1/problem-1.test.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,35 @@
const solution = (numbers) => {
const solution = (numbers) => (numbers.length ? numbers.reduce((acc, curr) => acc + curr) : 0);
Copy link
Contributor

Choose a reason for hiding this comment

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

꼬리재귀는 reduce로 변환이 가능하다는 것을 이용해서 해결해 주셨네요.

예를들어 코틀린 같은 다른 프로그래밍 언어에서는 배열에 가장 앞에 있는 값으로 reduce를 하는 것과
초기값이 주어지고 reduce를 하는 것을 fold로 구분합니다.
자바스크립트는 기본값을 주어지면 fold, 아니면 reduce로 동작하는데요. reduce는 빈 배열일 경우 에러가 발생합니다.
그래서 배열이 비어있는지 확인하신 것 같아요.

fold를 이용하면 빈 배열일 때도 기본값을 사용하도록 할 수 있어요.

const solution = (numbers) => numbers.reduce((acc, curr) => acc + curr, 0);

주로 fold는 타입이 달라질 때 사용해요. 지금은 같은 타입인 숫자지만, 기본 값으로 아무거나 들어갈 수 있으니까요. 이 차이점을 알아두시면 좋을 것 같습니다.


const solution2 = (numbers) => {
let acc = 0;

while (numbers.length > 0) {
acc += numbers.pop();
}

return acc;
};
Comment on lines +3 to 11
Copy link
Contributor

Choose a reason for hiding this comment

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

numbers목록에서 하나씩 제거해 가면서 값을 더하셨네요.

pop메서드는 주어진 배열 자체를 수정하는 것으로, 만약에 이 solution2에 전달한 numbers를 다른 곳에서 사용하고 있다면
값이 변경되어 당황스러운 일이 발생할 수 있어요.

따라서 numbers를 고치지 않고 값을 참조만 하는게 좋아보입니다.

const solution2 = (numbers) => {
  let index = 0;
  let acc = 0;

  while (index < numbers.length) {
    acc += numbers[index];
    index++;
  }

  return acc;
};


test('빈 배열은 0을 반환한다', () => {
expect(solution([])).toBe(0);

expect(solution2([])).toBe(0);
});

test('배열의 합을 반환한다', () => {
expect(solution([1, 2, 3, 4])).toBe(10);
expect(solution([-1, 3, 8, 9, 10, 11])).toBe(40);

expect(solution2([1, 2, 3, 4])).toBe(10);
expect(solution2([-1, 3, 8, 9, 10, 11])).toBe(40);
});

test('큰 배열이 입력으로 주어져도 RangeError를 던지지 않는다', () => {
const input = Array.from({ length: 10000 }, (_, i) => i + 1);

expect(() => solution(input))
.not.toThrowError(new RangeError('Maximum call stack size exceeded'));

expect(() => solution2(input))
.not.toThrowError(new RangeError('Maximum call stack size exceeded'));
});
16 changes: 16 additions & 0 deletions problem-2/problem-2.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,20 @@
const solution = (n) => {
if (n < 0) return 0;
if (n < 2) return n;

let current = 2;
let a = 0;
let b = 1;
let sum = a + b;

while (current < n) {
current += 1;
a = b;
b = sum;
sum = a + b;
}

return sum;
};

test('음수가 주어지면 0을 반환한다', () => {
Expand Down
14 changes: 14 additions & 0 deletions problem-3/problem-3.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
const solution = (n) => {
if (n === 0) {
return '0';
}

let memo = '';
let number = n;

while (number > 1) {
const remainder = number % 2;
memo = remainder + memo;
number = Math.floor(number / 2);
}

return `1${memo}`;
};

test('이진수 문자열을 반환한다', () => {
Expand Down
10 changes: 8 additions & 2 deletions problem-4/problem-4.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
const solution = () => {
};
const solution = (binNum) => binNum
.split('')
.reverse()
.map((x, idx) => {
if (x === '0') { return 0; }
return (2 ** idx);
})
.reduce((acc, curr) => acc + curr);
Comment on lines +1 to +8
Copy link
Contributor

Choose a reason for hiding this comment

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

binNum
  .split('')
  .map((it, index) => it === '0' ? 0 : (2 ** (binNum.length - 1 - index)))
  .reduce((acc, cur) => acc + cur);

앞에서부터 차례대로 하도록 하면 reverse로 뒤집지 않아도 해결할 수 있어요


test('10진수 숫자를 반환한다', () => {
expect(solution('0')).toBe(0);
Expand Down
4 changes: 3 additions & 1 deletion problem-5/problem-5.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const solution = () => {
const solution = (a, b) => {
const remainder = a % b;
return remainder === 0 ? b : solution(b, remainder);
};

test('최대 공약수를 반환한다', () => {
Expand Down
18 changes: 18 additions & 0 deletions problem-6/problem-6.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,22 @@
const solution = (n) => {
let a = 1;
if (n === 1) return a;

let b = 2;
if (n === 2) return b;

let count = 3;
let result = 4;

while (count < n) {
const temp = result;
result = a + b + result;
a = b;
b = temp;

count += 1;
}
return result;
};

test('계단에 오를 수 있는 가지 수를 반환한다', () => {
Expand Down