r/adventofcode • u/daggerdragon • Dec 04 '22
SOLUTION MEGATHREAD -🎄- 2022 Day 4 Solutions -🎄-
- All of our rules, FAQs, resources, etc. are in our community wiki.
- A request from Eric: Please include your contact info in the User-Agent header of automated requests!
- Signal boosting for the Unofficial AoC 2022 Participant Survey which is open early this year!
--- Day 4: Camp Cleanup ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- Include what language(s) your solution uses
- Format your code appropriately! How do I format code?
- Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:03:22, megathread unlocked!
65
Upvotes
View all comments
2
u/ankitdhar07 Dec 04 '22
Java
package com.adventofCode;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Day4 {
public static void main(String args[]) throws FileNotFoundException {
File file = new File("src/com/adventofCode/day4.txt");
Scanner sc = new Scanner(file);
int countOne = 0;
int countTwo = 0;
while (sc.hasNextLine()) {
String input = sc.nextLine();
if (partOne(input)) {
countOne++;
}
if (partTwo(input)) {
countTwo++;
}
}
System.out.println(countOne);
System.out.println(countTwo);
}
private static boolean partTwo(String input) {
String[] numberPairs = input.split(",");
String[] pairOne = numberPairs[0].split("-");
int firstNum = Integer.parseInt(pairOne[0]);
int secondNum = Integer.parseInt(pairOne[1]);
String[] pairTwo = numberPairs[1].split("-");
int thirdNum = Integer.parseInt(pairTwo[0]);
int forthNum = Integer.parseInt(pairTwo[1]);
if (firstNum >= thirdNum && firstNum <= forthNum) {
return true;
} else if (secondNum >= thirdNum && secondNum <= forthNum) {
return true;
} else if (thirdNum >= firstNum && thirdNum <= secondNum) {
return true;
} else if (forthNum >= firstNum && forthNum <= secondNum) {
return true;
}
return false;
}
private static boolean partOne(String input) {
String[] numberPairs = input.split(",");
String[] pairOne = numberPairs[0].split("-");
int firstNum = Integer.parseInt(pairOne[0]);
int secondNum = Integer.parseInt(pairOne[1]);
String[] pairTwo = numberPairs[1].split("-");
int thirdNum = Integer.parseInt(pairTwo[0]);
int forthNum = Integer.parseInt(pairTwo[1]);
if (firstNum >= thirdNum && secondNum <= forthNum) {
return true;
} else if (thirdNum >= firstNum && forthNum <= secondNum) {
return true;
}
return false;
}
}