|
| 1 | +package com.fishercoder.solutions.thirdthousand; |
| 2 | + |
| 3 | +public class _2409 { |
| 4 | + public static class Solution1 { |
| 5 | + /** |
| 6 | + * Brute force: check each day of the 365 days if both of them are in Rome. |
| 7 | + */ |
| 8 | + public int countDaysTogether(String arriveAlice, String leaveAlice, String arriveBob, String leaveBob) { |
| 9 | + int[] monthToDays = new int[]{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; |
| 10 | + int days = 0; |
| 11 | + String[] arriveAliceParts = arriveAlice.split("-"); |
| 12 | + String[] leaveAliceParts = leaveAlice.split("-"); |
| 13 | + String[] arriveBobParts = arriveBob.split("-"); |
| 14 | + String[] leaveBobParts = leaveBob.split("-"); |
| 15 | + for (int i = 1; i < monthToDays.length; i++) { |
| 16 | + int daysInMonth = monthToDays[i]; |
| 17 | + for (int j = 1; j <= daysInMonth; j++) { |
| 18 | + if (bothInRome(i, j, arriveAliceParts, leaveAliceParts, arriveBobParts, leaveBobParts)) { |
| 19 | + days++; |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | + return days; |
| 24 | + } |
| 25 | + |
| 26 | + private boolean bothInRome(int month, int day, String[] arriveAliceParts, String[] leaveAliceParts, String[] arriveBobParts, String[] leaveBobParts) { |
| 27 | + int aliceArriveMonth = Integer.parseInt(arriveAliceParts[0]); |
| 28 | + int aliceArriveDay = Integer.parseInt(arriveAliceParts[1]); |
| 29 | + int aliceLeaveMonth = Integer.parseInt(leaveAliceParts[0]); |
| 30 | + int aliceLeaveDay = Integer.parseInt(leaveAliceParts[1]); |
| 31 | + |
| 32 | + int bobArriveMonth = Integer.parseInt(arriveBobParts[0]); |
| 33 | + int bobArriveDay = Integer.parseInt(arriveBobParts[1]); |
| 34 | + int bobLeaveMonth = Integer.parseInt(leaveBobParts[0]); |
| 35 | + int bobLeaveDay = Integer.parseInt(leaveBobParts[1]); |
| 36 | + |
| 37 | + return inRome(aliceArriveMonth, aliceArriveDay, aliceLeaveMonth, aliceLeaveDay, month, day) && inRome(bobArriveMonth, bobArriveDay, bobLeaveMonth, bobLeaveDay, month, day); |
| 38 | + } |
| 39 | + |
| 40 | + private boolean inRome(int arriveMonth, int arriveDay, int leaveMonth, int leaveDay, int month, int day) { |
| 41 | + if (month < arriveMonth || month > leaveMonth) { |
| 42 | + return false; |
| 43 | + } |
| 44 | + if (month > arriveMonth && month < leaveMonth) { |
| 45 | + return true; |
| 46 | + } |
| 47 | + if (month == arriveMonth) { |
| 48 | + if (arriveMonth == leaveMonth) { |
| 49 | + return arriveDay <= day && leaveDay >= day; |
| 50 | + } else { |
| 51 | + return arriveDay <= day; |
| 52 | + } |
| 53 | + } |
| 54 | + //now, only this case: month == leaveMonth |
| 55 | + return day <= leaveDay; |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments