Big update: Adding all advent of codes to same repo

This commit is contained in:
2024-12-06 00:14:09 +00:00
parent 5116bd4696
commit 233dda4fe9
106 changed files with 7790 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
# Advent of Code 2020
These are my solutions, currently all in Java.

Binary file not shown.

View File

@@ -0,0 +1,41 @@
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class day1 {
public static void main(String[] args) {
try {
File myFile = new File("input.txt");
Scanner in = new Scanner(myFile);
int[] input = new int[200];
for (int i = 0; i < 200; i++) {
input[i] = Integer.parseInt(in.next());
}
for (int i = 0; i < 198; i++) {
for (int j = i + 1; j < 199; j++) {
//Following is for part1
//if (input[i] + input[j] == 2020) {
//System.out.println(input[i] * input[j]);
//}
for (int k = j + 1; k < 200; k++) {
if (input[i] + input[j] + input[k] == 2020) {
System.out.println(input[i] * input[j] * input[k]);
}
}
}
}
in.close();
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
}

Binary file not shown.

View File

@@ -0,0 +1,140 @@
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
class day10 {
static HashMap<ArrayList<Integer>, Long> cache = new HashMap<>();
public static void main(String[] args) {
File myFile = new File("input.txt");
try {
Scanner in = new Scanner(myFile);
ArrayList<Integer> nums = new ArrayList<>();
while (in.hasNext()) {
nums.add(Integer.parseInt(in.nextLine()));
}
nums.add(0);
Collections.sort(nums);
nums.add(nums.get(nums.size() - 1) + 3);
//Part 1 code
int one = 0;
int two = 0;
int three = 0;
for (int i = 1; i < nums.size(); i++) {
int diff = nums.get(i) - nums.get(i - 1);
if (diff == 1) {
one++;
} else if (diff == 2) {
two++;
} else if (diff == 3) {
three++;;
}
}
if (nums.get(0) == 1) one++; //From the plug to the first adaptor
three++; //Build in adaptor
//System.out.printf("One: %d | Two: %d | Three: %d \n", one, two, three);
//System.out.printf("Multiplied: %d", one * three);
//System.out.println(isValid(nums, nums.size()));
System.out.println(getSum(nums));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/*
Recursive method for part 2 solution
There is likely a method which has o(N) complexity, but seeing as this is a daily thing, and I don't have
all that much time this is still an elegant solution.
*/
public static long getSum(ArrayList<Integer> nums) {
long sum = 0;
if (nums.size() == 1) {
//System.out.println("Size 1");
return 1;
}
ArrayList<Integer> newNums = new ArrayList<>(nums);
for (int i = 1; i <= 3; i++) {
int pointer = nums.size() - 1 - i;
//System.out.println("Pointer: " + pointer);
//System.out.println("DSADS: " + nums.get(pointer));
if (pointer >= 0) {
if (nums.get(nums.size() - 1) - nums.get(pointer) <= 3) {
newNums.remove(pointer + 1);
/*System.out.println("============SENT==========");
for (int c : nums) System.out.println(c);
System.out.println("==========================");
System.out.println("==========================");
for (int c : newNums) System.out.println(c);
System.out.println("==========================");*/
if (cache.containsKey(newNums)) {
sum += cache.get(newNums);
} else {
long treeSum = getSum(newNums);
//System.out.println("Tree sum: " + treeSum);
cache.put(newNums, treeSum);
sum += treeSum;
}
}
}
}
return sum;
}
public static boolean isValid(ArrayList<Integer> nums) {
for (int i = 1; i < nums.size(); i++) {
int diff = nums.get(i) - nums.get(i - 1);
if (diff > 3) return false;
}
return true;
}
static int nCr(int n, int r) {
return fact(n) / (fact(r) *
fact(n - r));
}
// Returns factorial of n
static int fact(int n) {
int res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}
}

Binary file not shown.

View File

@@ -0,0 +1,157 @@
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class day11 {
public static void main(String[] args) {
File myFile = new File("input.txt");
try {
Scanner in = new Scanner(myFile);
char[][] seats = new char[91][94];
int index = 0;
while (in.hasNext()) {
seats[index] = in.nextLine().toCharArray();
index++;
}
boolean stable = false;
while (!stable) {
//char[][] newSeats = part1(seats);
char[][] newSeats = part2(seats);
boolean notEqual = false;
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[0].length; j++) {
if (newSeats[i][j] != seats[i][j]) notEqual = true;
}
}
if (notEqual) {
seats = newSeats;
} else {
stable = true;
}
}
int occupiedSeats = 0;
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[0].length; j++) {
if (seats[i][j] == '#') occupiedSeats++;
System.out.print(seats[i][j]);
}
System.out.println();
}
System.out.println("Answer: " + occupiedSeats);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
static char[][] part1(char[][] seats) {
char[][] newSeats = new char[seats.length][seats[0].length];
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[0].length; j++) {
int emptySeats = 0;
int occupiedSeats = 0;
if (seats[i][j] != '.') {
for (int checkX = -1; checkX <= 1; checkX++) {
for (int checkY = -1; checkY <= 1; checkY++) {
if (j + checkX >= 0 && i + checkY >= 0 &&
j + checkX < seats[0].length && i + checkY < seats.length &&
!(checkX == 0 && checkY == 0)) {
if (seats[i + checkY][j + checkX] == 'L') emptySeats++;
else if (seats[i + checkY][j + checkX] == '#') occupiedSeats++;
}
}
}
if (occupiedSeats == 0 && seats[i][j] == 'L') newSeats[i][j] = '#';
else if (occupiedSeats >= 4 && seats[i][j] == '#') newSeats[i][j] = 'L';
else newSeats[i][j] = seats[i][j];
} else newSeats[i][j] = '.';
}
}
return newSeats;
}
static char[][] part2(char[][] seats) {
char[][] newSeats = new char[seats.length][seats[0].length];
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[0].length; j++) {
int occupiedSeats = 0;
//System.out.print(seats[i][j]);
if (seats[i][j] != '.') {
for (int checkX = -1; checkX <= 1; checkX++) {
for (int checkY = -1; checkY <= 1; checkY++) {
if (!(checkX == 0 && checkY == 0)) {
int multipliedX = checkX;
int multipliedY = checkY;
boolean foundSeat = false;
while (j + multipliedX >= 0 && i + multipliedY >= 0 && j + multipliedX < seats[0].length && i + multipliedY < seats.length && foundSeat == false) {
if(seats[i + multipliedY][j + multipliedX] == 'L') {
foundSeat = true;
} else if (seats[i + multipliedY][j + multipliedX] == '#') {
occupiedSeats++;
foundSeat = true;
}
multipliedX += checkX;
multipliedY += checkY;
}
}
}
}
//System.out.print(occupiedSeats);
if (occupiedSeats >= 5 && seats[i][j] == '#') newSeats[i][j] = 'L';
else if (occupiedSeats == 0 && seats[i][j] == 'L') newSeats[i][j] = '#';
else newSeats[i][j] = seats[i][j];
} else newSeats[i][j] = '.';
}
//System.out.println();
}
return newSeats;
}
}

Binary file not shown.

View File

@@ -0,0 +1,50 @@
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
class day13 {
public static void main(String[] args) {
File myFile = new File("input.txt");
try {
Scanner in = new Scanner(myFile);
double timestamp = Double.parseDouble(in.nextLine());
String[] secondLine = in.nextLine().split(",");
ArrayList<Double> buses = new ArrayList<>();
for (String i : secondLine) {
if (!i.equals("x")) buses.add(Double.parseDouble(i));
}
double shortestTime = Double.MAX_VALUE;
double shortestBus = 0;
for (double i : buses) {
double closestTime = Math.ceil(timestamp / i) * i;
System.out.printf("Time: %f | Closest Time: %f \n", i, closestTime);
if (closestTime < shortestTime) {
shortestTime = closestTime;
shortestBus = i;
}
}
System.out.printf("Part 1: %f \n", (shortestTime - timestamp) * shortestBus);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Binary file not shown.

View File

@@ -0,0 +1,136 @@
import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class day14 {
public static void main(String[] args) {
try {
File inputFile = new File("input.txt");
Scanner in = new Scanner(inputFile);
HashMap<Long, Long> memory = new HashMap<>();
String mask = "";
while (in.hasNext()) {
String[] line = in.nextLine().split(" = ");
if (line[0].equals("mask")) {
mask = line[1];
System.out.println("Mask: " + mask);
} else {
int address = Integer.parseInt(line[0].substring(line[0].indexOf("[") + 1, line[0].indexOf("]")));
long value = Long.parseLong(line[1]);
//memory.put(address, maskedValue(mask, value));
long[] addresses = maskedAddresses(mask, address);
for (long a : addresses) {
System.out.printf("Address: %d | Value: %d \n", a, value);
memory.put(a, value);
}
}
}
long sumLong = 0;
for (long key : memory.keySet()) {
sumLong += memory.get(key);
}
System.out.println("Answer: " + sumLong);
} catch (Exception e) {
System.out.println(e);
}
}
static long maskedValue(String mask, int value) {
String binaryString = Integer.toBinaryString(value);
while (binaryString.length() != 36) binaryString = "0" + binaryString;
String returnString = new String();
System.out.println("Binary String: " + binaryString);
for (int i = binaryString.length() - 1; i >= 0; i--) {
if (binaryString.charAt(i) != mask.charAt(i) && mask.charAt(i) != 'X') {
returnString = mask.charAt(i) + returnString;
} else {
returnString = binaryString.charAt(i) + returnString;
}
}
System.out.println("Return String: " + returnString);
return toDenary(returnString);
}
static long[] maskedAddresses(String mask, int value) {
String binaryString = Integer.toBinaryString(value);
while (binaryString.length() != 36) binaryString = "0" + binaryString;
String returnString = new String();
ArrayList<Integer> xlist = new ArrayList<>();
System.out.println("Binary String: " + binaryString);
for (int i = binaryString.length() - 1; i >= 0; i--) {
if (mask.charAt(i) == 'X') xlist.add(i);
if (binaryString.charAt(i) != mask.charAt(i) && mask.charAt(i) != '0') {
returnString = mask.charAt(i) + returnString;
} else {
returnString = binaryString.charAt(i) + returnString;
}
}
System.out.println("Return string: " + returnString);
String[] binaryStrings = new String[(int) Math.pow(2, xlist.size())];
for (int i = 0; i < Math.pow(2, xlist.size()); i++) {
String currentI = Integer.toBinaryString(i);
while (currentI.length() < xlist.size()) currentI = "0" + currentI;
String newAddress = returnString;
for (int j = 0; j < currentI.length(); j++) {
newAddress = newAddress.replaceFirst(Pattern.quote("X"), Matcher.quoteReplacement(Character.toString(currentI.charAt(j))));
}
System.out.println("New address: " + newAddress);
binaryStrings[i] = newAddress;
}
long[] newAddresses = new long[binaryStrings.length];
for (int i = 0; i < newAddresses.length; i++) {
newAddresses[i] = toDenary(binaryStrings[i]);
}
return newAddresses;
}
static long toDenary(String binary) {
long value = 0;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1') {
value += Math.pow(2, (35 - i));
}
}
return value;
}
}

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,40 @@
import java.util.ArrayList;
import java.util.HashMap;
class day15 {
public static void main(String[] args) {
int[] startingNumbers = {17,1,3,16,19,0};
ArrayList<Integer> spokenNums = new ArrayList<>();
HashMap<Integer, Integer> seenLast = new HashMap<>();
int lastNumber = 0;
for (int i = 0; i < startingNumbers.length; i++) {
spokenNums.add(startingNumbers[i]);
lastNumber = startingNumbers[i];
if (i + 1 != startingNumbers.length) {
seenLast.put(startingNumbers[i], i + 1);
}
}
while (spokenNums.size() < 30000000) {
if (!seenLast.containsKey(lastNumber)) {
seenLast.put(lastNumber, spokenNums.size());
spokenNums.add(0);
lastNumber = 0;
} else {
int diff = spokenNums.size() - seenLast.get(lastNumber);
seenLast.put(lastNumber, spokenNums.size());
lastNumber = diff;
spokenNums.add(lastNumber);
}
}
System.out.println("Number: " + spokenNums.get(spokenNums.size() - 1));
}
}

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,197 @@
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import javax.print.attribute.standard.MediaSize.Other;
class day16 {
public static void main(String[] args) {
try {
File inputFile = new File("input.txt");
Scanner in = new Scanner(inputFile);
List<String> input = new ArrayList<>();
while (in.hasNext()) input.add(in.nextLine());
List<String> fields = input.subList(0, input.indexOf("your ticket:") - 1);
String ticket = input.get(input.indexOf("your ticket:") + 1);
List<String> otherTickets = input.subList(input.indexOf("nearby tickets:") + 1, input.size());
HashMap<Integer, Integer> ranges = new HashMap<>();
List<Field> formattedFields = new ArrayList<>();
for (String field : fields) {
//Part 1 uses the hasmap, part 2 doesnot
String[] currentRanges = field.substring(field.indexOf(":") + 2).split(" or ");
String[] currentUpperAndLower = currentRanges[0].split("-");
ranges.put(Integer.parseInt(currentUpperAndLower[0]), Integer.parseInt(currentUpperAndLower[1]));
int[] range1 = {Integer.parseInt(currentUpperAndLower[0]), Integer.parseInt(currentUpperAndLower[1])};
currentUpperAndLower = currentRanges[1].split("-");
ranges.put(Integer.parseInt(currentUpperAndLower[0]), Integer.parseInt(currentUpperAndLower[1]));
int[] range2 = {Integer.parseInt(currentUpperAndLower[0]), Integer.parseInt(currentUpperAndLower[1])};
String category = field.substring(0, field.indexOf(":"));
formattedFields.add(new Field(category, range1, range2));
}
long errorRate = 0;
List<Integer> toRemove = new ArrayList<>();
for (String value : otherTickets) {
String[] values = value.split(",");
int[] singleTicketValues = Arrays.stream(values).mapToInt(Integer::parseInt).toArray();
for (int singleValue : singleTicketValues) {
boolean valid = false;
for (int lower : ranges.keySet()) {
int upper = ranges.get(lower);
if (singleValue >= lower && singleValue <= upper) {
valid = true;
break;
}
}
if (!valid) {
toRemove.add(otherTickets.indexOf(value));
errorRate += singleValue;
}
}
}
List<String> newOtherTickets = new ArrayList<>();
for (int i = 0; i < otherTickets.size(); i++) {
if (!toRemove.contains(i)) newOtherTickets.add(otherTickets.get(i));
}
HashMap<Integer, List<Field>> possibleCombinations = new HashMap<>();
for (Field f : formattedFields) possibleCombinations.put(formattedFields.indexOf(f), new ArrayList<>());
for (int i = 0; i < newOtherTickets.size(); i++) {
String[] firstValues = newOtherTickets.get(i).split(",");
for (int j = 0; j < firstValues.length; j++) {
int currentValue = Integer.parseInt(firstValues[j]);
List<Field> possible = new ArrayList<>();
for (Field f : formattedFields) {
if (i == 0) {
if (f.range1[0] <= currentValue && f.range1[1] >= currentValue ||
f.range2[0] <= currentValue && f.range2[1] >= currentValue) {
possibleCombinations.get(j).add(f);
}
} else {
//Compare to this field;
if (f.range1[0] <= currentValue && f.range1[1] >= currentValue ||
f.range2[0] <= currentValue && f.range2[1] >= currentValue) {
possible.add(f);
}
}
}
//Compare withoutDuplicate and "possible"
if (i != 0) {
List<Field> newList = new ArrayList<>();
for (Field f : possible) if (possibleCombinations.get(j).contains(f) && possible.contains(f)) {
newList.add(f);
}
possibleCombinations.put(j, newList);
}
}
}
//Part 2
boolean done = false;
while (!done) {
for (int i : possibleCombinations.keySet()) {
if (possibleCombinations.get(i).size() == 1) {
Field knownField = possibleCombinations.get(i).get(0);
for (int j = 0; j < possibleCombinations.size(); j++) {
if (i != j && possibleCombinations.get(j).size() > 1) {
possibleCombinations.get(j).remove(knownField);
}
}
}
}
done = true;
for (int i : possibleCombinations.keySet()) {
if (possibleCombinations.get(i).size() != 1) done = false;
}
}
long multiplication = 1;
String[] myTicket = ticket.split(",");
for (int i : possibleCombinations.keySet()) {
Field currentField = possibleCombinations.get(i).get(0);
if (currentField.name.contains("departure")) {
multiplication *= Long.parseLong(myTicket[i]);
}
}
System.out.println("Part 1: " + errorRate);
System.out.println("Part 2: " + multiplication);
} catch (Exception e) {
System.out.println(e);
}
}
}
class Field {
public String name;
public int[] range1;
public int[] range2;
public int col = -1;
public Field(String name, int[] range1, int[] range2) {
this.name = name;
this.range1 = range1;
this.range2 = range2;
}
public String toString() {
return "Category: " + name + " | Range 1: " + range1[0] + "-" + range1[1] + " | Range 2: " + range2[0] + "-" + range2[1];
}
}

Binary file not shown.

View File

@@ -0,0 +1,243 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
class day17 {
public static void main(String[] args) {
List<int[]> points = new ArrayList<>();
List<int[]> pointsPart2 = new ArrayList<>();
char[][] input = {{'.', '.', '#', '.', '.', '#', '.', '.'},
{'#', '.', '#', '.', '.', '.', '#', '.'},
{'.', '.', '#', '.', '.', '.', '.', '.'},
{'#', '#', '.', '.', '.', '.', '#', '#'},
{'#', '.', '.', '#', '.', '#', '#', '#'},
{'.', '#', '.', '.', '#', '.', '.', '.'},
{'#', '#', '#', '.', '.', '#', '.', '.'},
{'.', '.', '.', '.', '#', '.', '.', '#'}};
/*char[][] input = {{'.', '#', '.'},
{'.', '.', '#'},
{'#', '#', '#'}};*/
//Part 1
//initialise
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input[0].length; j++) {
int[] newPoint = {j, i, 0, 0};
int[] newPointPart2 = {j, i, 0, 0, 0};
if (input[i][j] == '#') {
newPoint[3] = 1;
newPointPart2[4] = 1;
}
points.add(newPoint);
pointsPart2.add(newPointPart2);
}
}
for (int i = 0; i < 6; i++) {
points = step(points);
pointsPart2 = stepPart2(pointsPart2);
}
int counter = 0;
for (int[] p : points) {
if (p[3] == 1) counter++;
//System.out.printf("x: %d | y: %d | z: %d | State: %d \n", p[0], p[1], p[2], p[3]);
}
System.out.println("Part 1: " + counter);
counter = 0;
for (int[] p : pointsPart2) {
if (p[4] == 1) counter++;
//System.out.printf("x: %d | y: %d | z: %d | State: %d \n", p[0], p[1], p[2], p[3]);
}
System.out.println("Part 2: " + counter);
}
static List<int[]> step(List<int[]> points) {
List<int[]> newPoints = new ArrayList<>();
List<int[]> pointsToCheck = new ArrayList<>();
for (int[] p : points) {
int active = 0;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
for (int z = -1; z <= 1; z++) {
if (!(x == 0 && y == 0 && z == 0)) {
int[] potentialNeighboor = {p[0] + x, p[1] + y, p[2] + z, 0};
int index = contains(potentialNeighboor, points);
if (index != -1) {
int[] foundPoint = points.get(index);
if (foundPoint[3] == 1) {
active++;
}
} else {
if (contains(potentialNeighboor, pointsToCheck) == -1) pointsToCheck.add(potentialNeighboor);
}
}
}
}
}
int[] newPoint = {p[0], p[1], p[2], p[3]};
if (p[3] == 1) {
if (active != 2 && active != 3) newPoint[3] = 0;
} else {
if (active == 3) newPoint[3] = 1;
}
newPoints.add(newPoint);
}
for (int[] p : pointsToCheck) {
int active = 0;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
for (int z = -1; z <= 1; z++) {
if (!(x == 0 && y == 0 && z == 0)) {
int[] potentialNeighboor = {p[0] + x, p[1] + y, p[2] + z, 0};
int index = contains(potentialNeighboor, points);
if (index != -1) {
int[] foundPoint = points.get(index);
if (foundPoint[3] == 1) active++;
}
}
}
}
}
int[] newPoint = {p[0], p[1], p[2], p[3]};
if (active == 3){
newPoint[3] = 1;
//System.out.printf("x: %d | y: %d | z: %d | State: %d \n", newPoint[0], newPoint[1], newPoint[2], newPoint[3]);
}
newPoints.add(newPoint);
}
return newPoints;
}
static List<int[]> stepPart2(List<int[]> points) {
System.out.println(points.size());
List<int[]> newPoints = new ArrayList<>();
List<int[]> pointsToCheck = new ArrayList<>();
for (int[] p : points) {
int active = 0;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
for (int z = -1; z <= 1; z++) {
for (int w = -1; w <= 1; w++) {
if (!(x == 0 && y == 0 && z == 0 && w == 0)) {
int[] potentialNeighboor = {p[0] + x, p[1] + y, p[2] + z, p[3] + w, 0};
int index = containsPart2(potentialNeighboor, points);
if (index != -1) {
int[] foundPoint = points.get(index);
if (foundPoint[4] == 1) active++;
} else {
if (containsPart2(potentialNeighboor, pointsToCheck) == -1) pointsToCheck.add(potentialNeighboor);
}
}
}
}
}
}
int[] newPoint = {p[0], p[1], p[2], p[3], p[4]};
if (p[4] == 1) {
if (active != 2 && active != 3) newPoint[4] = 0;
} else {
if (active == 3) newPoint[4] = 1;
}
newPoints.add(newPoint);
}
for (int[] p : pointsToCheck) {
int active = 0;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
for (int z = -1; z <= 1; z++) {
for (int w = -1; w <= 1; w++) {
if (!(x == 0 && y == 0 && z == 0 && w == 0)) {
int[] potentialNeighboor = {p[0] + x, p[1] + y, p[2] + z, p[3] + w, 0};
int index = containsPart2(potentialNeighboor, points);
if (index != -1) {
int[] foundPoint = points.get(index);
if (foundPoint[4] == 1) active++;
}
}
}
}
}
}
int[] newPoint = {p[0], p[1], p[2], p[3], p[4]};
if (active == 3) newPoint[4] = 1;
newPoints.add(newPoint);
}
return newPoints;
}
static int contains(int[] p, List<int[]> points) {
for (int[] search : points) {
if (search[0] == p[0] && search[1] == p[1] && search[2] == p[2]) {
return points.indexOf(search);
}
}
return -1;
}
static int containsPart2(int[] p, List<int[]> points) {
for (int[] search : points) {
if (search[0] == p[0] && search[1] == p[1] && search[2] == p[2] && search[3] == p[3]) {
return points.indexOf(search);
}
}
return -1;
}
}

Binary file not shown.

View File

@@ -0,0 +1,167 @@
import java.util.Scanner;
import java.io.File;
import java.math.BigInteger;
public class day18 {
public static void main(String[] args) {
try {
File inputFile = new File("input.txt");
Scanner in = new Scanner(inputFile);
long total1 = 0;
long total2 = 0;
while (in.hasNext()) {
String expression = in.nextLine();
total1 += recursive(expression);
}
System.out.println("Total: " + total1);
} catch (Exception e) {
System.out.println(e);
}
}
public static long recursive(String expression) {
System.out.println(expression);
int openIndex = -1;
int closeIndex = 0;
int count = 0;
for (int i = 0; i < expression.length(); i++) {
char check = expression.charAt(i);
if (check == '(' && count == 0) {
count = 1;
openIndex = i;
} else if (check == '(' && count != 0) {
count++;
} else if (check == ')' && count > 1) {
count--;
} else if (check == ')' && count == 1) {
closeIndex = i;
count = 0;
long solved = recursive(expression.substring(openIndex + 1, closeIndex));
expression = expression.substring(0, openIndex) + solved + expression.substring(closeIndex + 1);
}
}
if (openIndex == -1) {
//return solve(expression);
//Part 2:
return part2(expression);
} else {
return recursive(expression);
}
}
public static long part2(String expression) {
expression = expression.replace("(", "");
expression = expression.replace(")", "");
expression = expression.replace(" ", "");
if (expression.contains("+") && expression.contains("*")) {
String[] split = expression.split("[*]");
long total = 1;
for (String s : split) {
total *= solve(s);
}
return total;
} else {
return solve(expression);
}
}
public static long solve(String expression) {
expression = expression.replace("(", "");
expression = expression.replace(")", "");
expression = expression.replace(" ", "");
int loops = 0;
//Looks bad but i think its faster than some REGEX or something,
//plus its needed for iteration
loops += expression.length() - expression.replace("+", "").length();
loops += expression.length() - expression.replace("*", "").length();
if (loops == 0) return Long.parseLong(expression);
long total = 0;
for (int i = 0; i < loops - 1; i++) {
int indexRest = 0;
int currentIndex = 0;
for (int j = 0; j < expression.length(); j++) {
if (!Character.isDigit(expression.charAt(j))) {
if (currentIndex == 0) {
currentIndex = j;
} else {
indexRest = j;
break;
}
}
}
String currentExpression = expression.substring(0, indexRest);
String[] split = currentExpression.split("[+*/-]");
long left = Long.parseLong(split[0]);
long right = Long.parseLong(split[1]);
char operation = expression.charAt(currentIndex);
long currentTotal = 0;
if (operation == '+') {
currentTotal = left + right;
} else if (operation == '-') {
currentTotal = left - right;
} else if (operation == '*') {
currentTotal = left * right;
} else if (operation == '/') {
currentTotal = left / right;
}
expression = currentTotal + expression.substring(indexRest);
}
int index = 0;
for (int i = 0; i < expression.length(); i++) {
if (!Character.isDigit(expression.charAt(i))) {
index = i;
break;
}
}
String[] split = expression.split("[+*]");
long left = Long.parseLong(split[0]);
long right = Long.parseLong(split[1]);
char operation = expression.charAt(index);
if (operation == '+') {
total = left + right;
} else if (operation == '*') {
total = left * right;
}
return total;
}
}

