Skip to content

Instantly share code, notes, and snippets.

@JamesMenetrey
Created December 2, 2021 13:48
Show Gist options
  • Save JamesMenetrey/9725f92b2167c1956fb7addca7bd1c4b to your computer and use it in GitHub Desktop.
Save JamesMenetrey/9725f92b2167c1956fb7addca7bd1c4b to your computer and use it in GitHub Desktop.
Advent of Code 2021 - day 2
// Advent of Code 2021, day 2, part 1.
// Solved using funny immutable and functional C#.
// Written by Jämes Ménétrey.
using System;
using System.IO;
using System.Linq;
var result = File.ReadAllLines("input.txt")
.Aggregate(new Submarine(), ParseInput, submarine => submarine.Result);
Console.WriteLine($"Result: {result}");
Submarine ParseInput(Submarine submarine, string input)
{
var (movement, x) = input.Split(' ') switch
{
var split when split.Length == 2 => (split[0], int.Parse(split[1])),
var split => throw new Exception($"The input '{split}' is invalid.")
};
return movement switch
{
"forward" => submarine.Forward(x),
"down" => submarine.Down(x),
"up" => submarine.Up(x),
_ => throw new Exception($"The action '{movement}' is not recognized.")
};
}
record Submarine(int Horizontal = 0, int Depth = 0)
{
public Submarine Forward(int x) => this with { Horizontal = Horizontal + x };
public Submarine Down(int x) => this with { Depth = Depth + x };
public Submarine Up(int x) => this with { Depth = Depth - x };
public int Result => Horizontal * Depth;
}
// Advent of Code 2021, day 2, part 2.
// Solved using funny immutable and functional C#.
// Written by Jämes Ménétrey.
using System;
using System.IO;
using System.Linq;
var result = File.ReadAllLines("input.txt")
.Aggregate(new Submarine(), ParseInput, submarine => submarine.Result);
Console.WriteLine($"Result: {result}");
Submarine ParseInput(Submarine submarine, string input)
{
var (movement, x) = input.Split(' ') switch
{
var split when split.Length == 2 => (split[0], int.Parse(split[1])),
var split => throw new Exception($"The input '{split}' is invalid.")
};
return movement switch
{
"forward" => submarine.Forward(x),
"down" => submarine.Down(x),
"up" => submarine.Up(x),
_ => throw new Exception($"The action '{movement}' is not recognized.")
};
}
record Submarine(int Horizontal = 0, int Depth = 0, int Aim = 0)
{
public Submarine Forward(int x) => this with { Horizontal = Horizontal + x, Depth = Depth + Aim * x };
public Submarine Down(int x) => this with { Aim = Aim + x };
public Submarine Up(int x) => this with { Aim = Aim - x };
public int Result => Horizontal * Depth;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment