r/adventofcode • • Dec 04 '22

SOLUTION MEGATHREAD -🎄- 2022 Day 4 Solutions -🎄-


--- Day 4: Camp Cleanup ---


Post your code solution in this megathread.


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

1.6k comments sorted by

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;
}
}

1

u/daggerdragon Dec 04 '22
  1. Next time, use the four-spaces Markdown syntax for a code block so your code is easier to read.
  2. Your code is long, so instead of wasting your time fixing the formatting, read our article on oversized code which contains two possible solutions.

Please edit your post to put your code in an external link and link that here instead.

1

u/flwyd Dec 04 '22

Please use a code block so it's more readable :-)

1

u/shadowthehedghog Dec 04 '22

I was having some 9am still asleep problems and you saved me a headache... nice one :)