View File

@@ -0,0 +1,115 @@
package main
import (
"fmt"
"os"
"regexp"
"strings"
)
func GetRule(rules *map[string]string, r string) string {
rule := (*rules)[r]
if strings.Contains(rule, `"`) {
// Base case
matchLetter := rule[1 : len(rule)-1]
return matchLetter
}
alternates := strings.Split(rule, " | ")
if len(alternates) == 1 {
ruleNumbers := strings.Split(alternates[0], " ")
str := ""
for _, n := range ruleNumbers {
str += GetRule(rules, n)
}
return str
}
if len(alternates) > 1 {
ruleNumbers := strings.Split(alternates[0], " ")
firstAlternate := ""
for _, n := range ruleNumbers {
firstAlternate += GetRule(rules, n)
}
ruleNumbers = strings.Split(alternates[1], " ")
secondAlternate := ""
for _, n := range ruleNumbers {
secondAlternate += GetRule(rules, n)
}
return fmt.Sprintf("(%s|%s)", firstAlternate, secondAlternate)
}
panic("should never be here")
}
func main() {
content, err := os.ReadFile("./input.txt")
if err != nil {
panic(err)
}
splitInput := strings.Split(string(content), "\n\n")
rules := strings.Split(splitInput[0], "\n")
ruleMap := make(map[string]string)
for _, rule := range rules {
splitRule := strings.Split(rule, ": ")
ruleNumber := splitRule[0]
ruleMap[ruleNumber] = splitRule[1]
}
tests := splitInput[1]
tests = tests[0 : len(tests)-1]
zeroRule := regexp.MustCompile("^" + GetRule(&ruleMap, "0") + "$")
matches := 0
for _, t := range strings.Split(tests, "\n") {
if zeroRule.Match([]byte(t)) {
matches++
}
}
fmt.Printf("Part 1: %d\n", matches)
fRule := regexp.MustCompile(GetRule(&ruleMap, "42"))
tRule := regexp.MustCompile(GetRule(&ruleMap, "31"))
matches = 0
for _, t := range strings.Split(tests, "\n") {
// rule 0 = 8 11
// 8 = 42+
// 11 = 42{n} 31{n}
// Therefore: 0 = 42 {n*2} 31{n}
fortyTwoMatch := fRule.FindStringIndex(t)
fortyTwoCount := 0
for fortyTwoMatch != nil && fortyTwoMatch[0] == 0 {
t = t[fortyTwoMatch[1]:]
fortyTwoMatch = fRule.FindStringIndex(t)
fortyTwoCount++
}
thirtyMatch := tRule.FindStringIndex(t)
thirtyCount := 0
for thirtyMatch != nil && thirtyMatch[0] == 0 {
t = t[thirtyMatch[1]:]
thirtyMatch = tRule.FindStringIndex(t)
thirtyCount++
}
if len(t) == 0 && thirtyCount > 0 && fortyTwoCount > thirtyCount {
matches++
}
}
fmt.Printf("Part 2: %d\n", matches)
}

View File

