-
항해 99 5기 TIL_5항해 99 2022. 1. 14. 14:46
▶ Today I Learned
<알고리즘 기초>
https://programmers.co.kr/learn/courses/30/lessons/12903?language=javascript
[가운데 글자 가져오기]
단어의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다.
let word = "123456789" // 출력할 임의의 문자열 // 문자열의 길이를 구한 후 이를 2로 나누어 나머지가 없으면 짝수, 있다면 홀수 if (word.length%2 == 0) { let start_index = word.length/2 //문자열의 길이를 2로 나누면 문자열에서 중간정도 위치 값을 구할 수 있음 위 숫자를 substring()에 대입 substring은 특정 문자열의 특정인덱스 부터 특정 인덱스의 전까지 출력됨 ex) 문자열 "사과나무" "사과나무".substring(0,2) = "사과" console.log(word.substring(start_index-1,start_index+1 )); //배열의 시작은 0부터이기에 짝수인 경우 위와 같이 코드를 작성하면 중간의 두 문자가 출력됨 } else { let start_index = Math.floor(word.length/2) // Math.floor()는 소수점 부분을 내림해주는 함수 substring에 들어갈 인덱스는 문자열의 순서를 나타내므로 0이상의 정수가 와야하기 때문! console.log(word.substring(start_index,start_index+1)) //배열의 시작은 0부터이기에 홀수인 경우 위와 같이 코드를 작성하면 중간의 한 문자가 출력됨 }
이를 프로그래머스에 제출한 것
cf) substring(출력시작 인덱스, 종료인덱스), 여기서 주의할 점은 출력이 종료인덱스까지가 아닌 종료인덱스의 바로 전 까지만 이루어진다는 것.
cf) 호이스팅, 이전 문제 해결 시 콘솔에 undefined라고 뜬 게 호이스팅이었다...!
변수가 초기화 단계를 거쳤지만 값이 할당되지는 않은 상태에 undefined가 나타난다.
var과 let/const의 초기화 시점은 다르다. var는 변수선언과 동시에 초기화, 그러나 let/const는 선언 하여도 코드가 실제로 선언문에 도달하여야 초기화가 됨, 그 전에 변수참조가 일어나면 Reference Error가 발생한다.
하단의 링크를 참조하면 도움이 될 듯 하다.
cf) 다른 사람의 풀이 중에 매우 아름다운 코드가 있었는데 그중 ? 기호가 있었다.
알고보니 이는 삼항 연산자였다. 삼항 연산자는 {조건문? True일 시 작동 : false일 시 작동} 형태로 구성되어 있다. 이제 한번 씩 활용해보아야지 ㅎㅎ
[두 정수 사이의 모든 정수 합 구하기]
https://programmers.co.kr/learn/courses/30/lessons/12912
function solution(a, b) { let c = 0 // 반복문에서 특정 값을 받기 위한 도구 if (a<=b) { for (a ; a<b + 1 ; a++) { // a<=b 라는 조건을 걸게되면 아래에서 a=b인 조건이 하나더 필요! ex) a = 5, b = 5라면 증감문이 a<=b일 때 함수가 작동하지 않음 // 코드를 줄이고자 b에 1을 더해버림! c = c + a } return c; } else { for (b; b < a + 1 ; b++) { // a = 5, b = 4 일때 증감문 조건이 b<a라면 a값을 포함 시킬 수 없음, // 그래서 1을 더함 c = c + b } return c; } }
+ 어렸을 적 책으로 보았던 가우스 덧셈이 생각났다. 다만 이를 함수로 바로 나타내보진 못했었다.
https://www.instiz.net/pt/5560215
해당 링크 속 그림을 참조하면 쉽게 이해할 수 있다.
(양끝수의 합)*(숫자의 처음부터 끝까지 갯수)나누기 2를 하면 된다
ex)
a = 3
b = 5
(a+b)(b-a+1)/2 = 12, 3+4+5를 한 것과 같다.
따라서 답은 아래의 코드다?
function solution(a, b) { return a == b ? a + b : (a+b)*(b-a+1)/2 }
그렇지 않다.. 이 경우는 두 정수가 음의 정수가 아니면서 서로 같지 않아야만 제대로 작동한다..
그렇다면 어떻게 할까?
function solution(a, b) { return (a+b)*(Math.abs(b-a)+1)/2; }
=> 프로그래머스에 올라온 답 중 가장 인기 답변이었다. 매우 깔끔..
위 알고리즘의 오류를 피하기 위해 a와 b의 절대값 차이를 두었다.
Math.abs()는 두 값의 절대 값을 반환하는 자바스크립트의 함수이다.
▶ 느낀 점
똑같은 알고리즘 이라도 푸는 방법은 천차만별이고 여러 함수와 개념을 사용한다. 누구는 코드를 몇십 줄을 짤 때, 누구는 단 몇 줄로 구현한다. 변수명을 적더라도 누군가는 짧고 명확하게 작성한다. 문제를 제출하고 프로그래머스 내 모범 답안을 보았을 때, 팀원들과 자신만의 풀이를 공유하였을 때, '아, 저렇게도 풀 수 있구나..'를 여실히 느꼈다. 리팩토링이라는 작업이 이래서 필요한 가 보다. 앞으로는 단순히 문제를 푸는 것을 넘어서서 관련 개념에는 무엇이 있고 어떤 특징을 가지고 있는 지, 어떻게 하면 더 효율적으로, 쉽고 명확하게 코드를 짜고 문제를 해결할 수 있는지 고민해 보아야겠다. 오늘 하루도 수고많았다! 내일도 화이팅팅 :)
▶ 공부 시 참고 링크들
https://curryyou.tistory.com/192
https://blog.fakecoding.com/archives/js-question-mark/
https://ko.javascript.info/types
https://jihyehwang09.github.io/2019/03/12/js-return-and-break/
'항해 99' 카테고리의 다른 글
항해 99 5기 TIL_7 (0) 2022.01.16 항해 99 5기 TIL_6 (0) 2022.01.15 항해 99 5기 TIL_4 (0) 2022.01.14 항해 99 5기 TIL_3 (0) 2022.01.13 항해 99 5기 TIL_2 (0) 2022.01.12