fix some warnings and switch to target-type new()
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Ben Harris 2021-12-01 14:56:16 -05:00
parent 212278cc64
commit d56f59b19b
18 changed files with 94 additions and 113 deletions

View File

@ -16,12 +16,12 @@ public sealed class Day01 : Day
private static int FullCost(int cost) private static int FullCost(int cost)
{ {
int total = 0, newcost, tmp = cost; int total = 0, newCost, tmp = cost;
while ((newcost = FuelCost(tmp)) >= 0) while ((newCost = FuelCost(tmp)) >= 0)
{ {
total += newcost; total += newCost;
tmp = newcost; tmp = newCost;
} }
return total; return total;

View File

@ -9,7 +9,7 @@ public sealed class Day02 : Day
input = Input.First().Split(',').Select(int.Parse); input = Input.First().Split(',').Select(int.Parse);
} }
public int RunIntCode(int noun, int verb) private int RunIntCode(int noun, int verb)
{ {
var v = input.ToList(); var v = input.ToList();
v[1] = noun; v[1] = noun;
@ -19,7 +19,8 @@ public sealed class Day02 : Day
v[v[i + 3]] = v[i] switch v[v[i + 3]] = v[i] switch
{ {
1 => v[v[i + 1]] + v[v[i + 2]], 1 => v[v[i + 1]] + v[v[i + 2]],
2 => v[v[i + 1]] * v[v[i + 2]] 2 => v[v[i + 1]] * v[v[i + 2]],
_ => throw new ArgumentOutOfRangeException(nameof(verb))
}; };
return v[0]; return v[0];

View File

@ -25,24 +25,24 @@ public sealed class Day03 : Day
private static Dictionary<(int, int), int> ParseWire(string line) private static Dictionary<(int, int), int> ParseWire(string line)
{ {
var r = new Dictionary<(int, int), int>(); var r = new Dictionary<(int, int), int>();
int x = 0, y = 0, c = 0, i; int x = 0, y = 0, c = 0;
foreach (var step in line.Split(',')) foreach (var step in line.Split(','))
{ {
var d = int.Parse(step[1..]); int i = 0, d = int.Parse(step[1..]);
switch (step[0]) switch (step[0])
{ {
case 'U': case 'U':
for (i = 0; i < d; i++) r.TryAdd((x, ++y), c++); for (; i < d; i++) r.TryAdd((x, ++y), c++);
break; break;
case 'D': case 'D':
for (i = 0; i < d; i++) r.TryAdd((x, --y), c++); for (; i < d; i++) r.TryAdd((x, --y), c++);
break; break;
case 'R': case 'R':
for (i = 0; i < d; i++) r.TryAdd((++x, y), c++); for (; i < d; i++) r.TryAdd((++x, y), c++);
break; break;
case 'L': case 'L':
for (i = 0; i < d; i++) r.TryAdd((--x, y), c++); for (; i < d; i++) r.TryAdd((--x, y), c++);
break; break;
} }
} }

View File

@ -2,9 +2,7 @@
public sealed class Day04 : Day public sealed class Day04 : Day
{ {
private readonly int end; private readonly int start, end;
private readonly int start;
public Day04() : base(4, "Secure Container") public Day04() : base(4, "Secure Container")
{ {
@ -17,9 +15,8 @@ public sealed class Day04 : Day
{ {
var prev = 0; var prev = 0;
var hasDup = false; var hasDup = false;
foreach (var c in i.ToString()) foreach (var curr in i.ToString().Select(c => c - '0'))
{ {
var curr = c - '0';
if (curr < prev) return false; if (curr < prev) return false;
if (curr == prev) hasDup = true; if (curr == prev) hasDup = true;
prev = curr; prev = curr;
@ -34,13 +31,9 @@ public sealed class Day04 : Day
return IsValid(i) && s.Select(c => s.Count(j => j == c)).Any(c => c == 2); return IsValid(i) && s.Select(c => s.Count(j => j == c)).Any(c => c == 2);
} }
public override string Part1() public override string Part1() =>
{ $"{Enumerable.Range(start, end).Count(IsValid)}";
return $"{Enumerable.Range(start, end).Count(IsValid)}";
}
public override string Part2() public override string Part2() =>
{ $"{Enumerable.Range(start, end).Count(HasOnePair)}";
return $"{Enumerable.Range(start, end).Count(HasOnePair)}";
}
} }

View File

@ -3,7 +3,6 @@
public sealed class Day05 : Day public sealed class Day05 : Day
{ {
private readonly IEnumerable<int> tape; private readonly IEnumerable<int> tape;
private int output; private int output;
public Day05() : base(5, "Sunny with a Chance of Asteroids") public Day05() : base(5, "Sunny with a Chance of Asteroids")
@ -11,7 +10,7 @@ public sealed class Day05 : Day
tape = Input.First().Split(',').Select(int.Parse); tape = Input.First().Split(',').Select(int.Parse);
} }
public void RunIntCode(List<int> v, int input) private void RunIntCode(IList<int> v, int input)
{ {
var i = 0; var i = 0;
while (i < v.Count && v[i] != 99) while (i < v.Count && v[i] != 99)

View File

@ -18,10 +18,8 @@ public sealed class Day06 : Day
return res; return res;
} }
public override string Part1() public override string Part1() =>
{ $"{input.Keys.Sum(o => GetParents(o).Count - 1)}";
return $"{input.Keys.Sum(o => GetParents(o).Count - 1)}";
}
public override string Part2() public override string Part2()
{ {

View File

@ -6,7 +6,7 @@ public sealed class Day07 : Day
public Day07() : base(7, "Amplification Circuit") public Day07() : base(7, "Amplification Circuit")
{ {
for (var i = 0; i < 5; i++) amplifiers[i] = new IntCodeVM(Input.First()); for (var i = 0; i < 5; i++) amplifiers[i] = new(Input.First());
} }
public override string Part1() public override string Part1()

View File

@ -6,7 +6,7 @@ public sealed class Day09 : Day
public Day09() : base(9, "Sensor Boost") public Day09() : base(9, "Sensor Boost")
{ {
vm = new IntCodeVM(Input.First()); vm = new(Input.First());
} }
public override string Part1() public override string Part1()

View File

@ -8,7 +8,7 @@ public sealed class Day11 : Day
public Day11() : base(11, "Space Police") public Day11() : base(11, "Space Police")
{ {
vm = new IntCodeVM(Input.First()); vm = new(Input.First());
} }
private void Move() private void Move()
@ -34,21 +34,14 @@ public sealed class Day11 : Day
private void Turn(long direction) private void Turn(long direction)
{ {
switch (heading) heading = heading switch
{ {
case Direction.Up: Direction.Up => direction == 0 ? Direction.Left : Direction.Right,
heading = direction == 0 ? Direction.Left : Direction.Right; Direction.Down => direction == 0 ? Direction.Right : Direction.Left,
break; Direction.Left => direction == 0 ? Direction.Down : Direction.Up,
case Direction.Down: Direction.Right => direction == 0 ? Direction.Up : Direction.Down,
heading = direction == 0 ? Direction.Right : Direction.Left; _ => heading
break; };
case Direction.Left:
heading = direction == 0 ? Direction.Down : Direction.Up;
break;
case Direction.Right:
heading = direction == 0 ? Direction.Up : Direction.Down;
break;
}
Move(); Move();
} }
@ -73,10 +66,7 @@ public sealed class Day11 : Day
return map; return map;
} }
public override string Part1() public override string Part1() => $"{PaintShip(0).Count}";
{
return $"{PaintShip(0).Count}";
}
public override string Part2() public override string Part2()
{ {

View File

@ -22,15 +22,17 @@ public sealed class Day12 : Day
moon.SetSiblings(moons); moon.SetSiblings(moons);
} }
public static long LCM(long a, long b) private static long Lcm(long a, long b) => a * b / Gcd(a, b);
{
return a * b / GCD(a, b);
}
public static long GCD(long a, long b) private static long Gcd(long a, long b)
{ {
if (b == 0) return a; while (true)
return GCD(b, a % b); {
if (b == 0) return a;
var a1 = a;
a = b;
b = a1 % b;
}
} }
private void Step() private void Step()
@ -59,65 +61,65 @@ public sealed class Day12 : Day
while (cycleX == 0 || cycleY == 0 || cycleZ == 0) while (cycleX == 0 || cycleY == 0 || cycleZ == 0)
{ {
Step(); Step();
if (cycleX == 0 && moons.All(m => m.dx == 0)) cycleX = step * 2; if (cycleX == 0 && moons.All(m => m.Dx == 0)) cycleX = step * 2;
if (cycleY == 0 && moons.All(m => m.dy == 0)) cycleY = step * 2; if (cycleY == 0 && moons.All(m => m.Dy == 0)) cycleY = step * 2;
if (cycleZ == 0 && moons.All(m => m.dz == 0)) cycleZ = step * 2; if (cycleZ == 0 && moons.All(m => m.Dz == 0)) cycleZ = step * 2;
} }
return $"{LCM(cycleX, LCM(cycleY, cycleZ))}"; return $"{Lcm(cycleX, Lcm(cycleY, cycleZ))}";
} }
public class Position public class Position
{ {
public int dx, dy, dz; public int Dx, Dy, Dz;
private List<Position> siblings; private List<Position> siblings;
public int x, y, z; private int x, y, z;
public Position(IList<int> moon) public Position(IList<int> moon)
{ {
x = moon[0]; x = moon[0];
y = moon[1]; y = moon[1];
z = moon[2]; z = moon[2];
dx = 0; Dx = 0;
dy = 0; Dy = 0;
dz = 0; Dz = 0;
siblings = new(); siblings = new();
} }
internal int KineticEnergy => private int KineticEnergy =>
Math.Abs(x) + Math.Abs(y) + Math.Abs(z); Math.Abs(x) + Math.Abs(y) + Math.Abs(z);
internal int PotentialEnergy => private int PotentialEnergy =>
Math.Abs(dx) + Math.Abs(dy) + Math.Abs(dz); Math.Abs(Dx) + Math.Abs(Dy) + Math.Abs(Dz);
internal int TotalEnergy => internal int TotalEnergy =>
KineticEnergy * PotentialEnergy; KineticEnergy * PotentialEnergy;
public void SetSiblings(List<Position> positions) public void SetSiblings(IEnumerable<Position> positions)
{ {
siblings = positions.Where(p => p != this).ToList(); siblings = positions.Where(p => p != this).ToList();
} }
public override string ToString() public override string ToString()
{ {
return $"pos=<x={x}, y={y}, z={z}> vel=<x={dx}, y={dy}, z={dz}>"; return $"pos=<x={x}, y={y}, z={z}> vel=<x={Dx}, y={Dy}, z={Dz}>";
} }
internal void Gravitate() internal void Gravitate()
{ {
foreach (var m in siblings) foreach (var m in siblings)
{ {
if (x != m.x) dx += x > m.x ? -1 : 1; if (x != m.x) Dx += x > m.x ? -1 : 1;
if (y != m.y) dy += y > m.y ? -1 : 1; if (y != m.y) Dy += y > m.y ? -1 : 1;
if (z != m.z) dz += z > m.z ? -1 : 1; if (z != m.z) Dz += z > m.z ? -1 : 1;
} }
} }
internal void Move() internal void Move()
{ {
x += dx; x += Dx;
y += dy; y += Dy;
z += dz; z += Dz;
} }
} }
} }

View File

@ -3,12 +3,11 @@ namespace aoc2019;
public sealed class Day13 : Day public sealed class Day13 : Day
{ {
private readonly Dictionary<(int x, int y), int> board; private readonly Dictionary<(int x, int y), int> board;
private readonly IntCodeVM vm; private readonly IntCodeVM vm;
public Day13() : base(13, "Care Package") public Day13() : base(13, "Care Package")
{ {
vm = new IntCodeVM(Input.First()); vm = new(Input.First());
board = new Dictionary<(int, int), int>(); board = new Dictionary<(int, int), int>();
} }

View File

@ -10,7 +10,7 @@ public sealed class Day14 : Day
{ {
reactions = Input reactions = Input
.Select(Reaction.Parse) .Select(Reaction.Parse)
.ToDictionary(r => r.product.Name); .ToDictionary(r => r.Product.Name);
available = new(); available = new();
} }
@ -36,19 +36,18 @@ public sealed class Day14 : Day
return false; return false;
var reaction = reactions[chem]; var reaction = reactions[chem];
var reactionCount = (long)Math.Ceiling((double)quantity / reaction.product.Quantity); var reactionCount = (long)Math.Ceiling((double)quantity / reaction.Product.Quantity);
foreach (var reactant in reaction.reactants) if (reaction.Reactants.Any(reactant => !Consume(reactant.Name, reactionCount * reactant.Quantity)))
if (!Consume(reactant.Name, reactionCount * reactant.Quantity)) return false;
return false;
available[chem] = available.GetValueOrDefault(chem) + reactionCount * reaction.product.Quantity; available[chem] = available.GetValueOrDefault(chem) + reactionCount * reaction.Product.Quantity;
return true; return true;
} }
public override string Part1() public override string Part1()
{ {
available = new Dictionary<string, long> { { "ORE", long.MaxValue } }; available = new() { { "ORE", long.MaxValue } };
Consume("FUEL", 1); Consume("FUEL", 1);
return $"{long.MaxValue - available["ORE"]}"; return $"{long.MaxValue - available["ORE"]}";
} }
@ -56,7 +55,7 @@ public sealed class Day14 : Day
public override string Part2() public override string Part2()
{ {
const long capacity = 1_000_000_000_000; const long capacity = 1_000_000_000_000;
available = new Dictionary<string, long> { { "ORE", capacity } }; available = new() { { "ORE", capacity } };
Consume("FUEL", 1); Consume("FUEL", 1);
var oreConsumed = capacity - available["ORE"]; var oreConsumed = capacity - available["ORE"];
@ -69,26 +68,26 @@ public sealed class Day14 : Day
private struct Component private struct Component
{ {
public string Name { get; set; } public string Name { get; init; }
public int Quantity { get; set; } public int Quantity { get; init; }
} }
private class Reaction private class Reaction
{ {
public readonly Component product; public readonly Component Product;
public readonly Component[] reactants; public readonly Component[] Reactants;
private Reaction(Component[] reactants, Component product) private Reaction(Component[] reactants, Component product)
{ {
this.reactants = reactants; Reactants = reactants;
this.product = product; Product = product;
} }
public static Reaction Parse(string s) public static Reaction Parse(string s)
{ {
var ss = s.Split(new[] { ", ", " => " }, StringSplitOptions.None); var ss = s.Split(new[] { ", ", " => " }, StringSplitOptions.None);
return new Reaction( return new(
ss.Take(ss.Length - 1).Select(ParseComponent).ToArray(), ss.Take(ss.Length - 1).Select(ParseComponent).ToArray(),
ParseComponent(ss[^1]) ParseComponent(ss[^1])
); );
@ -96,7 +95,7 @@ public sealed class Day14 : Day
static Component ParseComponent(string s) static Component ParseComponent(string s)
{ {
var spl = s.Split(' ', 2); var spl = s.Split(' ', 2);
return new Component return new()
{ {
Quantity = int.Parse(spl[0]), Quantity = int.Parse(spl[0]),
Name = spl[1] Name = spl[1]

View File

@ -7,7 +7,7 @@ public sealed class Day15 : Day
public Day15() : base(15, "Oxygen System") public Day15() : base(15, "Oxygen System")
{ {
vm = new IntCodeVM(Input.First()); vm = new(Input.First());
} }
public override string Part1() public override string Part1()
@ -30,13 +30,13 @@ public sealed class Day15 : Day
_ = new Location(x, y, Location.Opposites[direction], Location.Wall); _ = new Location(x, y, Location.Opposites[direction], Location.Wall);
break; break;
case Location.Empty: case Location.Empty:
currentLocation = new Location(x, y, Location.Opposites[direction]); currentLocation = new(x, y, Location.Opposites[direction]);
break; break;
case Location.System: case Location.System:
currentLocation = new Location(x, y, Location.Opposites[direction], Location.System); currentLocation = new(x, y, Location.Opposites[direction], Location.System);
break; break;
default: default:
throw new Exception($"Unknown IntCodeVM response: {vm.Result}"); throw new($"Unknown IntCodeVM response: {vm.Result}");
} }
} }
} }
@ -49,7 +49,7 @@ public sealed class Day15 : Day
currentLocation = vm.Result switch currentLocation = vm.Result switch
{ {
Location.Empty or Location.System => Location.GetLocation(currentLocation.Neighbor(direction)), Location.Empty or Location.System => Location.GetLocation(currentLocation.Neighbor(direction)),
_ => throw new Exception($"Unknown or unexpected response for previous room: {vm.Result}") _ => throw new($"Unknown or unexpected response for previous room: {vm.Result}")
}; };
} }
else else

View File

@ -19,7 +19,7 @@ public sealed class Day16 : Day
for (var i = 0; i < phaseCount; i++) for (var i = 0; i < phaseCount; i++)
CalculateSignal(i % 2 == 0 ? signal0 : signal1, i % 2 == 0 ? signal1 : signal0); CalculateSignal(i % 2 == 0 ? signal0 : signal1, i % 2 == 0 ? signal1 : signal0);
return new string( return new(
signal0.Take(8).Select(c => (char)(c + '0')) signal0.Take(8).Select(c => (char)(c + '0'))
.ToArray()); .ToArray());
} }
@ -37,7 +37,7 @@ public sealed class Day16 : Day
signal[i] = (signal[i + 1] + signal[i]) % 10; signal[i] = (signal[i + 1] + signal[i]) % 10;
} }
return new string(signal.Take(8).Select(c => (char)(c + '0')).ToArray()); return new(signal.Take(8).Select(c => (char)(c + '0')).ToArray());
} }
private static void CalculateSignal(IReadOnlyList<int> input, IList<int> output) private static void CalculateSignal(IReadOnlyList<int> input, IList<int> output)

View File

@ -6,7 +6,7 @@ public sealed class Day17 : Day
public Day17() : base(17, "Set and Forget") public Day17() : base(17, "Set and Forget")
{ {
vm = new IntCodeVM(Input.First()); vm = new(Input.First());
} }
public override string Part1() public override string Part1()

View File

@ -7,7 +7,7 @@ public sealed class Day19 : Day
public Day19() : base(19, "Tractor Beam") public Day19() : base(19, "Tractor Beam")
{ {
vm = new IntCodeVM(Input.First()); vm = new(Input.First());
grid = new long[50, 50]; grid = new long[50, 50];
} }

View File

@ -6,7 +6,7 @@ public sealed class Day21 : Day
public Day21() : base(21, "Springdroid Adventure") public Day21() : base(21, "Springdroid Adventure")
{ {
vm = new IntCodeVM(Input.First()); vm = new(Input.First());
} }
public override string Part1() public override string Part1()

View File

@ -22,8 +22,8 @@ public class IntCodeVM
relativeBase = 0; relativeBase = 0;
program = tape.Split(',').Select(long.Parse).ToArray(); program = tape.Split(',').Select(long.Parse).ToArray();
Memory = program; Memory = program;
input = new Queue<long>(); input = new();
Output = new Queue<long>(); Output = new();
} }
public long Result => Output.Dequeue(); public long Result => Output.Dequeue();
@ -76,7 +76,7 @@ public class IntCodeVM
0 => MemGet(param), 0 => MemGet(param),
1 => param, 1 => param,
2 => MemGet(relativeBase + param), 2 => MemGet(relativeBase + param),
_ => throw new Exception("invalid parameter mode") _ => throw new("invalid parameter mode")
}; };
} }
@ -88,11 +88,11 @@ public class IntCodeVM
case 0: case 0:
MemSet(param, val); MemSet(param, val);
break; break;
case 1: throw new Exception("cannot set in immediate mode"); case 1: throw new("cannot set in immediate mode");
case 2: case 2:
MemSet(relativeBase + param, val); MemSet(relativeBase + param, val);
break; break;
default: throw new Exception("invalid parameter mode"); default: throw new("invalid parameter mode");
} }
} }
@ -148,7 +148,7 @@ public class IntCodeVM
case 99: case 99:
return HaltType.Terminate; return HaltType.Terminate;
default: default:
throw new Exception($"unknown op {op} at {i}"); throw new($"unknown op {op} at {i}");
} }
} }