@@ -0,0 +1,253 @@
package main
import (
"fmt"
"os"
"strings"
)
var THREE_SIMPLE_RULE = `
func Rule%s(message string, index *int) error {
err := Rule%s(message, index)
if err != nil {
return err
}
err = Rule%s(message, index)
if err != nil {
return err
}
err = Rule%s(message, index)
if err != nil {
return err
}
return nil
}
`
var SIMPLE_RULE = `
func Rule%s(message string, index *int) error {
err := Rule%s(message, index)
if err != nil {
return err
}
err = Rule%s(message, index)
if err != nil {
return err
}
return nil
}
`
var ONE_SIMPLE_RULE = `
func Rule%s(message string, index *int) error {
err := Rule%s(message, index)
if err != nil {
return err
}
return nil
}
`
var ALTERNATE_RULE = `
func Rule%s(message string, index *int) error {
indexCopy := *index
err := Rule%sFirst(message, &indexCopy)
if err == nil {
*index = indexCopy
return nil
}
err = Rule%sSecond(message, index)
return err
}
%s
%s
`
var LITERAL_RULE = `
func Rule%s(message string, index *int) error {
if len(message) <= *index {
return errors.New("out of bounds")
}
if string(message[*index]) == "%c" {
*index++
return nil
}
return errors.New("Could not match")
}
`
func main() {
content, err := os.ReadFile("./input.txt")
if err != nil {
panic(err)
}
splitInput := strings.Split(string(content), "\n\n")
program := `
package main
import (
"errors"
"fmt"
"os"
"strings"
)
func main() {
content, err := os.ReadFile("./input.txt")
if err != nil {
panic(err)
}
splitInput := strings.Split(string(content), "\n\n")
toTry := splitInput[1]
counter := 0
toTrySplit := strings.Split(toTry, "\n")
for _, v := range toTrySplit[0: len(toTrySplit) - 1] {
index := 0
err := Rule0(v, &index)
if err == nil && index == len(v) {
counter++
}
}
fmt.Println(counter)
}
`
rules := strings.Split(splitInput[0], "\n")
for _, v := range rules {
/*
if v == "8: 42" {
v = "8: 42 | 42 8"
} else if v == "11: 42 31" {
v = "11: 42 31 | 42 11 31"
}
*/
program += CreateRule(v)
}
err = os.WriteFile("./parser.go", []byte(program), 0777)
if err != nil {
panic(err)
}
}
func CreateRule(rule string) (string) {
splitRule := strings.Split(rule, ": ")
ruleNumber := splitRule[0]
rules := strings.Split(splitRule[1], " | ")
if (len(rules) == 1) {
return CreateSingleRule(ruleNumber, rules[0])
}
return fmt.Sprintf(ALTERNATE_RULE, ruleNumber, ruleNumber, ruleNumber, CreateSingleRule(ruleNumber + "First", rules[0]), CreateSingleRule(ruleNumber + "Second", rules[1]))
}
// Single rule (4 5) or ("a")
func CreateSingleRule(ruleNumber string, rule string) string {
if string(rule[0]) == string('"') {
return fmt.Sprintf(LITERAL_RULE, ruleNumber, rule[1])
}
nums := strings.Split(rule, " ")
if len(nums) == 3 {
return fmt.Sprintf(THREE_SIMPLE_RULE, ruleNumber, nums[0], nums[1], nums[2])
} else if (len(nums) == 2) {
return fmt.Sprintf(SIMPLE_RULE, ruleNumber, nums[0], nums[1])
}
return fmt.Sprintf(ONE_SIMPLE_RULE, ruleNumber, nums[0])
}
/*
func Rule0(message string, index *int) error {
err := Rule1(message, index)
if err != nil {
return err
}
err := Rule2(message, index)
if err != nil {
return err
}
return nil
}
func Rule2(message string, index *int) error {
indexCopy := *index
err := Rule2First(message, &indexCopy)
if err == nil {
return nil
}
err = Rule2Second(message, index)
return err
}
func Rule2First(message string, index *int) error {
err := Rule1(message, index)
if err != nil {
return err
}
err := Rule3(message, index)
if err != nil {
return err
}
return nil
}
func Rule2Second(message string, index *int) error {
err := Rule3(message, index)
if err != nil {
return err
}
err := Rule1(message, index)
if err != nil {
return err
}
return nil
}
func Rule3(message string, index *int) errro {
if message[*index] == "b" {
x := 5
y := &x
*y = *y + 1
fmt.Println(x)
}
}
func Rule3(message string, index *int) error {
if string(message[*index]) == "b" {
*index++
return nil
}
return errors.New("Could not match")
}
*/

