├── .gitignore ├── Day-01 ├── bqn │ └── JohnnyJayJay │ │ └── Day01.bqn ├── clojure │ ├── JohnnyJayJay │ │ └── Day01.clj │ └── das_ │ │ └── day01.clj ├── cpp │ └── GameduJS │ │ └── Day1.cpp ├── go │ └── base2code │ │ └── main.go ├── java │ ├── B33fb0n3 │ │ ├── part1.java │ │ └── part2.java │ ├── LuftigerLuca │ │ └── Day1.java │ └── RainbowDashLabs │ │ └── Day1.java ├── kotlin │ ├── Amejonah1200 │ │ └── day1.kt │ ├── DerTev │ │ └── Day1.kt │ ├── Skyslycer │ │ └── Day1.kt │ └── StckOverflw │ │ ├── Part1.kt │ │ └── Part2.kt ├── python │ ├── Amejonah1200 │ │ └── day1.py │ ├── MoMMde │ │ ├── day01-first.py │ │ └── day01-second.py │ ├── RainbowDashLabs │ │ └── day_1.py │ ├── justentrix │ │ └── solution.py │ ├── paula003 │ │ └── day01.py │ └── stnwtr │ │ └── day01.py ├── ruby │ └── Taucher2003 │ │ └── day_01.rb ├── rust │ ├── Amejonah1200 │ │ └── day1.rs │ └── zFlxw │ │ └── main.rs └── scala │ └── SirYwell │ └── day01.scala ├── Day-02 ├── bqn │ └── JohnnyJayJay │ │ └── Day02.bqn ├── clojure │ └── das_ │ │ └── day02.clj ├── cpp │ └── GameduJS │ │ └── Day02.cpp ├── go │ └── base2code │ │ └── main.go ├── java │ ├── LuftigerLuca │ │ └── Day2.java │ └── RainbowDashLabs │ │ └── Day2.java ├── kotlin │ ├── Amejonah1200 │ │ └── day2.kt │ ├── DerTev │ │ └── Day2.kt │ ├── Skyslycer │ │ └── Day2.kt │ └── StckOverflw │ │ ├── Coordinates.kt │ │ ├── Part1.kt │ │ └── Part2.kt ├── python │ ├── Amejonah1200 │ │ └── day2.py │ ├── MoMMde │ │ ├── day02-first.py │ │ └── day02-second.py │ ├── RainbowDashLabs │ │ └── day_2.py │ ├── justentrix │ │ └── solution.py │ ├── paula003 │ │ └── day02.py │ └── stnwtr │ │ └── day02.py ├── ruby │ └── Taucher2003 │ │ └── day_02.rb ├── rust │ ├── Amejonah1200 │ │ └── day2.rs │ └── zFlxw │ │ └── main.rs ├── scala │ └── SirYwell │ │ └── day02.scala └── sql │ └── stnwtr │ └── day02_part01.sql ├── Day-03 ├── bqn │ └── JohnnyJayJay │ │ └── Day03.bqn ├── clojure │ └── das_ │ │ └── day03.clj ├── cpp │ └── GameduJS │ │ └── Day03.cpp ├── java │ └── RainbowDashLabs │ │ └── Day3.java ├── kotlin │ ├── Amejonah1200 │ │ └── day3.kt │ └── Skyslycer │ │ └── Day3.kt ├── python │ ├── RainbowDasLabs │ │ └── day_3.py │ ├── paula003 │ │ └── day03.py │ └── stnwtr │ │ └── day03.py ├── ruby │ └── Taucher2003 │ │ └── day_03.rb ├── rust │ └── zFlxw │ │ └── main.rs └── scala │ └── SirYwell │ └── day03.scala ├── Day-04 ├── bqn │ └── JohnnyJayJay │ │ └── Day04.bqn ├── cpp │ └── GameduJS │ │ └── Day04.cpp ├── kotlin │ ├── Amejonah1200 │ │ └── day4.kt │ └── Skyslycer │ │ └── Day4.kt ├── python │ └── RainbowDashLabs │ │ └── day_4.py └── scala │ └── SirYwell │ └── day04.scala ├── Day-05 ├── bqn │ └── JohnnyJayJay │ │ └── Day05.bqn ├── cpp │ └── GameduJS │ │ └── Day05.cpp ├── kotlin │ └── Amejonah1200 │ │ └── day5.kt ├── python │ └── RainbowDashLabs │ │ └── day_5.py └── scala │ └── SirYwell │ └── day05.scala ├── Day-06 ├── bqn │ └── JohnnyJayJay │ │ └── Day06.bqn ├── clojure │ └── JohnnyJayJay │ │ └── Day06.clj ├── cpp │ └── GameduJS │ │ └── Day06.cpp ├── java │ └── B33fb0n3 │ │ └── day6.java ├── kotlin │ └── Amejonah1200 │ │ └── day6.kt ├── python │ ├── RainbowDashLabs │ │ └── day_6.py │ └── stnwtr │ │ └── day06.py ├── rust │ └── zFlxw │ │ └── main.rs └── scala │ └── SirYwell │ └── day06.scala ├── Day-07 ├── bqn │ └── JohnnyJayJay │ │ └── Day07.bqn ├── cpp │ └── GameduJS │ │ └── Day07.cpp ├── java │ └── B33fb0n3 │ │ ├── part1.java │ │ └── part2.java ├── python │ ├── RainbowDashLabs │ │ └── day_7.py │ └── stnwtr │ │ └── day07.py └── rust │ └── zFlxw │ └── main.rs ├── Day-08 ├── clojure │ └── JohnnyJayJay │ │ └── Day08.clj ├── java │ └── B33fb0n3 │ │ └── part1.java └── python │ ├── RainbowDashLabs │ └── day_8.py │ └── stnwtr │ └── day08.py ├── Day-09 ├── bqn │ └── JohnnyJayJay │ │ └── Day09.bqn ├── java │ └── B33fb0n3 │ │ ├── part1.java │ │ └── part2.java └── python │ ├── RainbowDashLabs │ └── day_9.py │ └── stnwtr │ └── day09.py ├── Day-10 ├── bqn │ └── JohnnyJayJay │ │ └── Day10.bqn ├── clojure │ └── JohnnyJayJay │ │ └── Day10.clj └── python │ └── RainbowDashLabs │ └── day_10.py ├── Day-11 └── python │ └── RainbowDashLabs │ └── day_11.py ├── Day-12 └── python │ └── RainbowDashLabs │ └── day_12.py ├── Day-13 └── python │ └── RainbowDashLabs │ └── day_13.py ├── Day-14 └── python │ └── RainbowDashLabs │ └── day_14.py ├── Day-15 └── python │ └── RainbowDashLabs │ └── day_15.py ├── Day-16 ├── python │ └── RainbowDashLabs │ │ └── day_16.py └── scala │ └── SirYwell │ └── day16.scala ├── README.md └── shared ├── GameduJS ├── FileReader.cpp └── FileReader.h └── justentrix └── file_reader.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | out/ 3 | build/ 4 | __pycache__ 5 | -------------------------------------------------------------------------------- /Day-01/bqn/JohnnyJayJay/Day01.bqn: -------------------------------------------------------------------------------- 1 | input ← •BQN¨ •file.Lines ⊑ •args 2 | 3 | PartOne ← +´∘(<˝˘)∘(2⊸↕) 4 | 5 | PartTwo ← PartOne∘(+˝˘)∘(3⊸↕) 6 | 7 | •Out PartOne input 8 | •Out PartTwo input 9 | -------------------------------------------------------------------------------- /Day-01/clojure/JohnnyJayJay/Day01.clj: -------------------------------------------------------------------------------- 1 | (ns Day01 2 | (:require [clojure.string :as str])) 3 | 4 | (def input (map #(Long/parseLong %) (str/split-lines (slurp (first *command-line-args*))))) 5 | 6 | (defn part-one [input] 7 | (->> input 8 | (partition 2 1) 9 | (filter (partial apply <)) 10 | count)) 11 | 12 | (defn part-two [input] 13 | (->> input 14 | (partition 3 1) 15 | (map (partial apply +)) 16 | part-one)) 17 | -------------------------------------------------------------------------------- /Day-01/clojure/das_/day01.clj: -------------------------------------------------------------------------------- 1 | (ns day01 2 | (:require [clojure.string :as str])) 3 | 4 | (defn count-increasing-numbers [window coll] 5 | (->> coll 6 | (partition window 1) 7 | (map #(reduce + %)) 8 | (partition-all 2 1) 9 | (drop-last) 10 | (filter #(> (second %) (first %))) 11 | (count))) 12 | 13 | (defn part-1 [input] (count-increasing-numbers 1 input)) 14 | 15 | (defn part-2 [input] (count-increasing-numbers 3 input)) 16 | 17 | (defn read-numbers-from-file [file] 18 | (->> file 19 | (slurp) 20 | (str/split-lines) 21 | (map #(Integer/parseInt %)))) 22 | 23 | (defn -main [& args] 24 | (if (not= (count args) 0) 25 | (let [input (read-numbers-from-file (first args))] 26 | (println "Part 1:" (part-1 input)) 27 | (println "Part 2:" (part-2 input))) 28 | (println "Please enter the input file as an argument!"))) 29 | -------------------------------------------------------------------------------- /Day-01/cpp/GameduJS/Day1.cpp: -------------------------------------------------------------------------------- 1 | #include "iostream" 2 | #include "vector" 3 | #include "fstream" 4 | 5 | void part1(std::vector measurements); 6 | void part2(std::vector measurements); 7 | 8 | int main() { 9 | std::vector measurements; 10 | // cmake-build-debug 11 | std::ifstream fileStream("../shared/Day1/Measurements.txt"); 12 | 13 | if(!fileStream.is_open()) 14 | return 0; 15 | 16 | std::string line; 17 | while(std::getline(fileStream, line)) 18 | { 19 | measurements.push_back(std::stoi(line)); 20 | } 21 | 22 | part1(measurements); 23 | part2(measurements); 24 | return 0; 25 | } 26 | 27 | void part1(std::vector measurements) 28 | { 29 | int increased = 0; 30 | for(int i = 1; i < measurements.size(); i++) 31 | { 32 | if(measurements[i] > measurements[i -1]) 33 | increased++; 34 | } 35 | std::cout << "Part 1: " << increased << std::endl; 36 | } 37 | 38 | void part2(std::vector measurements) 39 | { 40 | if(measurements.size() < 3) 41 | return; 42 | 43 | int lastMeasuring = 0; 44 | int increased = 0; 45 | 46 | for(int i = 1; i < measurements.size() - 2; ++i) 47 | { 48 | int currentSize = measurements[i - 1] + measurements[i] + measurements[i + 1]; 49 | 50 | if(lastMeasuring < currentSize) 51 | increased++; 52 | 53 | lastMeasuring = currentSize; 54 | } 55 | 56 | std::cout << "Part 2: " << increased << std::endl; 57 | } 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /Day-01/go/base2code/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | ) 9 | 10 | func main() { 11 | numberArray, err := readLines("input-day-1") 12 | if err != nil { 13 | panic(err) 14 | } 15 | 16 | increased := 0 17 | 18 | for i := 1; i < len(numberArray); i++ { 19 | currentDepth := numberArray[i] 20 | previousDepth := numberArray[i-1] 21 | if currentDepth > previousDepth { 22 | increased++ 23 | } 24 | } 25 | 26 | fmt.Println("Part 1: " + fmt.Sprint(increased)) 27 | 28 | // Reset previous variables 29 | increased = 0 30 | for i := 2; i < len(numberArray)-1; i++ { 31 | currentDepthSum := numberArray[i-1] + numberArray[i] + numberArray[i+1] 32 | previousDepthSum := numberArray[i-2] + numberArray[i-1] + numberArray[i] 33 | if currentDepthSum > previousDepthSum { 34 | increased++ 35 | } 36 | } 37 | 38 | fmt.Println("Part 2: " + fmt.Sprint(increased)) 39 | } 40 | 41 | // readLines reads a whole file into memory 42 | func readLines(path string) ([]int, error) { 43 | file, err := os.Open(path) 44 | if err != nil { 45 | return nil, err 46 | } 47 | defer func(file *os.File) { 48 | err := file.Close() 49 | if err != nil { 50 | panic(err) 51 | } 52 | }(file) 53 | 54 | var lines []int 55 | scanner := bufio.NewScanner(file) 56 | for scanner.Scan() { 57 | number, _ := strconv.Atoi(scanner.Text()) 58 | lines = append(lines, number) 59 | } 60 | return lines, scanner.Err() 61 | } 62 | -------------------------------------------------------------------------------- /Day-01/java/B33fb0n3/part1.java: -------------------------------------------------------------------------------- 1 | public class MyClass { 2 | public static void main(String args[]) { 3 | int increases = 0; 4 | 5 | int lastone = 0; 6 | 7 | for(int i = 0; i < args.length - 2; i++) { 8 | 9 | if(Integer.parseInt(args[i]) > lastone) 10 | increases++; 11 | 12 | lastone = Integer.parseInt(args[i]); 13 | 14 | } 15 | 16 | System.out.println("Increases: " +increases); 17 | } 18 | } -------------------------------------------------------------------------------- /Day-01/java/B33fb0n3/part2.java: -------------------------------------------------------------------------------- 1 | public class MyClass { 2 | public static void main(String args[]) { 3 | int increases = 0; 4 | 5 | int lastone = 0; 6 | 7 | for(int i = 1; i < args.length - 2; i++) { 8 | 9 | int sum = Integer.parseInt(args[i-1]) + Integer.parseInt(args[i]) + Integer.parseInt(args[i+1]); 10 | 11 | if(sum > lastone) 12 | increases++; 13 | 14 | lastone = sum; 15 | 16 | } 17 | 18 | System.out.println("Increases: " +increases); 19 | } 20 | } -------------------------------------------------------------------------------- /Day-01/java/LuftigerLuca/Day1.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.nio.file.Files; 3 | import java.nio.file.Path; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | public class Day1 { 8 | 9 | static List measurements = new ArrayList<>(); 10 | 11 | public static void main(String[] args) { 12 | int increasedMeasurements = 0; 13 | getMeasurements(); 14 | 15 | //Part1 16 | for (int i = 0; i < measurements.size(); i++) { 17 | if(i != 0){ 18 | if(measurements.get(i) > measurements.get(i-1)) increasedMeasurements++; 19 | } 20 | } 21 | System.out.println("There are " + increasedMeasurements + " measurements deeper than the previous one"); 22 | 23 | //Part2 24 | int window1 = 0; 25 | int window2 = -1; 26 | increasedMeasurements = 0; 27 | 28 | for (int i = 0; i < measurements.size(); i++) { 29 | if(i+2 >= measurements.size()) break; 30 | window1 = measurements.get(i) + measurements.get(i+1) + measurements.get(i+2); 31 | if(window1 > window2 && window2 != -1) increasedMeasurements++; 32 | 33 | window2 = window1; 34 | window1 = 0; 35 | 36 | } 37 | 38 | System.out.println("There are " + increasedMeasurements + " windows deeper than the previous window"); 39 | } 40 | 41 | private static void getMeasurements(){ 42 | try { 43 | for (String line : Files.readAllLines(Path.of("shared/LuftigerLuca/inputs/day-01.txt"))) { 44 | measurements.add(Integer.parseInt(line)); 45 | } 46 | } catch (IOException e) { 47 | e.printStackTrace(); 48 | } 49 | } 50 | 51 | 52 | } 53 | -------------------------------------------------------------------------------- /Day-01/java/RainbowDashLabs/Day1.java: -------------------------------------------------------------------------------- 1 | import java.io.IOException; 2 | import java.nio.file.Files; 3 | import java.nio.file.Path; 4 | import java.util.ArrayDeque; 5 | import java.util.stream.Collectors; 6 | 7 | public class Day1 { 8 | public static void main(String[] args) throws IOException { 9 | var inputs = Files.readAllLines(Path.of("puzzle.txt")).stream().map(Integer::parseInt).collect(Collectors.toList()); 10 | 11 | var last = Integer.MAX_VALUE; 12 | var increased = 0; 13 | for (var input : inputs) { 14 | if (last < input) increased++; 15 | last = input; 16 | } 17 | 18 | System.out.println("First part " + increased); 19 | 20 | increased = 0; 21 | var frame = new ArrayDeque(); 22 | last = 0; 23 | for (var input : inputs) { 24 | last = frame.stream().mapToInt(value -> value).sum(); 25 | frame.add(input); 26 | if(frame.size() > 3){ 27 | frame.pop(); 28 | if(last < frame.stream().mapToInt(value -> value).sum()) increased++; 29 | } 30 | } 31 | System.out.println("Second part " + increased); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Day-01/kotlin/Amejonah1200/day1.kt: -------------------------------------------------------------------------------- 1 | fun main() { 2 | val measurements = readInput("day1").map { it.toInt() } 3 | println("First Answer: ${part1(measurements)}") 4 | println("Second Answer: ${part2(measurements)}") 5 | } 6 | 7 | fun part2(measurements: List): Int = part1(measurements.windowed(3, 1).map { it.sum() }) 8 | 9 | fun part1(measurements: List) = measurements.windowed(2, 1) 10 | .count { window -> window.first() < window.last() } 11 | -------------------------------------------------------------------------------- /Day-01/kotlin/DerTev/Day1.kt: -------------------------------------------------------------------------------- 1 | package de.dertev 2 | 3 | fun day1() { 4 | //Part 1 5 | var firstNumber = true 6 | var currentDeep = 0 7 | var points = 0 8 | 9 | inputFile.forEachLine { 10 | if (!firstNumber) { 11 | if (it.toInt() > currentDeep) { 12 | points += 1 13 | } 14 | } else { 15 | firstNumber = false 16 | } 17 | currentDeep = it.toInt() 18 | } 19 | 20 | println("Part 1: $points") 21 | 22 | //Part 2 23 | val window = inputFile.readLines().windowed(size = 3) 24 | val sumList = mutableListOf() 25 | firstNumber = true 26 | currentDeep = 0 27 | points = 0 28 | 29 | window.forEach { thisWindow -> 30 | sumList.add(thisWindow.sumOf { it.toInt() }) 31 | } 32 | 33 | sumList.forEach { 34 | if (!firstNumber) { 35 | if (it > currentDeep) { 36 | points += 1 37 | } 38 | } else { 39 | firstNumber = false 40 | } 41 | currentDeep = it 42 | } 43 | 44 | println("Part 2: $points") 45 | } -------------------------------------------------------------------------------- /Day-01/kotlin/Skyslycer/Day1.kt: -------------------------------------------------------------------------------- 1 | import java.nio.file.Files 2 | import java.nio.file.Paths 3 | 4 | fun main() { 5 | val measurements = Files.readAllLines(Paths.get("./inputs/day1/input.txt")).mapNotNull { it.toIntOrNull() } 6 | 7 | // Part 1 8 | var increasedValues = 0 9 | 10 | measurements.forEachIndexed { position, measurement -> 11 | measurements.getOrNull(position + 1)?.let { 12 | if (measurement < it) { 13 | increasedValues++ 14 | } 15 | } 16 | } 17 | 18 | println("First solution: $increasedValues") 19 | 20 | // Part 2 21 | var increasedTrippleValues = 0 22 | 23 | repeat(measurements.size) { 24 | if (it == 0) return@repeat 25 | 26 | if (getThreeMeasurementSum(measurements, it - 1) < getThreeMeasurementSum(measurements, it)) { 27 | increasedTrippleValues++ 28 | } 29 | } 30 | 31 | println("Second solution: $increasedTrippleValues") 32 | } 33 | 34 | fun getThreeMeasurementSum(measurements: List, index: Int): Int { 35 | var sum = 0 36 | var counter = 0 37 | 38 | repeat(3) { 39 | measurements.getOrNull(index + counter)?.let { 40 | sum += it 41 | } 42 | 43 | counter++ 44 | } 45 | 46 | return sum 47 | } -------------------------------------------------------------------------------- /Day-01/kotlin/StckOverflw/Part1.kt: -------------------------------------------------------------------------------- 1 | fun main() { 2 | val input = {}.javaClass.getResource("/input.txt")?.readText() ?: error("No input.txt in resources") 3 | 4 | val numbers = input.lines().map { it.toInt() } 5 | 6 | println(numbers.zipWithNext().count { (a, b) -> b > a }) 7 | } -------------------------------------------------------------------------------- /Day-01/kotlin/StckOverflw/Part2.kt: -------------------------------------------------------------------------------- 1 | fun main() { 2 | val input = {}.javaClass.getResource("/input.txt")?.readText() ?: error("No input.txt in resources") 3 | 4 | val numbers = input.lines().map { it.toInt() } 5 | 6 | val increasing = numbers.windowed(3).mapTo(ArrayList()) { 7 | it[0] + it[1] + it[2] 8 | }.zipWithNext().count { (a, b) -> b > a } 9 | 10 | println(increasing) 11 | } -------------------------------------------------------------------------------- /Day-01/python/Amejonah1200/day1.py: -------------------------------------------------------------------------------- 1 | def part1(measurements: list[int]) -> int: 2 | count = 0 3 | for i in range(len(measurements) - 1): 4 | if measurements[i] < measurements[i + 1]: 5 | count += 1 6 | return count 7 | 8 | 9 | def part2(measurements: list[int]) -> int: 10 | return part1([sum(t) for t in zip(measurements, measurements[1:], measurements[2:])]) 11 | 12 | 13 | if __name__ == '__main__': 14 | with open('../inputs/day1.txt', 'r') as f: 15 | measurements = [int(line) for line in f.readlines()] 16 | print("Part1:", part1(measurements)) 17 | print("Part2:", part2(measurements)) 18 | -------------------------------------------------------------------------------- /Day-01/python/MoMMde/day01-first.py: -------------------------------------------------------------------------------- 1 | def get_input(file: str) -> list[int]: 2 | lines = [] 3 | with open(file) as f: 4 | for line in f.readlines(): 5 | lines.append(int(line)) 6 | return lines 7 | 8 | 9 | def count_increases(content: list[int]) -> int: 10 | result = 0 11 | for i in range(1, len(content)): 12 | if content[i] > content[i-1]: 13 | result += 1 14 | return result 15 | 16 | 17 | if __name__ == '__main__': 18 | INPUT_FILE = './input' 19 | INPUT = get_input(INPUT_FILE) 20 | print(count_increases(INPUT)) 21 | -------------------------------------------------------------------------------- /Day-01/python/MoMMde/day01-second.py: -------------------------------------------------------------------------------- 1 | def count_increases(content: list[int]) -> int: 2 | result = 0 3 | for i in range(1, len(content)): 4 | if content[i] > content[i-1]: 5 | result += 1 6 | return result 7 | 8 | 9 | def get_input(file: str) -> list[int]: 10 | lines = [] 11 | with open(file) as f: 12 | for line in f.readlines(): 13 | lines.append(int(line)) 14 | return lines 15 | 16 | 17 | if __name__ == '__main__': 18 | FILE = './input' 19 | INPUT = get_input(FILE) 20 | LIST = [] 21 | LENGTH = len(INPUT) 22 | for line in range(LENGTH): 23 | if LENGTH < line + 3 or LENGTH < line + 2: 24 | break 25 | three_measurements = INPUT[line] + INPUT[line+1] + INPUT[line+2] 26 | LIST.append(three_measurements) 27 | print('Iterated over {length} lines. Final Result is: {result}'.format( 28 | length=LENGTH, result=count_increases(LIST))) 29 | -------------------------------------------------------------------------------- /Day-01/python/RainbowDashLabs/day_1.py: -------------------------------------------------------------------------------- 1 | with open('puzzle.txt') as f: 2 | depths = [int(i) for i in f.readlines()] 3 | 4 | last = None 5 | 6 | 7 | def eval(curr_last, curr): 8 | global last 9 | last = curr 10 | return 0 if curr_last is None else (1 if curr_last < curr else 0) 11 | 12 | 13 | increased = sum([eval(last, depth) for depth in depths]) 14 | 15 | print(f"Part one {increased}") 16 | 17 | frame = [] 18 | last = 0 19 | increased = 0 20 | 21 | for depth in depths: 22 | last = sum(frame) 23 | frame.append(depth) 24 | if len(frame) > 3: 25 | frame.pop(0) 26 | increased += 1 if last < sum(frame) else 0 27 | 28 | print(f"Part two {increased}") 29 | -------------------------------------------------------------------------------- /Day-01/python/justentrix/solution.py: -------------------------------------------------------------------------------- 1 | from file_reader import read_numbers 2 | 3 | lines = read_numbers('day01.txt') 4 | result_count = 0 5 | 6 | # Part one 7 | for i in range(1, len(lines)): 8 | if lines[i] > lines[i - 1]: 9 | result_count += 1 10 | 11 | print('Part one:', result_count) 12 | 13 | # Part two 14 | result_count = 0 15 | segment_size = 3 16 | 17 | for i in range(segment_size, len(lines)): 18 | a = sum(lines[i - segment_size:i]) 19 | b = sum(lines[i - segment_size + 1:i + 1]) 20 | if b > a: 21 | result_count += 1 22 | 23 | print('Part two:', result_count) 24 | -------------------------------------------------------------------------------- /Day-01/python/paula003/day01.py: -------------------------------------------------------------------------------- 1 | def task1(): 2 | count = -1 3 | previous = -1 4 | with open('./day01.txt') as file: 5 | for line in file: 6 | if int(line) > previous: 7 | count += 1 8 | previous = int(line) 9 | print('Lösung der 1. Aufgabe: {}'.format(count)) 10 | 11 | 12 | def task2(): 13 | count = -1 14 | previous = -1 15 | with open('./day01.txt') as file: 16 | measurements = [int(i) for i in file.readlines()] 17 | for j, depth in enumerate(measurements[0:-2]): 18 | sum = depth + measurements[j + 1] + measurements[j + 2] 19 | if sum > previous: 20 | count += 1 21 | previous = sum 22 | print('Lösung der 2. Aufgabe: {}'.format(count)) 23 | 24 | 25 | task1() 26 | task2() 27 | -------------------------------------------------------------------------------- /Day-01/python/stnwtr/day01.py: -------------------------------------------------------------------------------- 1 | def calculate(depths, window_size): 2 | increased = 0 3 | for i in range(len(depths) - window_size): 4 | if depths[i] < depths[i + window_size]: 5 | increased += 1 6 | return increased 7 | 8 | 9 | if __name__ == '__main__': 10 | with open('input/01.txt', 'r') as f: 11 | lines = list(map(int, f.readlines())) 12 | print(calculate(lines, 1)) 13 | print(calculate(lines, 3)) 14 | -------------------------------------------------------------------------------- /Day-01/ruby/Taucher2003/day_01.rb: -------------------------------------------------------------------------------- 1 | input = ARGF.read 2 | return if input == nil 3 | 4 | lines = input.split("\n").map { |item| item.to_i } 5 | 6 | last_number = nil 7 | last_numbers = [] 8 | results = [0, 0] 9 | 10 | lines.each do |num| 11 | # Part 1 12 | if last_number != nil 13 | results[0] += 1 if num > last_number 14 | end 15 | last_number = num 16 | 17 | # Part 2 18 | if last_numbers.length == 3 19 | current_numbers = last_numbers.last(2) << num 20 | results[1] += 1 if current_numbers.sum > last_numbers.sum 21 | last_numbers = last_numbers.drop(1) 22 | end 23 | last_numbers << num 24 | end 25 | 26 | puts "Part 1: #{results[0]}" 27 | puts "Part 2: #{results[1]}" 28 | -------------------------------------------------------------------------------- /Day-01/rust/Amejonah1200/day1.rs: -------------------------------------------------------------------------------- 1 | pub(crate) fn start() { 2 | let measurements: Vec = include_str!("../../inputs/day1.txt").lines().map(|line| line.parse::().unwrap()).collect(); 3 | println!("Part 1: {}", part1(&measurements)); 4 | println!("Part 2: {}", part2(&measurements)); 5 | } 6 | 7 | fn part1(measurements: &Vec) -> usize { 8 | measurements.windows(2).filter(|pair| pair[0] < pair[1]).count() 9 | } 10 | 11 | fn part2(measurements: &Vec) -> usize { 12 | part1(&measurements.windows(3).map(|window| window.iter().sum::()).collect()) 13 | } 14 | -------------------------------------------------------------------------------- /Day-01/rust/zFlxw/main.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | use std::ops::Add; 3 | 4 | fn main() { 5 | // File input - may have to change your path. 6 | let content_string: String = fs::read_to_string("./input.txt").unwrap(); 7 | let contents: Vec<&str> = content_string.lines().collect(); 8 | 9 | part_01(&contents); 10 | part_02(&contents); 11 | } 12 | 13 | fn part_01(contents: &Vec<&str>) { 14 | let mut measurements: u16 = 0; 15 | let mut last_measurement: u16 = 0; 16 | 17 | for i in 1..contents.len() { 18 | let content: &str = contents[i]; 19 | let num_content: u16 = content.to_string().parse::().unwrap(); 20 | if num_content > last_measurement { 21 | measurements += 1; 22 | } 23 | 24 | last_measurement = num_content; 25 | } 26 | 27 | println!("Measurements: {}", measurements); 28 | } 29 | 30 | fn part_02(contents: &Vec<&str>) { 31 | let mut measurements: u16 = 0; 32 | let mut last_measurement: u16 = 0; 33 | let mut index: u16 = 0; 34 | 35 | loop { 36 | if index + 2 < contents.len() as u16 { 37 | let mut one: u16 = contents.get(index as usize).unwrap().to_string().parse().unwrap(); 38 | let mut two: u16 = contents.get(index as usize + 1).unwrap().to_string().parse().unwrap(); 39 | let mut three: u16 = contents.get(index as usize + 2).unwrap().to_string().parse().unwrap(); 40 | 41 | println!("{} {} {}", one, two, three); 42 | 43 | // not first iteration 44 | if last_measurement != 0 { 45 | if one + two + three > last_measurement { 46 | measurements += 1; 47 | } 48 | } 49 | 50 | last_measurement = one + two + three; 51 | println!("{}", last_measurement); 52 | index += 1; 53 | } else { 54 | break; 55 | } 56 | } 57 | 58 | println!("Measurements: {}", measurements); 59 | } 60 | -------------------------------------------------------------------------------- /Day-01/scala/SirYwell/day01.scala: -------------------------------------------------------------------------------- 1 | import scala.io.Source.fromFile 2 | // scala day01 3 | @main def day01(filePath: String): Unit = { 4 | val list = fromFile(filePath).getLines().map(_.toInt).toList 5 | val printCount = (iterator: Iterator[Int]) => println( 6 | iterator 7 | .sliding(2) 8 | .count(s => s.head < s.tail.head) 9 | ) 10 | printCount(list.iterator) 11 | printCount(list 12 | .sliding(3) 13 | .map(_.sum) 14 | ) 15 | } 16 | -------------------------------------------------------------------------------- /Day-02/bqn/JohnnyJayJay/Day02.bqn: -------------------------------------------------------------------------------- 1 | # input parsing 2 | inputLines ← •file.Lines ⊑ •args 3 | 4 | Split ← (⊑⊐⟜' ')(↑⋈↓)⊢ 5 | 6 | # The idea behind this solution is that the instructions can be split into commands and values. 7 | # Each command has a unit value associated with it that defines how it affects the state of the submarine. 8 | # To calculate the end result, a delta is calculated for each instruction representing what it changes. 9 | # Then those deltas are folded. 10 | 11 | cmds ← "forward"‿"down"‿"up" 12 | 13 | input ← Split¨ inputLines 14 | inputCmds ← ((cmds⊸⊐⌾<)∘⊑)¨ input 15 | inputVals ← (•BQN∘(1⊸⊑))¨ input 16 | 17 | # Part 1 18 | changes ← ⟨1‿0, 0‿1, 0‿¯1⟩ # units for part one. first is the horizontal position, second is the depth. 19 | 20 | Steps1 ← (⊑⟜changes)¨×⊢ # multiplies instruction values with corresponding units to get a the deltas 21 | PartOne ← ×´∘(+´)∘Steps1 # fold it to get the end result 22 | 23 | # Part 2 24 | plainChanges ← ⟨1‿0, 0‿0, 0‿0⟩ # units for part two that are simply multiplied by the instruction value 25 | aimFactorChanges ← ⟨0‿1, 0‿0, 0‿0⟩ # units for part two that are multiplied by the instruction value and the current aim 26 | aimChanges ← 0‿1‿¯1 # units for how the aim is affected 27 | 28 | # calculate states by applying both state change types and incorperating the running sum (scan) of the aim changes 29 | Steps2 ← ((+`∘((⊑⟜aimChanges)¨×⊢))×((⊑⟜aimFactorChanges)¨×⊢))+((⊑⟜plainChanges)¨×⊢) 30 | PartTwo ← ×´∘(+´)∘Steps2 31 | 32 | •Out (inputCmds PartOne inputVals) 33 | •Out (inputCmds PartTwo inputVals) 34 | -------------------------------------------------------------------------------- /Day-02/clojure/das_/day02.clj: -------------------------------------------------------------------------------- 1 | (ns day02 2 | (:require [clojure.string :as str])) 3 | 4 | (defn read-input [input] 5 | (->> input 6 | (str/split-lines) 7 | (map #(str/split % #" ")) 8 | (map #(list (first %) (Integer/parseInt (second %)))))) 9 | 10 | (defn sum-map [key map] 11 | (->> (get map key) 12 | (clojure.core/map second) 13 | (reduce +))) 14 | 15 | (defn part-1 [input] 16 | (let [actions (group-by first (read-input input)) 17 | horizontal (sum-map "forward" actions) 18 | vertical (- (sum-map "down" actions) (sum-map "up" actions))] 19 | (* horizontal vertical))) 20 | 21 | (defn part-2 [input] 22 | (loop [inputs (read-input input) 23 | horizontal 0 24 | vertical 0 25 | aim 0] 26 | (if (empty? inputs) 27 | (* horizontal vertical) 28 | (let [value (second (first inputs))] 29 | (condp = (first (first inputs)) 30 | "up" (recur (rest inputs) horizontal vertical (- aim value)) 31 | "down" (recur (rest inputs) horizontal vertical (+ aim value)) 32 | "forward" (recur (rest inputs) (+ horizontal value) (+ vertical (* aim value)) aim)))))) 33 | 34 | (defn -main [& args] 35 | (println (part-1 (slurp (first args)))) 36 | (println (part-2 (slurp (first args))))) 37 | -------------------------------------------------------------------------------- /Day-02/cpp/GameduJS/Day02.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "iostream" 3 | #include "fstream" 4 | #include "vector" 5 | 6 | int x = 0; 7 | int y = 0; 8 | int aim = 0; 9 | 10 | std::vector split(std::string string, std::string delimiter); 11 | 12 | int main() 13 | { 14 | std::vector commandCollection; 15 | 16 | std::ifstream stream("../shared/Day02/CommandInput.txt"); 17 | 18 | if(!stream.is_open()) 19 | return 0; 20 | 21 | std::string line; 22 | while(std::getline(stream, line)) 23 | { 24 | commandCollection.push_back(line); 25 | } 26 | 27 | for(int i = 0; i < commandCollection.size(); ++i) 28 | { 29 | std::string commands = commandCollection[i]; 30 | std::vector commandSplit = split(commands, " "); 31 | 32 | std::string command = commandSplit[0]; 33 | int commandValue = std::stoi(commandSplit[1]); 34 | 35 | if(command == "forward") 36 | { 37 | x+=commandValue; 38 | } 39 | if(command == "down") 40 | { 41 | y+=commandValue; 42 | } 43 | if(command == "up") 44 | { 45 | y-=commandValue; 46 | } 47 | 48 | } 49 | 50 | std::cout << " Part 1 solution: " << x * y << std::endl; 51 | x = 0; 52 | y = 0; 53 | 54 | // Part 2 55 | for(int i = 0; i < commandCollection.size(); ++i) 56 | { 57 | std::string commands = commandCollection[i]; 58 | std::vector commandSplit = split(commands, " "); 59 | 60 | std::string command = commandSplit[0]; 61 | int commandValue = std::stoi(commandSplit[1]); 62 | 63 | if(command == "down") 64 | aim+=commandValue; 65 | if(command == "up") 66 | aim-=commandValue; 67 | if(command == "forward") 68 | { 69 | x+=commandValue; 70 | y+=aim * commandValue; 71 | } 72 | } 73 | 74 | std::cout << "Part 2 solution: " << x * y << std::endl; 75 | 76 | 77 | 78 | 79 | return 0; 80 | } 81 | 82 | std::vector split(std::string string, std::string delimiter) 83 | { 84 | std::vector vector; 85 | 86 | size_t pos = 0; 87 | std::string token; 88 | if ((pos = string.find(delimiter)) != std::string::npos) { 89 | token = string.substr(0, pos); 90 | vector.push_back(token); 91 | vector.push_back(string.substr(token.size() + 1)); 92 | } 93 | 94 | return vector; 95 | } -------------------------------------------------------------------------------- /Day-02/go/base2code/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | func main() { 12 | instructionArray, err := readLines("input-day-2") 13 | if err != nil { 14 | panic(err) 15 | } 16 | 17 | depth := 0 18 | horizontal := 0 19 | 20 | for i := 0; i < len(instructionArray); i++ { 21 | lineSplit := strings.Split(instructionArray[i], " ") 22 | instruction := lineSplit[0] 23 | value, _ := strconv.Atoi(lineSplit[1]) 24 | if instruction == "forward" { 25 | horizontal += value 26 | } else if instruction == "up" { 27 | depth -= value 28 | } else if instruction == "down" { 29 | depth += value 30 | } 31 | } 32 | 33 | fmt.Println("Part 1: Depth: " + fmt.Sprint(depth) + " Horizontal: " + fmt.Sprint(horizontal) + " Multiplied: " + fmt.Sprint(horizontal*depth)) 34 | 35 | depth = 0 36 | horizontal = 0 37 | aim := 0 38 | 39 | for i := 0; i < len(instructionArray); i++ { 40 | lineSplit := strings.Split(instructionArray[i], " ") 41 | instruction := lineSplit[0] 42 | value, _ := strconv.Atoi(lineSplit[1]) 43 | if instruction == "forward" { 44 | horizontal += value 45 | depth += value * aim 46 | } else if instruction == "up" { 47 | aim -= value 48 | } else if instruction == "down" { 49 | aim += value 50 | } 51 | } 52 | 53 | fmt.Println("Part 1: Depth: " + fmt.Sprint(depth) + " Horizontal: " + fmt.Sprint(horizontal) + " Multiplied: " + fmt.Sprint(horizontal*depth)) 54 | 55 | } 56 | 57 | // readLines reads a whole file into memory 58 | func readLines(path string) ([]string, error) { 59 | file, err := os.Open(path) 60 | if err != nil { 61 | return nil, err 62 | } 63 | defer func(file *os.File) { 64 | err := file.Close() 65 | if err != nil { 66 | panic(err) 67 | } 68 | }(file) 69 | 70 | var lines []string 71 | scanner := bufio.NewScanner(file) 72 | for scanner.Scan() { 73 | lines = append(lines, scanner.Text()) 74 | } 75 | return lines, scanner.Err() 76 | } 77 | -------------------------------------------------------------------------------- /Day-02/java/LuftigerLuca/Day2.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.IOException; 3 | import java.nio.file.Files; 4 | import java.nio.file.Path; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class Day2 { 9 | 10 | public static List movement = new ArrayList<>(); 11 | 12 | public static void main(String[] args) { 13 | getMovement(); 14 | 15 | //Part1 16 | int positionForward = 0; 17 | int positionDepth = 0; 18 | 19 | for (String move : movement) { 20 | String[] splitMove = move.split(" "); 21 | switch (splitMove[0].toLowerCase()){ 22 | case "forward" -> positionForward += Integer.parseInt(splitMove[1]); 23 | case "down" -> positionDepth += Integer.parseInt(splitMove[1]); 24 | case "up" -> positionDepth -= Integer.parseInt(splitMove[1]); 25 | } 26 | } 27 | 28 | System.out.println("The submarine is at position " + positionForward * positionDepth); 29 | 30 | //Part2 31 | int aim = 0; 32 | positionForward = 0; 33 | positionDepth = 0; 34 | for (String move : movement){ 35 | String[] splitMove = move.split(" "); 36 | int i = Integer.parseInt(splitMove[1]); 37 | 38 | if(splitMove[0].equalsIgnoreCase("down")) aim += i; 39 | if (splitMove[0].equalsIgnoreCase("up")) aim -= i; 40 | if(splitMove[0].equalsIgnoreCase("forward")){ 41 | positionForward += i; 42 | positionDepth += i * aim; 43 | } 44 | } 45 | 46 | System.out.println("The submarine is at position " + positionForward * positionDepth); 47 | } 48 | 49 | public static void getMovement(){ 50 | try { 51 | movement.addAll(Files.readAllLines(Path.of("src/main/resources/movement.txt"))); 52 | } catch (IOException e) { 53 | e.printStackTrace(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Day-02/java/RainbowDashLabs/Day2.java: -------------------------------------------------------------------------------- 1 | import java.io.IOException; 2 | import java.nio.file.Files; 3 | import java.nio.file.Path; 4 | import java.util.stream.Collectors; 5 | 6 | public class Day2 { 7 | public static void main(String[] args) throws IOException { 8 | var values = Files.readAllLines(Path.of("puzzle.txt")).stream() 9 | .map(e -> new Entry(e.split(" ")[0], Integer.parseInt(e.split(" ")[1]))) 10 | .collect(Collectors.toList()); 11 | 12 | var depth = 0; 13 | var horizontal = 0; 14 | 15 | for (var entry : values) { 16 | if ("forward".equals(entry.direction)) { 17 | horizontal += entry.amount; 18 | } else { 19 | depth += "down".equals(entry.direction) ? entry.amount : -entry.amount; 20 | } 21 | } 22 | 23 | System.out.println("Part one is " + (depth * horizontal)); 24 | 25 | 26 | depth = 0; 27 | horizontal = 0; 28 | var aim = 0; 29 | 30 | for (var entry : values) { 31 | if ("forward".equals(entry.direction)) { 32 | horizontal += entry.amount; 33 | depth += aim * entry.amount; 34 | } else { 35 | aim += "down".equals(entry.direction) ? entry.amount : -entry.amount; 36 | } 37 | } 38 | 39 | System.out.println("Part two is " + (depth * horizontal)); 40 | } 41 | 42 | private record Entry(String direction, int amount) { 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Day-02/kotlin/Amejonah1200/day2.kt: -------------------------------------------------------------------------------- 1 | enum class Action { 2 | FORWARD, UP, DOWN 3 | } 4 | 5 | data class Submarine(var horizontal: Long, var depth: Long, var aim: Long) 6 | 7 | fun main() { 8 | val actions = readInput("day2").map { 9 | val (action, amount) = Regex("""(\w+) (\d+)""").matchEntire(it.trim())!!.destructured 10 | Action.valueOf(action.uppercase()) to amount.toLong() 11 | } 12 | println("First: " + actions.fold(Submarine(0, 0, 0), ::part1).let { "${it.horizontal * it.depth}" }) 13 | println("Second: " + actions.fold(Submarine(0, 0, 0), ::part2).let { "${it.horizontal * it.depth}" }) 14 | } 15 | 16 | fun part1(submarine: Submarine, action: Pair): Submarine { 17 | val (actionType, amount) = action 18 | when (actionType) { 19 | Action.FORWARD -> submarine.horizontal += amount 20 | Action.UP -> submarine.depth -= amount 21 | Action.DOWN -> submarine.depth += amount 22 | } 23 | return submarine 24 | } 25 | 26 | fun part2(submarine: Submarine, action: Pair): Submarine { 27 | val (actionType, amount) = action 28 | when (actionType) { 29 | Action.FORWARD -> { 30 | submarine.horizontal += amount 31 | submarine.depth += submarine.aim * amount 32 | } 33 | Action.UP -> submarine.aim -= amount 34 | Action.DOWN -> submarine.aim += amount 35 | } 36 | return submarine 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Day-02/kotlin/DerTev/Day2.kt: -------------------------------------------------------------------------------- 1 | package de.dertev 2 | 3 | fun day2() { 4 | //Part 1 5 | var horizontal = 0 6 | var depth = 0 7 | 8 | inputFile.forEachLine { currentCommand -> 9 | val currentNumber = currentCommand.split(" ")[1].toInt() 10 | 11 | when (currentCommand.dropLast(2)) { 12 | "forward" -> horizontal += currentNumber 13 | "down" -> depth += currentNumber 14 | "up" -> depth -= currentNumber 15 | } 16 | } 17 | 18 | println("Part 1: ${horizontal*depth}") 19 | 20 | //Part 2 21 | var aim = 0 22 | depth = 0 23 | horizontal = 0 24 | 25 | inputFile.forEachLine { currentCommand -> 26 | val currentNumber = currentCommand.split(" ")[1].toInt() 27 | 28 | when (currentCommand.dropLast(2)) { 29 | "forward" -> { 30 | horizontal += currentNumber 31 | depth += aim*currentNumber 32 | } 33 | "down" -> aim += currentNumber 34 | "up" -> aim -= currentNumber 35 | } 36 | } 37 | 38 | println("Part 2: ${horizontal*depth}") 39 | } -------------------------------------------------------------------------------- /Day-02/kotlin/Skyslycer/Day2.kt: -------------------------------------------------------------------------------- 1 | import java.nio.file.Files 2 | import java.nio.file.Paths 3 | 4 | fun main() { 5 | val instructions = Files.readAllLines(Paths.get("./inputs/day2/input.txt")) 6 | 7 | var position = 0 8 | var depth = 0 9 | 10 | // First part 11 | instructions.map { it.split(" ") }.forEach { 12 | when (it[0]) { 13 | "forward" -> position += it[1].toInt() 14 | "up" -> depth -= it[1].toInt() 15 | "down" -> depth += it[1].toInt() 16 | } 17 | } 18 | 19 | println("First solution: ${position * depth}") 20 | 21 | // Second part 22 | var aim = 0 23 | position = 0 24 | depth = 0 25 | 26 | instructions.map { it.split(" ") }.forEach { 27 | when (it[0]) { 28 | "forward" -> { 29 | position += it[1].toInt() 30 | depth += aim * it[1].toInt() 31 | } 32 | "up" -> aim -= it[1].toInt() 33 | "down" -> aim += it[1].toInt() 34 | } 35 | } 36 | 37 | println("Second solution: ${position * depth}") 38 | } -------------------------------------------------------------------------------- /Day-02/kotlin/StckOverflw/Coordinates.kt: -------------------------------------------------------------------------------- 1 | data class Coordinates(val horizontal: Int = 0, val depth: Int = 0, val aim: Int = 0) -------------------------------------------------------------------------------- /Day-02/kotlin/StckOverflw/Part1.kt: -------------------------------------------------------------------------------- 1 | fun main() { 2 | val input = {}.javaClass.getResource("/input.txt")?.readText()?.lines() ?: error("No input.txt in resources") 3 | 4 | val (horizontal, depth) = input.fold(Coordinates()) { coordinates, inputString -> 5 | val (instructionName, value) = inputString.split(' ') 6 | if (instructionName.equals("forward", true)) { 7 | coordinates.copy(horizontal = coordinates.horizontal + value.toInt()) 8 | } else { 9 | coordinates.copy(depth = coordinates.depth + if (instructionName.equals("down", true)) value.toInt() else -value.toInt()) 10 | } 11 | } 12 | 13 | println("Solution: " + (horizontal * depth)) 14 | } 15 | -------------------------------------------------------------------------------- /Day-02/kotlin/StckOverflw/Part2.kt: -------------------------------------------------------------------------------- 1 | fun main() { 2 | val input = {}.javaClass.getResource("/input.txt")?.readText()?.lines() ?: error("No input.txt in resources") 3 | 4 | val (horizontal, depth) = input.fold(Coordinates()) { coordinates, inputString -> 5 | val (instructionName, value) = inputString.split(' ') 6 | if (instructionName.equals("forward", true)) { 7 | coordinates.copy( 8 | horizontal = coordinates.horizontal + value.toInt(), 9 | depth = coordinates.depth + coordinates.aim * value.toInt() 10 | ) 11 | } else { 12 | coordinates.copy( 13 | aim = coordinates.aim + if (instructionName.equals("down", true)) value.toInt() else -value.toInt() 14 | ) 15 | } 16 | } 17 | 18 | println("Solution: " + (horizontal * depth)) 19 | } -------------------------------------------------------------------------------- /Day-02/python/Amejonah1200/day2.py: -------------------------------------------------------------------------------- 1 | def part1(actions: list[(str, int)]) -> int: 2 | depth = 0 3 | horizontal = 0 4 | for (action, amount) in actions: 5 | match action: 6 | case "forward": 7 | horizontal += amount 8 | case "up": 9 | depth -= amount 10 | case "down": 11 | depth += amount 12 | return depth * horizontal 13 | 14 | 15 | def part2(actions: list[(str, int)]) -> int: 16 | aim = 0 17 | depth = 0 18 | horizontal = 0 19 | for (action, amount) in actions: 20 | match action: 21 | case "forward": 22 | horizontal += amount 23 | depth += aim * amount 24 | case "up": 25 | aim -= amount 26 | case "down": 27 | aim += amount 28 | return depth * horizontal 29 | 30 | 31 | if __name__ == '__main__': 32 | with open('../inputs/day2.txt', 'r') as f: 33 | actions: list[tuple[str, int]] = [(line.split(' ')[0], int(line.split(' ')[1])) for line in f.readlines()] 34 | print("Part1:", part1(actions)) 35 | print("Part2:", part2(actions)) 36 | -------------------------------------------------------------------------------- /Day-02/python/MoMMde/day02-first.py: -------------------------------------------------------------------------------- 1 | from enum import Enum, auto 2 | 3 | submarine_x = 0 # Forward 4 | submarine_y = 0 # Depth 5 | 6 | 7 | def get_input(file: str) -> list[str]: 8 | lines = [] 9 | with open(file) as f: 10 | for line in f.readlines(): 11 | lines.append(line) 12 | return lines 13 | 14 | 15 | class Direction(Enum): 16 | UP = auto() 17 | DOWN = auto() 18 | FORWARD = auto() 19 | 20 | 21 | def handle_direction(direction: Direction, x: int): 22 | global submarine_x, submarine_y 23 | if direction == Direction.DOWN: 24 | submarine_y -= x 25 | elif direction == Direction.UP: 26 | submarine_y += x 27 | elif direction == Direction.FORWARD: 28 | submarine_x += x 29 | 30 | 31 | def parse_direction(command: str) -> [Direction, int]: 32 | direction_str, amount_str = command.split(' ') 33 | return [Direction[direction_str.upper()], int(amount_str)] 34 | 35 | 36 | if __name__ == '__main__': 37 | FILE = 'input' 38 | CONTENT = get_input(FILE) 39 | for line in CONTENT: 40 | direction_parsed = parse_direction(line) 41 | handle_direction(direction_parsed[0], direction_parsed[1]) 42 | print('X: {x}'.format(x=submarine_x)) 43 | print('Y: {y}'.format(y=submarine_y)) 44 | print('Result: {r}'.format( 45 | r=str(submarine_x * -submarine_y))) 46 | -------------------------------------------------------------------------------- /Day-02/python/MoMMde/day02-second.py: -------------------------------------------------------------------------------- 1 | from enum import Enum, auto 2 | 3 | submarine_x = 0 # Horizontal 4 | submarine_y = 0 # Depth 5 | submarine_aim = 0 # Aim 6 | 7 | 8 | def get_input(file: str) -> list[str]: 9 | lines = [] 10 | with open(file) as f: 11 | for line in f.readlines(): 12 | lines.append(line) 13 | return lines 14 | 15 | 16 | class Direction(Enum): 17 | DOWN = auto() 18 | UP = auto() 19 | FORWARD = auto() 20 | 21 | 22 | def handle_direction(direction: Direction, x: int): 23 | global submarine_x, submarine_y, submarine_aim 24 | if direction == Direction.DOWN: 25 | submarine_aim += x 26 | elif direction == Direction.UP: 27 | submarine_aim -= x 28 | elif direction == Direction.FORWARD: 29 | submarine_x += x 30 | submarine_y -= x * submarine_aim 31 | 32 | 33 | def parse_direction(command: str) -> [Direction, int]: 34 | direction_str, amount_str = command.split(' ') 35 | return [Direction[direction_str.upper()], int(amount_str)] 36 | 37 | 38 | if __name__ == '__main__': 39 | FILE = './input' 40 | INPUT = get_input(FILE) 41 | for line in INPUT: 42 | direction_parsed = parse_direction(line) 43 | handle_direction(direction_parsed[0], direction_parsed[1]) 44 | print('X: {x}'.format(x=submarine_x)) 45 | print('Y: {y}'.format(y=submarine_y)) 46 | print('Result: {r}'.format( 47 | r=str(submarine_x * -submarine_y))) 48 | -------------------------------------------------------------------------------- /Day-02/python/RainbowDashLabs/day_2.py: -------------------------------------------------------------------------------- 1 | values = [(e.split(" ")[0], int(e.split(" ")[1])) for e in open("puzzle.txt")] 2 | 3 | depth = 0 4 | horizontal = 0 5 | 6 | for k, v in values: 7 | if k == "forward": 8 | horizontal += v 9 | else: 10 | depth += v if k == "down" else -v 11 | 12 | print(f"Part one {depth * horizontal}") 13 | 14 | 15 | depth = 0 16 | horizontal = 0 17 | aim = 0 18 | 19 | for k, v in values: 20 | if k == "forward": 21 | horizontal += v 22 | depth += aim * v 23 | else: 24 | aim += v if k == "down" else -v 25 | 26 | print(f"Part two {depth * horizontal}") 27 | -------------------------------------------------------------------------------- /Day-02/python/justentrix/solution.py: -------------------------------------------------------------------------------- 1 | from file_reader import read_lines 2 | 3 | lines = read_lines('day02.txt') 4 | 5 | depth = 0 6 | depth2 = 0 7 | position = 0 8 | aim = 0 9 | 10 | for line in lines: 11 | split = line.split() 12 | value = int(split[1]) 13 | 14 | match split[0]: 15 | case 'forward': 16 | position += value 17 | depth2 += aim * value 18 | case 'down': 19 | depth += value 20 | aim += value 21 | case 'up': 22 | depth -= value 23 | aim -= value 24 | 25 | # Part one 26 | result = position * depth 27 | print('Part one:', result) 28 | 29 | # Part two 30 | result = position * depth2 31 | print('Part two:', result) 32 | -------------------------------------------------------------------------------- /Day-02/python/paula003/day02.py: -------------------------------------------------------------------------------- 1 | def task1(): 2 | depth = 0 3 | horizontal = 0 4 | with open('./day02.txt') as file: 5 | for line in file: 6 | cmd = line.split(' ')[0] 7 | value = int(line.split(' ')[1]) 8 | if cmd == 'forward': 9 | horizontal += value 10 | elif cmd == 'up': 11 | depth -= value 12 | elif cmd == 'down': 13 | depth += value 14 | print('Lösung der 1. Aufgabe: {}'.format(depth * horizontal)) 15 | 16 | 17 | def task2(): 18 | depth = 0 19 | horizontal = 0 20 | aim = 0 21 | with open('./day02.txt') as file: 22 | for line in file: 23 | cmd = line.split(' ')[0] 24 | value = int(line.split(' ')[1]) 25 | if cmd == 'forward': 26 | horizontal += value 27 | depth += aim * value 28 | elif cmd == 'up': 29 | aim -= value 30 | elif cmd == 'down': 31 | aim += value 32 | print('Lösung der 2. Aufgabe: {}'.format(depth * horizontal)) 33 | 34 | 35 | task1() 36 | task2() 37 | -------------------------------------------------------------------------------- /Day-02/python/stnwtr/day02.py: -------------------------------------------------------------------------------- 1 | def part1(commands): 2 | depth = 0 3 | forward = 0 4 | for command in commands: # not unpacking here because of trying cool 3.10 features 5 | match command: 6 | case ("down", value): 7 | depth += value 8 | case ("up", value): 9 | depth -= value 10 | case ("forward", value): 11 | forward += value 12 | return depth * forward 13 | 14 | 15 | def part2(commands): 16 | depth = 0 17 | forward = 0 18 | aim = 0 19 | for command, value in commands: # unpacking here but still use match 20 | match command: 21 | case "down": 22 | aim += value 23 | case "up": 24 | aim -= value 25 | case "forward": 26 | forward += value 27 | depth += aim * value 28 | return depth * forward 29 | 30 | 31 | def lines_mapper(line): 32 | command, value = line.split(" ") 33 | return command, int(value) 34 | 35 | 36 | if __name__ == '__main__': 37 | with open('input/02.txt', 'r') as f: 38 | lines = list(map(lines_mapper, f.readlines())) 39 | print(part1(lines)) 40 | print(part2(lines)) 41 | -------------------------------------------------------------------------------- /Day-02/ruby/Taucher2003/day_02.rb: -------------------------------------------------------------------------------- 1 | input = ARGF.read 2 | lines = input.split("\n").map { |line| line.split(" ") } 3 | 4 | results = [[0, 0], [0, 0, 0]] 5 | 6 | lines.each do |line| 7 | command = line[0] 8 | value = line[1].to_i 9 | 10 | # Part 1 11 | results[0][0] += value if command == "forward" 12 | results[0][1] += value if command == "down" 13 | results[0][1] -= value if command == "up" 14 | 15 | # Part 2 16 | if command == "forward" 17 | results[1][0] += value 18 | results[1][1] += results[1][2] * value 19 | end 20 | results[1][2] += value if command == "down" 21 | results[1][2] -= value if command == "up" 22 | end 23 | 24 | puts "Part 1: #{results[0][0] * results[0][1]}" 25 | puts "Part 2: #{results[1][0] * results[1][1]}" 26 | -------------------------------------------------------------------------------- /Day-02/rust/Amejonah1200/day2.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Display; 2 | 3 | pub(crate) fn start() { 4 | let actions: Vec<(&str, u64)> = include_str!("../../inputs/day2.txt").lines().map(|line| { 5 | let mut split = line.split(' '); 6 | (split.next().unwrap(), split.next().unwrap().parse::().unwrap()) 7 | }).collect(); 8 | println!("Part 1: {}", part1(&actions)); 9 | println!("Part 2: {}", part2(&actions)); 10 | } 11 | 12 | struct Submarine { 13 | horizontal: u64, 14 | depth: u64, 15 | aim: u64, 16 | } 17 | 18 | impl Display for Submarine { 19 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 20 | write!(f, "{}", self.horizontal * self.depth) 21 | } 22 | } 23 | 24 | fn part1(actions: &[(&str, u64)]) -> Submarine { 25 | let mut submarine = Submarine { horizontal: 0, depth: 0, aim: 0 }; 26 | for (action, amount) in actions { 27 | match *action { 28 | "forward" => { submarine.horizontal += amount; } 29 | "up" => { submarine.depth -= amount; } 30 | "down" => { submarine.depth += amount; } 31 | _ => {} 32 | } 33 | } 34 | submarine 35 | } 36 | 37 | fn part2(actions: &[(&str, u64)]) -> Submarine { 38 | let mut submarine = Submarine { horizontal: 0, depth: 0, aim: 0 }; 39 | for (action, amount) in actions { 40 | match *action { 41 | "forward" => { 42 | submarine.horizontal += amount; 43 | submarine.depth += submarine.aim * amount; 44 | } 45 | "up" => { submarine.aim -= amount; } 46 | "down" => { submarine.aim += amount; } 47 | _ => {} 48 | } 49 | } 50 | submarine 51 | } 52 | -------------------------------------------------------------------------------- /Day-02/rust/zFlxw/main.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | use std::ops::Add; 3 | 4 | fn main() { 5 | // File input 6 | let content_string: String = fs::read_to_string("./input.txt").unwrap(); 7 | let contents: Vec<&str> = content_string.lines().collect(); 8 | 9 | part_01(&contents); 10 | part_02(&contents); 11 | } 12 | 13 | fn part_01(contents: &Vec<&str>) { 14 | let mut horizontal_position: u32 = 0; 15 | let mut depth: u32 = 0; 16 | 17 | for content in contents { 18 | let arguments: Vec<&str> = content.split(" ").collect(); 19 | let operation: &str = arguments.first().unwrap(); 20 | let num: u32 = arguments.get(1).unwrap().to_string().parse().unwrap(); 21 | if operation == "forward" { 22 | horizontal_position += num; 23 | } else if operation == "down" { 24 | depth += num; 25 | } else if operation == "up" { 26 | depth -= num; 27 | } 28 | } 29 | 30 | println!("Result: {}", horizontal_position * depth); 31 | } 32 | 33 | fn part_02( contents: &Vec<&str>) { 34 | let mut horizontal_position: u32 = 0; 35 | let mut depth: u32 = 0; 36 | let mut aim: u32 = 0; 37 | 38 | for content in contents { 39 | let arguments: Vec<&str> = content.split(" ").collect(); 40 | let operation: &str = arguments.first().unwrap(); 41 | let num: u32 = arguments.get(1).unwrap().to_string().parse().unwrap(); 42 | if operation == "forward" { 43 | horizontal_position += num; 44 | depth += aim * num; 45 | } else if operation == "down" { 46 | aim += num; 47 | } else if operation == "up" { 48 | aim -= num; 49 | } 50 | } 51 | 52 | println!("Result: {}", horizontal_position * depth); 53 | } 54 | -------------------------------------------------------------------------------- /Day-02/scala/SirYwell/day02.scala: -------------------------------------------------------------------------------- 1 | import scala.io.Source 2 | import scala.io.Source.fromFile 3 | 4 | @main def day02(filePath: String) = { 5 | val input = fromFile(filePath).getLines() 6 | val mapToVec = (a: Array[String]) => a.apply(0) match { 7 | case "forward" => (a.apply(1).toInt, 0) 8 | case "down" => (0, a.apply(1).toInt) 9 | case "up" => (0, -a.apply(1).toInt) 10 | } 11 | val vecs = input.map(_.split(" ")) 12 | .map(mapToVec).toList 13 | val (x1, y1) = vecs.reduce { case ((xo, yo), (xn, yn)) => (xo + xn, yo + yn) } 14 | println(x1 * y1) 15 | val (x2, y2, _) = vecs.foldLeft((0, 0, 0)) { case ((x, y, aim), (f, a)) => (x + f, y + f * aim, aim + a) } 16 | println(x2 * y2) 17 | } 18 | -------------------------------------------------------------------------------- /Day-02/sql/stnwtr/day02_part01.sql: -------------------------------------------------------------------------------- 1 | -- TABLE: commands(command varchar, value int) 2 | select ( 3 | ((select sum(value) from commands WHERE command="down") - 4 | (select sum(value) from commands where command="up")) * 5 | (SELECT sum(value) from commands WHERE command="forward") 6 | ) as result; 7 | -------------------------------------------------------------------------------- /Day-03/bqn/JohnnyJayJay/Day03.bqn: -------------------------------------------------------------------------------- 1 | Parse ← >('1'⊸=⚇¯2) # Turn list of strings into table of bits 2 | Bits ← (÷⟜2∘⊑≢)≤+˝ # Get list of most common bits in columns of a table 3 | Convert ← +´((2⊸⋆∘↕≠)×⌽) # List of bits -> number 4 | 5 | PartOne ← ((Convert¬)×Convert) Bits # Solve part one 6 | 7 | _step ← {((=⟜(𝕩⊑𝔽Bits 𝕨)𝕩⊸⊑)˘ 𝕨)/𝕨} # Create stepping function for filtering process depending on criteria 8 | _calc ← {⥊∘⊑((=⟜1≠)¨/⊢)∘(<𝔽_step`(↕(1⊑≢)))} # Calculate the list of bits that survives for given criteria 9 | PartTwo ← ⊢_calc(×○Convert)¬_calc # solve part two 10 | 11 | input ← Parse •FLines ⊑ •args 12 | •Out PartOne input 13 | •Out PartTwo input 14 | -------------------------------------------------------------------------------- /Day-03/clojure/das_/day03.clj: -------------------------------------------------------------------------------- 1 | (ns day03 2 | (:require [clojure.string :as str])) 3 | 4 | (defn string->bits [coll] 5 | (mapv #(Character/digit % 2) coll)) 6 | 7 | (defn read-input [file-content] 8 | (->> file-content 9 | str/split-lines 10 | (mapv string->bits))) 11 | 12 | (defn get-column [index coll] 13 | (mapv #(get % (int index)) coll)) 14 | 15 | (defn sorted-bit-frequencies [coll] 16 | (mapv #(sort-by val (frequencies %)) (for [i (range (count (first coll)))] (get-column i coll)))) 17 | 18 | (defn find-bit [index preferred-bit coll] 19 | (if (and (= (last (first coll)) (last (last coll))) (not= (first coll) (last coll))) 20 | preferred-bit 21 | (first (nth coll index (first coll))))) 22 | 23 | (defn get-frequent-bits-by-frequency-index [index preferred-bit frequencies] 24 | (mapv #(find-bit index preferred-bit %) frequencies)) 25 | 26 | (defn binary->int [string] 27 | (Integer/parseInt (apply str string) 2)) 28 | 29 | (defn part-1 [file-content] 30 | (let [input (read-input file-content) 31 | sorted-frequencies (sorted-bit-frequencies input) 32 | gamma (get-frequent-bits-by-frequency-index 1 1 sorted-frequencies) 33 | epsilon (get-frequent-bits-by-frequency-index 0 0 sorted-frequencies)] 34 | (* (binary->int gamma) (binary->int epsilon)))) 35 | 36 | (defn filter-binary [bit index coll] 37 | (filter #(= bit (nth % index)) coll)) 38 | 39 | (defn filter-input-by-frequency-index [index input] 40 | (loop [i 0 41 | coll input] 42 | (if (= i (count (first input))) 43 | coll 44 | (recur (inc i) (filter-binary (nth (get-frequent-bits-by-frequency-index index index (sorted-bit-frequencies coll)) i) i coll))))) 45 | 46 | (defn part-2 [file-content] 47 | (let [input (read-input file-content) 48 | oxygen-generator-rating (->> input (filter-input-by-frequency-index 1) first binary->int) 49 | co2-scrubber-rating (->> input (filter-input-by-frequency-index 0) first binary->int)] 50 | (* oxygen-generator-rating co2-scrubber-rating))) 51 | 52 | (defn -main [& args] 53 | (println "Part 1:" (-> args first slurp part-1)) 54 | (println "Part 2:" (-> args first slurp part-2))) 55 | -------------------------------------------------------------------------------- /Day-03/cpp/GameduJS/Day03.cpp: -------------------------------------------------------------------------------- 1 | #include "iostream" 2 | #include "FileReader.h" 3 | #include 4 | #include 5 | 6 | int convert(long long n); 7 | int getDominatingBit(const std::vector& list, bool mostCommonBit, int index); 8 | std::string matchDataPack(std::vector &listBase, int index, bool mostCommonBit); 9 | 10 | int main() 11 | { 12 | FileReader fileReader("../shared/Puzzle.txt"); 13 | std::vector vector = fileReader.readLines(); 14 | 15 | std::string gamma; 16 | std::string epsilon; 17 | for(int i = 0; i < vector[0].length(); ++i) 18 | { 19 | 20 | gamma+=std::to_string(getDominatingBit(vector, true, i)); 21 | epsilon+=std::to_string(getDominatingBit(vector, false, i)); 22 | } 23 | 24 | std::cout << "Part 1: " << convert(std::stoll(gamma)) * convert(std::stoll(epsilon)) << std::endl; 25 | std::cout << "Part 2: " << convert(std::stoll(matchDataPack(vector, 0, true))) * convert(std::stoll(matchDataPack(vector, 0, false))) << std::endl; 26 | 27 | return 0; 28 | } 29 | 30 | std::string matchDataPack(std::vector &listBase, int index, bool mostCommonBit) 31 | { 32 | std::vector list(listBase); 33 | if(list.size() == 1) 34 | return list[0]; 35 | int bit = getDominatingBit(list, mostCommonBit, index); 36 | 37 | list.erase(std::remove_if(list.begin(), list.end(), [&index, &bit](std::string s){ 38 | return s.at(index) - '0' == bit; 39 | }), list.end()); 40 | 41 | return matchDataPack(list, index + 1, mostCommonBit); 42 | } 43 | 44 | int getDominatingBit(const std::vector& list, bool mostCommonBit, int index) 45 | { 46 | int sum = 0; 47 | for(std::string dataPack : list) 48 | { 49 | char singleBit = dataPack.at(index); 50 | sum+=(singleBit - '0'); 51 | } 52 | // Majority of ones 53 | auto ones = sum >= (double) list.size() / 2.0; 54 | return mostCommonBit ? ones ? 1 : 0 : ones ? 0 : 1; 55 | } 56 | 57 | int convert(long long n) { 58 | int dec = 0, i = 0, rem; 59 | while (n!=0) { 60 | rem = n % 10; 61 | n /= 10; 62 | dec += rem * pow(2, i); 63 | ++i; 64 | } 65 | return dec; 66 | } 67 | -------------------------------------------------------------------------------- /Day-03/java/RainbowDashLabs/Day3.java: -------------------------------------------------------------------------------- 1 | import java.io.IOException; 2 | import java.nio.file.Files; 3 | import java.nio.file.Path; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | import java.util.stream.IntStream; 7 | 8 | public class Day3 { 9 | private static int toNum(String str, int index){ 10 | return Character.getNumericValue(str.charAt(index)); 11 | } 12 | 13 | private static int commonBit(List val, int index, Method method) { 14 | var zeroCommon = val.stream().mapToInt(e -> toNum(e, index)).sum() < val.size() / 2.0; 15 | return method == Method.MOST ? zeroCommon ? 0 : 1 : zeroCommon ? 1 : 0; 16 | } 17 | 18 | private static String calcBits(List val, Method method) { 19 | return IntStream.range(0, val.get(0).length()) 20 | .mapToObj(i -> String.valueOf(commonBit(val, i, method))) 21 | .collect(Collectors.joining()); 22 | } 23 | 24 | private static String bitFilter(List val, int index, Method method) { 25 | if (val.size() <= 1) return val.get(0); 26 | var bit = commonBit(val, index, method); 27 | return bitFilter(val.stream().filter(e -> toNum(e, index) == bit).collect(Collectors.toList()), index + 1, method); 28 | } 29 | 30 | public static void main(String[] args) throws IOException { 31 | var input = Files.readAllLines(Path.of("puzzle.txt")); 32 | 33 | System.out.printf("Part one %s%n", Integer.parseInt(calcBits(input, Method.MOST), 2) * Integer.parseInt(calcBits(input, Method.LEAST), 2)); 34 | 35 | System.out.printf("Part two %s%n", Integer.parseInt(bitFilter(input, 0, Method.MOST), 2) * Integer.parseInt(bitFilter(input, 0, Method.LEAST), 2)); 36 | } 37 | 38 | private enum Method { 39 | LEAST, MOST 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Day-03/kotlin/Amejonah1200/day3.kt: -------------------------------------------------------------------------------- 1 | import kotlin.math.roundToInt 2 | 3 | fun main() { 4 | val input = readInput("day3") 5 | println("Part 1: ${part1(input)}") 6 | println("Part 2: ${part2(input)}") 7 | } 8 | 9 | fun part1(input: List): Int { 10 | val count = input.fold(IntArray(12)) { acc, line -> 11 | line.trim().forEachIndexed { index, c -> if (c == '1') acc[index]++ } 12 | acc 13 | } 14 | val gamma = count.map { if (it > input.size / 2) 1 else 0 }.joinToString("").toInt(2) 15 | val epsilon = gamma.inv() and 0b111111111111 16 | return gamma * epsilon 17 | } 18 | 19 | fun part2(input: List): Int { 20 | val oxy = part2(0, input, '1') { count, size -> count >= (size / 2.0).roundToInt() }.first().toInt(2) 21 | val co2 = part2(0, input, '0') { count, size -> count > (size / 2) }.first().toInt(2) 22 | return oxy * co2 23 | } 24 | 25 | fun part2(pos: Int, input: List, c: Char, criteria: (Int, Int) -> Boolean): List { 26 | if (input.size <= 1 || pos > 11) return input 27 | return part2(pos + 1, 28 | (if (criteria(input.count { it[pos] == c }, input.size)) '1' else '0').let { c -> input.filter { it[pos] == c } }, 29 | c, criteria 30 | ) 31 | } 32 | -------------------------------------------------------------------------------- /Day-03/kotlin/Skyslycer/Day3.kt: -------------------------------------------------------------------------------- 1 | import java.nio.file.Files 2 | import java.nio.file.Paths 3 | 4 | fun main() { 5 | val instructions = Files.readAllLines(Paths.get("./inputs/day3/input.txt")).filter { it.isNotBlank() } 6 | val values = HashMap>() 7 | 8 | var gammaBinaryNumber = "" 9 | var epsilonBinaryNumber = "" 10 | 11 | var oxygenFilter = "" 12 | var scrubberFilter = "" 13 | 14 | var oxygenNumber = "" 15 | var scrubberNumber = "" 16 | 17 | // First and second part 18 | instructions.forEach { string -> 19 | string.forEachIndexed { index, char -> 20 | if (!values.containsKey(index)) { 21 | values[index] = mutableListOf() 22 | } 23 | 24 | values[index]!!.add(char.toString()) 25 | } 26 | } 27 | 28 | values.forEach { (_, chars) -> 29 | val mostUsed = chars.groupingBy { it }.eachCount() 30 | val mostUsedFilteredOxygen = chars.filterIndexed { index, _ -> instructions[index].startsWith(oxygenFilter) }.groupingBy { it }.eachCount() 31 | val mostUsedFilteredScrubber = chars.filterIndexed { index, _ -> instructions[index].startsWith(scrubberFilter) }.groupingBy { it }.eachCount() 32 | var mostUsedNumber = "0" 33 | var leastUsedNumber = "1" 34 | 35 | if ((mostUsed["1"] ?: 0) >= (mostUsed["0"] ?: 0)) { 36 | mostUsedNumber = "1" 37 | leastUsedNumber = "0" 38 | } 39 | 40 | gammaBinaryNumber += mostUsedNumber 41 | epsilonBinaryNumber += leastUsedNumber 42 | 43 | mostUsedNumber = "0" 44 | leastUsedNumber = "1" 45 | 46 | if ((mostUsedFilteredOxygen["1"] ?: 0) >= (mostUsedFilteredOxygen["0"] ?: 0)) { 47 | mostUsedNumber = "1" 48 | } 49 | 50 | oxygenFilter += mostUsedNumber 51 | 52 | if ((mostUsedFilteredScrubber["1"] ?: 0) >= (mostUsedFilteredScrubber["0"] ?: 0)) { 53 | leastUsedNumber = "0" 54 | } 55 | 56 | scrubberFilter += leastUsedNumber 57 | 58 | if (instructions.filter { it.startsWith(oxygenFilter) }.size == 1) { 59 | oxygenNumber = instructions.filter { it.startsWith(oxygenFilter) }[0] 60 | oxygenFilter = oxygenNumber 61 | } 62 | 63 | if (instructions.filter { it.startsWith(scrubberFilter) }.size == 1) { 64 | scrubberNumber = instructions.filter { it.startsWith(scrubberFilter) }[0] 65 | scrubberFilter = scrubberNumber 66 | } 67 | } 68 | 69 | println("First solution: ${Integer.parseInt(gammaBinaryNumber, 2) * Integer.parseInt(epsilonBinaryNumber, 2)}") 70 | println("Second solution: ${Integer.parseInt(oxygenNumber, 2) * Integer.parseInt(scrubberNumber, 2)}") 71 | } -------------------------------------------------------------------------------- /Day-03/python/RainbowDasLabs/day_3.py: -------------------------------------------------------------------------------- 1 | values = [e.strip() for e in open("puzzle.txt") if e.strip()] 2 | 3 | 4 | def common_bit(val: list[str], index: int, method: str = "most") -> int: 5 | zero_common = sum([int(e[index]) for e in val]) < len(val) / 2 6 | return (0 if zero_common else 1) if method == "most" else (1 if zero_common else 0) 7 | 8 | 9 | def calc_bits(val: list[str], method: str = "most") -> str: 10 | return "".join([str(common_bit(val, i, method)) for i in range(len(val[0]))]) 11 | 12 | 13 | print(f"Part one {int(calc_bits(values, 'most'), 2) * int(calc_bits(values, 'least'), 2)}") 14 | 15 | 16 | def bit_filter(val: list[str], index: int, method: str): 17 | if len(val) == 1: 18 | return val[0] 19 | bit = common_bit(val, index, method) 20 | return bit_filter([e for e in val if int(e[index]) == bit], index + 1, method) 21 | 22 | 23 | print(f"Part two {int(bit_filter(values, 0, 'most'), 2) * int(bit_filter(values, 0, 'least'), 2)}") 24 | -------------------------------------------------------------------------------- /Day-03/python/paula003/day03.py: -------------------------------------------------------------------------------- 1 | def task1(): 2 | gamma = '' 3 | epsilon = '' 4 | with open('day03.txt') as file: 5 | values = [list(i) for i in file.readlines()] 6 | for column in list(zip(*values)): 7 | if column.count('0') > column.count('1'): 8 | gamma += '0' 9 | epsilon += '1' 10 | else: 11 | gamma += '1' 12 | epsilon += '0' 13 | print('Lösung der 1. Aufgabe: {}'.format(int(gamma, 2) * int(epsilon, 2))) 14 | 15 | 16 | def task2(): 17 | with open('day03.txt') as file: 18 | values = [list(i) for i in file.readlines()] 19 | for i, line in enumerate(values): 20 | line = list(filter(lambda j: j != '\n', line)) 21 | values[i] = line 22 | print('Lösung der 2. Augabe: {}'.format( 23 | int(check_column(values, 0, True), 2) * int(check_column(values, 0, False), 2) 24 | )) 25 | 26 | 27 | def check_column(values, column, more): 28 | zipped = list(zip(*values)) 29 | if more: 30 | if zipped[column].count('0') > zipped[column].count('1'): 31 | values = filter(lambda row: row[column] == '0', values) 32 | else: 33 | values = filter(lambda row: row[column] == '1', values) 34 | else: 35 | if zipped[column].count('0') > zipped[column].count('1'): 36 | values = filter(lambda row: row[column] == '1', values) 37 | else: 38 | values = filter(lambda row: row[column] == '0', values) 39 | values = list(values) 40 | if len(values) > 1: 41 | column += 1 42 | if (len(values[0])) > column: 43 | return check_column(values, column, more) 44 | else: 45 | return "".join(str(i) for i in values[0]) 46 | 47 | 48 | task1() 49 | task2() 50 | -------------------------------------------------------------------------------- /Day-03/python/stnwtr/day03.py: -------------------------------------------------------------------------------- 1 | def part1(lines): 2 | iterable = list(zip(*list(map(int, list(line.strip())) for line in lines))) 3 | bits = [0 if x.count(0) > len(x) // 2 else 1 for x in iterable] 4 | return int("".join(map(str, bits)), 2) * int("".join(map(str, [1 - x for x in bits])), 2) 5 | 6 | 7 | def part2(lines): 8 | oxygen = int(calculate(lines, 0, "oxygen")[0], 2) 9 | co2 = int(calculate(lines, 0, "co2")[0], 2) 10 | return oxygen * co2 11 | 12 | 13 | def calculate(lines, x, rating): 14 | if len(lines) == 1: 15 | return lines 16 | 17 | zeros, ones = [], [] 18 | for line in lines: 19 | if line[x] == "0": 20 | zeros.append(line) 21 | else: 22 | ones.append(line) 23 | 24 | if len(zeros) == len(ones): 25 | return calculate(ones if rating == "oxygen" else zeros, x + 1, rating) 26 | else: 27 | if len(zeros) > len(ones): 28 | return calculate(zeros if rating == "oxygen" else ones, x + 1, rating) 29 | else: 30 | return calculate(ones if rating == "oxygen" else zeros, x + 1, rating) 31 | 32 | 33 | if __name__ == '__main__': 34 | with open('input/03.txt', 'r') as f: 35 | lines = f.readlines() 36 | print(part1(lines)) 37 | print(part2(list(map(lambda s: s.strip(), lines)))) 38 | -------------------------------------------------------------------------------- /Day-03/ruby/Taucher2003/day_03.rb: -------------------------------------------------------------------------------- 1 | input = ARGF.read 2 | lines = input.split("\n").map { |value| value.split("").map { |string| string.to_i } } 3 | 4 | def transpose(array) 5 | transposed = [] 6 | array[0].length.times do |i| 7 | transposing = [] 8 | array.length.times do |j| 9 | transposing << array[j][i] 10 | end 11 | transposed << transposing 12 | end 13 | transposed 14 | end 15 | 16 | def invert(array) 17 | array.map { |value| if value == 1; 0 else 1 end } 18 | end 19 | 20 | def find_common(array) 21 | array.max_by { |number| array.select { |val| val == number }.length } 22 | end 23 | 24 | transposed = transpose(lines) 25 | 26 | # Part 1 27 | gamma_array = transposed.map { |array| find_common(array) } 28 | epsilon_array = invert(gamma_array) 29 | gamma = gamma_array.join.to_i(2) 30 | epsilon = epsilon_array.join.to_i(2) 31 | 32 | puts "Part 1: #{gamma * epsilon}" 33 | 34 | -------------------------------------------------------------------------------- /Day-03/rust/zFlxw/main.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | 3 | fn main() { 4 | // File input 5 | let content_string: String = fs::read_to_string("./input.txt").unwrap(); 6 | let contents: Vec<&str> = content_string.lines().collect(); 7 | 8 | part_01(&contents); 9 | part_02(&contents); 10 | } 11 | 12 | fn part_01(contents: &Vec<&str>) { 13 | let mut gamma_rate: String = String::from(""); 14 | let mut epsilon_rate: String = String::from(""); 15 | let vector: &mut Vec> = &mut get_mapped_vector(contents); 16 | let _length: usize = contents[0].len(); 17 | 18 | let mut temp_zero: usize = 0; 19 | let mut temp_one: usize = 0; 20 | 21 | for i in 0.._length { 22 | vector.iter().for_each(|vec| if vec[i] == 0 { temp_zero += 1 } else { temp_one += 1 }); 23 | gamma_rate.push_str(if temp_zero > temp_one { "0" } else { "1" }); 24 | epsilon_rate.push_str(if temp_zero < temp_one { "0" } else { "1" }); 25 | temp_zero = 0; 26 | temp_one = 0; 27 | } 28 | 29 | let parsed_gamma = usize::from_str_radix(&gamma_rate, 2).unwrap(); 30 | let parsed_epsilon = usize::from_str_radix(&epsilon_rate, 2).unwrap(); 31 | 32 | println!("Consumption: {}", &parsed_gamma * &parsed_epsilon); 33 | } 34 | 35 | fn part_02(contents: &Vec<&str>) { 36 | let vector: &mut Vec> = &mut get_mapped_vector(contents); 37 | let _length: usize = contents[0].len(); 38 | let oxygen: String = get_oxygen_generator_rating(&mut String::from(""), 0, vector[0].len(), &vector); 39 | let co2: String = get_co2_scrubber_rating(&mut String::from(""), 0, vector[0].len(), &vector); 40 | 41 | let oxygen_radix = usize::from_str_radix(&oxygen, 2).unwrap(); 42 | let co2_radix = usize::from_str_radix(&co2, 2).unwrap(); 43 | 44 | println!("Oxygen: {} : {}", oxygen, &oxygen_radix); 45 | println!("CO2 Scrubber: {} : {}", co2, &co2_radix); 46 | println!("Life support rating: {}", &co2_radix * &oxygen_radix); 47 | } 48 | 49 | fn get_oxygen_generator_rating(rating: &mut String, index: usize, len: usize, vector: &Vec>) -> String { 50 | if index < len { 51 | let most_common: usize = get_most_common_value(index, &vector); 52 | let mut vec: Vec> = Vec::new(); 53 | vector.into_iter().filter(|v| v[index] == most_common).for_each(|v| vec.push(v.to_vec())); 54 | rating.push_str(&most_common.to_string()); 55 | 56 | return get_oxygen_generator_rating(rating, index + 1, len, &vec); 57 | } 58 | 59 | rating.to_string() 60 | } 61 | 62 | fn get_co2_scrubber_rating(rating: &mut String, index: usize, len: usize, vector: &Vec>) -> String { 63 | if index < len { 64 | let less_common: usize = get_less_common_value(index, &vector); 65 | let mut vec: Vec> = Vec::new(); 66 | vector.into_iter().filter(|v| v[index] == less_common).for_each(|v| vec.push(v.to_vec())); 67 | rating.push_str(&less_common.to_string()); 68 | 69 | return get_co2_scrubber_rating(rating, index + 1, len, &vec); 70 | } 71 | 72 | rating.to_string() 73 | } 74 | 75 | fn get_most_common_value(index: usize, vector: &Vec>) -> usize { 76 | let mut tmp_zero: usize = 0; 77 | let mut tmp_one: usize = 0; 78 | 79 | vector.iter().for_each(|vec| if vec[index] == 0 { tmp_zero += 1 } else { tmp_one += 1 }); 80 | if vector.len() == 1 { 81 | return vector[0][index]; 82 | } 83 | 84 | if tmp_zero == tmp_one { 85 | return 1; 86 | } 87 | 88 | if tmp_zero > tmp_one { 89 | return 0; 90 | } 91 | 92 | 1 93 | } 94 | 95 | fn get_less_common_value(index: usize, vector: &Vec>) -> usize { 96 | let mut tmp_zero: usize = 0; 97 | let mut tmp_one: usize = 0; 98 | 99 | vector.iter().for_each(|vec| if vec[index] == 0 { tmp_zero += 1 } else { tmp_one += 1 }); 100 | if vector.len() == 1 { 101 | return vector[0][index]; 102 | } 103 | 104 | if tmp_zero == tmp_one { 105 | return 0; 106 | } 107 | 108 | if tmp_zero < tmp_one { 109 | return 0; 110 | } 111 | 112 | 1 113 | } 114 | 115 | fn get_mapped_vector(contents: &Vec<&str>) -> Vec> { 116 | let vector: &mut Vec> = &mut Vec::new(); 117 | let _length: usize = 0; 118 | 119 | for content in contents { 120 | vector.push(content.chars().map(|c| c.to_string().parse().unwrap()).collect()); 121 | } 122 | 123 | vector.to_vec() 124 | } 125 | -------------------------------------------------------------------------------- /Day-03/scala/SirYwell/day03.scala: -------------------------------------------------------------------------------- 1 | import scala.io.Source.fromFile 2 | 3 | @main def day03(filePath: String) = { 4 | val input = fromFile(filePath).getLines().toList 5 | val digits = input.map(_.toList.map(_ - '0')) 6 | val countToBinary = (list: List[Int]) => list.map(i => if i * 2 >= input.length then 1 else 0) 7 | val binaryToTuple = (list: List[Int]) => list.reverse.zipWithIndex.foldLeft((0, 0)) { 8 | case ((g, e), (v, i)) => (g | (v << i), e | (((v - 1) & 1) << i)) 9 | } 10 | val counts = countOnes(digits) 11 | val (gamma, epsilon) = (countToBinary andThen binaryToTuple) (counts) 12 | println(gamma * epsilon) 13 | val listToInt = binaryToTuple andThen (_ (0)) 14 | val reduce = reduceByCount(digits) 15 | println(listToInt(reduce(1)) * listToInt(reduce(0))) 16 | } 17 | 18 | def countOnes(list: List[List[Int]]): List[Int] = list.reduce((l, r) => l.zip(r).map { case (a, b) => a + b }) 19 | 20 | def reduceByCount(inputList: List[List[Int]])(toKeep: Int): List[Int] = 21 | var list = inputList 22 | val length = list(0).length 23 | for (i <- 0 until length if list.length > 1) { 24 | val c = countOnes(list)(i) * 2 25 | list = list.filter(e => (e(i) == toKeep) == c >= list.length) 26 | } 27 | list(0) 28 | -------------------------------------------------------------------------------- /Day-04/bqn/JohnnyJayJay/Day04.bqn: -------------------------------------------------------------------------------- 1 | Split ← (¬-˜⊢×·+`»⊸>)∘≠⊔⊢ # Split list 𝕩 at element 𝕨 2 | RmEmpty ← 1⊸⌊∘≠¨⊸/ # Remove empty lists from depth 2 array 𝕩 3 | DrawOrder ← •BQN∘('⟨'⊸∾)∾⟜'⟩'∘⊑ # Parse number order from input lines 𝕩 4 | Boards ← >¨((5˙/(↕∘÷⟜5∘≠))⊔(•BQN⚇¯2' '⊸Split¨))∘RmEmpty∘(1⊸↓) # Parse bingo boards from input lines 𝕩 5 | Winner ← (+˝∨○(∨´=⟜5)+˝˘) =⟜¯1 # Determine if the board 𝕩 has a bingo 6 | Mark ← (÷0-=)⌊⊣ # "Replace" 𝕩s in board 𝕨 with ¯1 7 | Step ← (¬∘Winner¨/⊣)Mark¨⊢ # Advance a set of boards (𝕨) by playing a number (𝕩) 8 | Play ← (<⊣)Step`⊢ # Calculate all game states given a list of numbers to draw 𝕩 and an array of boards 𝕨 9 | Winners ← Winner⚇¯2/¨⊢ # For a series of game states 𝕩, only keep the winning boards in each one 10 | Score ← (+´⥊)∘(⌈⟜0) # Calculate final score of a board (winning number already included) by adding up all unmarked entries 11 | FinalBoards ← ∾´(Winners∘Play×⊢) 12 | PartOne ← Score ⊑∘FinalBoards 13 | PartTwo ← Score ⊑∘⌽∘FinalBoards 14 | 15 | input ← •FLines ⊑ •args 16 | numbers ← DrawOrder input 17 | b ← Boards input 18 | •Out b PartOne numbers 19 | •Out b PartTwo numbers 20 | -------------------------------------------------------------------------------- /Day-04/cpp/GameduJS/Day04.cpp: -------------------------------------------------------------------------------- 1 | #include "iostream" 2 | #include "FileReader.h" 3 | #include "map" 4 | #include 5 | #include 6 | 7 | 8 | void extractNumbers(char delimiter, std::string *string, std::vector *writeTo); 9 | std::string replaceAll(std::string str, const std::string& from, const std::string& to); 10 | 11 | int test(std::map> *boards, std::vector marked, bool returnBest) 12 | { 13 | for(const auto& tables : *boards) 14 | { 15 | int tableNum = tables.first; 16 | std::vector table = tables.second; 17 | 18 | for(int q = 0; q < 2; ++q) 19 | { 20 | /* 0 = rows, 1 = Columns */ 21 | for(int a = 0; a < 5; ++a) 22 | { 23 | //std::cout << "-----------" << std::endl; 24 | std::vector bingoSet; 25 | for(int b = 0; b < 5; ++b) 26 | { 27 | int index = (q == 0) ? (5*a + b) : (a + 5*b); 28 | if(std::find(marked.begin(), marked.end(), table[index]) != marked.end()) { 29 | bingoSet.push_back(table[index]); 30 | } 31 | 32 | } 33 | 34 | if(bingoSet.size() == 5) { 35 | int k = 0; 36 | for(auto t : table) 37 | { 38 | if(std::find(marked.begin(), marked.end(), t) == marked.end()) { 39 | k = k + t; 40 | } 41 | } 42 | bingoSet.clear(); 43 | if(!returnBest) 44 | boards->erase(tableNum); 45 | return returnBest ? k : boards->empty() ? k : test(boards, marked, returnBest); 46 | } 47 | } 48 | } 49 | } 50 | return -1; 51 | } 52 | 53 | int main() 54 | { 55 | FileReader fileReader("../shared/Puzzle.txt"); 56 | std::vector readFile = fileReader.readLines(); 57 | std::map> boards; 58 | std::vector marker_numbers; 59 | std::vector marked; 60 | 61 | extractNumbers(',', &readFile[0], &marker_numbers); 62 | 63 | // 0*6 + x[1-6]; 1*6 + x[1-6];... 64 | for(int tIndex = 0; tIndex < (readFile.size() - 1) / 6; tIndex++) 65 | { 66 | std::vector table; 67 | 68 | for(int lIndex = 1; lIndex < 7; lIndex++) 69 | { 70 | int index = tIndex * 6 + lIndex; 71 | if(readFile[index].empty()) 72 | continue; 73 | std::vector in; 74 | std::string input = replaceAll(readFile[index], " ", " "); 75 | extractNumbers(' ', &input, &in); 76 | 77 | for(int item : in) 78 | { 79 | //lIndex*5 + i 80 | table.push_back(item); 81 | } 82 | } 83 | 84 | boards.insert({tIndex, table}); 85 | 86 | } 87 | 88 | // Part 1 89 | auto part1Boards(boards); 90 | for(int i = 0; i < marker_numbers.size(); i++) 91 | { 92 | int item = marker_numbers[i]; 93 | marked.push_back(item); 94 | 95 | bool found = false; 96 | // Bingo = 5 in der Reihe 97 | if(i > 4) { 98 | int summa = test(&part1Boards, marked, true); 99 | if(summa != -1) 100 | { 101 | std::cout << summa * item << std::endl; 102 | found = true; 103 | } 104 | } 105 | if(found) 106 | break; 107 | } 108 | 109 | // Part2 110 | auto part2Boards(boards); 111 | for(int i = 0; i < marker_numbers.size(); i++) 112 | { 113 | int item = marker_numbers[i]; 114 | marked.push_back(item); 115 | 116 | bool found = false; 117 | // Bingo = 5 in der Reihe 118 | if(i > 4) { 119 | int summa = test(&part2Boards, marked, false); 120 | if(summa != -1) 121 | { 122 | std::cout << summa * item << std::endl; 123 | found = true; 124 | } 125 | } 126 | if(found) 127 | break; 128 | } 129 | 130 | return 0; 131 | } 132 | 133 | void extractNumbers(char delimiter, std::string *string, std::vector *writeTo) { 134 | std::string number; 135 | for(int i = 0; i < string->size(); ++i) 136 | { 137 | char c = string->at(i); 138 | if(c != delimiter) 139 | number+=c; 140 | if(c == delimiter || i == string->size() - 1) 141 | { 142 | if(!number.empty()) 143 | writeTo->push_back(std::stoi(number)); 144 | number = ""; 145 | } 146 | } 147 | } 148 | 149 | std::string replaceAll(std::string str, const std::string& from, const std::string& to) { 150 | size_t start_pos = 0; 151 | while((start_pos = str.find(from, start_pos)) != std::string::npos) { 152 | str.replace(start_pos, from.length(), to); 153 | start_pos += to.length(); 154 | } 155 | return str; 156 | } -------------------------------------------------------------------------------- /Day-04/kotlin/Amejonah1200/day4.kt: -------------------------------------------------------------------------------- 1 | import java.nio.file.Path 2 | import kotlin.io.path.readText 3 | 4 | class BingoCard(val card: List) { 5 | val marked = mutableSetOf() 6 | val bingos = mutableSetOf() 7 | 8 | fun mark(number: Int): Boolean { 9 | if (number !in card) return false 10 | marked.add(number) 11 | card.chunked(5).forEachIndexed { index, nbs -> if (nbs.all { it in marked }) bingos.add(10 + index) } 12 | for (x in 0..4) { 13 | if ((0..4).all { y -> card[y * 5 + x] in marked }) bingos.add(x) 14 | } 15 | return bingos.isNotEmpty() 16 | } 17 | 18 | fun score(): Int { 19 | return card.filter { it !in marked }.sum() * marked.last() 20 | } 21 | 22 | fun clone(): BingoCard { 23 | return BingoCard(card) 24 | } 25 | } 26 | 27 | fun main() { 28 | val input = Path.of("./inputs/day4.txt").readText() 29 | val numbers = Regex("""(?:\A|,)(\d+)""").findAll(input).map { it.groupValues[1].toInt() }.toList() 30 | val bingoCards = Regex(""" ?(\d+) +(\d+) +(\d+) +(\d+) +(\d+)""").findAll(input).chunked(5) { 31 | BingoCard(it.flatMap { it.groups.drop(1).map { it!!.value.toInt() } }) 32 | } 33 | println("Part 1: ${part1(numbers, bingoCards.map { it.clone() }.toList())}") 34 | println("Part 2: ${part2(numbers, bingoCards.map { it.clone() }.toList())}") 35 | } 36 | 37 | fun part1(numbers: List, bingoCards: List): Int { 38 | numbers.first { n -> bingoCards.any { it.mark(n) } } 39 | return bingoCards.filter { it.bingos.isNotEmpty() }.map { it.score() }.first() 40 | } 41 | 42 | fun part2(numbers: List, bingoCards: List): Int { 43 | return numbers.flatMap { n -> 44 | bingoCards.filter { it.bingos.isEmpty() }.filter { it.mark(n) } 45 | }.last().score() 46 | } 47 | -------------------------------------------------------------------------------- /Day-04/kotlin/Skyslycer/Day4.kt: -------------------------------------------------------------------------------- 1 | import java.nio.file.Files 2 | import java.nio.file.Paths 3 | 4 | fun main() { 5 | val instructions = Files.readAllLines(Paths.get("./inputs/day4/input.txt")).filter { it.isNotBlank() } 6 | val winnerNumbers = instructions[0].split(",").map { it.toInt() } 7 | val boards = mutableListOf() 8 | val winningBoards = mutableMapOf() 9 | 10 | var first = false 11 | 12 | var board: Board? = null 13 | var counter = 0 14 | 15 | instructions.subList(1, instructions.size).forEach { 16 | if (board == null) { 17 | board = Board(arrayOf(arrayOf(), arrayOf(), arrayOf(), arrayOf(), arrayOf())) 18 | } 19 | 20 | board!!.numbers[counter] = matchNumbers(it).toTypedArray() 21 | 22 | counter++ 23 | 24 | if (counter == 5) { 25 | counter = 0 26 | boards.add(board!!) 27 | board = null 28 | } 29 | } 30 | 31 | winnerNumbers.forEach outerForEach@ { number -> 32 | boards.forEach { loopBoard -> 33 | val uncalled = mutableListOf() 34 | 35 | loopBoard.numbers.forEach { arrayOfNumbers -> 36 | arrayOfNumbers.forEach { 37 | if (it.value == number || it.called) { 38 | it.called = true 39 | uncalled.remove(it) 40 | } else { 41 | uncalled.add(it) 42 | } 43 | } 44 | } 45 | 46 | if (checkBoard(loopBoard)) { 47 | if (winningBoards.containsKey(loopBoard)) { 48 | return@forEach 49 | } 50 | 51 | val sum = if (uncalled.isEmpty()) { 52 | 0 53 | } else { 54 | uncalled.map { it.value }.reduce { acc, number -> acc + number } 55 | } 56 | 57 | if (!first) { 58 | println("First solution: ${sum * number}") 59 | first = true 60 | } 61 | 62 | winningBoards[loopBoard] = sum * number 63 | 64 | return@forEach 65 | } 66 | } 67 | } 68 | 69 | println("Second solution: ${winningBoards.values.last()}") 70 | } 71 | 72 | fun matchNumbers(numbers: String): List { 73 | var subString = 0 74 | 75 | if (numbers.startsWith(" ")) { 76 | subString = 1 77 | } 78 | 79 | return numbers.substring(subString).split(" ").filter { it != " " && it != "" }.map { it.toInt() }.map { Number(false, it) } 80 | } 81 | 82 | fun checkBoard(board: Board): Boolean { 83 | board.numbers.forEach { row -> 84 | if (row.filter { it.called }.size == 5) { 85 | return true 86 | } 87 | } 88 | 89 | repeat(5) { outerIndex -> 90 | val column = mutableListOf() 91 | 92 | repeat(5) { innerIndex -> 93 | column.add(board.numbers[innerIndex][outerIndex]) 94 | } 95 | 96 | if (column.filter { it.called }.size == 5) { 97 | return true 98 | } 99 | } 100 | 101 | return false 102 | } 103 | 104 | class Board(val numbers: Array>) 105 | 106 | class Number(var called: Boolean, val value: Int) -------------------------------------------------------------------------------- /Day-04/python/RainbowDashLabs/day_4.py: -------------------------------------------------------------------------------- 1 | values: list[str] = [e.strip() for e in open("puzzle.txt") if e.strip()] 2 | numbers = [int(num) for num in values[0].split(",")] 3 | del values[0] 4 | 5 | 6 | class Board: 7 | def __init__(self, field): 8 | self.field = [[int(val) for val in row.split(r" ") if val] for row in field] 9 | self.checked = [[False for val in self.field[0]] for val in self.field] 10 | self.last_num = 0 11 | 12 | def __repr__(self): 13 | return f"Done: {self.is_done()}\n{self.field.__repr__()}\n{self.checked.__repr__()}" 14 | 15 | def _find_index(self, num): 16 | for row, content in enumerate(self.field): 17 | if num in content: 18 | return row, content.index(num) 19 | return None 20 | 21 | def get_checked_row(self, row): 22 | return list(self.checked[row]) 23 | 24 | def get_checked_col(self, col): 25 | return [row[col] for row in self.checked] 26 | 27 | def set(self, num): 28 | #if self.is_done(): 29 | # return True 30 | index = self._find_index(num) 31 | if index is None: 32 | return False 33 | self.last_num = num 34 | self.checked[index[0]][index[1]] = True 35 | return self._is_done_pos(index[0], index[1]) 36 | 37 | def _is_done_pos(self, row, col): 38 | col = self.get_checked_col(col) 39 | row = self.get_checked_row(row) 40 | return sum(col) == len(col) or sum(row) == len(row) 41 | 42 | def is_done(self): 43 | for i in range(len(self.field)): 44 | for j in range(len(self.field[0])): 45 | if self._is_done_pos(i, j): 46 | return True 47 | 48 | def get_unset_nums(self): 49 | unchecked = [] 50 | for i, row in enumerate(self.checked): 51 | for col, check in enumerate(self.checked[i]): 52 | if not check: 53 | unchecked.append(self.field[i][col]) 54 | 55 | return unchecked 56 | 57 | def score(self): 58 | return sum(self.get_unset_nums()) * self.last_num 59 | 60 | 61 | fields: list[list[str]] = [values[f:f + 5] for f in range(0, len(values), 5)] 62 | fields: list[Board] = [Board(field) for field in fields] 63 | 64 | 65 | 66 | def part_1(numbers, fields): 67 | for num in numbers: 68 | for index, board in enumerate(fields): 69 | if board.set(num): 70 | print(board.score()) 71 | return 72 | 73 | 74 | part_1(numbers, fields) 75 | 76 | 77 | fields: list[list[str]] = [values[f:f + 5] for f in range(0, len(values), 5)] 78 | fields: list[Board] = [Board(field) for field in fields] 79 | 80 | def part_2(numbers, boards): 81 | last = None 82 | for num in numbers: 83 | for index, board in enumerate(boards): 84 | if board.is_done(): 85 | continue 86 | if board.set(num): 87 | last = board 88 | print(last.score()) 89 | 90 | part_2(numbers, fields) 91 | -------------------------------------------------------------------------------- /Day-04/scala/SirYwell/day04.scala: -------------------------------------------------------------------------------- 1 | import scala.io.Source.fromFile 2 | 3 | @main def day04(filePath: String): Unit = { 4 | val input = fromFile(filePath).getLines().toList 5 | val numbers = input.head.split(",").map(_.toInt) 6 | val boardsRaw = for start <- Range(2, input.length, 6) yield { 7 | for i <- start until (start + 5) yield input(i).split(" ").filterNot(_.isEmpty).map(_.toInt).toList 8 | }.toList 9 | 10 | type BoardList = List[List[List[(Int, Boolean)]]] 11 | val filterLinewise = (_: BoardList).filter(!_.forall(!_.forall(_ (1)))) 12 | val sumWinner = ((b: BoardList, f: (Int => Unit)) => 13 | if b.nonEmpty then f(b.head.flatten.filterNot(_ (1)).map(_ (0)).sum)).curried 14 | 15 | var state = boardsRaw.toList.map(_.map(_.map(i => (i, false)))) 16 | for v <- numbers do { 17 | val shouldPrint = state.size == boardsRaw.size || state.size == 1 // first winner (part 1) || last winner (part 2) 18 | state = state.map(_.map(_.map(p => if p(0) == v then (p(0), true) else p))) 19 | val boardsWithWinningRow = filterLinewise(state) 20 | val rowWinner = sumWinner(boardsWithWinningRow) 21 | val boardsWithWinningColumn = filterLinewise(state.map(_.transpose)) 22 | val columnWinner = sumWinner(boardsWithWinningColumn) 23 | if shouldPrint then 24 | rowWinner(a => println("Found winning board row: %d".format(v * a))) 25 | columnWinner(a => println("Found winning board column: %d".format(v * a))) 26 | state = state.filterNot(b => boardsWithWinningRow.contains(b) || boardsWithWinningColumn.contains(b.transpose)) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Day-05/bqn/JohnnyJayJay/Day05.bqn: -------------------------------------------------------------------------------- 1 | # Line descriptor = list of starting and ending point, e.g. ⟨3‿9, 6‿9⟩ 2 | Direction ← ×-˜´ # For a line descriptor, return the directional vector 3 | Steps ← 1+(⌈´|∘-˜´) # For a line descriptor, return how steps are required to get from the former to the latter ("0th" step included) 4 | Points ← {(⊑𝕩)⊸+¨ (Direction 𝕩)⊸ר ↕Steps 𝕩} # For a line descriptor, return all the points the line traverses 5 | Straight ← ∨´=´ # Return 1 if a line is straight, 0 if it's diagonal 6 | # Collect all points all lines traverse, group by equality, filter out groups of only 1 point, count remaining 7 | PartTwo ← {+´ 2≤≠¨ ⊔⊐ ∾ Points¨ 𝕩} 8 | PartOne ← PartTwo∘(Straight¨/⊢) 9 | 10 | Parse ← •BQN¨('⟨'⊸∾∾⟜'⟩')¨∘((⊑⊐⟜' ') (↑⋈(+⟜4⊸↓))⊢) # "x1,y1 -> x2,y2" => ⟨x1‿y1, x2‿y2⟩ 11 | 12 | input ← Parse¨ •FLines ⊑ •args 13 | 14 | •Out PartOne input 15 | •Out PartTwo input 16 | -------------------------------------------------------------------------------- /Day-05/cpp/GameduJS/Day05.cpp: -------------------------------------------------------------------------------- 1 | #include "FileReader.h" 2 | #include "iostream" 3 | #include "algorithm" 4 | #include "cmath" 5 | #include "map" 6 | 7 | using namespace std; 8 | 9 | struct Point { 10 | int x; 11 | int y; 12 | }; 13 | 14 | struct Coordinate { 15 | Point pointFrom; 16 | Point pointTo; 17 | 18 | bool equalX() const 19 | { 20 | return pointFrom.x == pointTo.x; 21 | } 22 | 23 | bool equalY() const 24 | { 25 | return pointFrom.y == pointTo.y; 26 | } 27 | 28 | vector calculatePoints() const 29 | { 30 | vector points; 31 | int x1 = pointFrom.x; int x2 = pointTo.x; 32 | int y1 = pointFrom.y; int y2 = pointTo.y; 33 | 34 | // Horizontal 35 | if(equalX() || equalY()) 36 | { 37 | for(int i = min(pointFrom.x, pointTo.x); i <= max(pointFrom.x, pointTo.x); i++) 38 | { 39 | for(int j = min(pointFrom.y, pointTo.y); j <= max(pointFrom.y, pointTo.y); j++) 40 | { 41 | points.push_back(Point{i, j}); 42 | } 43 | } 44 | return points; 45 | } 46 | 47 | int interval = abs(y1 - y2); // Since when it's a diagonal the x and y interval is the same 48 | for(int i = 0; i <= interval; ++i) 49 | points.push_back({(x1 < x2) ? x1 + i : x1 - i, (y1 < y2) ? y1 + i : y1 - i}); 50 | return points; 51 | } 52 | 53 | }; 54 | 55 | vector split(string delimiter, string s); 56 | vector parseCoordinates(const vector& readFile); 57 | 58 | int part(const vector& coordinates, bool diagonal); 59 | void insertHeatMap(map, int>* heatMap, Coordinate* coordinate); 60 | 61 | int main() 62 | { 63 | FileReader fileReader("../shared/Puzzle.txt"); 64 | vector readFile = fileReader.readLines(); 65 | 66 | vector coordinates = parseCoordinates(readFile); 67 | 68 | cout << "Part 1: " << part(coordinates, false) << endl; 69 | cout << "Part 2: " << part(coordinates, true) << endl; 70 | 71 | return 0; 72 | } 73 | 74 | int part(const vector& coordinates, bool diagonal) 75 | { 76 | map, int> heatMap; 77 | for(Coordinate coordinate : coordinates) 78 | { 79 | if(diagonal) 80 | { 81 | insertHeatMap(&heatMap, &coordinate); 82 | continue; 83 | } 84 | 85 | if(coordinate.equalX() || coordinate.equalY()) 86 | { 87 | insertHeatMap(&heatMap, &coordinate); 88 | } 89 | } 90 | 91 | int a = 0; 92 | for(auto & it : heatMap) 93 | { 94 | if(it.second >= 2) 95 | a++; 96 | } 97 | 98 | return a; 99 | } 100 | 101 | void insertHeatMap(map, int>* heatMap, Coordinate* coordinate) 102 | { 103 | for(auto point : coordinate->calculatePoints()) { 104 | auto it = heatMap->find({point.x, point.y}); 105 | if(it != heatMap->end()) 106 | it->second=it->second+1; 107 | else 108 | heatMap->insert({{point.x, point.y}, 1}); 109 | } 110 | } 111 | 112 | vector split(string delimiter, string s) 113 | { 114 | size_t pos_start = 0, pos_end, delim_len = delimiter.length(); 115 | string token; 116 | vector res; 117 | 118 | while ((pos_end = s.find (delimiter, pos_start)) != string::npos) { 119 | token = s.substr (pos_start, pos_end - pos_start); 120 | pos_start = pos_end + delim_len; 121 | res.push_back (token); 122 | } 123 | 124 | res.push_back (s.substr (pos_start)); 125 | return res; 126 | } 127 | vector parseCoordinates(const vector& readFile) 128 | { 129 | vector coordinates; 130 | for(const auto& cords : readFile) 131 | { 132 | auto eachPoint = split(" -> ", cords); 133 | auto point1 = split(",", eachPoint[0]); 134 | auto point2 = split(",", eachPoint[1]); 135 | 136 | coordinates.push_back(Coordinate{stoi(point1[0]), stoi(point1[1]), stoi(point2[0]), stoi(point2[1])}); 137 | } 138 | 139 | return coordinates; 140 | } 141 | -------------------------------------------------------------------------------- /Day-05/kotlin/Amejonah1200/day5.kt: -------------------------------------------------------------------------------- 1 | import java.nio.file.Path 2 | import kotlin.io.path.readText 3 | import kotlin.math.absoluteValue 4 | 5 | data class Point(val x: Int, val y: Int) 6 | class Line(val start: Point, val end: Point) { 7 | fun points(): List { 8 | val (x1, y1) = start 9 | val (x2, y2) = end 10 | return if (y1 == y2) { 11 | (if (x1 < x2) x1..x2 else x1 downTo x2).map { Point(it, y1) } 12 | } else if (x1 == x2) { 13 | (if (y1 < y2) y1..y2 else y1 downTo y2).map { Point(x1, it) } 14 | } else (0..(x2 - x1).absoluteValue).map { Point(if (x1 < x2) x1 + it else x1 - it, if (y1 < y2) y1 + it else y1 - it) } 15 | 16 | } 17 | 18 | override fun toString(): String { 19 | return "${start.x},${start.y} -> ${end.x},${end.y}" 20 | } 21 | 22 | fun isVertical() = start.x == end.x 23 | fun isHorizontal() = start.y == end.y 24 | } 25 | 26 | fun main() { 27 | val lines = Regex("""(\d+),(\d+) -> (\d+),(\d+)""").findAll( 28 | Path.of("./inputs/day5.txt").readText() 29 | ).map { it.destructured }.map { (x, y, x2, y2) -> Line(Point(x.toInt(), y.toInt()), Point(x2.toInt(), y2.toInt())) }.toList() 30 | println("Part 1: ${part1(lines)}") 31 | println("Part 2: ${part2(lines)}") 32 | } 33 | 34 | fun part1(lines: List) = heatMap(lines.filter { it.isVertical() || it.isHorizontal() }).filter { it.value >= 2 }.count() 35 | fun part2(lines: List) = heatMap(lines).filter { it.value >= 2 }.count() 36 | 37 | fun heatMap(lines: List): Map { 38 | val points = mutableMapOf() 39 | for (line in lines) { 40 | line.points().forEach { point -> 41 | points[point] = points.getOrDefault(point, 0) + 1 42 | } 43 | } 44 | return points 45 | } 46 | -------------------------------------------------------------------------------- /Day-05/python/RainbowDashLabs/day_5.py: -------------------------------------------------------------------------------- 1 | from typing import Callable, Union 2 | 3 | 4 | class Point: 5 | def __init__(self, x, y): 6 | self.x = int(x) 7 | self.y = int(y) 8 | 9 | def __repr__(self): 10 | return f"{self.x},{self.y}" 11 | 12 | def __sub__(self, other: Union["Point", int, float]): 13 | if isinstance(other, Point): 14 | return Point(self.x - other.x, self.y - other.y) 15 | return Point(self.x - other, self.y - other) 16 | 17 | def __add__(self, other: Union["Point", int, float]): 18 | if isinstance(other, Point): 19 | return Point(self.x + other.x, self.y + other.y) 20 | return Point(self.x + other, self.y + other) 21 | 22 | def __mul__(self, other: Union["Point", int, float]): 23 | if isinstance(other, Point): 24 | return Point(self.x * other.x, self.y * other.y) 25 | return Point(self.x * other, self.y * other) 26 | 27 | def between(self, point: "Point"): 28 | direction = point - self 29 | steps = (abs(direction.x) / (direction.x or 1), abs(direction.y) / (direction.y or 1)) 30 | max_range = max((abs(direction.x)) + 1, (abs(direction.y)) + 1) 31 | return [self + (Point(steps[0], steps[1]) * x) for x in range(max_range)] 32 | 33 | def is_diagonal(self, other): 34 | return not (self.x == other.x or self.y == other.y) 35 | 36 | def __eq__(self, other): 37 | return self.x == other.x and self.y == other.y 38 | 39 | def __hash__(self): 40 | return hash((self.x, self.y)) 41 | 42 | 43 | class Line: 44 | def __init__(self, line: str): 45 | coords: list[list[str]] = [e.split(",") for e in line.split(" -> ")] 46 | self.start = Point(coords[0][0], coords[0][1]) 47 | self.end = Point(coords[1][0], coords[1][1]) 48 | 49 | def __repr__(self): 50 | return f"{self.start} -> {self.end} | Diagonal {self.is_diagonal()} | Points {self.points()}" 51 | 52 | def points(self): 53 | return self.start.between(self.end) 54 | 55 | def is_diagonal(self): 56 | return self.start.is_diagonal(self.end) 57 | 58 | 59 | class Map: 60 | def __init__(self): 61 | self.coords = {} 62 | 63 | def add(self, point: Point): 64 | if point in self.coords: 65 | self.coords[point] += 1 66 | else: 67 | self.coords[point] = 1 68 | 69 | def add_all(self, lines: list[Line], predicate: Callable[[Line], bool] = lambda x: True): 70 | for line in lines: 71 | if not predicate(line): 72 | continue 73 | for point in line.points(): 74 | self.add(point) 75 | 76 | def __iter__(self): 77 | return self.coords.items().__iter__() 78 | 79 | def count(self, predicate: Callable[[Point, int], bool]): 80 | return len([v for k, v in self if predicate(k, v)]) 81 | 82 | 83 | lines = [Line(e) for e in open("puzzle.txt") if e.strip()] 84 | 85 | my_map = Map() 86 | my_map.add_all(lines, lambda point: not point.is_diagonal()) 87 | 88 | print(f"Part one {my_map.count(lambda k, v: v > 1)}") 89 | 90 | my_map = Map() 91 | my_map.add_all(lines) 92 | 93 | print(f"Part two {my_map.count(lambda k, v: v > 1)}") 94 | -------------------------------------------------------------------------------- /Day-05/scala/SirYwell/day05.scala: -------------------------------------------------------------------------------- 1 | import scala.io.Source.fromFile 2 | 3 | @main def day05(filePath: String): Unit = { 4 | val input = fromFile(filePath).getLines() 5 | .map(_.split(" -> ")) 6 | .map(a => a.map(_.split(",")).map(b => (b(0).toInt, b(1).toInt))) 7 | .map(a => (a(0), a(1))) 8 | .toList 9 | 10 | val step = (a: Int, b: Int) => if a == b then 0 else if a < b then 1 else -1 11 | val linesToCount = (lines: List[((Int, Int), (Int, Int))]) => lines.flatMap { case ((x1, y1), (x2, y2)) => 12 | val xStep = step(x1, x2) 13 | val yStep = step(y1, y2) 14 | for s <- 0 to Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)) yield (x1 + s * xStep, y1 + s * yStep) 15 | }.groupBy(identity).mapValues(_.size).count(_ (1) >= 2) 16 | 17 | println(s"Part 1: ${linesToCount(input.filter { case ((x1, y1), (x2, y2)) => x1 == x2 || y1 == y2 })}") 18 | println(s"Part 2: ${linesToCount(input)}") 19 | } 20 | -------------------------------------------------------------------------------- /Day-06/bqn/JohnnyJayJay/Day06.bqn: -------------------------------------------------------------------------------- 1 | Parse ← •BQN¨ ','((⊢-˜+`׬)∘=⊔⊢)⊑ # Turn list of input lines into list of lanternfish timers 2 | 3 | # 256 (+9) length array, where each element represents the fish count after that day (index) 4 | # when starting with a single fish whose reproduction timer is at 6. 5 | # E.g. the element at index 7 represents the amount of lanternfish after 7 days (2 fish). 6 | fish ← {𝕩∾+´¯7‿¯9⊏𝕩}⍟256 1+/7‿2 7 | # For a list of fish timers 𝕩 and a number of days 𝕨, calculate the cumulative amount of fish after that number of days. 8 | Count ← +´ (⊏⟜fish)∘(6+-) 9 | 10 | input ← Parse •FLines ⊑ •args 11 | •Out 80 Count input 12 | •Out 256 Count input 13 | -------------------------------------------------------------------------------- /Day-06/clojure/JohnnyJayJay/Day06.clj: -------------------------------------------------------------------------------- 1 | (ns Day06 2 | (:require [clojure.string :as str])) 3 | 4 | (def fish 5 | (lazy-cat (repeat 7 1) [2 2] (map + fish (drop 2 fish)))) 6 | 7 | 8 | (defn fish-count [days init-timer] 9 | (nth fish (+ days (- 6 init-timer)))) 10 | 11 | (defn solve [days timers] 12 | (reduce + (map (partial fish-count days) timers))) 13 | 14 | (defn parse [file] 15 | (map #(Long/parseLong %) (-> file slurp str/trim (str/split #",")))) 16 | 17 | (let [input (parse (first *command-line-args*))] 18 | (println (solve 80 input)) 19 | (println (solve 256 input))) 20 | -------------------------------------------------------------------------------- /Day-06/cpp/GameduJS/Day06.cpp: -------------------------------------------------------------------------------- 1 | #include "iostream" 2 | #include "FileReader.h" 3 | #include "map" 4 | 5 | using namespace std; 6 | 7 | vector split(const string& delimiter, const string& s); 8 | unsigned long long cycleDays(int daysToPass, map* fishMap); 9 | 10 | int main() 11 | { 12 | FileReader fileReader("../shared/Puzzle.txt"); 13 | vector input = fileReader.readLines(); 14 | 15 | // Internal Time, Count of fishes 16 | map baseFishes; 17 | for(int i = 0; i < 9; i++) 18 | baseFishes.insert({i, 0l}); 19 | 20 | for(const auto& inputLine : input) 21 | for(const auto& internalTime : split(",", inputLine)) 22 | { 23 | int itnTime = stoi(internalTime); 24 | auto it = baseFishes.find(itnTime); 25 | 26 | if(it != baseFishes.end()) 27 | it->second = it->second+1; 28 | else 29 | baseFishes.insert({itnTime, 1}); 30 | } 31 | auto part1Map(baseFishes); 32 | cout << "Part 1: " << cycleDays(80, &part1Map) << endl; 33 | cout << "Part 2: " << cycleDays(256, &baseFishes) << endl; 34 | 35 | 36 | return 0; 37 | } 38 | 39 | unsigned long long cycleDays(int daysToPass, map* fishMap) 40 | { 41 | if(daysToPass == 0) // Sum all fishes 42 | { 43 | unsigned long long a = 0; 44 | for(auto & fish : *fishMap) 45 | { 46 | a+=fish.second; 47 | } 48 | return a; 49 | } 50 | 51 | unsigned long long fishToSpawn = fishMap->find(0)->second; 52 | 53 | for(int i = 0; i < 8; ++i) { 54 | fishMap->find(i)->second = fishMap->find(i + 1)->second; 55 | } 56 | 57 | fishMap->find(6)->second +=fishToSpawn; 58 | fishMap->find(8)->second = fishToSpawn; 59 | 60 | return cycleDays(daysToPass - 1, fishMap); 61 | } 62 | 63 | vector split(const string& delimiter, const string& s) 64 | { 65 | size_t pos_start = 0, pos_end, delim_len = delimiter.length(); 66 | string token; 67 | vector res; 68 | 69 | while ((pos_end = s.find (delimiter, pos_start)) != string::npos) { 70 | token = s.substr (pos_start, pos_end - pos_start); 71 | pos_start = pos_end + delim_len; 72 | res.push_back (token); 73 | } 74 | 75 | res.push_back (s.substr (pos_start)); 76 | return res; 77 | } -------------------------------------------------------------------------------- /Day-06/java/B33fb0n3/day6.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class MyClass { 5 | private static ArrayList fishes; 6 | 7 | public static void main(String args[]) { 8 | int day = 1; 9 | fishes = new ArrayList<>(Arrays.asList(args)); 10 | for(int i = 0; i < 256; i++) { // bzw. hier 80 für Part 1 11 | removeOne(); 12 | day++; 13 | } 14 | System.out.println("After "+(day-1)+" day: " + fishes.size()); 15 | } 16 | 17 | private static void removeOne() { 18 | for(int i = 0; i < fishes.size(); i++) { 19 | int fishI = Integer.parseInt(fishes.get(i)); 20 | int newTime = fishI - 1; 21 | if(newTime < 0) { 22 | fishes.set(i, String.valueOf(6)); 23 | fishes.add(String.valueOf(9)); 24 | continue; 25 | } 26 | fishes.set(i, String.valueOf(newTime)); 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Day-06/kotlin/Amejonah1200/day6.kt: -------------------------------------------------------------------------------- 1 | import java.nio.file.Path 2 | import kotlin.io.path.readText 3 | 4 | fun main() { 5 | val initialState = Path.of("./inputs/day6.txt").readText() 6 | .split(",").groupBy { it.trim().toLong() }.mapValues { it.value.size.toLong() } 7 | println("Part 1: ${live(80, initialState).map { it.value }.sum()}") 8 | println("Part 2: ${live(256, initialState).map { it.value }.sum()}") 9 | } 10 | 11 | fun live(days: Long, state: Map): Map { 12 | if (days == 0L) return state 13 | return live(days - 1, 14 | buildMap { 15 | val new = state.mapKeys { it.key - 1 } 16 | val pregnants = new.getOrDefault(-1, 0) 17 | putAll(new.filter { it.key >= 0 }) 18 | put(8, pregnants) 19 | put(6, pregnants + getOrDefault(6, 0)) 20 | } 21 | ) 22 | } 23 | 24 | -------------------------------------------------------------------------------- /Day-06/python/RainbowDashLabs/day_6.py: -------------------------------------------------------------------------------- 1 | class Ocean: 2 | def __init__(self, breed_rate, mature_delay, fishes: list[int] = None): 3 | self.breed_rate = breed_rate 4 | self.mature_delay = mature_delay 5 | self.new_breed_rate = breed_rate + mature_delay 6 | self.fishes = {} 7 | if fishes: 8 | self.set_fishes(fishes) 9 | 10 | def set_fishes(self, fishes: list[int]): 11 | self.clear() 12 | for fish in fishes: 13 | self.add_fish(fish) 14 | 15 | def add_fish(self, day: int, amount: int = 1): 16 | if day in self.fishes: 17 | self.fishes[day] += amount 18 | else: 19 | self.fishes[day] = amount 20 | 21 | def next_day(self): 22 | old_fishes = self.fishes 23 | self.clear() 24 | for day, amount in old_fishes.items(): 25 | if day == 0: 26 | self.add_fish(self.breed_rate, amount) 27 | self.add_fish(self.new_breed_rate, amount) 28 | continue 29 | self.add_fish(day - 1, amount) 30 | 31 | def progress_days(self, days): 32 | for day in range(days): 33 | self.next_day() 34 | 35 | def fish_count(self): 36 | return sum(self.fishes.values()) 37 | 38 | def clear(self): 39 | self.fishes = {} 40 | 41 | 42 | nums = [int(e) for e in open("puzzle.txt").read().split(",")] 43 | 44 | ocean = Ocean(6, 2) 45 | 46 | ocean.set_fishes(nums) 47 | ocean.progress_days(80) 48 | print(f"Part one {ocean.fish_count()}") 49 | 50 | ocean.progress_days(256 - 80) 51 | print(f"Part two {ocean.fish_count()}") 52 | -------------------------------------------------------------------------------- /Day-06/python/stnwtr/day06.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | def grow(fish, amount): 5 | return {8: amount, 6: amount, 0: -amount} if fish == 0 else {fish: -amount, fish - 1: amount} 6 | 7 | 8 | def calculate(initial_fish, days): 9 | fish_counter = Counter(initial_fish) 10 | for _ in range(days): 11 | for fish in {*fish_counter.items()}: 12 | fish_counter.update(grow(*fish)) 13 | return sum(fish_counter.values()) 14 | 15 | 16 | def main(): 17 | with open('input/06.txt', 'r') as f: 18 | initial_fish = list(map(int, f.read().split(','))) 19 | print(calculate(initial_fish, 80)) 20 | print(calculate(initial_fish, 256)) 21 | 22 | 23 | if __name__ == '__main__': 24 | main() 25 | -------------------------------------------------------------------------------- /Day-06/rust/zFlxw/main.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | 3 | fn main() { 4 | // File input 5 | let content_string: String = fs::read_to_string("./input.txt").unwrap(); 6 | 7 | // Part 1 - Works with the second method as well, but this was my first try and I didn't want to just discard it. 8 | // (But it's still slow as hell) 9 | calculate_fishes(80, &content_string); 10 | 11 | // Part 2 12 | // technically works, but takes forever and the length of a vector is just too short. 13 | // calculate_fishes(256, &content_string); 14 | // This method is way faster. 15 | calculate_fishs_but_fast(256, &content_string); 16 | } 17 | 18 | fn calculate_fishes(days: u16, content_string: &String) { 19 | let lantern_fishs: &mut Vec = &mut vec![]; 20 | // Map and store values in vector 21 | content_string.split(",").map(|num_str| num_str.parse::().unwrap()).for_each(|num| { 22 | lantern_fishs.push(num); 23 | }); 24 | 25 | // days to calculate the fishs for 26 | for i in 1..=days { 27 | for fish_index in 0..lantern_fishs.len() { 28 | let fish_timer = lantern_fishs[fish_index]; 29 | let mut new_timer = fish_timer - 1; 30 | if new_timer < 0 { 31 | new_timer = 6; 32 | lantern_fishs.push(8); 33 | } 34 | 35 | lantern_fishs[fish_index] = new_timer; 36 | } 37 | 38 | println!("Day {}: ({})", i, lantern_fishs.len()); 39 | } 40 | } 41 | 42 | fn calculate_fishs_but_fast(days: u16, content_string: &String) { 43 | let mut num_state = [0 as u64; 9]; 44 | for n in content_string.split(",").map(|num_str| num_str.parse::().unwrap()) { 45 | num_state[n] += 1; 46 | } 47 | 48 | for day in 0..days { 49 | let spawn = num_state[0]; 50 | for i in 0..=7 { 51 | num_state[i] = num_state[i + 1]; 52 | } 53 | 54 | num_state[6] += spawn; 55 | num_state[8] = spawn; 56 | 57 | println!("Day {}: {}", day, num_state.into_iter().fold(0, |acc, n| acc + n)); 58 | } 59 | } -------------------------------------------------------------------------------- /Day-06/scala/SirYwell/day06.scala: -------------------------------------------------------------------------------- 1 | import scala.collection.mutable.Queue 2 | import scala.io.Source.fromFile 3 | 4 | @main def day06(filePath: String): Unit = { 5 | val input = fromFile(filePath).getLines().toList.head.split(",").map(_.toInt).toList 6 | 7 | val map = input.groupBy(_ % 7).view.mapValues(_.length.toLong) 8 | var state = (0 to 7).map(i => map.getOrElse(i, 0L)) 9 | val toAdd = new Queue[Long]() 10 | (0 to 8).foreach(i => toAdd += 0) 11 | for day <- 0 until 256 do 12 | state = state.zipWithIndex.map { case (l, i) => l + (if day % 7 == i then toAdd.dequeue() else 0) } 13 | toAdd += state(day % 7) 14 | if day == 79 || day == 255 then println(s"Population after ${day + 1} days: ${state.sum + toAdd.sum}") 15 | } 16 | -------------------------------------------------------------------------------- /Day-07/bqn/JohnnyJayJay/Day07.bqn: -------------------------------------------------------------------------------- 1 | Prefix ← 1⊸+⊸ט÷2˙ # n(n+1)/2. Distance -> Fuel function for part 2 2 | # Minimum fuel needed, given a function 𝔽 that defines the fuel needed to move a given distance and a list of crab positions 𝕩. 3 | _fuel ← {⌊´+´𝔽¨|(↕1+⌈´𝕩)⊸-¨ 𝕩} 4 | Parse ← •BQN¨ ','((⊢-˜+`׬)∘=⊔⊢)⊑ 5 | input ← Parse •FLines ⊑ •args 6 | •Out ⊢_fuel input 7 | •Out Prefix _fuel input 8 | -------------------------------------------------------------------------------- /Day-07/cpp/GameduJS/Day07.cpp: -------------------------------------------------------------------------------- 1 | #include "FileReader.h" 2 | #include "iostream" 3 | #include "cmath" 4 | 5 | using namespace std; 6 | 7 | int calc_fuel(const vector& positions, int max_pos, bool crabEngineering); 8 | 9 | int main() 10 | { 11 | FileReader fileReader("../shared/Puzzle.txt"); 12 | 13 | vector input; 14 | int max_pos = 0; 15 | for(const string & line : fileReader.readLines()) 16 | for(const string & rawNumber : fileReader.split(",", line)) 17 | { 18 | int a = stoi(rawNumber); 19 | input.push_back(a); 20 | max_pos = max(a, max_pos); 21 | } 22 | 23 | cout << "Part 1: " << calc_fuel(input, max_pos, false) << endl; 24 | cout << "Part 2: " << calc_fuel(input, max_pos, true) << endl; 25 | 26 | return 0; 27 | } 28 | 29 | int calc_fuel(const vector& positions, int max_pos, bool crabEngineering) 30 | { 31 | int fuel = 0; 32 | for(int i = 0; i < max_pos; i++) 33 | { 34 | int fuelUsed = 0; 35 | for (const auto &pos: positions) 36 | { 37 | int baseFuelUsed = abs(pos - i); 38 | 39 | if(crabEngineering) 40 | { 41 | for(int j = 1; j < baseFuelUsed + 1; ++j) 42 | fuelUsed+=j; 43 | } else 44 | { 45 | fuelUsed+=baseFuelUsed; 46 | } 47 | } 48 | fuel = fuel == 0 ? fuelUsed : min(fuelUsed, fuel); 49 | } 50 | 51 | return fuel; 52 | } 53 | -------------------------------------------------------------------------------- /Day-07/java/B33fb0n3/part1.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | import java.util.*; 4 | 5 | 6 | 7 | public class MyClass { 8 | 9 | public static void main(String args[]) { 10 | 11 | List fuel = new ArrayList<>(); 12 | 13 | int maxValue = -1; 14 | 15 | for(String arg : args[0].split(",")) { 16 | 17 | int value = Integer.parseInt(arg); 18 | 19 | if(maxValue < value) 20 | maxValue = value; 21 | 22 | fuel.add(value); 23 | 24 | } 25 | 26 | int minLostFuel = Integer.MAX_VALUE; 27 | 28 | for(int i = 1; i < maxValue; i++) { 29 | 30 | int positionLostFuel = 0; 31 | 32 | for(int f = 0; f < fuel.size(); f++) { 33 | 34 | // hier passieren die Steps; 35 | 36 | int minus = fuel.get(f) - i; 37 | 38 | if(minus < 0) 39 | minus = minus / -1; 40 | 41 | positionLostFuel += minus; 42 | 43 | } 44 | 45 | if(positionLostFuel < minLostFuel) 46 | minLostFuel = positionLostFuel; 47 | 48 | } 49 | 50 | System.out.println(minLostFuel + " | Answer"); 51 | 52 | } 53 | 54 | } -------------------------------------------------------------------------------- /Day-07/java/B33fb0n3/part2.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | import java.util.*; 4 | 5 | 6 | 7 | public class MyClass { 8 | 9 | public static void main(String args[]) { 10 | 11 | List fuel = new ArrayList<>(); 12 | 13 | int maxValue = -1; 14 | 15 | for(String arg : args[0].split(",")) { 16 | 17 | int value = Integer.parseInt(arg); 18 | 19 | if(maxValue < value) 20 | maxValue = value; 21 | 22 | fuel.add(value); 23 | 24 | } 25 | 26 | int minLostFuel = Integer.MAX_VALUE; 27 | 28 | for(int i = 1; i < maxValue; i++) { 29 | 30 | int positionLostFuel = 0; 31 | 32 | for(int f = 0; f < fuel.size(); f++) { 33 | int minus = fuel.get(f) - i; 34 | 35 | if(minus < 0) 36 | minus = minus / -1; 37 | 38 | int currentCosts = 1; 39 | int fuelCosts = 0; 40 | for(int step = 0; step < minus; step++) { 41 | fuelCosts += currentCosts; 42 | currentCosts++; 43 | } 44 | 45 | positionLostFuel += fuelCosts; 46 | 47 | } 48 | 49 | if(positionLostFuel < minLostFuel) 50 | minLostFuel = positionLostFuel; 51 | 52 | } 53 | 54 | System.out.println(minLostFuel + " | Answer"); 55 | 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /Day-07/python/RainbowDashLabs/day_7.py: -------------------------------------------------------------------------------- 1 | from typing import Callable 2 | from time import time_ns as time 3 | 4 | def calc_fuel(center: int, distances: list[int], cost: Callable[[int], int] = lambda x: x * 1): 5 | return sum([cost(abs(center - distance)) for distance in distances]) 6 | 7 | 8 | nums = [int(e) for e in open("puzzle.txt").read().split(",")] 9 | nums.sort() 10 | # We ignore the first and last third. It is very unlikely that we find the result there. 11 | lower_bound = nums[int(len(nums) / 3)] 12 | upper_bound = nums[len(nums) - int(len(nums) / 3)] 13 | 14 | start = time() 15 | # Part 1 solved by brute force 16 | costs = min([calc_fuel(num, nums) for num in range(lower_bound, upper_bound)]) 17 | print(f"Part 1 {costs} in {(time() - start) / 1000000} ms") 18 | 19 | start = time() 20 | # Precompute costs for faster calculation. 75 times faster. 21 | cost_list = [sum(range(num + 1)) for num in range(min(nums), max(nums))] 22 | costs = min([calc_fuel(num, nums, lambda x: cost_list[x]) for num in range(lower_bound, upper_bound)]) 23 | 24 | print(f"Part 2 {costs} in {(time() - start) / 1000000} ms") 25 | -------------------------------------------------------------------------------- /Day-07/python/stnwtr/day07.py: -------------------------------------------------------------------------------- 1 | def calculate(positions, mapper): 2 | return min(map(mapper, [[abs(x - pos) for x in positions] for pos in range(min(positions), max(positions))])) 3 | 4 | 5 | def main(): 6 | with open('input/07.txt', 'r') as f: 7 | positions = list(map(int, f.read().split(','))) 8 | print(calculate(positions, lambda x: sum(x))) 9 | print(calculate(positions, lambda x: sum(y * (y + 1) // 2 for y in x))) 10 | 11 | 12 | if __name__ == '__main__': 13 | main() 14 | -------------------------------------------------------------------------------- /Day-07/rust/zFlxw/main.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | 3 | fn main() { 4 | // File input 5 | let content_string: String = fs::read_to_string("./input.txt").unwrap(); 6 | let contents: Vec<&str> = content_string.lines().collect(); 7 | 8 | let positions: Vec = content_string.split(",").map(|s| s.parse::().unwrap()).collect(); 9 | println!("Num: {}", calc_lowest_fuel(true, &positions)); 10 | } 11 | 12 | fn calc_lowest_fuel(incr: bool, positions: &Vec) -> isize { 13 | let mut current_lowest: isize = isize::MAX; 14 | let highest_num: isize = positions.clone().into_iter().max().unwrap(); 15 | 16 | for i in 0..=highest_num { 17 | let fuel = calc_fuel(incr, i, &positions); 18 | // I don't know why, but if I remove this line of code, it doesn't finish at all. HOW? 19 | println!("{}: {}", i, fuel); 20 | if current_lowest > fuel { 21 | current_lowest = fuel; 22 | } 23 | } 24 | 25 | current_lowest 26 | } 27 | 28 | fn calc_fuel(incr: bool, pos: isize, positions: &Vec) -> isize { 29 | let mut fuel: isize = 0; 30 | for i in 0..positions.len() { 31 | let from_pos = positions[i]; 32 | let diff = isize::abs(from_pos - pos); 33 | fuel += diff; 34 | 35 | if incr { 36 | // Part 2 37 | for j in 0..diff { 38 | fuel += j; 39 | } 40 | } 41 | } 42 | 43 | fuel 44 | } 45 | -------------------------------------------------------------------------------- /Day-08/clojure/JohnnyJayJay/Day08.clj: -------------------------------------------------------------------------------- 1 | (ns Day08 2 | (:require [clojure.set :as sets] 3 | [clojure.string :as str])) 4 | 5 | (def signals (set "abcdefg")) 6 | 7 | (def steps (map set ["cf" "acf" "bcdf" "adg" "abfg"])) 8 | 9 | (def numbers ["abcefg" "cf" "acdeg" "acdfg" "bcdf" "abdfg" "abdefg" "acf" "abcdefg" "abcdfg"]) 10 | 11 | (def signal->number 12 | (zipmap (map set numbers) (range))) 13 | 14 | (def init (zipmap signals (repeat signals))) 15 | 16 | (defn candidate-update [cand-map [affected cand-update]] 17 | (reduce-kv (fn [cand-map char _] 18 | (update cand-map char (if (contains? affected char) sets/intersection sets/difference) cand-update)) 19 | cand-map 20 | cand-map)) 21 | 22 | (defn candidates->translation [cand-map] 23 | (into {} (map (juxt (comp first second) first) cand-map))) 24 | 25 | (defn decode-digits [patterns signals] 26 | (let [trans (->> patterns 27 | (map set) 28 | (group-by count) 29 | vals 30 | (sort-by (comp count first)) 31 | (map (partial apply sets/intersection)) 32 | (map vector steps) 33 | (reduce candidate-update init) 34 | candidates->translation)] 35 | (->> signals 36 | (map (partial map trans)) 37 | (map (comp signal->number set))))) 38 | 39 | (defn part-one [decoded-signals] 40 | (->> decoded-signals 41 | (mapcat identity) 42 | (filter #{1 4 7 8}) 43 | count)) 44 | 45 | (def dec-powers (map #(int (Math/pow 10 %)) (range))) 46 | 47 | (defn part-two [decoded-signals] 48 | (->> decoded-signals 49 | (map reverse) 50 | (map (partial map * dec-powers)) 51 | (map (partial reduce +)) 52 | (reduce +))) 53 | 54 | (defn parse-input-line [line] 55 | (map #(str/split % #" ") (str/split line #" \| "))) 56 | 57 | (let [input (map parse-input-line (str/split-lines (slurp (first *command-line-args*)))) 58 | decoded (map (partial apply decode-digits) input)] 59 | (println (part-one decoded)) 60 | (println (part-two decoded))) 61 | -------------------------------------------------------------------------------- /Day-08/java/B33fb0n3/part1.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | import java.util.*; 4 | 5 | 6 | 7 | public class MyClass { 8 | 9 | public static void main(String args[]) { 10 | 11 | int answer = 0; 12 | 13 | Scanner s = new Scanner(System.in); 14 | 15 | s.useDelimiter("\n"); 16 | 17 | int ones = 0; 18 | 19 | int sevens = 0; 20 | 21 | int fours = 0; 22 | 23 | int eights = 0; 24 | 25 | while(s.hasNext()){ 26 | 27 | String line = s.next(); 28 | 29 | String argsAfter = line.split("\\|")[1]; 30 | 31 | String[] split = argsAfter.split(" "); 32 | 33 | for(int i = 1; i < split.length; i++) { 34 | 35 | String teil = split[i]; 36 | 37 | String[] letters = teil.split(""); 38 | 39 | switch(letters.length) { 40 | 41 | case 2: 42 | 43 | ones++; 44 | 45 | break; 46 | 47 | case 3: 48 | 49 | sevens++; 50 | 51 | break; 52 | 53 | case 4: 54 | 55 | fours++; 56 | 57 | break; 58 | 59 | case 7: 60 | 61 | eights++; 62 | 63 | break; 64 | 65 | } 66 | 67 | } 68 | 69 | } 70 | answer = ones + sevens + fours + eights; 71 | System.out.println("Answer: " + answer); 72 | 73 | } 74 | 75 | } -------------------------------------------------------------------------------- /Day-08/python/RainbowDashLabs/day_8.py: -------------------------------------------------------------------------------- 1 | class Panel: 2 | _panel = { 3 | "abcefg": 0, 4 | "cf": 1, 5 | "acdeg": 2, 6 | "acdfg": 3, 7 | "bcdf": 4, 8 | "abdfg": 5, 9 | "abdefg": 6, 10 | "acf": 7, 11 | "abcdefg": 8, 12 | "abcdfg": 9 13 | } 14 | 15 | def __init__(self, input: str): 16 | input = input.split(" | ") 17 | self.pattern = input[0].split(" ") 18 | self.output = [x.strip() for x in input[1].split(" ")] 19 | self.mapping = {} 20 | self.build_map() 21 | 22 | def num(self, length: int): 23 | return [x for x in self.pattern if len(x) == length][0] 24 | 25 | def add_mapping(self, curr: str, original: str): 26 | self.mapping[curr] = original 27 | 28 | def map(self, curr) -> int: 29 | return self._panel[("".join(sorted([self.mapping[x] for x in curr])))] 30 | 31 | def remove_mapped(self, pattern: str): 32 | return "".join([x for x in pattern if x not in self.mapping]) 33 | 34 | def char_count(self): 35 | chars = list("".join(self.pattern)) 36 | return {chars.count(x): x for x in chars} 37 | 38 | def build_map(self): 39 | counts = self.char_count() 40 | self.add_mapping(counts[9], "f") 41 | self.add_mapping(counts[4], "e") 42 | self.add_mapping(counts[6], "b") 43 | 44 | self.add_mapping(self.remove_mapped(self.num(2)), "c") 45 | self.add_mapping(self.remove_mapped(self.num(4)), "d") 46 | self.add_mapping(self.remove_mapped(self.num(3)), "a") 47 | self.add_mapping(self.remove_mapped(self.num(7)), "g") 48 | 49 | def transformed_output(self) -> list[int]: 50 | return [self.map(x) for x in self.output] 51 | 52 | 53 | panels = [Panel(e) for e in open("puzzle.txt").readlines()] 54 | 55 | nums = [] 56 | for panel in panels: 57 | nums = nums + panel.transformed_output() 58 | 59 | print(f"Part one {nums.count(1) + nums.count(4) + nums.count(7) + nums.count(8)}") 60 | 61 | nums = [int("".join(map(str, panel.transformed_output()))) for panel in panels] 62 | 63 | print(f"Part two {sum(nums)}") 64 | -------------------------------------------------------------------------------- /Day-08/python/stnwtr/day08.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | from collections import Counter 3 | 4 | """ 5 | +---+---------------+-----------------------------------------------------------+ 6 | | | A B C D E F G | len order explanation | 7 | +---+---------------+-----------------------------------------------------------+ 8 | | 1 | A B - - - - - | 2 1 only 2 segments | 9 | | 7 | A B - D - - - | 3 2 only 3 segments | 10 | | 4 | A B - - E F - | 4 3 only 4 segments | 11 | | 2 | A - C D - F G | 5 10 last one with 5 segments | 12 | | 3 | A B C D - F - | 5 5 5 segments and both from 1 | 13 | | 5 | - B C D E F - | 5 9 5 segments and 6/9 contains all | 14 | | 0 | A B C D E - G | 6 8 last one with 6 segments | 15 | | 6 | - B C D E F G | 6 6 6 segments and only one from 1 | 16 | | 9 | A B C D E F - | 6 7 6 segments and all from 3 | 17 | | 8 | A B C D E F G | 7 4 only 7 segments | 18 | +---+---------------+-----------------------------------------------------------+ 19 | """ 20 | 21 | 22 | class Display: 23 | def __init__(self, line: str): 24 | self.mixed, self.result = map(lambda s: s.strip().split(' '), line.split('|')) 25 | self.mixed = [''.join(sorted(x)) for x in self.mixed] 26 | self.result = [''.join(sorted(x)) for x in self.result] 27 | 28 | def _solution_dict(self) -> dict[str, int]: 29 | digits = dict() 30 | digits[1] = [p for p in self.mixed if len(p) == 2][0] 31 | digits[7] = [p for p in self.mixed if len(p) == 3][0] 32 | digits[4] = [p for p in self.mixed if len(p) == 4][0] 33 | digits[8] = [p for p in self.mixed if len(p) == 7][0] 34 | digits[3] = [p for p in self.mixed if len(p) == 5 and all([b in p for b in digits[1]])][0] 35 | digits[6] = [p for p in self.mixed if len(p) == 6 and (digits[1][0] in p) ^ (digits[1][1] in p)][0] 36 | digits[9] = [p for p in self.mixed if len(p) == 6 and all([b in p for b in digits[3]])][0] 37 | digits[0] = [p for p in self.mixed if len(p) == 6 and p != digits[6] and p != digits[9]][0] 38 | digits[5] = [p for p in self.mixed if len(p) == 5 and all([b in digits[9] for b in p]) and p != digits[3]][0] 39 | digits[2] = [p for p in self.mixed if len(p) == 5 and p != digits[3] and p != digits[5]][0] 40 | return {v: k for k, v in digits.items()} 41 | 42 | def resolve(self) -> int: 43 | digits = self._solution_dict() 44 | return int(''.join([str(digits[x]) for x in self.result])) 45 | 46 | 47 | def part1(displays: list[Display]) -> int: 48 | counter = Counter(itertools.chain(*[[len(r) for r in d.result] for d in displays])) 49 | return sum([i[1] for i in counter.items() if i[0] in (2, 3, 4, 7)]) 50 | 51 | 52 | def part2(displays: list[Display]) -> int: 53 | return sum([display.resolve() for display in displays]) 54 | 55 | 56 | def main(): 57 | with open('input/08.txt', 'r') as f: 58 | displays = [Display(line) for line in f.readlines()] 59 | print(part1(displays)) 60 | print(part2(displays)) 61 | 62 | 63 | if __name__ == '__main__': 64 | main() 65 | -------------------------------------------------------------------------------- /Day-09/bqn/JohnnyJayJay/Day09.bqn: -------------------------------------------------------------------------------- 1 | Surround ← {⍉⌽𝕨∾˘𝕩}⍟4 # Surround a rank 2 matrix 𝕩 with 𝕨, increasing its dimensions by 2 on each axis 2 | adj ← -⊸∾⟨1‿0, 0‿1⟩ # The directional vectors to get adjacent positions 3 | Positions ← ⥊∘(⊑((1+⋈⌜)○(↕-⟜2))1⊸⊑)≢ # Returns a flat list of all x,y positions in a given matrix 4 | LowPoints ← { (∧´⊑⟜𝕩<(⊑⟜𝕩¨adj+<))¨ Positions 𝕩}/Positions # Returns a list of low point positions 5 | 6 | # A breadth-first-search implementation that sums the amount of nodes it encounters 7 | Bfs ← { g B ⟨f, v⟩ : 8 | { 9 | 0=≠f ? 0 ; 10 | (≠f) + g B ⟨⍷((9≠⊑⟜g)¨∧(¬∊⟜v))⊸/(⥊f+⌜adj), ⍷f∾v⟩ 11 | } 12 | } 13 | 14 | PartOne ← +´1+{⊑⟜𝕩¨ 𝕨} # Given a list of low points 𝕨 and a matrix 𝕩, return their sum of risk levels 15 | PartTwo ← {×´3↑∨(𝕩⊸Bfs ⋈⋈⟨⟩˙)¨ 𝕨} # Given a list of low points 𝕨 and a matrix 𝕩, calculate the product of the 3 largest basin sizes 16 | 17 | Parse ← > -⟜'0'⚇¯2 # Parse a list of input lines to a matrix 18 | input ← 9 Surround Parse •FLines ⊑ •args 19 | l ← LowPoints input 20 | •Out l PartOne input 21 | •Out l PartTwo input 22 | -------------------------------------------------------------------------------- /Day-09/java/B33fb0n3/part1.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | import java.util.*; 4 | 5 | 6 | 7 | public class MyClass { 8 | 9 | public static void main(String args[]) { 10 | 11 | List lines = new ArrayList<>(); 12 | 13 | Scanner scanner = new Scanner(System.in); 14 | 15 | 16 | while (scanner.hasNext()) { 17 | 18 | lines.add(scanner.next()); 19 | 20 | } 21 | 22 | 23 | scanner.close(); 24 | 25 | int sum = 0; 26 | 27 | for(int i = 0; i < lines.size(); i++) { 28 | 29 | int length = lines.get(i).length(); 30 | 31 | 32 | 33 | String upperLine = ""; 34 | 35 | String downLine = ""; 36 | 37 | for(int l = 0; l < length; l++) { 38 | 39 | upperLine += "9"; 40 | 41 | downLine += "9"; 42 | 43 | } 44 | 45 | 46 | 47 | if(i > 0) 48 | 49 | upperLine = lines.get(i-1); 50 | 51 | 52 | 53 | String middleLine = lines.get(i); 54 | 55 | 56 | 57 | if(i+1 < lines.size()) 58 | 59 | downLine = lines.get(i+1); 60 | 61 | 62 | 63 | String[] upperLineLetters = upperLine.split(""); 64 | 65 | String[] middleLineLetters = middleLine.split(""); 66 | 67 | String[] downLineLetters = downLine.split(""); 68 | 69 | 70 | 71 | //System.out.println("U: "+ upperLine +"\nM: "+ middleLine +"\nD: "+ downLine +""); 72 | 73 | 74 | 75 | for(int letter = 0; letter < length; letter++) { 76 | 77 | int center = Integer.parseInt(middleLineLetters[letter]); 78 | 79 | 80 | 81 | int above = Integer.parseInt(upperLineLetters[letter]); 82 | 83 | int under = Integer.parseInt(downLineLetters[letter]); 84 | 85 | 86 | 87 | int left = 9; 88 | 89 | if(letter != 0) 90 | 91 | left = Integer.parseInt(middleLineLetters[letter-1]); 92 | 93 | 94 | 95 | int right = 9; 96 | 97 | if(letter+1 < length) 98 | 99 | right =Integer.parseInt( middleLineLetters[letter+1]); 100 | 101 | 102 | 103 | //System.out.println("XXXX A: "+above + " XXXX"); 104 | 105 | //System.out.println("L: "+left+" C: "+center+" R: "+right); 106 | 107 | //System.out.println("XXXX U: "+under + " XXXX"); 108 | 109 | 110 | 111 | //System.out.println("C: "+center + " < A: " + above); 112 | 113 | //System.out.println("C: "+center + " < U: " + under); 114 | 115 | //System.out.println("C: "+center + " < L: " + left); 116 | 117 | //System.out.println("C: "+center + " < R: " + right); 118 | 119 | if(center < above && center < under && center < left && center < right) { 120 | 121 | sum += center + 1; 122 | 123 | //System.out.println("XXX COUNT XXX"); 124 | 125 | } 126 | 127 | } 128 | 129 | } 130 | 131 | System.out.println("Answer: " + sum); 132 | 133 | } 134 | 135 | } -------------------------------------------------------------------------------- /Day-09/java/B33fb0n3/part2.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | import java.util.*; 4 | 5 | 6 | 7 | public class MyClass { 8 | 9 | private static List alreadyHad = new ArrayList<>(); 10 | 11 | private static int singleBasin = 0; 12 | 13 | private static int finalAnswer = 0; 14 | 15 | 16 | 17 | public static void main(String args[]) { 18 | 19 | List lines = new ArrayList<>(); 20 | 21 | Scanner scanner = new Scanner(System.in); 22 | 23 | 24 | while (scanner.hasNext()) { 25 | 26 | lines.add(scanner.next()); 27 | 28 | } 29 | 30 | 31 | scanner.close(); 32 | 33 | int sum = 0; 34 | 35 | List basins = new ArrayList<>(); 36 | 37 | for(int i = 0; i < lines.size(); i++) { 38 | 39 | int length = lines.get(i).length(); 40 | 41 | for(int letter = 0; letter < length; letter++) { 42 | 43 | int[] arounds = getAround(i, letter, lines, length); 44 | 45 | if(arounds[2] < arounds[0] && arounds[2] < arounds[4] && arounds[2] < arounds[1] && arounds[2] < arounds[3]) { 46 | 47 | sum += arounds[2] + 1; 48 | 49 | findNext(i, letter, lines, length, arounds); 50 | 51 | basins.add(singleBasin); 52 | 53 | singleBasin = 0; 54 | 55 | } 56 | 57 | } 58 | 59 | } 60 | 61 | setFinalAnswer(basins); 62 | 63 | System.out.println("Answer: " + finalAnswer); 64 | 65 | } 66 | 67 | 68 | 69 | private static void setFinalAnswer(List basins) { 70 | 71 | Collections.sort(basins); 72 | 73 | List top3 = new ArrayList(basins.subList(basins.size() -3, basins.size())); 74 | 75 | finalAnswer = top3.get(0) * top3.get(1) * top3.get(2); 76 | 77 | } 78 | 79 | 80 | 81 | private static int findNext(int line, int letterPosition, List lines, int length, int[] arounds) { 82 | 83 | if(alreadyHad.contains(line+";"+letterPosition)) 84 | 85 | return -1; 86 | 87 | singleBasin++; 88 | 89 | int[] newArounds = getAround(line, letterPosition, lines, length); 90 | 91 | for(int side = 0; side < arounds.length; side++) { 92 | 93 | if(side == 2) 94 | 95 | continue; 96 | 97 | if(newArounds[side] != 9) { 98 | 99 | alreadyHad.add(line + ";" + letterPosition); 100 | 101 | switch(side) { 102 | 103 | case 0: 104 | 105 | if(line-1 > 0) 106 | 107 | findNext(line-1, letterPosition, lines, length, newArounds); 108 | 109 | break; 110 | 111 | case 1: 112 | 113 | alreadyHad.add(line + ";" + letterPosition); 114 | 115 | if(letterPosition-1 >= 0) 116 | 117 | findNext(line, letterPosition-1, lines, length, newArounds); 118 | 119 | break; 120 | 121 | case 3: 122 | 123 | alreadyHad.add(line + ";" + letterPosition); 124 | 125 | if(letterPosition+1 < length) 126 | 127 | findNext(line, letterPosition+1, lines, length, newArounds); 128 | 129 | break; 130 | 131 | case 4: 132 | 133 | alreadyHad.add(line + ";" + letterPosition); 134 | 135 | if(line+1 < lines.size()) 136 | 137 | findNext(line+1, letterPosition, lines, length, newArounds); 138 | 139 | break; 140 | 141 | default: 142 | 143 | break; 144 | 145 | } 146 | 147 | } else 148 | 149 | continue; 150 | 151 | } 152 | 153 | return singleBasin; 154 | 155 | } 156 | 157 | 158 | 159 | private static int[] getAround(int line, int letterPosition, List lines, int length) { 160 | 161 | /* 162 | 163 | [0] = Above 164 | 165 | [1] = Left 166 | 167 | [2] = Center 168 | 169 | [3] = Right 170 | 171 | [4] = Under 172 | 173 | */ 174 | 175 | int[] returner = {-1,-1,-1,-1,-1}; 176 | 177 | 178 | 179 | String upperLine = ""; 180 | 181 | String downLine = ""; 182 | 183 | for(int l = 0; l < length; l++) { 184 | 185 | upperLine += "9"; 186 | 187 | downLine += "9"; 188 | 189 | } 190 | 191 | 192 | 193 | if(line > 0) 194 | 195 | upperLine = lines.get(line-1); 196 | 197 | 198 | 199 | String middleLine = lines.get(line); 200 | 201 | 202 | 203 | if(line+1 < lines.size()) 204 | 205 | downLine = lines.get(line+1); 206 | 207 | 208 | 209 | String[] upperLineLetters = upperLine.split(""); 210 | 211 | String[] middleLineLetters = middleLine.split(""); 212 | 213 | String[] downLineLetters = downLine.split(""); 214 | 215 | 216 | 217 | returner[2] = Integer.parseInt(middleLineLetters[letterPosition]); 218 | 219 | 220 | 221 | returner[0] = Integer.parseInt(upperLineLetters[letterPosition]); 222 | 223 | returner[4] = Integer.parseInt(downLineLetters[letterPosition]); 224 | 225 | 226 | 227 | returner[1] = 9; 228 | 229 | if(letterPosition != 0) 230 | 231 | returner[1] = Integer.parseInt(middleLineLetters[letterPosition-1]); 232 | 233 | 234 | 235 | returner[3] = 9; 236 | 237 | if(letterPosition+1 < length) 238 | 239 | returner[3] =Integer.parseInt( middleLineLetters[letterPosition+1]); 240 | 241 | return returner; 242 | 243 | } 244 | 245 | } -------------------------------------------------------------------------------- /Day-09/python/RainbowDashLabs/day_9.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | class HeightMap: 5 | def __init__(self, height_map: list[str]): 6 | self.height_map: list[list[int]] = [[int(e) for e in list(e.strip())] for e in height_map] 7 | self.x_dim = len(self.height_map) 8 | self.y_dim = len(self.height_map[0]) 9 | self.risk_map = [[self._risk_score(x, y) for y in range(self.y_dim)] for x in range(self.x_dim)] 10 | 11 | def _risk_score(self, x: int, y: int) -> (int, int): 12 | origin = self._height(x, y) 13 | heights = [self._height(*e) for e in self._adjacent_points(x, y)] 14 | return (1 + origin, self._basin_score(x, y)) if all([e > origin for e in heights]) else (0, 0) 15 | 16 | def _basin_score(self, x, y): 17 | done = set() 18 | queue: (int, int) = [(x, y)] 19 | while len(queue) != 0: 20 | coord = queue.pop() 21 | done.add(coord) 22 | for c in self._adjacent_points(*coord): 23 | if c in done: 24 | continue 25 | if self._height(*c) != 9: 26 | queue.append(c) 27 | return len(done) 28 | 29 | def _adjacent_points(self, x, y) -> list[(int, int)]: 30 | points = [c for c in [(x, y + y_o) for y_o in range(-1, 2, 2)] if self._exists(*c)] 31 | return points + [c for c in [(x + x_o, y) for x_o in range(-1, 2, 2)] if self._exists(*c)] 32 | 33 | def _exists(self, x, y): 34 | return 0 <= x < self.x_dim and 0 <= y < self.y_dim 35 | 36 | def _height(self, x: int, y: int): 37 | return self.height_map[x][y] 38 | 39 | def risk_sum(self): 40 | return sum([sum([num[0] for num in e]) for e in self.risk_map]) 41 | 42 | def basins(self, limit: int = None): 43 | return [e for e in list(reversed(sorted([e[1] for inner in [e for e in self.risk_map] for e in inner])))[ 44 | :limit or len(self.risk_map)]] 45 | 46 | 47 | height_map = HeightMap(list(open("puzzle.txt").readlines())) 48 | 49 | print(f"Part one {height_map.risk_sum()}") 50 | 51 | print(f"Part two {math.prod(height_map.basins(3))}") 52 | -------------------------------------------------------------------------------- /Day-09/python/stnwtr/day09.py: -------------------------------------------------------------------------------- 1 | class Cave: 2 | def __init__(self, grid: list[list[int]]): 3 | self.grid = grid 4 | self.smallest = None 5 | 6 | def __getitem__(self, item: int) -> list[int]: 7 | return self.grid[item] 8 | 9 | def __len__(self): 10 | return len(self.grid) 11 | 12 | def _is_smallest_adjacent(self, i: int, j: int) -> bool: 13 | return self[i][j] < min([self.get_or(i - 1, j, 9), 14 | self.get_or(i + 1, j, 9), 15 | self.get_or(i, j - 1, 9), 16 | self.get_or(i, j + 1, 9)]) 17 | 18 | def get_or(self, i: int, j: int, default: int) -> int: 19 | if i < 0 or i > len(self) - 1 or j < 0 or j > len(self[i]) - 1: 20 | return default 21 | return self[i][j] 22 | 23 | def get_smallest_indices(self) -> list[tuple[int, int]]: 24 | if self.smallest is not None: 25 | return self.smallest 26 | 27 | self.smallest = [] 28 | for i in range(len(self)): 29 | for j in range(len(self[i])): 30 | if self._is_smallest_adjacent(i, j): 31 | self.smallest.append((i, j)) 32 | 33 | return self.smallest 34 | 35 | # this looks bad - could probably be a 1-liner using list comprehension somehow ... I'm too lazy 36 | # did this after driving hundreds of kilometers and being tired for such a long time 37 | def get_basin_indices_at(self, i: int, j: int) -> set[tuple[int, int]]: 38 | indices = [(i, j)] 39 | value = self[i][j] 40 | a = self.get_or(i - 1, j, 9) 41 | b = self.get_or(i + 1, j, 9) 42 | c = self.get_or(i, j - 1, 9) 43 | d = self.get_or(i, j + 1, 9) 44 | 45 | if 9 > a > value: 46 | indices += self.get_basin_indices_at(i - 1, j) 47 | if 9 > b > value: 48 | indices += self.get_basin_indices_at(i + 1, j) 49 | if 9 > c > value: 50 | indices += self.get_basin_indices_at(i, j - 1) 51 | if 9 > d > value: 52 | indices += self.get_basin_indices_at(i, j + 1) 53 | 54 | return set(indices) 55 | 56 | 57 | def part1(cave: Cave) -> int: 58 | smallest_values = [cave[i][j] for i, j in cave.get_smallest_indices()] 59 | return sum(smallest_values) + len(smallest_values) 60 | 61 | 62 | def part2(cave: Cave) -> int: 63 | bs = sorted([len([cave.get_or(*x, 9) for x in cave.get_basin_indices_at(*si)]) for si in cave.get_smallest_indices()]) 64 | return bs.pop() * bs.pop() * bs.pop() 65 | 66 | 67 | def main(): 68 | with open('input/09.txt', 'r') as f: 69 | cave = Cave([[int(x) for x in line.strip()] for line in f.readlines()]) 70 | print(part1(cave)) 71 | print(part2(cave)) 72 | 73 | 74 | if __name__ == '__main__': 75 | main() 76 | -------------------------------------------------------------------------------- /Day-10/bqn/JohnnyJayJay/Day10.bqn: -------------------------------------------------------------------------------- 1 | # A list of all brackets. Used to assign a number to each bracket (pair) 2 | bracks ← "()[]{}<>" 3 | 4 | # Given a "stack" 𝕩 and a bracket number 𝕨, updates the stack: 5 | # - if it is a closing bracket, pops an element from the stack if it matches the bracket, otherwise appends the bracket to the end 6 | # - if it is an opening bracket, adds it to the front of the stack 7 | StepStack ← { 8 | 2|𝕨 ? 1↓ 𝕨 (=⟜(1+⊑)◶(∾˜)‿⊢) 𝕩 ; 9 | 𝕨∾𝕩 10 | } 11 | 12 | PartOne ← {+´ (⊑⟜3‿57‿1197‿25137(⌊÷⟜2)∘⊑)¨ (×≠¨)⊸/ (2⊸|⊸/)¨ 𝕩} 13 | 14 | PartTwo ← {(⌊≠÷2˙)⊸⊑ ∧ {𝕨+5×𝕩}´¨ ⌽¨ (1+÷⟜2)⚇¯2 {¬∨´2|𝕩}¨⊸/ 𝕩} 15 | 16 | Parse ← ⌽∘>(bracks⊸⊐)¨ 17 | input ← (⟨⟩⊸(StepStack´))¨ Parse¨ •FLines ⊑ •args 18 | 19 | •Out PartOne input 20 | •Out PartTwo input 21 | -------------------------------------------------------------------------------- /Day-10/clojure/JohnnyJayJay/Day10.clj: -------------------------------------------------------------------------------- 1 | (ns Day10 2 | (:require [clojure.string :as str])) 3 | 4 | (def brackets 5 | (zipmap ")]}>" "([{<")) 6 | 7 | (defn process-bracket [stack bracket] 8 | (if-some [opening (brackets bracket)] 9 | (if (= (peek stack) opening) 10 | (pop stack) 11 | (reduced bracket)) 12 | (conj stack bracket))) 13 | 14 | (def checker-scores 15 | {\) 3 16 | \] 57 17 | \} 1197 18 | \> 25137}) 19 | 20 | (defn part-one [input] 21 | (->> input 22 | (remove coll?) 23 | (map checker-scores) 24 | (reduce +))) 25 | 26 | (def completer-scores 27 | {\( 1 28 | \[ 2 29 | \{ 3 30 | \< 4}) 31 | 32 | (defn score-step [acc score] 33 | (+ (* 5 acc) score)) 34 | 35 | (defn part-two [input] 36 | (let [scores (->> input 37 | (filter coll?) 38 | (map (partial map completer-scores)) 39 | (map (partial reduce score-step 0)) 40 | sort 41 | vec)] 42 | (nth scores (quot (count scores) 2)))) 43 | 44 | (let [input (->> *command-line-args* 45 | first 46 | slurp 47 | str/split-lines 48 | (map (partial reduce process-bracket ())))] 49 | (println (part-one input)) 50 | (println (part-two input))) 51 | -------------------------------------------------------------------------------- /Day-10/python/RainbowDashLabs/day_10.py: -------------------------------------------------------------------------------- 1 | def is_illegal(line: str): 2 | last = [] 3 | for e in list(line): 4 | if e in chunk_marker: 5 | last.append(e) 6 | continue 7 | close = chunk_marker[last.pop()][0] 8 | if close == e: 9 | continue 10 | return e, close 11 | 12 | 13 | def repair(line: str): 14 | last = [] 15 | for e in list(line): 16 | if e in chunk_marker: 17 | last.append(e) 18 | continue 19 | last.pop() 20 | return [chunk_marker[e][0] for e in reversed(last)] 21 | 22 | 23 | def score_illegal(chars: list[str]): 24 | return sum([chars.count(marker[0]) * marker[1] for marker in chunk_marker.values()]) 25 | 26 | 27 | def score_repair(chars: list[str], scores: dict): 28 | score = 0 29 | for char in chars: 30 | score = score * 5 + scores[char] 31 | return score 32 | 33 | 34 | lines = [e.strip() for e in open("puzzle.txt").readlines()] 35 | chunk_marker = {"(": (")", 3, 1), "[": ("]", 57, 2), "{": ("}", 1197, 3), "<": (">", 25137, 4)} 36 | 37 | result = score_illegal([is_illegal(line)[0] for line in lines if is_illegal(line)]) 38 | print(f'Part one {result}') 39 | 40 | scores = {e[0]: e[2] for e in chunk_marker.values()} 41 | repaired = sorted([score_repair(repair(line), scores) for line in lines if not is_illegal(line)]) 42 | print(f'Part two {repaired[int(len(repaired) / 2)]}') 43 | -------------------------------------------------------------------------------- /Day-11/python/RainbowDashLabs/day_11.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from itertools import product 3 | 4 | @dataclass 5 | class Octopus: 6 | energy: int 7 | flashed = False 8 | flashes = 0 9 | 10 | def proceed(self): 11 | self.flashed = False 12 | self.energy += 1 13 | 14 | def add_energy(self): 15 | if not self.flashed: 16 | self.energy += 1 17 | 18 | def try_flash(self): 19 | if self.energy < 10: 20 | return False 21 | self.flashed = True 22 | self.flashes += 1 23 | self.energy = 0 24 | return True 25 | 26 | 27 | class Ocean: 28 | def __init__(self, octopuses: list[list[Octopus]]): 29 | self.octopuses = octopuses 30 | self.x_dim = len(self.octopuses) 31 | self.y_dim = len(self.octopuses[0]) 32 | self.coords = list(product(range(self.x_dim), range(self.y_dim))) 33 | 34 | def _exists(self, x, y): 35 | return 0 <= x < self.x_dim and 0 <= y < self.y_dim 36 | 37 | def _adjacent(self, x, y) -> list[(int, int)]: 38 | return [e for e in product(range(x - 1, x + 2), range(y - 1, y + 2)) if self._exists(*e) and e != (x, y)] 39 | 40 | def _try_flash(self, x, y): 41 | flashed = self.octopuses[x][y].try_flash() 42 | if flashed: 43 | [self.get(*point).add_energy() for point in self._adjacent(x, y)] 44 | return flashed 45 | 46 | def get(self, x, y): 47 | return self.octopuses[x][y] 48 | 49 | def proceed(self): 50 | for coord in self.coords: 51 | self.get(*coord).proceed() 52 | 53 | flashed = True 54 | while flashed: 55 | flashed = any([self._try_flash(*coord) for coord in self.coords]) 56 | 57 | def flash_sum(self): 58 | return sum([sum([o.flashes for o in e]) for e in self.octopuses]) 59 | 60 | def synced_flash(self): 61 | return sum([sum([o.energy for o in e]) for e in self.octopuses]) == 0 62 | 63 | 64 | octopuses = [[Octopus(int(o)) for o in list(e.strip())] for e in open("puzzle.txt").readlines()] 65 | ocean = Ocean(octopuses) 66 | 67 | for day in range(100): 68 | ocean.proceed() 69 | 70 | print(f'Part one {ocean.flash_sum()}') 71 | 72 | octopuses = [[Octopus(int(o)) for o in list(e.strip())] for e in open("puzzle.txt").readlines()] 73 | ocean = Ocean(octopuses) 74 | 75 | day = 0 76 | while True: 77 | day += 1 78 | ocean.proceed() 79 | if ocean.synced_flash(): 80 | break 81 | 82 | print(f'Part two {day}') 83 | 84 | 85 | -------------------------------------------------------------------------------- /Day-12/python/RainbowDashLabs/day_12.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | import time 3 | 4 | edges = [e.strip() for e in open("puzzle.txt").readlines()] 5 | 6 | 7 | class Cave: 8 | def __init__(self, name: str): 9 | self.name = name 10 | self.small = name.islower() 11 | self.start = self.name == "start" 12 | self.end = self.name == "end" 13 | self.caves = set() 14 | self.hash = hash(self.name) 15 | 16 | def add_connection(self, cave): 17 | self.caves.add(cave) 18 | 19 | def __eq__(self, other): 20 | return other.name == self.name 21 | 22 | def __hash__(self): 23 | return self.hash 24 | 25 | def __repr__(self): 26 | return self.name 27 | 28 | 29 | class Way: 30 | def __init__(self, start: Union[Cave, list[Cave]]): 31 | if isinstance(start, Cave): 32 | self.caves: list[Cave] = [] 33 | self.caves.append(start) 34 | if isinstance(start, list): 35 | self.caves: list[Cave] = start 36 | self.hash = hash("".join([e.name for e in self.caves])) 37 | 38 | def last(self): 39 | return self.caves[-1] 40 | 41 | def split(self, double_small) -> set["Way"]: 42 | ways: set[Way] = set() 43 | for e in self.last().caves: 44 | if self.can_add(e, double_small): 45 | ways.add(Way([*self.caves, e])) 46 | return ways 47 | 48 | def has_double_small(self): 49 | return max([self.caves.count(e) for e in self.caves if e.small]) > 1 50 | 51 | def can_add(self, cave: Cave, double_small: bool): 52 | if self.last().end or cave.start: 53 | return False 54 | if not cave.small: 55 | return True 56 | if not double_small: 57 | return cave not in self.caves 58 | if not self.has_double_small(): 59 | return True 60 | return cave not in self.caves 61 | 62 | def __eq__(self, other): 63 | return self.hash == other.hash 64 | 65 | def __hash__(self): 66 | return self.hash 67 | 68 | 69 | class Graph: 70 | def __init__(self, caves: list[str], double_small: bool = False): 71 | self.caves: dict[str, Cave] = {} 72 | for e in caves: 73 | edge = e.split("-") 74 | first = edge[0] 75 | second = edge[1] 76 | self.get(first).add_connection(self.get(second)) 77 | self.get(second).add_connection(self.get(first)) 78 | self.ways = [] 79 | self.double_small = double_small 80 | self.build_graph() 81 | 82 | def get(self, name: str): 83 | if name not in self.caves: 84 | self.caves[name] = Cave(name) 85 | return self.caves[name] 86 | 87 | def __repr__(self): 88 | return self.caves.__repr__() 89 | 90 | def build_graph(self): 91 | start = self.get("start") 92 | ways = {Way(start)} 93 | while True: 94 | new_ways = set() 95 | for way in ways: 96 | splitted = way.split(self.double_small) 97 | if len(splitted): 98 | [new_ways.add(e) for e in splitted] 99 | else: 100 | if way.last().end: 101 | new_ways.add(way) 102 | if len(new_ways) == len(ways): 103 | break 104 | ways = new_ways 105 | self.ways = ways 106 | 107 | def get_ways(self) -> list[Way]: 108 | return self.ways 109 | 110 | 111 | start = time.time() 112 | graph = Graph(edges) 113 | print(f"Part one {len(graph.get_ways())} took {round(time.time() - start, 4)} seconds") 114 | 115 | start = time.time() 116 | graph = Graph(edges, double_small=True) 117 | print(f"Part two {len(graph.get_ways())} took {round(time.time() - start, 4)} seconds") 118 | -------------------------------------------------------------------------------- /Day-13/python/RainbowDashLabs/day_13.py: -------------------------------------------------------------------------------- 1 | from collections import namedtuple 2 | 3 | lines = [e.strip() for e in open("puzzle.txt")] 4 | points = [list(map(int, e.split(","))) for e in lines if e and not e.startswith("fold along")] 5 | folds = [e.split(" ")[-1].split("=") for e in lines if e.startswith("fold along")] 6 | 7 | Dot = namedtuple("Dot", "x y") 8 | 9 | 10 | class Paper: 11 | def __init__(self, dots: list[list[int, int]]): 12 | self.dots: list[Dot] = [Dot(*e) for e in dots] 13 | 14 | def fold(self, axis: str, index: str): 15 | i = int(index) 16 | if axis == "y": 17 | self.dots = set([Dot(e.x, i - (e.y - i)) for e in self.dots if e.y > i] + [e for e in self.dots if e.y < i]) 18 | else: 19 | self.dots = set([Dot(i - (e.x - i), e.y) for e in self.dots if e.x > i] + [e for e in self.dots if e.x < i]) 20 | 21 | def dot_count(self): 22 | return len(self.dots) 23 | 24 | def __str__(self): 25 | row = [' '] * (max([e.x for e in self.dots]) + 1) 26 | table = [list(row) for i in range(max([e.y for e in self.dots]) + 1)] 27 | for dot in self.dots: 28 | table[dot.y][dot.x] = "█" 29 | return "\n".join(["".join(e) for e in table]) 30 | 31 | 32 | paper = Paper(points) 33 | paper.fold(*folds[0]) 34 | print(f"Part one {paper.dot_count()}") 35 | 36 | paper = Paper(points) 37 | for fold in folds: 38 | paper.fold(*fold) 39 | print(f"Part two\n{paper}") 40 | -------------------------------------------------------------------------------- /Day-14/python/RainbowDashLabs/day_14.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | 4 | class Rule: 5 | def __init__(self, transformation: str): 6 | split = transformation.split(" -> ") 7 | self.pattern: str = split[0] 8 | self.insertion: str = split[1] 9 | self._transformed = (self.pattern[0] + self.insertion, self.insertion + self.pattern[1]) 10 | 11 | def transformed(self) -> (str, str): 12 | return self._transformed 13 | 14 | 15 | class Polymer: 16 | def __init__(self, template, rules: list[Rule]): 17 | self.rules = rules 18 | self.count = {} 19 | self.elements = {} 20 | window = [template[0]] 21 | self.add_count(template[0]) 22 | for e in template[1:]: 23 | self.add_count(e) 24 | window.append(e) 25 | self.add_element("".join(window)) 26 | window.pop(0) 27 | 28 | def add_count(self, element, count: int = 1): 29 | if element not in self.count: 30 | self.count[element] = 0 31 | self.count[element] += count 32 | 33 | def add_element(self, element, count: int = 1): 34 | if element not in self.elements: 35 | self.elements[element] = 0 36 | self.elements[element] += count 37 | 38 | def transform(self): 39 | old = self.elements 40 | self.elements = {} 41 | for rule in self.rules: 42 | if rule.pattern in old: 43 | count = old[rule.pattern] 44 | transformed = rule.transformed() 45 | self.add_element(transformed[0], count) 46 | self.add_element(transformed[1], count) 47 | self.add_count(rule.insertion, count) 48 | 49 | def progress(self, count): 50 | for i in range(0, count): 51 | self.transform() 52 | 53 | def most(self): 54 | return max(self.count.values()) 55 | 56 | def least(self): 57 | return min(self.count.values()) 58 | 59 | 60 | lines = [e.strip() for e in open("puzzle.txt")] 61 | 62 | polymer = Polymer(lines[0], [Rule(e) for e in lines if e and "->" in e]) 63 | start = time.time() 64 | polymer.progress(10) 65 | print(f"Part one {polymer.most() - polymer.least()} took {round((time.time() - start) * 1000, 4)} ms") 66 | 67 | polymer.progress(30) 68 | print(f"Part two {polymer.most() - polymer.least()} took {round((time.time() - start) * 1000, 4)} ms") 69 | 70 | -------------------------------------------------------------------------------- /Day-15/python/RainbowDashLabs/day_15.py: -------------------------------------------------------------------------------- 1 | import time 2 | from collections import namedtuple 3 | from queue import PriorityQueue 4 | from typing import Union 5 | 6 | Pos = namedtuple("Pos", "x y") 7 | 8 | 9 | class Grid: 10 | def __init__(self, grid: list[list[int]]): 11 | self.queue = PriorityQueue() 12 | self.x_dim = len(grid) 13 | self.y_dim = len(grid[0]) 14 | self.grid = grid 15 | self.visited = [[False for e in range(self.y_dim)] for e in range(self.x_dim)] 16 | self.dist = [[float('inf') for e in range(self.y_dim)] for e in range(self.x_dim)] 17 | self.start = Pos(0, 0) 18 | self.end = Pos(self.x_dim - 1, self.y_dim - 1) 19 | 20 | def search(self): 21 | self.set_weight(0, self.start) 22 | self.visit(self.start) 23 | point = self.next_point() 24 | while point != self.end: 25 | self.visit(point) 26 | point = self.next_point() 27 | 28 | def visit(self, pos: Pos): 29 | self.visited[pos.x][pos.y] = True 30 | [self.queue_point(p) for p in self.unvisited_adjacent(pos) if self.set_weight(self.get_weight(pos), p)] 31 | 32 | def queue_point(self, pos: Pos): 33 | self.queue.put((self.get_weight(pos), pos)) 34 | 35 | def next_point(self) -> Pos: 36 | return self.queue.get()[1] 37 | 38 | def exists(self, pos: Pos): 39 | return 0 <= pos.x < self.x_dim and 0 <= pos.y < self.y_dim 40 | 41 | def unvisited_adjacent(self, pos: Pos): 42 | points = [c for c in [Pos(pos.x, pos.y + y_o) for y_o in range(-1, 2, 2)] if self.exists(c)] 43 | points = points + [c for c in [Pos(pos.x + x_o, pos.y) for x_o in range(-1, 2, 2)] if self.exists(c)] 44 | return [c for c in points if not self.visited[c.x][c.y]] 45 | 46 | def set_weight(self, parent_weight: int, pos: Pos): 47 | new_weight = parent_weight + self.grid[pos.x][pos.y] 48 | if new_weight < self.get_weight(pos): 49 | self.dist[pos.x][pos.y] = new_weight 50 | return True 51 | return False 52 | 53 | def get_weight(self, pos: Pos) -> Union[int, float]: 54 | return self.dist[pos.x][pos.y] 55 | 56 | def shortest_path_weight(self) -> int: 57 | return self.get_weight(self.end) - self.get_weight(self.start) 58 | 59 | 60 | cave = [list(map(int, list(e.strip()))) for e in open("puzzle.txt") if e.strip()] 61 | 62 | start = time.time() 63 | grid = Grid(cave) 64 | grid.search() 65 | print(f"Part one {grid.shortest_path_weight()} took {round((time.time() - start) * 1000, 4)} ms") 66 | 67 | 68 | def add_clipped(num, addition): 69 | return addition + num - 9 if num + addition > 9 else num + addition 70 | 71 | 72 | new_cave = list(cave) 73 | for addition in range(1, 5): 74 | for i in range(len(cave)): 75 | new_cave[i] = new_cave[i] + [add_clipped(num, addition) for num in cave[i]] 76 | 77 | for addition in range(1, 5): 78 | for i in range(len(cave)): 79 | new_cave.append([add_clipped(num, addition) for num in new_cave[i]]) 80 | 81 | start = time.time() 82 | grid = Grid(new_cave) 83 | grid.search() 84 | print(f"Part two {grid.shortest_path_weight()} took {round((time.time() - start) * 1000, 4)} ms") 85 | -------------------------------------------------------------------------------- /Day-16/python/RainbowDashLabs/day_16.py: -------------------------------------------------------------------------------- 1 | import math 2 | from typing import Union 3 | 4 | bits = "".join([str(bin(int(char, 16)))[2:].zfill(4) for char in list(open("puzzle.txt").read().strip())]) 5 | 6 | 7 | class Packet: 8 | types = { 9 | 0: lambda x: sum([e for e in x]), 10 | 1: lambda x: math.prod([e for e in x]), 11 | 2: lambda x: min([e for e in x]), 12 | 3: lambda x: max([e for e in x]), 13 | 4: lambda x: x, 14 | 5: lambda x: int(x[0] > x[1]), 15 | 6: lambda x: int(x[0] < x[1]), 16 | 7: lambda x: int(x[0] == x[1]) 17 | } 18 | 19 | def __init__(self, content): 20 | self.raw_content = content 21 | self._content = content 22 | self.parsed_content = "" 23 | self.version = self.next_bytes_int(3) 24 | self.type_id = self.next_bytes_int(3) 25 | self.value: Union[int, list["Packet"]] = self.parse_content() 26 | 27 | def next_bytes(self, amount) -> str: 28 | curr_content = self._content[:amount] 29 | self._content = self._content[amount:] 30 | self.parsed_content += curr_content 31 | return curr_content 32 | 33 | def next_bytes_int(self, amount) -> int: 34 | return int(self.next_bytes(amount), 2) 35 | 36 | def parse_content(self) -> Union[int, list["Packet"]]: 37 | if self.type_id == 4: 38 | return self.extract_literal() 39 | length_type_id = self.next_bytes_int(1) 40 | iter_range = self.next_bytes_int(15 if not length_type_id else 11) 41 | sub_packets = [] 42 | if length_type_id == 0: 43 | parsed = 0 44 | while parsed < iter_range: 45 | sub_packets.append(self.sub_packet()) 46 | self.skip_bytes(sub_packets[-1].length()) 47 | parsed += sub_packets[-1].length() 48 | else: 49 | for i in range(iter_range): 50 | sub_packets.append(self.sub_packet()) 51 | self.skip_bytes(sub_packets[-1].length()) 52 | return sub_packets 53 | 54 | def sub_packet(self): 55 | return self.__class__(self._content) 56 | 57 | def extract_literal(self) -> (int, int): 58 | groups = [] 59 | while True: 60 | content = self.next_bytes(5) 61 | groups.append(content[1:5]) 62 | if content[0] == "0": 63 | break 64 | return int("".join(groups), 2) 65 | 66 | def __repr__(self): 67 | return f"Packet(Version {self.version} | Type {self.type_id} | Value {self.value})" 68 | 69 | def length(self): 70 | return len(self.parsed_content) 71 | 72 | def skip_bytes(self, num): 73 | self.next_bytes(num) 74 | 75 | def version_sum(self): 76 | if isinstance(self.value, int): 77 | return self.version 78 | return self.version + sum(e.version_sum() for e in self.value if isinstance(e, Packet)) 79 | 80 | def type_value(self): 81 | if self.type_id == 4: 82 | return self.value 83 | return Packet.types[self.type_id]([e.type_value() for e in self.value]) 84 | 85 | 86 | packet = Packet(bits) 87 | print(f"Part one {packet.version_sum()}") 88 | print(f"Part two {packet.type_value()}") 89 | -------------------------------------------------------------------------------- /Day-16/scala/SirYwell/day16.scala: -------------------------------------------------------------------------------- 1 | import scala.annotation.tailrec 2 | import scala.io.Source.fromFile 3 | 4 | @main def day16(filePath: String): Unit = { 5 | val input = fromFile(filePath).getLines().next() 6 | val bits = input.map(c => Character.digit(c, 16)) 7 | .flatMap(i => "%4s".formatted(i.toBinaryString).replace(' ', '0').map(_ - '0')).toList 8 | val packet = parsePacket(bits) 9 | println(s"version sum: ${sum(packet._1)}") 10 | println(s"eval result: ${evaluate(packet._1)}") 11 | } 12 | 13 | def sum(packet: Packet): Int = packet match { 14 | case Literal(version, _) => version 15 | case PacketContainer(version, _, packets) => version + packets.map(sum).sum 16 | } 17 | def evaluate(packet: Packet): Long = packet match { 18 | case PacketContainer(_, 0, packets) => packets.map(evaluate).sum 19 | case PacketContainer(_, 1, packets) => packets.map(evaluate).product 20 | case PacketContainer(_, 2, packets) => packets.map(evaluate).min 21 | case PacketContainer(_, 3, packets) => packets.map(evaluate).max 22 | case Literal(_, v) => v 23 | case PacketContainer(_, 5, List(l, r)) => if evaluate(l) > evaluate(r) then 1 else 0 24 | case PacketContainer(_, 6, List(l, r)) => if evaluate(l) < evaluate(r) then 1 else 0 25 | case PacketContainer(_, 7, List(l, r)) => if evaluate(l) == evaluate(r) then 1 else 0 26 | } 27 | 28 | def parsePacket(bits: List[Int]): (Packet, List[Int]) = { 29 | val (version, (typeId, rest)) = parseVersion(bits) map (p => (p._1, parseTypeId(p._2))) 30 | if typeId == 4 then parseLiteral(list = rest) map (p => (Literal(version, p._1), p._2)) 31 | else 32 | val (packets, r) = 33 | if rest.head == 0 then parseBits(rest.tail, 15) map parsePacketsByLength 34 | else parseBits(rest.tail, 11) map parsePacketsByAmount 35 | (PacketContainer(version, typeId, packets), r) 36 | } 37 | def parseBits(value: List[Int], n: Int): (Int, List[Int]) = 38 | if n == 1 then (value.head, value.tail) 39 | else parseBits(value.tail, n - 1) map (p => ((value.head << (n - 1)) | p._1, p._2)) 40 | 41 | def parseVersion(list: List[Int]): (Int, List[Int]) = parseBits(list, 3) 42 | def parseTypeId(list: List[Int]): (Int, List[Int]) = parseBits(list, 3) 43 | @tailrec 44 | def parseLiteral(value: Long = 0L, list: List[Int]): (Long, List[Int]) = list.head match { 45 | case 0 => parseBits(list.tail, 4) map (p => ((value << 4) | p._1, p._2)) 46 | case 1 => 47 | val (v, r) = parseBits(list.tail, 4) 48 | parseLiteral((value << 4) | v, r) 49 | } 50 | def parsePacketsByLength(length: Int, list: List[Int]): (List[Packet], List[Int]) = { 51 | val (packets, remaining) = list.splitAt(length) 52 | var p = parsePacket(packets) 53 | var l = List(p._1) 54 | while p._2.nonEmpty do { 55 | p = parsePacket(p._2) 56 | l = l.appended(p._1) 57 | } 58 | (l, remaining) 59 | } 60 | def parsePacketsByAmount(count: Int, list: List[Int]): (List[Packet], List[Int]) = { 61 | val (packet, remaining) = parsePacket(list) 62 | if count == 1 then (List(packet), remaining) 63 | else parsePacketsByAmount(count - 1, remaining) map (e => (packet :: e._1, e._2)) 64 | } 65 | 66 | trait Packet: 67 | def version: Int 68 | 69 | case class PacketContainer(version: Int, typeId: Int, packets: List[Packet]) extends Packet 70 | 71 | case class Literal(version: Int, literalValue: Long) extends Packet 72 | 73 | extension[I <: (?, ?)] (t: I) 74 | def map[O](f: I => O): O = f(t) 75 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # adventofcode-21 2 | 3 | Ein Sammel-Repository für [Advent of Code](https://adventofcode.com) 2021-Lösungen der deutschen [DevCord](https://discord.gg/tNMq2K4)-Community. 4 | 5 | A repository collecting [Advent of Code](https://adventofcode.com) 2021 solutions made by the German [DevCord](https://discord.gg/tNMq2K4) community. 6 | 7 | ## Überblick/Overview 8 | 9 | Hier ist ein Überblick über die Vollständigkeit sowie die existierenden Lösungen und verwendeten Sprachen in diesem Repository: 10 | 11 | Here's an overview of the completeness as well as the existing solutions and languages used in this repository: 12 | 13 | | Day/Lang | Java | Python | Scala | Kotlin | Ruby | Clojure | Go | Rust | C++ | BQN | SQL | 14 | |---------------------------------------| ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | ------ | 15 | | 01 - Sonar Sweep | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | 16 | | 02 - Dive! | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | (✅) | 17 | | 03 - Binary Diagnostic | ✅ | ✅ | ✅ | ✅ | (✅) | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | 18 | | 04 - Giant Squid | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | 19 | | 05 - Hydrothermal Venture | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | 20 | | 06 - Lanternfish | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | 21 | | 07 - The Treachery of Whales | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | 22 | | 08 - Seven Segment Search | (✅) | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 23 | | 09 - Smoke Basin | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | 24 | | 10 - Syntax Scoring | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | 25 | | 11 - Dumbo Octopus | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | 26 | | 12 - Passage Pathing | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | 27 | | 13 - Transparent Origami | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | 28 | | 14 - Extended Polymerization | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | 29 | 30 | ❌ = Keine Lösung/No solution, 31 | ✅ = Voll gelöst/Fully solved, 32 | (✅) = Erster Teil gelöst/First part solved 33 | 34 | ## Ordnerstruktur/Directory Structure 35 | 36 | Die Struktur dieses Repositorys ist wie folgt: 37 | 38 | The structure of this repository is as follows: 39 | 40 | - shared (1) 41 | - `user` 42 | - \* 43 | - Day-`XX` (2) 44 | - `lang` (3) 45 | - `user` (4) 46 | 47 | (1) Der *shared*-Order ist für zusätzliche Dateien, die neben der Lösungsdatei benötigt werden, etwa Hilfscode oder Bibliotheken. Jede\*r Beitragende darf dort einen eigenen, entsprechend benannten Ordner erstellen, über den frei verfügt werden darf. 48 | 49 | (2) Jeder neue Tag bekommt einen eigenen Ordner, der nach dem Schema *Day-`XX`* benannt ist, wobei `XX` die zwei Ziffern des Tages darstellen. Also z.B. steht *Day-01* für Tag 1 und *Day-15* für Tag 15. 50 | 51 | (3) Jeder Tag hat je einen Unterordner für die Programmiersprachen, in denen er gelöst wurde. Dabei ist für den Namen des Ordners der kleingeschriebene Name der Sprache zu verwenden, also z.B. *java*, *go* oder *javascript*. 52 | 53 | (4) Es können mehrere Lösungen von unterschiedlichen Beitragenden in der gleichen Programmiersprache abgegeben werden. Deshalb sollte sich pro Lösung ein Ordner in dem entsprechenden Sprachen-Ordner befinden, der den Namen des\*der Beitragenden trägt und den Quellcode der Lösung (für beide Teilaufgaben, falls vorhanden) enthält. Der Name dieses Ordners sollte identisch mit dem Namen des dazu passenden Ordner in *shared* sein, falls einer existiert. 54 | 55 | ---------------- 56 | 57 | (1) The *shared* directory can be used for additional files and resources contributors might need besides their solution file, such as helper code or libraries. Every contributor may create an own directory in *shared* that corresponds to their name. 58 | 59 | (2) Every day of the challenge gets an own directory named with the scheme of *Day-`XX`*, where `XX` stands for the two digits of the day. E.g. *Day-01* is for day 1 and *Day-15* is for day 15. 60 | 61 | (3) Every day gets one sub directory for each language it has been solved in. The name of those directories must be the name of the programming language in lower case, e.g. *java*, *go* or *javascript*. 62 | 63 | (4) There can be more than one solution in each language for each day by different contributors. For this reason, for each solution, there should be one directory in the corresponding language directory for the day named after the contributor who created it containing the source code of that solution. This should be the same name that is also used for the personal directory in *shared*, should one exist. 64 | 65 | ## Lösungen ausführen/Run the solutions 66 | 67 | TODO 68 | 69 | ## Anleitung zum Beitragen (only for DevCord members) 70 | 71 | Wenn du zu den Lösungen beitragen möchtest, hast du zwei Optionen: **Selbst mit git arbeiten und Pull Requests erstellen** oder **deine Lösungen der Verwaltung dieses Repositories auf Discord schicken**. Wir empfehlen ersteres, wenn du schon mal git benutzt hast und zweiteres, wenn du von diesem System nur Bahnhof verstehst. 72 | 73 | ### Pull Requests erstellen 74 | 75 | 1. Forke dieses Repository in deinen GitHub-Account (oben rechts auf "Fork" klicken) 76 | 2. Klone das Repository bei dir lokal 77 | 3. Füge deine Lösungen hinzu und bearbeite sie - **beachte dabei die [Ordnerstruktur](#ordnerstrukturdirectory-structure)** 78 | 4. Bearbeite **nicht** die README! Die Tabelle wird von uns ergänzt. 79 | 5. Mache eine Pull Request wann immer du 80 | - neue funktionierende Lösung(en) hast 81 | - Lust drauf hast (du musst nicht jeden Tag eine Pull Request machen, kannst dir auch Zeit damit lassen) 82 | 83 | **Bitte achte darauf, dass die Lösungen nicht deine kompletten IDE-Dateien enthalten, sondern ausschließlich den relevanten Quellcode zur Lösung des Problems!** 84 | 85 | ### Lösungen an die Verwaltung geben 86 | 87 | 1. Löse die Aufgabe(n) 88 | 2. Schicke sie an einen der folgenden DevCord-User mit Informationen zu Sprache, Tag, evtl. benötigten zusätzlichen Dateien und Namen: 89 | - `das_#9677` 90 | - `Johnny#3826` 91 | 92 | -------------------------------------------------------------------------------- /shared/GameduJS/FileReader.cpp: -------------------------------------------------------------------------------- 1 | #include "FileReader.h" 2 | #include "fstream" 3 | #include "iostream" 4 | #include "cstring" 5 | 6 | FileReader::FileReader(std::string path) { 7 | this->path=path; 8 | } 9 | 10 | std::vector FileReader::readLines() { 11 | std::ifstream fileStream(path); 12 | 13 | if(!fileStream.is_open()) 14 | return collection; 15 | 16 | std::string line; 17 | while(std::getline(fileStream, line)) 18 | { 19 | collection.push_back(line); 20 | } 21 | 22 | return collection; 23 | } 24 | 25 | std::vector FileReader::readLinesAsInt() { 26 | std::vector strings = readLines(); 27 | std::vector intCollection; 28 | 29 | for(const auto& str : strings) 30 | { 31 | intCollection.push_back(std::stoi(str)); 32 | } 33 | 34 | return intCollection; 35 | } 36 | 37 | std::vector FileReader::split(const std::string& delimiter, const std::string& s) 38 | { 39 | size_t pos_start = 0, pos_end, delim_len = delimiter.length(); 40 | std::string token; 41 | std::vector res; 42 | 43 | while ((pos_end = s.find (delimiter, pos_start)) != std::string::npos) { 44 | token = s.substr (pos_start, pos_end - pos_start); 45 | pos_start = pos_end + delim_len; 46 | res.push_back (token); 47 | } 48 | 49 | res.push_back (s.substr (pos_start)); 50 | return res; 51 | } 52 | -------------------------------------------------------------------------------- /shared/GameduJS/FileReader.h: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Yves on 02.12.2021. 3 | // 4 | 5 | #ifndef AOC_21_FILEREADER_H 6 | #define AOC_21_FILEREADER_H 7 | 8 | #include "string" 9 | #include "vector" 10 | #pragma once 11 | 12 | class FileReader { 13 | public: 14 | FileReader(std::string path); 15 | std::vector readLines(); 16 | std::vector readLinesAsInt(); 17 | std::vector split(const std::string& delimiter, const std::string& s); 18 | private: 19 | std::string path; 20 | std::vector collection; 21 | }; 22 | 23 | 24 | #endif //AOC_21_FILEREADER_H 25 | -------------------------------------------------------------------------------- /shared/justentrix/file_reader.py: -------------------------------------------------------------------------------- 1 | from os.path import join, dirname 2 | 3 | inputs_dir = join(dirname(__file__), 'inputs') 4 | 5 | def read_file(file_name): 6 | return open(f'{inputs_dir}/{file_name}', 'r').read() 7 | 8 | def read_lines(file_name): 9 | content = read_file(file_name) 10 | return content.splitlines() 11 | 12 | def read_numbers(file_name): 13 | lines = read_lines(file_name) 14 | return list(map(int, lines)) 15 | --------------------------------------------------------------------------------