-
10.[Programmers]알고리즘 문제 Java script 2016 요일구하기 (사서 고생하는 사람의 노가다 구경하실래요?)Algorithm 2022. 12. 21. 00:44728x90
2016년의 a월b일이 무슨 요일인지 구하는 함수를 만들어야 하는 문제
....
그렇게 다시 시작된 노가다..
function solution(a, b) { var answer = ''; const yoil=['THU','FRI','SAT','SUN','MON','TUE','WED']; let day=0; if (a=1){ day=b }else if (a=2){ day=31+b }else if (a=3){ day=60+b }else if (a=4){ day=91+b }else if (a=5){ day=121+b }else if (a=6){ day=152+b }else if (a=7){ day=182+b }else if (a=8){ day=213+b }else if (a=9){ day=244+b }else if (a=10){ day=274+b }else if (a=11){ day=305+b }else if (a=12){ day=335+b } rest=day%7; answer=yoil[rest] return answer; } solution()
요일을 구하는 정규식이 있을거란걸 모르진 않았다.
다만 내 방식으로 이렇게도 된다고 세상에 보여주고싶었을 뿐...
1. 우선 a월b일을 몇 번째 날인지 표현한다.
월별로 30일까지인 달도 있고, 31일까지인 달도 있다.
그렇기 때문에 모두 if else 를 이용해 1월부터 12월까지 분리해서 몇 번재 날인지 담을 day라는 변수를 설정했다.
2. 그렇게 해서 day의 값을 7로 나눈 뒤 나머지수를 구해서 그 나머지수를 index에 대입시키면 요일을 찾을 수 있을거라 생각했다!
const yoil=['THU','FRI','SAT','SUN','MON','TUE','WED']1월1일은 금요일,
근데 순서가 목요일부터 시작하는 이유는, index는 0부터 카운팅이 시작되기에..
논리적으로 너무 완벽히 될 것이라 생각했고, 각 변수에 내가 지정한 날짜를 대입시켜 2016년 달력을 보며 맞춰봐도 모두 일치해서 설레는 마음에 답안 제출....
그리고
ㅋㅋㅋㅋ.......
😊🔫🔫🔫
사서고생하지말고 정규식 쓰자! ㅎㅎ
Date함수는 1월이 0으로 표현되고, 12월이 11로 표현된다는 점!
이렇게 간단하게 풀리는 문제였던 것이다...
function getDayName(a,b){ var date = new Date(2016, (a - 1), b); return date.toString().slice(0, 3).toUpperCase(); }
그리고 이건 date함수 없이 풀어낸 다른 블로그에서 퍼온 모범답안
한 수 배웠다.. 감사합니다
function solution(a, b) { let arr = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; let week = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"]; // 1월 1일부터 a월 b일까지 며칠 차이인지 저장할 변수 let passedDays = 0; // a달 전까지의 모든 달에 대해 각 달의 날짜 수 더해줌 for (let i = 1; i < a; i++) passedDays += arr[i]; // b일 더해주고 1월 0일이 아닌 1월 1일부터 시작하므로 1 빼줌 passedDays += b - 1; return week[(5 + passedDays) % 7]; }
출처 https://cherish-my-codes.tistory.com/entry/Programmers-Level1-2016%EB%85%84JavaScript
잘 보면, arr는 1월부터12월까지 마지막날짜로 (0번째 인덱스는 비워둠) 배열을 만들어 두었고,
week는 SUN~SAT 일주일을 배열화했는데 여기선 monday가 배열의 [1]번째에 오게세팅을 하셨다.
for문을 이용해 a월b일과 2016년 1월1일간의 difference를 구한다.
arr의 [i]번째에 해당 월의 날짜 수가 오게끔.. 천재다
그렇게 passedDays에 a를통해 구한 지난 달의 전체 합 + b를 더한 값 -1 (1월 0일이 아닌, 1일부터이기때문이라고함)
마지막으로 week배열의 5(1월1일이 금요일이라서) + passedDays 를 하고 %7을 한 나머지수만큼의 인덱스를 정답으로 도출....
찢었다..
내가 만들고 싶었던 코드에서 노가다를 전부 제거한 깔끔한 방식의 코드를 몇 번씩 반복해서 보면서 많이 배웠다
그리고
앞으론 진짜 고집부리지말고 정규식 찾아서 써야지
728x90'Algorithm' 카테고리의 다른 글
알고리즘 하드코딩 장인 [프로그래머스] 약수의 개수와 덧셈 (코드 간결화) (0) 2023.04.11 HackerRank 문제 해석, 풀이 Plus Minus- Java script (0) 2023.04.06 [알고리즘풀기] 프로그래머스 로그인성공? (0) 2023.03.30 [알고리즘풀기] 프로그래머스 문자열 나누기 Java script (0) 2023.03.28 9. [Programmers] 알고리즘 문제풀기 Java script 문자열 다루기 기본 (0) 2022.12.20