1056
AdventOfCode2020/day19/parser.go Executable file

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@@ -0,0 +1,51 @@
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class Main {
public static void main(String[] args) {
try {
File myFile = new File("input.txt");
Scanner in = new Scanner(myFile);
int valid = 0;
for (int i = 0; i < 1000; i++) {
String line = in.nextLine();
String[] firstSplit = line.split(" ");
//0 - numbers
//1 - letter
//2 - Password
String[] boundsStr = firstSplit[0].split("-");
int[] bounds = {Integer.parseInt(boundsStr[0]), Integer.parseInt(boundsStr[1])};
char letter = firstSplit[1].charAt(0);
String password = firstSplit[2];
//int counter = 0;
//Part 1 code
/*for (char c : password.toCharArray()) {
if (c == letter) counter++;
}
if (counter >= bounds[0] && counter <= bounds[1]) valid++;*/
//Second part code
if ((password.charAt(bounds[0] - 1) == letter || password.charAt(bounds[1] - 1) == letter) && !(password.charAt(bounds[0] - 1) == letter && password.charAt(bounds[1] - 1) == letter)) valid++;
}
System.out.println(valid);
in.close();
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
}

View File

@@ -0,0 +1,140 @@
package main
import (
"fmt"
"os"
"slices"
"strings"
)
func contains(arr []string, search string) bool {
for _, val := range arr {
if val == search {
return true
}
}
return false
}
func remove(arr []string, item string) []string {
newThing := make([]string, 0)
for _, val := range arr {
if val != item {
newThing = append(newThing, val)
}
}
return newThing
}
func mergeSets(set1 []string, set2 []string) []string {
merged := make([]string, 0)
for _, val := range set1 {
if (contains(set2, val)) {
merged = append(merged, val)
}
}
return merged
}
func isMapSingleValue(myMap map[string][]string) bool {
for _, v := range myMap {
if len(v) > 1 {
return false
}
}
return true
}
func main() {
content, err := os.ReadFile("./input.txt")
if err != nil {
panic(err)
}
_lines := strings.Split(string(content), "\n")
lines := _lines[:len(_lines) - 1]
myMap := make(map[string][]string)
totalIngredients := make([]string, 0)
for _, line := range lines {
split := strings.Split(line, " (contains ")
if (len(split) == 0) {
continue
}
ingredients := strings.Split(split[0], " ")
for _, i := range ingredients {
totalIngredients = append(totalIngredients, i)
}
formatted := strings.Split(strings.TrimSuffix(split[1], ")"), ", ")
for _, v := range formatted {
val, exists := myMap[v]
if !exists {
myMap[v] = ingredients
continue
}
newSets := mergeSets(val, ingredients)
myMap[v] = newSets
if (len(newSets) == 1) {
found := newSets[0]
for key, mapVal := range myMap {
if key == v {
continue
}
if (contains(mapVal, found)) {
myMap[key] = remove(mapVal, found)
}
}
}
}
}
for !isMapSingleValue(myMap) {
for firstK, v := range myMap {
if len(v) == 1 {
for k, i := range myMap {
if k == firstK {
continue
}
myMap[k] = remove(i, v[0])
}
}
}
}
allMapValues := make([]string, 0)
for _, v := range myMap {
for _, j := range v {
if (!contains(allMapValues, j)) {
allMapValues = append(allMapValues, j)
}
}
}
fmt.Printf("%+v\n", myMap)
for _, v := range allMapValues {
totalIngredients = remove(totalIngredients, v)
}
myIngredientList := make([]string, 0)
for k := range myMap {
myIngredientList = append(myIngredientList, k)
}
slices.Sort(myIngredientList)
part2 := ""
for _, v := range myIngredientList {
part2 += myMap[v][0] + ","
}
part2 = strings.TrimSuffix(part2, ",")
fmt.Println(len(totalIngredients))
fmt.Println(part2)
}

View File

@@ -0,0 +1,189 @@
package main
import (
"fmt"
"os"
"slices"
"strconv"
"strings"
)
type Queue struct {
arr []int
head uint
tail uint
}
func (s *Queue) Dequeue() int {
s.head++
return s.arr[s.head - 1]
}
func (s *Queue) Enqueue(num int) {
if len(s.arr) <= int(s.tail) {
s.arr = append(s.arr, num)
} else {
s.arr[s.tail] = num
}
s.tail++
}
func (s *Queue) Print() string {
str := ""
for i := s.head; i < s.tail; i++ {
str += strconv.Itoa(s.arr[i]) + ","
}
return str
}
func main() {
content, err := os.ReadFile("./input.txt")
if err != nil {
panic(err)
}
players := strings.Split(string(content), "\n\n")
player1 := strings.Split(players[0], "\n")[1:]
player2 := strings.Split(players[1], "\n")[1:]
player1Cards := Queue{
arr: make([]int, 0),
head: 0,
tail: 0,
}
player2Cards := Queue{
arr: make([]int, 0),
head: 0,
tail: 0,
}
for _, v := range player1 {
n, err := strconv.Atoi(v)
if err != nil {
panic(err)
}
player1Cards.Enqueue(n)
}
for _, v := range player2 {
if len(v) == 0 {
continue
}
n, err := strconv.Atoi(v)
if err != nil {
panic(err)
}
player2Cards.Enqueue(n)
}
/*
rounds := 0
for {
if player1Cards.head == player1Cards.tail || player2Cards.head == player2Cards.tail {
break
}
player1Card := player1Cards.Dequeue()
player2Card := player2Cards.Dequeue()
if player1Card > player2Card {
player1Cards.Enqueue(player1Card)
player1Cards.Enqueue(player2Card)
} else {
player2Cards.Enqueue(player2Card)
player2Cards.Enqueue(player1Card)
}
rounds++
}
*/
_, p1, p2 := PlayGame(player1Cards, player2Cards)
var winningScore uint = 0
if p1.tail - p1.head < p2.tail - p2.head {
for i := p2.head; i < p2.tail; i++ {
winningScore += (p2.tail - i) * uint(p2.arr[i])
}
} else {
for i := p1.head; i < p1.tail; i++ {
winningScore += (p1.tail - i) * uint(p1.arr[i])
}
}
fmt.Println(winningScore)
}
// true = player1, false = player2
func PlayGame(player1 Queue, player2 Queue) (bool, *Queue, *Queue) {
cache1 := make(map[string]bool)
cache2 := make(map[string]bool)
for {
if player1.head == player1.tail || player2.head == player2.tail {
return player2.head == player2.tail, &player1, &player2
}
// Before drawing, check.
player1string := player1.Print()
player2string := player2.Print()
_, exists := cache1[player1string]
if exists {
return true, &player1, &player2
}
_, exists = cache2[player2string]
if exists {
return true, &player1, &player2
}
cache1[player1string] = true
cache2[player2string] = true
player1Card := player1.Dequeue()
player2Card := player2.Dequeue()
if int(player1.tail) - int(player1.head) >= player1Card && int(player2.tail) - int(player2.head) >= player2Card {
// Recursive case!
player1Copy := Queue{
arr: slices.Clone(player1.arr),
head: player1.head,
tail: player1.head + uint(player1Card),
}
player2Copy := Queue{
arr: slices.Clone(player2.arr),
head: player2.head,
tail: player2.head + uint(player2Card),
}
winner, _, _ := PlayGame(player1Copy, player2Copy)
if winner {
player1.Enqueue(player1Card)
player1.Enqueue(player2Card)
} else {
player2.Enqueue(player2Card)
player2.Enqueue(player1Card)
}
} else {
if player1Card > player2Card {
player1.Enqueue(player1Card)
player1.Enqueue(player2Card)
} else {
player2.Enqueue(player2Card)
player2.Enqueue(player1Card)
}
}
}
}
func GetString(arr []int) string {
s := ""
for _, v := range arr {
s += "," + strconv.Itoa(v)
}
return s
}

View File

@@ -0,0 +1,75 @@
package main
import (
"fmt"
)
type CustomLinkedList struct {
head *CustomListNode
length int64
}
type CustomListNode struct {
payload int64
next *CustomListNode
}
func (l *CustomLinkedList) prepend(n *CustomListNode) {
second := l.head
l.head = n
l.head.next = second
l.length++
}
func (l *CustomLinkedList) append(n *CustomListNode) {
if l.head == nil {
l.head = n
} else {
node := l.head
for node.next != nil {
node = node.next
}
node.next = n
}
l.length++
}
func (l *CustomLinkedList) appendNextTo(n *CustomListNode, pointer *CustomListNode) {
node := l.head
for node != nil {
if node == pointer {
next := node.next
node.next = n
n.next = next
l.length++
break
}
node = node.next
}
}
func main() {
linkedList := CustomLinkedList{}
linkedList.append(&CustomListNode{payload: 10})
node1 := &CustomListNode{payload: 1}
node2 := &CustomListNode{payload: 2}
node3 := &CustomListNode{payload: 3}
linkedList.append(node1)
linkedList.append(node2)
linkedList.append(node3)
linkedList.appendNextTo(&CustomListNode{payload: 69}, node2)
node := linkedList.head
for node != nil {
fmt.Println(node.payload)
node = node.next
}
fmt.Println("Length: ", linkedList.length)
}

View File

View File

@@ -0,0 +1,3 @@
module main
go 1.16

View File

@@ -0,0 +1,178 @@
package main
import (
"fmt"
"os"
"regexp"
"strconv"
"strings"
)
type Hex struct {
q int
r int
s int
}
func CreateHex(q int, r int, s int) Hex {
return Hex{
q: q,
r: r,
s: s,
}
}
func (h *Hex) Print() string {
return strconv.Itoa(h.q) + "," + strconv.Itoa(h.r) + "," + strconv.Itoa(h.s)
}
func Count(arr []string, search string) int {
counter := 0
for i := 0; i < len(arr); i++ {
if arr[i] == search {
counter++
}
}
return counter
}
func AdjustValues(hexMap map[string]bool, key string, white *int, black *int) {
v, exists := hexMap[key]
if !exists {
return
}
if v {
*white++
} else {
*black++
}
}
func AddIfMissing(hexMap map[string]bool, hex string) {
_, exists := hexMap[hex]
if !exists {
hexMap[hex] = true
}
}
func AddAdjacents(hexMap map[string]bool, hex string) {
split := strings.Split(hex, ",")
q, _ := strconv.Atoi(split[0])
r, _ := strconv.Atoi(split[1])
s, _ := strconv.Atoi(split[2])
nw := strconv.Itoa(q) + "," + strconv.Itoa(r - 1) + "," + strconv.Itoa(s + 1)
w := strconv.Itoa(q - 1) + "," + strconv.Itoa(r) + "," + strconv.Itoa(s + 1)
sw := strconv.Itoa(q - 1) + "," + strconv.Itoa(r + 1) + "," + strconv.Itoa(s)
se := strconv.Itoa(q) + "," + strconv.Itoa(r + 1) + "," + strconv.Itoa(s - 1)
e := strconv.Itoa(q + 1) + "," + strconv.Itoa(r) + "," + strconv.Itoa(s - 1)
ne := strconv.Itoa(q + 1) + "," + strconv.Itoa(r - 1) + "," + strconv.Itoa(s)
AddIfMissing(hexMap, nw)
AddIfMissing(hexMap, w)
AddIfMissing(hexMap, sw)
AddIfMissing(hexMap, se)
AddIfMissing(hexMap, e)
AddIfMissing(hexMap, ne)
}
func CountAdjacent(hexMap map[string]bool, hex string) (int, int) {
white := 0
black := 0
split := strings.Split(hex, ",")
q, _ := strconv.Atoi(split[0])
r, _ := strconv.Atoi(split[1])
s, _ := strconv.Atoi(split[2])
nw := strconv.Itoa(q) + "," + strconv.Itoa(r - 1) + "," + strconv.Itoa(s + 1)
w := strconv.Itoa(q - 1) + "," + strconv.Itoa(r) + "," + strconv.Itoa(s + 1)
sw := strconv.Itoa(q - 1) + "," + strconv.Itoa(r + 1) + "," + strconv.Itoa(s)
se := strconv.Itoa(q) + "," + strconv.Itoa(r + 1) + "," + strconv.Itoa(s - 1)
e := strconv.Itoa(q + 1) + "," + strconv.Itoa(r) + "," + strconv.Itoa(s - 1)
ne := strconv.Itoa(q + 1) + "," + strconv.Itoa(r - 1) + "," + strconv.Itoa(s)
AdjustValues(hexMap, nw, &white, &black)
AdjustValues(hexMap, w, &white, &black)
AdjustValues(hexMap, sw, &white, &black)
AdjustValues(hexMap, se, &white, &black)
AdjustValues(hexMap, e, &white, &black)
AdjustValues(hexMap, ne, &white, &black)
return white, black
}
func main() {
fmt.Println("Day 24 Part 1")
file, err := os.ReadFile("input.txt")
if err != nil {
panic(err)
}
_content := strings.Split(string(file), "\n")
content := _content[:len(_content) - 1]
directionRegex := regexp.MustCompile("e|se|sw|w|nw|ne")
// true = white, false = black
cache := make(map[string]bool)
for _, line := range content {
matches := directionRegex.FindAllString(line, -1)
nw := Count(matches, "nw")
w := Count(matches, "w")
sw := Count(matches, "sw")
se := Count(matches, "se")
e := Count(matches, "e")
ne := Count(matches, "ne")
hex := CreateHex(ne + e - sw - w, se + sw - ne - nw, w + nw - se - e)
white, exists := cache[hex.Print()]
if !exists {
cache[hex.Print()] = false
} else {
cache[hex.Print()] = !white
}
}
blackTiles := 0
for _, white := range cache {
if !white {
blackTiles++
}
}
fmt.Printf("Part 1: %d\n", blackTiles)
for i := 0; i < 100; i++ {
toFlip := make([]string, 0)
for k := range cache {
AddAdjacents(cache, k)
}
for k, isWhite := range cache {
_, black := CountAdjacent(cache, k)
if isWhite && black == 2 {
toFlip = append(toFlip, k)
} else if !isWhite && (black == 0 || black > 2) {
toFlip = append(toFlip, k)
}
}
for _, k := range toFlip {
cache[k] = !cache[k]
}
myTiles := 0
for _, white := range cache {
if !white {
myTiles++
}
}
fmt.Println(i, myTiles)
}
}

View File

@@ -0,0 +1,40 @@
package main
import "fmt"
func main() {
var dividerr int64 = 20201227
// var cardPKey int64 = 5764801
// var doorPKey int64 = 17807724
var cardPKey int64 = 16915772
var doorPKey int64 = 18447943
var cardValue int64 = 1
var cardLoopSize int64 = 0
for cardValue != cardPKey {
cardValue *= 7 // Subject number
cardValue = cardValue % dividerr
cardLoopSize++
}
var doorValue int64 = 1
var doorLoopSize int64 = 0
for doorValue != doorPKey {
doorValue *= 7 // Subject number
doorValue = doorValue % dividerr
doorLoopSize++
}
var part1 int64 = 1
var i int64 = 0
for i = 0; i < cardLoopSize; i++ {
part1 *= doorPKey
part1 = part1 % dividerr
}
fmt.Printf("Part 1: %d %d %d\n", cardLoopSize, doorLoopSize, part1)
}

Binary file not shown.

View File

@@ -0,0 +1,70 @@
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class day3 {
public static void main(String[] args) {
try {
File myFile = new File("input.txt");
Scanner in = new Scanner(myFile);
String[] trees = new String[323];
int lineLength;
long multiple = 1;
int numOfTrees = 0;
int x = 0;
for (int i = 0; i < 323; i++) {
trees[i] = in.nextLine();
}
lineLength = trees[0].length();
/*Part 1 code
for (String line : trees) {
char current = line.charAt(x % lineLength);
if (current == '#') numOfTrees++;
x = x + 3;
}
*/
for (int dy = 1; dy < 3; dy++) {
for (int dx = 1; dx < 8; dx = dx + 2) {
if (!(dy == 2 && dx > 1)) {
numOfTrees = 0;
x = 0;
for (int i = 0; i < 323; i = i + dy) {
char current = trees[i].charAt(x % lineLength);
if (current == '#') numOfTrees++;
x = x + dx;
}
System.out.println(numOfTrees);
multiple *= numOfTrees;
}
}
}
System.out.println(multiple);
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
}

Binary file not shown.

View File

@@ -0,0 +1,133 @@
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class day4 {
public static void main(String[] args) {
try {
File myFile = new File("input.txt");
Scanner in = new Scanner(myFile);
ArrayList<String> passports = new ArrayList<String>();
String line = "";
String input = "";
while (in.hasNext()) {
input = "";
input = in.nextLine();
if (input.length() == 0) {
passports.add(line);
line = "";
} else {
line += input;
}
}
passports.add(input);
int valid = 0;
for (String current : passports) {
String currentNoSpace = current.replaceAll("\\s","");
String[] fields = currentNoSpace.split(":");
int counter = 0;
String currentField = "";
for (int i = 0; i < fields.length - 1; i++) {
currentField = fields[i].substring(fields[i].length() - 3);
System.out.println("Next value: " + fields[i + 1]);
String value = "";
try {
value = fields[i + 1].substring(0, fields[i + 1].length() - 3);
} catch (Exception e) {
value = "";
}
if (i == fields.length - 2) {
value = fields[i + 1];
}
System.out.println(currentField);
System.out.println(value);
if (currentField.equals("hcl")) {
String HEX_PATTERN = "^#([A-Fa-f0-9]{6})$";
if(value.matches(HEX_PATTERN)) counter++;
} else if (currentField.equals("pid")) {
String DIGITS_PATTERN = "\\d+";
if (value.matches(DIGITS_PATTERN) && value.length() == 9) counter++;
} else if (currentField.equals("ecl")) {
if (value.equals("amb") || value.equals("blu") || value.equals("brn") || value.equals("gry")
|| value.equals("grn") || value.equals("hzl") || value.equals("oth")) counter++;
} else if (currentField.equals("eyr")) {
String DIGITS_PATTERN = "\\d+";
if (value.matches(DIGITS_PATTERN)) {
int year = Integer.parseInt(value);
if (year >= 2020 && year <= 2030) counter++;
}
} else if (currentField.equals("hgt")) {
String DIGITS_PATTERN = "\\d+";
if (value.substring(0, value.length() - 2).matches(DIGITS_PATTERN)) {
if (value.substring(value.length() - 2, value.length()).equals("in")) {
int num = Integer.parseInt(value.substring(0, value.length() - 2));
if (num >= 59 && num <= 76) counter++;
} else if (value.substring(value.length() - 2, value.length()).equals("cm")) {
int num = Integer.parseInt(value.substring(0, value.length() - 2));
if (num >= 150 && num <= 193) counter++;
}
}
} else if (currentField.equals("byr")) {
String DIGITS_PATTERN = "\\d+";
if (value.matches(DIGITS_PATTERN)) {
int year = Integer.parseInt(value);
if (year >= 1920 && year <= 2002) counter++;
}
} else if (currentField.equals("iyr")) {
String DIGITS_PATTERN = "\\d+";
if (value.matches(DIGITS_PATTERN)) {
int year = Integer.parseInt(value);
if (year >= 2010 && year <= 2020) counter++;
}
}
}
if (counter == 7) valid++;
counter = 0;
}
System.out.println("Valid: " + valid);
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
}

Binary file not shown.

View File

@@ -0,0 +1,63 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class day5 {
public static void main(String[] args) {
File inputs = new File("input.txt");
try {
Scanner in = new Scanner(inputs);
String[] input = new String[884];
for (int i = 0; i < 884; i++) input[i] = in.nextLine();
int highest = 0;
int lowest = 99999999;
ArrayList<Integer> seatIDs = new ArrayList<Integer>();
for (String line : input) {
int row = binaryConvertion(line.substring(0, line.length() - 3), 'B');
int collumn = binaryConvertion(line.substring(line.length() - 3), 'R');
int calculation = row * 8 + collumn;
if (calculation > highest) highest = calculation;
else if (calculation < lowest) lowest = calculation;
seatIDs.add(calculation);
}
for (int i = lowest; i <= highest; i++) {
if (seatIDs.contains(i) == false) {
System.out.println(i);
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static int binaryConvertion(String givenInputs, char one) {
int counter = 0;
for (int i = givenInputs.length() - 1; i >= 0; i--) {
if (givenInputs.charAt(i) == one) {
counter += Math.pow(2, givenInputs.length() - i - 1);
}
}
return counter;
}
}

Binary file not shown.

View File

@@ -0,0 +1,64 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class day6 {
public static void main(String[] args) {
File myFile = new File("input.txt");
try {
Scanner in = new Scanner(myFile);
ArrayList<String> inputs = new ArrayList<String>();
String line = "";
String input = "";
while (in.hasNext()) {
input = "";
input = in.nextLine();
if (input.length() == 0) {
inputs.add(line.substring(0, line.length() - 1));
line = "";
} else {
line += input + ",";
}
}
inputs.add(line.substring(0, line.length() - 1));
int sum = 0;
for (String current : inputs) {
HashMap<Character, Integer> map = new HashMap<>();
String[] currentSplit = current.split(",");
for (String single : currentSplit) {
for (char c : single.toCharArray()) {
if (map.get(c) == null) {
map.put(c, 1);
} else {
map.put(c, map.get(c) + 1);
}
}
}
for (char c : map.keySet()) {
if (map.get(c) == currentSplit.length) sum++;
}
}
System.out.printf("Total sum %d", sum);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,117 @@
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.ArrayList;
class day7 {
public static HashMap<String, ArrayList<BagInfo>> map = new HashMap<>();
public static void main(String[] args) {
File myFile = new File("input.txt");
try {
Scanner in = new Scanner(myFile);
String[] inputs = new String[594];
for (int i = 0; i < 594; i++) {
inputs[i] = in.nextLine();
}
for (String bag : inputs) {
String[] bags = bag.split(" bags contain ");
String outerBag = bags[0];
String innerBag = bags[1];
innerBag = innerBag.replace("bags", "").replace("bag", "");
innerBag = innerBag.substring(0, innerBag.length() - 2);
if (innerBag.equals("no other")) {
map.put(outerBag, new ArrayList<BagInfo>());
} else {
String[] Innerbags = innerBag.split(" , ");
ArrayList<BagInfo> innerBagList = new ArrayList<>();
for (String innerbag : Innerbags) {
BagInfo current = new BagInfo();
current.quantity = Integer.parseInt(innerbag.substring(0, 1));
current.bag = innerbag.substring(2);
innerBagList.add(current);
}
map.put(outerBag, innerBagList);
}
}
int sum = 0;
//Part 1 solution
/*for (String bag : map.keySet()) {
if (isBagInside(bag, "shiny gold")) {
sum++;
};
}*/
//Part 2 solution
//System.out.println(map);
System.out.println(howManyBags("shiny gold") - 1);
//System.out.println(sum);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static int howManyBags(String bagName) {
ArrayList<BagInfo> innerBags = map.get(bagName);
if (innerBags.size() == 0)
return 1;
int total = 1;
for (BagInfo innerbag : innerBags) {
total += (innerbag.quantity * howManyBags(innerbag.bag));
}
return total;
}
public static boolean isBagInside(String bagName, String searchBag) {
ArrayList<BagInfo> innerBags = map.get(bagName);
if (innerBags.size() != 0) {
for (BagInfo innerbag : innerBags) {
if (innerbag.bag.equals(searchBag)) return true;
}
for (BagInfo innerbag : innerBags) {
//Don't return to early, my god this took me ages.
boolean idkwhattocallthis = isBagInside(innerbag.bag, searchBag);
if (idkwhattocallthis) return true;
}
} else {
return false;
}
return false;
}
}
class BagInfo {
public int quantity;
public String bag;
public String toString() {
return "Quantity: " + quantity + " | BagName: " + bag;
}
}

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,109 @@
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
class day8 {
public static void main(String[] args) {
File myFile = new File("input.txt");
try {
Scanner in = new Scanner(myFile);
ArrayList<Instruction> instructions = new ArrayList<>();
while (in.hasNext()) {
String[] split = in.nextLine().split(" ");
Instruction current = new Instruction(split[0], Integer.parseInt(split[1]), false);
instructions.add(current);
}
boolean done = false;
int currentChangingInstruction = 0;
ArrayList<Integer> checked = new ArrayList<>();
while (!done) {
while (instructions.get(currentChangingInstruction).instruction.equals("acc") || checked.contains(currentChangingInstruction)) {
currentChangingInstruction++;
}
checked.add(currentChangingInstruction);
Instruction currentChange = instructions.get(currentChangingInstruction);
if (currentChange.instruction.equals("jmp")) currentChange.instruction = "nop";
else currentChange.instruction = "jmp";
instructions.set(currentChangingInstruction, currentChange);
for (Instruction i : instructions) System.out.println(i);
int acc = 0;
int instructionIndex = 0;
Instruction currentInstruction = instructions.get(instructionIndex);
while (currentInstruction.ran == false && done == false) {
instructions.set(instructionIndex, new Instruction(currentInstruction.instruction, currentInstruction.arg, true));
if (currentInstruction.instruction.equals("acc")) {
acc += currentInstruction.arg;
instructionIndex++;
} else if (currentInstruction.instruction.equals("jmp")) {
if (currentInstruction.arg + instructionIndex >= 0 && currentInstruction.arg + instructionIndex <= instructions.size()) {
instructionIndex += currentInstruction.arg;
} else {
instructionIndex = instructions.size() % currentInstruction.arg;
}
} else {
instructionIndex++;
}
if (instructionIndex == instructions.size()) {
done = true;
System.out.println("Acc: " + acc);
} else {
currentInstruction = instructions.get(instructionIndex);
}
}
if (currentChange.instruction.equals("jmp")) currentChange.instruction = "nop";
else currentChange.instruction = "jmp";
instructions.set(currentChangingInstruction, currentChange);
for (int i = 0; i < instructions.size(); i++) {
Instruction changeRan = instructions.get(i);
changeRan.ran = false;
instructions.set(i, changeRan);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
class Instruction {
public String instruction;
public int arg;
public boolean ran;
public Instruction(String instruction, int arg, boolean ran) {
this.instruction = instruction;
this.arg = arg;
this.ran = ran;
}
public String toString() {
return "Instruction : " + this.instruction + " | Arg: " + this.arg + " | Ran: " + this.ran;
}
}

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,101 @@
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
class day9 {
public static void main(String[] args) {
File myFile = new File("input.txt");
try {
Scanner in = new Scanner(myFile);
ArrayList<Long> nums = new ArrayList<>();
while (in.hasNext()) {
nums.add(Long.parseLong(in.nextLine()));
}
//final int preamble = 25;
//int lower = 0;
long target = 1309761972;
for (int i = 0; i < nums.size() - 1; i++) {
boolean over = false;
long sum = 0;
ArrayList<Long> currentSet = new ArrayList<>();
for (int j = i; j < nums.size() && over == false; j++) {
sum += nums.get(j);
currentSet.add(nums.get(j));
if (sum == target) {
long highest = 0;
long lowest = Long.MAX_VALUE;
for (int k = 0; k < currentSet.size(); k++) {
long current = currentSet.get(k);
if (current < lowest) lowest = current;
if (current > highest) highest = current;
}
over = true;
System.out.println("Lowest: " + lowest);
System.out.println("highest: " + highest);
System.out.println(highest + lowest);
break;
} else if (sum > target) {
over = true;
}
}
}
//Part 1, very inefficient code, had no time to do this one today
//Made easier using a stack and an array to which the combination of numbers in the stack would add up to
//Pop and remove from the stack and remove the last 25 items from array/list
//And that would be the most efficient with an efficiency of O(n^2)? instead of O(n^3) - I think, not sure
/*for (int currentNum = preamble; currentNum < nums.size(); currentNum++) {
boolean adds = false;
for (int i = currentNum - preamble; i < currentNum - 1; i++) {
for (int j = i + 1; j < currentNum; j++) {
System.out.printf("Adding %d and %d, Current Num: %d \n", nums.get(i), nums.get(j), nums.get(currentNum));
if (nums.get(i) + nums.get(j) == nums.get(currentNum)) {
adds = true;
}
}
}
System.out.println(adds);
if (!adds) {
System.out.println(nums.get(currentNum));
break;
}
}*/
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}