Skip to content

Commit f96f180

Browse files
committed
Merge branch 'master' of https://github.com/devcordde/adventofcode-20 into master
2 parents be48223 + dbb2328 commit f96f180

File tree

12 files changed

+1493
-0
lines changed

12 files changed

+1493
-0
lines changed

Day-07/kotlin/NyCodeGHG/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
*.txt

Day-07/kotlin/NyCodeGHG/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Kotlin Solution
2+
I recommend to use [kscript](https://github.com/holgerbrandl/kscript) by [@holgerbrandl](https://github.com/holgerbrandl) to execute the script file.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import java.nio.file.Files
2+
import java.nio.file.Paths
3+
import kotlin.system.exitProcess
4+
5+
val allBags = arrayListOf<Bag>()
6+
7+
val contentRegex = "([0-9]+) ([\\w]+ [\\w]+) bag[s]?".toRegex()
8+
9+
val bags = Files.readAllLines(Paths.get("input.txt"))
10+
.map { it.removeSuffix(".") }
11+
.filterNot { it.contains("no other") }
12+
.map { it.replace("bag[s]?".toRegex(), "").replace("contain", ",").split(",") }
13+
.map { it.map(String::trim) }
14+
.map { it[0] to Bag(it[0], toChildBags(it.subList(1, it.size))) }.toMap()
15+
16+
println(bags.filter { it.value.hasColor("shiny gold", bags) }.count())
17+
println(bags["shiny gold"]?.getChildBagNumber(bags))
18+
19+
data class Bag(val color: String, val childBags: Map<String, Int>)
20+
21+
fun Bag.hasColor(color: String, bags: Map<String, Bag>): Boolean =
22+
if (this.childBags.keys.contains(color)) true
23+
else this.childBags.keys.any { bags[it]?.hasColor(color, bags) == true }
24+
25+
fun toChildBags(bags: List<String>): Map<String, Int> {
26+
return bags.map { it.substring(2) to Integer.parseInt(it.substring(0, 1)) }.toMap()
27+
}
28+
29+
fun Bag.getChildBagNumber(bags: Map<String, Bag>): Int {
30+
return this.childBags.map { (bags[it.key]?.getChildBagNumber(bags) ?: 0) * it.value + it.value }.sum()
31+
}

Day-07/python/paul2708/solution.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
from assertions import assert_equals
2+
from input_reader import read_lines
3+
from printer import aoc_print
4+
5+
6+
def contains_bag(root: str, needle: str) -> bool:
7+
ignore_counts = map(lambda x: x[0], bag_rules[root])
8+
9+
if needle in ignore_counts:
10+
return True
11+
else:
12+
for bag in bag_rules[root]:
13+
if contains_bag(bag[0], needle):
14+
return True
15+
16+
return False
17+
18+
19+
def count_bags(root: str) -> int:
20+
total_sum = 0
21+
for rule in bag_rules[root]:
22+
total_sum += rule[1] + rule[1] * count_bags(rule[0])
23+
24+
return total_sum
25+
26+
27+
# Parse input (plz forgive me python god and regex skiller)
28+
rule_list = read_lines("day07")
29+
30+
# {str, [(int,str)]}
31+
bag_rules = {}
32+
33+
for rule in rule_list:
34+
rule = rule[:-1].replace("bags", "").replace("bag", "")
35+
36+
bag = rule.split(" contain ")[0].strip()
37+
container_bags = []
38+
39+
container = rule.split(" contain ")[1].strip()
40+
if "," in container:
41+
for single_bag in container.split(", "):
42+
count = int(single_bag.split(" ")[0])
43+
bag_type = single_bag[len(single_bag.split(" ")[0]):].strip()
44+
container_bags.append((bag_type, count))
45+
elif "no " not in container:
46+
count = int(container.split(" ")[0])
47+
bag_type = container[len(rule.split(" contain ")[1].strip().split(" ")[0]):].strip()
48+
container_bags.append((bag_type, count))
49+
50+
bag_rules[bag] = container_bags
51+
52+
# Part one
53+
res = len([bag for bag in bag_rules.keys() if contains_bag(bag, "shiny gold")])
54+
55+
aoc_print(f"{res} bag colors can contain at least one shiny gold.")
56+
assert_equals(302, res)
57+
58+
# Part two
59+
res = count_bags("shiny gold")
60+
61+
aoc_print(f"It requires {res} bags in my shiny gold bag.")
62+
assert_equals(4165, res)

Day-08/kotlin/NyCodeGHG/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
*.txt

Day-08/kotlin/NyCodeGHG/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Kotlin Solution
2+
I recommend to use [kscript](https://github.com/holgerbrandl/kscript) by [@holgerbrandl](https://github.com/holgerbrandl) to execute the script file.
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import java.nio.file.Files
2+
import java.nio.file.Paths
3+
import kotlin.system.measureTimeMillis
4+
5+
val instructions = Files.readAllLines(Paths.get("input.txt"))
6+
.map { it.split(" ") }
7+
.mapIndexed { index, splitten -> Instruction(index, splitten[0], splitten[1].toInt()) }
8+
.toTypedArray()
9+
10+
val program = Program(instructions.createCopy())
11+
val result = program.execute()
12+
println("accumulator is at ${result.accumulator}")
13+
14+
val alternativeProgramResult = instructions
15+
.filter { it.type in arrayOf("jmp", "nop") }
16+
.map {
17+
val program = Program(instructions.createCopy())
18+
program.instructions[it.index].flipType("jmp", "nop")
19+
program.execute()
20+
}
21+
.firstOrNull { it.exitCode == 0 }
22+
23+
println("accumulator with fixed program is ${alternativeProgramResult?.accumulator}")
24+
25+
fun Instruction.execute(program: Program): Int {
26+
this.executions++
27+
return when (type) {
28+
"acc" -> {
29+
program.accumulator += this.value
30+
1
31+
}
32+
"jmp" -> {
33+
this.value
34+
}
35+
else -> {
36+
1
37+
}
38+
}
39+
}
40+
41+
fun Array<Instruction>.createCopy() = this.map { it.copy() }.toTypedArray()
42+
43+
fun Program.execute(): ExecutionResult {
44+
var currentInstruction = 0
45+
46+
while (currentInstruction < this.instructions.size) {
47+
val instruction = this.instructions[currentInstruction]
48+
if (instruction.executions > 0) {
49+
return ExecutionResult(accumulator, -1)
50+
}
51+
currentInstruction += instruction.execute(this)
52+
}
53+
return ExecutionResult(accumulator, 0)
54+
}
55+
56+
fun Instruction.flipType(first: String, second: String) {
57+
when (this.type) {
58+
first -> {
59+
this.type = second
60+
}
61+
second -> {
62+
this.type = first
63+
}
64+
}
65+
}
66+
67+
data class Program(val instructions: Array<Instruction>, var accumulator: Int = 0)
68+
data class ExecutionResult(val accumulator: Int, val exitCode: Int)
69+
data class Instruction(var index: Int, var type: String, val value: Int, var executions: Int = 0) : Cloneable

Day-08/python/paul2708/solution.py

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
from assertions import assert_equals
2+
from input_reader import read_lines
3+
from printer import aoc_print
4+
5+
6+
class Program():
7+
def __init__(self, instructions: [str]):
8+
self.accumulator = 0
9+
self.instruction_pointer = 0
10+
self.instructions = list(instructions)
11+
12+
def run(self):
13+
instruction = instructions[self.instruction_pointer]
14+
op_code = instruction.split(" ")[0]
15+
16+
self.instruction_pointer += 1
17+
18+
if op_code == "nop":
19+
pass
20+
elif op_code == "jmp":
21+
self.instruction_pointer += int(instruction.split(" ")[1]) - 1
22+
elif op_code == "acc":
23+
self.accumulator += int(instruction.split(" ")[1])
24+
else:
25+
print("invalid instruction")
26+
27+
def run_all(self):
28+
while self.instruction_pointer < len(instructions):
29+
self.run()
30+
31+
def terminates(self) -> bool:
32+
executed_lines = set()
33+
34+
while self.instruction_pointer not in executed_lines:
35+
executed_lines.add(program.instruction_pointer)
36+
37+
if self.instruction_pointer >= len(self.instructions):
38+
return True
39+
40+
self.run()
41+
42+
return False
43+
44+
45+
instructions = read_lines("day08")
46+
program = Program(instructions)
47+
48+
# Part one
49+
program.terminates()
50+
51+
aoc_print(f"The program gets interrupted with an accumulator of {program.accumulator}.")
52+
assert_equals(1801, program.accumulator)
53+
54+
55+
# Part two
56+
def replace_all(base_list: [str], old: str, new: str) -> [[str]]:
57+
total = list()
58+
index = 0
59+
60+
while True:
61+
tup = replace(list(base_list), old, new, index)
62+
if tup[1] == -1:
63+
break
64+
65+
total.append(tup[0])
66+
index = tup[1]
67+
68+
return total
69+
70+
71+
def replace(replacement_list: [str], old: str, new: str, start: int) -> ([str], int):
72+
for i in range(start, len(replacement_list)):
73+
if old in replacement_list[i]:
74+
replacement_list[i] = replacement_list[i].replace(old, new)
75+
return replacement_list, i + 1
76+
77+
return [], -1
78+
79+
80+
replaced_instructions_list = replace_all(instructions, "jmp", "nop") \
81+
+ replace_all(instructions, "nop", "jmp")
82+
83+
for instructions in replaced_instructions_list:
84+
program = Program(instructions)
85+
if program.terminates():
86+
program = Program(instructions)
87+
program.run_all()
88+
89+
aoc_print(f"The program terminates with an accumulator of {program.accumulator}.")
90+
assert_equals(2060, program.accumulator)

0 commit comments

Comments
 (0)