Day 8 - bash

This commit is contained in:
Gleb Koval 2023-12-09 01:02:52 +00:00
parent 663f9012f0
commit bf73a34e73
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
4 changed files with 90 additions and 34 deletions

View File

@ -36,4 +36,9 @@ I'll probably try to vary languages a bit to get some variety.
### [Day 7](day7/)
**Language**: JavaScript (Node)
**Note**: Yes, I used JSDoc for type-hints. But I think only insane people use JavaScript without JSDoc.
**Note**: Yes, I used JSDoc for type-hints. But I think only insane people use JavaScript without JSDoc.
### [Day 8](day8/)
**Language**: Bash
**Note**: Here begin languages I'm not great at.

9
day8/eg1.txt Normal file
View File

@ -0,0 +1,9 @@
RL
AAA = (BBB, CCC)
BBB = (DDD, EEE)
CCC = (ZZZ, GGG)
DDD = (DDD, DDD)
EEE = (EEE, EEE)
GGG = (GGG, GGG)
ZZZ = (ZZZ, ZZZ)

View File

@ -1,33 +0,0 @@
import math
if __name__ == "__main__":
with open("input.txt") as f:
lines = f.read().split("\n")
instructions = lines[0]
d = {}
for l in lines[2:]:
pair = l.split(" = ")
d[pair[0]] = pair[1][1:-1].split(", ")
cur = "AAA"
count = 0
while cur != "ZZZ":
for i in instructions:
count += 1
cur = d[cur][0 if i == "L" else 1]
if cur == "ZZZ":
break
print(count)
cur = [k for k in d.keys() if k[-1] == "A"]
counts = [0 for _ in range(len(cur))]
while not all([s[-1] == "Z" for s in cur]):
for i in instructions:
for idx in range(len(cur)):
if cur[idx][-1] == "Z":
continue
counts[idx] += 1
cur[idx] = d[cur[idx]][0 if i == "L" else 1]
if all([s[-1] == "Z" for s in cur]):
break
print(math.lcm(*counts))

75
day8/solution.sh Executable file
View File

@ -0,0 +1,75 @@
#!/bin/bash
declare -A mappings
gcd() {
local a=$1
local b=$2
while [ $b -ne 0 ]
do
local t=$b
b=$(($a % $b))
a=$t
done
echo ${a#-}
}
lcm() {
local d=$(gcd $1 $2)
echo $(($1 * $2 / $d))
}
findcount() {
cur=$1
instructions=$2
pattern=$3
count=0
while [[ $cur != $pattern ]]
do
for (( idx = 0; idx < ${#instructions}; idx++ ))
do
((count += 1))
instruction=${instructions:$idx:1}
part=0
if [ $instruction = "R" ]
then
part=4
fi
mapping=${mappings[$cur]}
cur=${mapping:$part:3}
if [[ $cur == $pattern ]]
then
break
fi
done
done
echo $count
}
# Parse inputs
file="input.txt"
instructions=$(head -n1 $file)
while read line || [ -n "$line" ]
do
key=${line%% *}
values=${line##*(}
values=${values%)}
mappings[$key]=${values/,/}
done <<< $(tail -n +3 $file)
# Part 1
echo "Part 1: $(findcount "AAA" $instructions "ZZZ")"
# Part 2
count=1
for key in ${!mappings[@]}
do
if [[ $key != *A ]]
then
continue
fi
cur=$key
count=$(lcm $count $(findcount $cur $instructions "*Z"))
done
echo "Part 2: $count"