Advent of Code 2022 Day 2
Language of the day: Nim
Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula.
In general Nim looks less “close to the machine” than Zig yesterday.
Installation is easier than yesterday, just sudo aptitude install nim
Compiling: nim c day2.nim
Task of the day
A list of two letter combinations is given, each letter signifies a rock, paper, scissors symbol, so the two letters are a round and the task is to count the points of one of the players (6 for winning, 1 for rock, 2 for paper, 3 for scissors).
The second task changes the meaning of the strategy and therefore the computation of the sum.
The code
The code can be found here. Let’s go through it:
import strutils
Import some string utilites
let file = readFile("../input.txt")
Read the input from a file and make it available as a string. Not sure if this is done at compile or runtime.
let games = file.splitlines()
Split the string by line endings.
var sum = 0
# Part one
for game in games:
case game
of "A X":
sum += 3 + 1
of "B X":
sum += 0 + 1
of "C X":
sum += 6 + 1
of "A Y":
sum += 6 + 2
of "B Y":
sum += 3 + 2
of "C Y":
sum += 0 + 2
of "A Z":
sum += 0 + 3
of "B Z":
sum += 6 + 3
of "C Z":
sum += 3 + 3
echo $sum
First a variable sum
is declared by using var
(which means it is mutable). I did not add a type
declaration here, although that is possible, just for the reason of being lazy.
Then the for
loop iterates over the lines. I chose to implement the scenarios with switch .. case
since the number of scenarios is quite small (9) and I did not want to implement some smarter logic.
Lastly the sum is printed using echo
and $sum
automagically transforms the number to it’s string
representation.
# Part two
var sum2 = 0
for game in games:
case game
of "A X":
sum2 += 0 + 3
of "B X":
sum2 += 0 + 1
of "C X":
sum2 += 0 + 2
of "A Y":
sum2 += 3 + 1
of "B Y":
sum2 += 3 + 2
of "C Y":
sum2 += 3 + 3
of "A Z":
sum2 += 6 + 2
of "B Z":
sum2 += 6 + 3
of "C Z":
sum2 += 6 + 1
echo $sum2
This is pretty much the same as above, but with different values for the games.
Conclusion
Given that specific kind of task, it was much easier and fast to implement it in Nim than in Zig, which is probably not surprising given the focus of the two languages. Also Nim might be more mature than Zig, although this judgement is mostly taken from the fact, that it is packaged in debian. In general, Nim is probably worth a look if the low level control is not needed, but again one should probably have spent more than an hour using it, to be a judge of that.