
😎풀이
- 12달에 대한 일 수 정의
Alice의 로마 거주 시작 및 종료일자 일 수로 치환하여 기록
Bob의 로마 거주 시작 및 종료일자 일 수로 치환하여 기록
- 한 해를 1일부터 365일까지 순회
4-1. Alice의 거주 시작일 이후인지 검증
4-2. Bob의 거주 시작일 이후인지 검증
4-3. Alice의 이주 이전인지 검증
4-4. Bob의 이주 이전인지 검증
4-5. 모든 조건을 통과하는 경우 둘 다 로마에 있었음
- 둘 다 로마에 있었던 일 수 반환
const DAY_PER_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
function countDaysTogether(arriveAlice: string, leaveAlice: string, arriveBob: string, leaveBob: string): number {
const [arriveAliceMonth, arriveAliceDay] = transferDateToNumArr(arriveAlice)
const aliceStart = transferDateToDay(arriveAliceMonth, arriveAliceDay)
const [leaveAliceMonth, leaveAliceDay] = transferDateToNumArr(leaveAlice)
const aliceEnd = transferDateToDay(leaveAliceMonth, leaveAliceDay)
const [arriveBobMonth, arriveBobDay] = transferDateToNumArr(arriveBob)
const bobStart = transferDateToDay(arriveBobMonth, arriveBobDay)
const [leaveBobMonth, leaveBobDay] = transferDateToNumArr(leaveBob)
const bobEnd = transferDateToDay(leaveBobMonth, leaveBobDay)
let togetherDays = 0
for(let i = 1; i <= 365; i++) {
if(i < aliceStart) continue
if(i < bobStart) continue
if(i > aliceEnd) continue
if(i > bobEnd) continue
togetherDays++
}
return togetherDays
};
function transferDateToDay(month: number, day: number) {
const months = DAY_PER_MONTH.slice(0, month - 1)
const monthSum = months.reduce((acc, cur) => acc + cur, 0)
return monthSum + day
}
function transferDateToNumArr(date: string) {
const [month, day] = date.split("-")
return [Number(month), Number(day)]
}