코딩테스트 연습 - 기능개발 | 프로그래머스 스쿨 (programmers.co.kr)
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이 1
로직 굉장히 이상한 것 같은데 어쨌든 테케 다 통과하긴 함
내가 생각한 로직
1. 필요한 일수를 구한다.
2. 큰수1 ____ 큰수2 ____ 이렇게 나눠서 보면 됨
개인적으로 보는 지금 코드 문제점 (이따가 더 생각해보거나 다른 사람 솔루션 보기)
1. mutable 하다 (count, stack, maxValue)
→ 관련 mutable한 코드는 왜 바람직하지 못한 코드인가 (tistory.com) 보면 좋음
2. 변수명 이상함 (사실 첨엔 큐 or 스택 써볼려고 했어서 stack 이라고 지었음. 변수명 바꿔야할듯 stack → answer 이런식으로,,)
3. 로직을 더 괜찮게 수정할 수 있을 것 같다. → 다들 비슷하게 풀어서 걍 냅둠 (reduce + acc 초기 값으로 객체 사용하면 괜찮을듯)
# 2022.12.04.
추가 리팩토링 해봄
풀이 2
변수명
stack : Array[] → releaseTimes
maxValue: number → currentRelease 로 변경
let 선언 대신 객체 내부에서 값을 변경하는 것으로 수정함
인덴트랑, 같은 if 문 조건이 분기점마다 있어서 이래도 되나 좀 걱정 (cur이 마지막 인덱스 값일 경우 무조건 push 해준다 조건)
그리고 객체 부르는 법 개념 헷갈림 obj[prop] 이라고 썼었음
객체
ko.javascript.info
대괄호 표기법의 경우에는 obj['prop'] 이렇게 문자열로 불러옴
아니면 obj.prop 이렇게 써야함.
reduce 메서드 내에서 acc 객체 변경하는 법
const obj = {
prop1: 'value1',
prop2: 'value2',
};
const arr = [1, 2, 3, 4, 5];
const result = arr.reduce((acc, cur) => {
// Access the value of the prop1 property using the bracket notation
console.log(acc['prop1']);
// Set the value of the prop1 property using the bracket notation
acc['prop1'] = cur;
// Return a new object that includes the updated prop1 property
return { ...acc, prop1: acc['prop1'] };
}, obj);
그래도 두번째 풀이가 나은 이유
킹공지능 GPT ChatGPT (openai.com) 에게 여쭈어보니
이 경우, 첫 번째 코드는 for 루프를 사용하는 반면, 두 번째 코드는 reduce 메서드를 사용하여 필요한 Workday 배열을 반복하기 때문에 더 빠릅니다.
일반적으로 reduce 메서드는 배열에 대한 단일 패스만 필요로 하는 반면 for 루프는 다중 패스를 필요로 하기 때문에 for 루프보다 더 효율적일 수 있습니다. 또한 reduce 메서드를 사용하면 accumulator 의 초기 값을 지정할 수 있으므로 시간을 절약하고 성능을 향상시킬 수 있습니다.
두 코드 사이의 성능 차이에 대한 또 다른 잠재적인 이유는 첫 번째 코드가 여러 개의 추가 변수(예: let count = 0 및 let stack = 0)를 사용하고 반복 중에 이러한 변수들을 변형시키는 반면, 두 번째 코드는 누적된 값을 저장하기 위해 단일 개체를 사용하고 반복 중에 변수를 변형시키지 않기 때문입니다.
변수를 변환하는 것은 추가적인 메모리 작업이 필요하기 때문에 변수를 변환하지 않는 것보다 느릴 수 있습니다.
따라서, 두 번째 코드는 더 효율적인 reduce 메서드를 사용 (iterate 연산이 더 효율적임)하고, 또 반복 중에 변수가 변형되는 것을 피하기 때문에 더 빠를 것입니다.
- 원문 -
As I mentioned before, the computational speed of a piece of code can be affected by a number of factors. In this case, the second code is likely faster because it uses the reduce method to iterate over the requiredWorkday array, while the first code uses a for loop. In general, the reduce method can be more efficient than a for loop because it only requires a single pass over the array, whereas a for loop requires multiple passes. Additionally, the reduce method allows you to specify an initial value for the accumulator, which can save time and improve performance.
Another potential reason for the difference in performance between the two codes is that the first code uses a number of additional variables (such as count and stack) and mutates those variables during the iteration, whereas the second code uses a single object to store the accumulated values and does not mutate any variables during the iteration. Mutating variables can be slower than not mutating them because it requires additional memory operations.
Overall, the second code is likely faster because it uses the more efficient reduce method and avoids mutating variables during the iteration.
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스 Lv.2] 영어 끝말잇기 JavaScript 풀이 (0) | 2022.12.07 |
---|---|
[프로그래머스 Lv 2] 행렬의 곱셈 JavaScript 풀이 (0) | 2022.12.05 |
[프로그래머스 Lv 2] 카펫 JavaScript 풀이 (0) | 2022.12.03 |
[프로그래머스 Lv 2] JadenCase 문자열 만들기 JavaScript 풀이 (0) | 2022.12.02 |
[프로그래머스 Lv2] 롤케이크 자르기 JavaScript 풀이 (0) | 2022.11.28 |