Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: ✨ Day 01-02 (WIP) #2

Merged
merged 6 commits into from
Dec 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Build and Test

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3

- name: Set up JDK 21
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '21'
cache: maven

- name: Check formatting
run: mvn spotless:check

- name: Build with Maven
run: mvn -B package --file pom.xml
33 changes: 33 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/

### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/

### VS Code ###
.vscode/
39 changes: 38 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,38 @@
# advent-of-code-2024
# Advent of Code 2024

[![Build and Test](https://github.com/edwinhern/advent-of-code-2024/actions/workflows/build.yml/badge.svg)](https://github.com/edwinhern/advent-of-code-2024/actions/workflows/build.yml)

My solutions for [Advent of Code 2024](https://adventofcode.com/2024) implemented in Java.

## Project Structure

- `src/main/java/dayXX` - Contains solution for each day
- `src/main/resources/dayXX` - Contains input files for each day's puzzle

## Running Solutions

This is a Maven project. To run:

1. Clone the repository
2. Build the project: `mvn clean package`
3. Run individual day solutions through their respective main methods

## Development

- Java 17
- Maven for build management
- Spotless for code formatting

### Code Formatting

Format code before committing:

```bash
mvn spotless:apply
```

## Progress

- [x] Day 1
- [x] Day 2
- [ ] Day 3-25 (Coming Soon)
21 changes: 21 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,27 @@
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0</version>
</plugin>

<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<version>2.41.1</version>
<configuration>
<java>
<googleJavaFormat>
<version>1.17.0</version>
<style>GOOGLE</style>
</googleJavaFormat>
</java>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
81 changes: 48 additions & 33 deletions src/main/java/day01/Day01.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,66 @@

import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Logger;

public class Day01 {
private static final Logger LOGGER = Logger.getLogger(Day01.class.getName());

public static void main(String[] args) throws IOException {
List<Integer> left = new ArrayList<>();
List<Integer> right = new ArrayList<>();

public static void main(String[] args) throws IOException, CsvValidationException {
// read through the csv file
// iterate and create left and right list
List<List<String>> records = new ArrayList<>();
try (CSVReader csvReader = new CSVReader(new FileReader("src/main/resources/day01/input.csv"))) {
String[] values = null;
while ((values = csvReader.readNext()) != null) {
records.add(Arrays.asList(values));
try (Scanner scanner = new Scanner(new FileReader("src/main/resources/day01/input.txt"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter(" ");
left.add(lineScanner.nextInt());
right.add(lineScanner.nextInt());

lineScanner.close();
}
}

List<Integer> left = new ArrayList<>();
List<Integer> right = new ArrayList<>();
// Part 1: Calculate total distance between sorted lists
LOGGER.info(() -> "Part 1 Solution: " + part1(left, right));

for (List<String> record : records) {
left.add(Integer.parseInt(record.get(0)));
right.add(Integer.parseInt(record.get(1)));
// Part 2: Calculate similarity score
LOGGER.info(() -> "Part 2 Solution: " + part2(left, right));
}

private static int part1(List<Integer> left, List<Integer> right) {
List<Integer> sortedLeft = new ArrayList<>(left);
List<Integer> sortedRight = new ArrayList<>(right);
sortedLeft.sort(Integer::compareTo);
sortedRight.sort(Integer::compareTo);

int totalDistance = 0;
for (int i = 0; i < sortedLeft.size(); i++) {
totalDistance += Math.abs(sortedLeft.get(i) - sortedRight.get(i));
}

// take first list and sort in asc
// take second list and sort in asc
Collections.sort(left);
Collections.sort(right);

// create sum variable to hold difference
int sum = 0;
// iterate through first list
for (int i = 0; i < left.size(); i++) {
// access left and right based on i
// sum += Math.abs(left[i] - right[i])
sum += Math.abs(left.get(i) - right.get(i));
return totalDistance;
}

private static int part2(List<Integer> left, List<Integer> right) {
Map<Integer, Integer> rightMap = new HashMap<>();
for (int num : right) {
rightMap.merge(num, 1, Integer::sum);
}

int similarityScore = 0;
for (int num : left) {
if (rightMap.containsKey(num)) {
similarityScore += num * rightMap.getOrDefault(num, 0);
}
}

System.out.println(sum);
return similarityScore;
}
}
51 changes: 51 additions & 0 deletions src/main/java/day02/Day02.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package day02;

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public class Day02 {
private static final Logger LOGGER = Logger.getLogger(Day02.class.getName());

public static void main(String[] args) throws IOException {
List<List<Integer>> reports = new ArrayList<>();

try (Scanner scanner = new Scanner(new FileReader("src/main/resources/day02/input.txt"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
List<Integer> levels =
Arrays.stream(line.split(" ")).map(Integer::parseInt).collect(Collectors.toList());

reports.add(levels);
}
}

LOGGER.info(() -> "Part 1 Solution: " + part1(reports));
}

private static int part1(List<List<Integer>> reports) {
return (int) reports.stream().filter(Day02::isSafeReport).count();
}

private static boolean isSafeReport(List<Integer> levels) {
boolean isIncreasing = levels.get(1) > levels.get(0);

for (int i = 1; i < levels.size(); i++) {
int diff = levels.get(i) - levels.get(i - 1);

// Validate if diff is within bounds (1-3) or if it's increasing or decreasing
boolean isWithinBounds = diff == 0 || Math.abs(diff) > 3;
boolean isIncreasingBounds = isIncreasing && diff < 0;
boolean isDecreasingBounds = !isIncreasing && diff > 0;
if (isWithinBounds || isIncreasingBounds || isDecreasingBounds) {
return false;
}
}
return true;
}
}
Loading
Loading