From 36bb28af87e81a9b3cab1abd79d11106cd610f6c Mon Sep 17 00:00:00 2001 From: Ben Harris Date: Wed, 2 Dec 2020 00:36:24 -0500 Subject: [PATCH] update gitignore and run resharper cleanup --- .gitignore | 436 ++++++++++++++++++++++++++++++++++++++++++++-- Day.cs | 3 +- Day1.cs | 23 ++- Day10.cs | 14 +- Day11.cs | 73 +++++--- Day12.cs | 123 +++++++------ Day13.cs | 12 +- Day14.cs | 97 ++++++----- Day15.cs | 89 +--------- Day16.cs | 10 +- Day2.cs | 17 +- Day3.cs | 22 ++- Day4.cs | 18 +- Day5.cs | 17 +- Day6.cs | 15 +- Day7.cs | 10 +- Day8.cs | 9 +- Day9.cs | 7 +- Program.cs | 12 +- lib/Extensions.cs | 9 +- lib/IntCodeVM.cs | 54 +++--- 21 files changed, 735 insertions(+), 335 deletions(-) diff --git a/.gitignore b/.gitignore index b5e7d97..920d1cd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,18 +1,21 @@ -*.swp -*.*~ -project.lock.json -.DS_Store -*.pyc - -# Visual Studio Code -.vscode +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # User-specific files +*.rsuser *.suo *.user *.userosscache *.sln.docstates +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + # Build results [Dd]ebug/ [Dd]ebugPublic/ @@ -20,13 +23,420 @@ project.lock.json [Rr]eleases/ x64/ x86/ -build/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ bld/ [Bb]in/ [Oo]bj/ -msbuild.log -msbuild.err -msbuild.wrn +[Ll]og/ +[Ll]ogs/ -# Visual Studio 2015 +# Visual Studio 2015/2017 cache/options directory .vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*[.json, .xml, .info] + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# JetBrains Rider +.idea/ +*.sln.iml + +## +## Visual Studio Code +## +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json diff --git a/Day.cs b/Day.cs index 54c4b5d..d8e7e7c 100644 --- a/Day.cs +++ b/Day.cs @@ -8,6 +8,7 @@ namespace aoc2019 public abstract class Day { public abstract int DayNumber { get; } + public virtual IEnumerable Input => File.ReadLines($"input/day{DayNumber}.in"); @@ -33,4 +34,4 @@ namespace aoc2019 public abstract string Part1(); public abstract string Part2(); } -} +} \ No newline at end of file diff --git a/Day1.cs b/Day1.cs index 53b808c..979db5f 100644 --- a/Day1.cs +++ b/Day1.cs @@ -5,15 +5,20 @@ namespace aoc2019 { internal sealed class Day1 : Day { - public override int DayNumber => 1; - private readonly IEnumerable masses; + public Day1() { masses = Input.Select(int.Parse); } - private static int FuelCost(int weight) => weight / 3 - 2; + public override int DayNumber => 1; + + private static int FuelCost(int weight) + { + return weight / 3 - 2; + } + private static int FullCost(int cost) { int total = 0, newcost, tmp = cost; @@ -27,8 +32,14 @@ namespace aoc2019 return total; } - public override string Part1() => $"{masses.Sum(FuelCost)}"; + public override string Part1() + { + return $"{masses.Sum(FuelCost)}"; + } - public override string Part2() => $"{masses.Sum(FullCost)}"; + public override string Part2() + { + return $"{masses.Sum(FullCost)}"; + } } -} +} \ No newline at end of file diff --git a/Day10.cs b/Day10.cs index eec1e57..5886556 100644 --- a/Day10.cs +++ b/Day10.cs @@ -1,14 +1,12 @@ -using aoc2019.lib; using System; using System.Collections.Generic; using System.Linq; +using aoc2019.lib; namespace aoc2019 { internal sealed class Day10 : Day { - public override int DayNumber => 10; - private readonly HashSet<(int x, int y)> asteroids = new HashSet<(int x, int y)>(); private (int x, int y) best = (x: -1, y: -1); private int bestcansee; @@ -23,12 +21,14 @@ namespace aoc2019 .ToHashSet(); } + public override int DayNumber => 10; + public override string Part1() { foreach (var asteroid in asteroids) { var cansee = asteroids - .Except(new[] { asteroid }) + .Except(new[] {asteroid}) .Select(a => (x: a.x - asteroid.x, y: a.y - asteroid.y)) .GroupBy(a => Math.Atan2(a.y, a.x)) .Count(); @@ -39,12 +39,14 @@ namespace aoc2019 bestcansee = cansee; } } + return $"{bestcansee}"; } public override string Part2() { - static IEnumerable<(int x, int y, double angle, double dist)> GetValue(Queue<(int x, int y, double angle, double dist)> q) + static IEnumerable<(int x, int y, double angle, double dist)> GetValue( + Queue<(int x, int y, double angle, double dist)> q) { if (q.Count > 0) yield return q.Dequeue(); } @@ -70,4 +72,4 @@ namespace aoc2019 .ToString(); } } -} +} \ No newline at end of file diff --git a/Day11.cs b/Day11.cs index 4fc323b..647be9a 100644 --- a/Day11.cs +++ b/Day11.cs @@ -1,48 +1,62 @@ -using aoc2019.lib; using System; using System.Collections.Generic; using System.Linq; +using aoc2019.lib; namespace aoc2019 { internal sealed class Day11 : Day { - public override int DayNumber => 11; - private readonly IntCodeVM vm; - private long x, y; private Direction heading; + private long x, y; public Day11() { vm = new IntCodeVM(Input.First()); } - enum Direction - { - Up, Down, Left, Right - } + public override int DayNumber => 11; private void Move() { switch (heading) { - case Direction.Up: y++; break; - case Direction.Down: y--; break; - case Direction.Left: x--; break; - case Direction.Right: x++; break; - }; + case Direction.Up: + y++; + break; + case Direction.Down: + y--; + break; + case Direction.Left: + x--; + break; + case Direction.Right: + x++; + break; + } + + ; } private void Turn(long direction) { switch (heading) { - case Direction.Up: heading = direction == 0 ? Direction.Left : Direction.Right; break; - case Direction.Down: heading = direction == 0 ? Direction.Right : Direction.Left; break; - case Direction.Left: heading = direction == 0 ? Direction.Down : Direction.Up; break; - case Direction.Right: heading = direction == 0 ? Direction.Up : Direction.Down; break; + case Direction.Up: + heading = direction == 0 ? Direction.Left : Direction.Right; + break; + case Direction.Down: + heading = direction == 0 ? Direction.Right : Direction.Left; + break; + case Direction.Left: + heading = direction == 0 ? Direction.Down : Direction.Up; + break; + case Direction.Right: + heading = direction == 0 ? Direction.Up : Direction.Down; + break; } + Move(); } @@ -51,7 +65,8 @@ namespace aoc2019 var map = new Dictionary<(long, long), long>(); vm.Reset(); heading = Direction.Up; - x = 0; y = 0; + x = 0; + y = 0; map[(x, y)] = initialVal; var haltType = IntCodeVM.HaltType.Waiting; @@ -73,19 +88,27 @@ namespace aoc2019 public override string Part2() { var map = PaintShip(1); - int minX = (int)map.Keys.Select(x => x.x).Min(); - int maxX = (int)map.Keys.Select(x => x.x).Max(); - int minY = (int)map.Keys.Select(x => x.y).Min(); - int maxY = (int)map.Keys.Select(x => x.y).Max(); + var minX = (int) map.Keys.Select(x => x.x).Min(); + var maxX = (int) map.Keys.Select(x => x.x).Max(); + var minY = (int) map.Keys.Select(x => x.y).Min(); + var maxY = (int) map.Keys.Select(x => x.y).Max(); return Enumerable.Range(minY, maxY - minY + 1) .Select(y => Enumerable.Range(minX, maxX - minX + 1) - .Select(x => map.GetValueOrDefault((x, y)) == 0 ? ' ' : '#') - .ToDelimitedString() + .Select(x => map.GetValueOrDefault((x, y)) == 0 ? ' ' : '#') + .ToDelimitedString() ) .Reverse() .ToDelimitedString(Environment.NewLine); } + + private enum Direction + { + Up, + Down, + Left, + Right + } } -} +} \ No newline at end of file diff --git a/Day12.cs b/Day12.cs index efb380a..b04426d 100644 --- a/Day12.cs +++ b/Day12.cs @@ -1,4 +1,3 @@ -using aoc2019.lib; using System; using System.Collections.Generic; using System.Linq; @@ -7,21 +6,20 @@ namespace aoc2019 { internal sealed class Day12 : Day { - public override int DayNumber => 12; - - private List moons; private readonly List startingPositions; + + private readonly List moons; private int step; public Day12() { moons = Input - .Select(moon => + .Select(moon => moon - .TrimStart('<') - .TrimEnd('>') - .Split(",") - .Select(val => int.Parse(val.Split("=").Last())) + .TrimStart('<') + .TrimEnd('>') + .Split(",") + .Select(val => int.Parse(val.Split("=").Last())) ) .Select(moon => new Position(moon.ToList())) .ToList(); @@ -32,56 +30,11 @@ namespace aoc2019 startingPositions = moons; } - public class Position - { - public int x, y, z; - public int dx, dy, dz; - List siblings; - - public Position(IList moon) - { - x = moon[0]; - y = moon[1]; - z = moon[2]; - dx = 0; dy = 0; dz = 0; - } - - public void SetSiblings(List positions) - { - siblings = positions.Where(p => p != this).ToList(); - } - - public override string ToString() => - $"pos= vel="; - - internal void Gravitate() - { - foreach (var m in siblings) - { - if (x != m.x) dx += x > m.x ? -1 : 1; - if (y != m.y) dy += y > m.y ? -1 : 1; - if (z != m.z) dz += z > m.z ? -1 : 1; - } - } - - internal void Move() - { - x += dx; - y += dy; - z += dz; - } - - internal int KineticEnergy => - Math.Abs(x) + Math.Abs(y) + Math.Abs(z); - internal int PotentialEnergy => - Math.Abs(dx) + Math.Abs(dy) + Math.Abs(dz); - internal int TotalEnergy => - KineticEnergy * PotentialEnergy; - } + public override int DayNumber => 12; public static long LCM(long a, long b) { - return (a * b) / GCD(a, b); + return a * b / GCD(a, b); } public static long GCD(long a, long b) @@ -113,7 +66,8 @@ namespace aoc2019 { int cycleX = 0, cycleY = 0, cycleZ = 0; - while (cycleX == 0 || cycleY == 0 || cycleZ == 0) { + while (cycleX == 0 || cycleY == 0 || cycleZ == 0) + { Step(); if (cycleX == 0 && moons.All(m => m.dx == 0)) cycleX = step * 2; if (cycleY == 0 && moons.All(m => m.dy == 0)) cycleY = step * 2; @@ -122,5 +76,58 @@ namespace aoc2019 return $"{LCM(cycleX, LCM(cycleY, cycleZ))}"; } + + public class Position + { + public int dx, dy, dz; + private List siblings; + public int x, y, z; + + public Position(IList moon) + { + x = moon[0]; + y = moon[1]; + z = moon[2]; + dx = 0; + dy = 0; + dz = 0; + } + + internal int KineticEnergy => + Math.Abs(x) + Math.Abs(y) + Math.Abs(z); + + internal int PotentialEnergy => + Math.Abs(dx) + Math.Abs(dy) + Math.Abs(dz); + + internal int TotalEnergy => + KineticEnergy * PotentialEnergy; + + public void SetSiblings(List positions) + { + siblings = positions.Where(p => p != this).ToList(); + } + + public override string ToString() + { + return $"pos= vel="; + } + + internal void Gravitate() + { + foreach (var m in siblings) + { + if (x != m.x) dx += x > m.x ? -1 : 1; + if (y != m.y) dy += y > m.y ? -1 : 1; + if (z != m.z) dz += z > m.z ? -1 : 1; + } + } + + internal void Move() + { + x += dx; + y += dy; + z += dz; + } + } } -} +} \ No newline at end of file diff --git a/Day13.cs b/Day13.cs index 31425c0..17e053d 100644 --- a/Day13.cs +++ b/Day13.cs @@ -1,16 +1,15 @@ -using aoc2019.lib; using System; using System.Collections.Generic; using System.Linq; +using aoc2019.lib; namespace aoc2019 { internal sealed class Day13 : Day { - public override int DayNumber => 13; + private readonly Dictionary<(int x, int y), int> board; private readonly IntCodeVM vm; - private readonly Dictionary<(int x, int y), int> board; public Day13() { @@ -18,9 +17,11 @@ namespace aoc2019 board = new Dictionary<(int, int), int>(); } + public override int DayNumber => 13; + private void UpdateTiles(IEnumerable queue) { - var input = queue.Select(i => (int)i).ToList(); + var input = queue.Select(i => (int) i).ToList(); for (var i = 0; i < input.Count - 2; i += 3) { @@ -33,7 +34,6 @@ namespace aoc2019 else board.Add((x, y), val); } - } private void PrintBoard() @@ -87,4 +87,4 @@ namespace aoc2019 return $"after {gameTicks} moves, the score is: {board[(-1, 0)]}"; } } -} +} \ No newline at end of file diff --git a/Day14.cs b/Day14.cs index 7706c0b..e4c46e8 100644 --- a/Day14.cs +++ b/Day14.cs @@ -6,48 +6,18 @@ namespace aoc2019 { internal sealed class Day14 : Day { - public override int DayNumber => 14; - - private Dictionary available; private readonly Dictionary reactions; - private struct Component + private Dictionary available; + + public Day14() { - public string Name { get; set; } - public int Quantity { get; set; } + reactions = Input + .Select(Reaction.Parse) + .ToDictionary(r => r.product.Name); } - private class Reaction - { - public readonly Component product; - public readonly Component[] reactants; - - private Reaction(Component[] reactants, Component product) - { - this.reactants = reactants; - this.product = product; - } - - public static Reaction Parse(string s) - { - var ss = s.Split(new[] { ", ", " => " }, System.StringSplitOptions.None); - - return new Reaction( - ss.Take(ss.Length - 1).Select(ParseComponent).ToArray(), - ParseComponent(ss[^1]) - ); - - static Component ParseComponent(string s) - { - var spl = s.Split(' ', 2); - return new Component - { - Quantity = int.Parse(spl[0]), - Name = spl[1] - }; - } - } - } + public override int DayNumber => 14; private bool Consume(string chem, long quantity) { @@ -70,7 +40,7 @@ namespace aoc2019 return false; 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 (!Consume(reactant.Name, reactionCount * reactant.Quantity)) @@ -80,23 +50,56 @@ namespace aoc2019 return true; } - public Day14() - { - reactions = Input - .Select(Reaction.Parse) - .ToDictionary(r => r.product.Name); - } - public override string Part1() { - available = new Dictionary { { "ORE", long.MaxValue } }; + available = new Dictionary {{"ORE", long.MaxValue}}; Consume("FUEL", 1); return $"{long.MaxValue - available["ORE"]}"; } public override string Part2() { + available = new Dictionary {{"ORE", 1000000000000}}; + Consume("FUEL", long.MaxValue); return ""; } + + private struct Component + { + public string Name { get; set; } + public int Quantity { get; set; } + } + + private class Reaction + { + public readonly Component product; + public readonly Component[] reactants; + + private Reaction(Component[] reactants, Component product) + { + this.reactants = reactants; + this.product = product; + } + + public static Reaction Parse(string s) + { + var ss = s.Split(new[] {", ", " => "}, StringSplitOptions.None); + + return new Reaction( + ss.Take(ss.Length - 1).Select(ParseComponent).ToArray(), + ParseComponent(ss[^1]) + ); + + static Component ParseComponent(string s) + { + var spl = s.Split(' ', 2); + return new Component + { + Quantity = int.Parse(spl[0]), + Name = spl[1] + }; + } + } + } } -} +} \ No newline at end of file diff --git a/Day15.cs b/Day15.cs index b68d251..487030f 100644 --- a/Day15.cs +++ b/Day15.cs @@ -1,97 +1,22 @@ -using System; -using System.Collections.Generic; using System.Linq; +using aoc2019.lib; namespace aoc2019 { internal sealed class Day15 : Day { - public override int DayNumber => 15; - - private Dictionary? available; - private readonly Dictionary? reactions; - - private struct Component - { - public string Name { get; set; } - public int Quantity { get; set; } - } - - private class Reaction - { - public Component product; - public Component[] reactants; - - public Reaction(Component[] reactants, Component product) - { - this.reactants = reactants; - this.product = product; - } - - public static Reaction Parse(string s) - { - var ss = s.Split(new[] { ", ", " => " }, System.StringSplitOptions.None); - - return new Reaction( - ss.Take(ss.Length - 1).Select(ParseComponent).ToArray(), - ParseComponent(ss[^1]) - ); - - static Component ParseComponent(string s) - { - var i = s.IndexOf(' '); - return new Component - { - Name = s[(i + 1)..], - Quantity = int.Parse(s.Substring(i)) - }; - } - } - } - - private bool Consume(string chem, long quantity) - { - if (quantity <= 0) - throw new ArgumentOutOfRangeException(); - - if (!available!.ContainsKey(chem)) - available[chem] = 0; - - if (available[chem] < quantity && !Produce(chem, quantity - available[chem])) - return false; - - available[chem] -= quantity; - return true; - } - - private bool Produce(string chem, long quantity) - { - if (chem == "ORE") - return false; - - var reaction = reactions[chem]; - var reactionCount = (long)Math.Ceiling((double)quantity / reaction.product.Quantity); - - foreach (var reactant in reaction.reactants) - if (!Consume(reactant.Name, reactionCount * reactant.Quantity)) - return false; - - available![chem] = available.GetValueOrDefault(chem) + reactionCount * reaction.product.Quantity; - return true; - } + private readonly IntCodeVM vm; public Day15() { - reactions = Input - .Select(Reaction.Parse) - .ToDictionary(r => r.product.Name); + vm = new IntCodeVM(Input.First()); } + public override int DayNumber => 15; + public override string Part1() { - available = new Dictionary { { "ORE", long.MaxValue } }; - Consume("FUEL", 1); - return $"{long.MaxValue - available["ORE"]}"; + return "intcode solution"; } public override string Part2() @@ -99,4 +24,4 @@ namespace aoc2019 return ""; } } -} +} \ No newline at end of file diff --git a/Day16.cs b/Day16.cs index 095f152..7baa2c9 100644 --- a/Day16.cs +++ b/Day16.cs @@ -1,17 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; - namespace aoc2019 { internal sealed class Day16 : Day { public override int DayNumber => 16; - public Day16() - { - } - public override string Part1() { return ""; @@ -22,4 +14,4 @@ namespace aoc2019 return ""; } } -} +} \ No newline at end of file diff --git a/Day2.cs b/Day2.cs index 580571f..f4b11e6 100644 --- a/Day2.cs +++ b/Day2.cs @@ -5,18 +5,20 @@ namespace aoc2019 { internal sealed class Day2 : Day { - public override int DayNumber => 2; - private readonly IEnumerable input; + public Day2() { input = Input.First().Split(',').Select(int.Parse); } + public override int DayNumber => 2; + public int RunIntCode(int noun, int verb) { var v = input.ToList(); - v[1] = noun; v[2] = verb; + v[1] = noun; + v[2] = verb; for (var i = 0; v[i] != 99; i += 4) v[v[i + 3]] = v[i] switch @@ -36,12 +38,11 @@ namespace aoc2019 public override string Part2() { for (var i = 0; i < 100; i++) - for (var j = 0; j < 100; j++) - if (RunIntCode(i, j) == 19690720) - return $"{100 * i + j}"; + for (var j = 0; j < 100; j++) + if (RunIntCode(i, j) == 19690720) + return $"{100 * i + j}"; return string.Empty; } } -} - +} \ No newline at end of file diff --git a/Day3.cs b/Day3.cs index 6bdf8ea..12f10d4 100644 --- a/Day3.cs +++ b/Day3.cs @@ -6,8 +6,6 @@ namespace aoc2019 { internal sealed class Day3 : Day { - public override int DayNumber => 3; - private readonly IEnumerable<(int, int)> intersections; private readonly List> wires; @@ -17,6 +15,8 @@ namespace aoc2019 intersections = wires[0].Keys.Intersect(wires[1].Keys); } + public override int DayNumber => 3; + public override string Part1() { return $"{intersections.Min(x => Math.Abs(x.Item1) + Math.Abs(x.Item2))}"; @@ -38,14 +38,22 @@ namespace aoc2019 var d = int.Parse(step.Substring(1)); switch (step[0]) { - case 'U': for (i = 0; i < d; i++) r.TryAdd((x, ++y), c++); break; - case 'D': for (i = 0; i < d; i++) r.TryAdd((x, --y), c++); break; - case 'R': for (i = 0; i < d; i++) r.TryAdd((++x, y), c++); break; - case 'L': for (i = 0; i < d; i++) r.TryAdd((--x, y), c++); break; + case 'U': + for (i = 0; i < d; i++) r.TryAdd((x, ++y), c++); + break; + case 'D': + for (i = 0; i < d; i++) r.TryAdd((x, --y), c++); + break; + case 'R': + for (i = 0; i < d; i++) r.TryAdd((++x, y), c++); + break; + case 'L': + for (i = 0; i < d; i++) r.TryAdd((--x, y), c++); + break; } } return r; } } -} +} \ No newline at end of file diff --git a/Day4.cs b/Day4.cs index b6b2c91..53d335d 100644 --- a/Day4.cs +++ b/Day4.cs @@ -4,28 +4,31 @@ namespace aoc2019 { internal sealed class Day4 : Day { - public override int DayNumber => 4; + private readonly int end; private readonly int start; - private readonly int end; public Day4() { var range = Input.First().Split('-').Select(int.Parse).ToList(); - start = range[0]; end = range[1]; + start = range[0]; + end = range[1]; } + public override int DayNumber => 4; + private bool IsValid(int i) { - int prev = 0; bool hasDup = false; + var prev = 0; + var hasDup = false; foreach (var c in i.ToString()) { - int curr = c - '0'; + var curr = c - '0'; if (curr < prev) return false; if (curr == prev) hasDup = true; prev = curr; } - + return i >= start && i <= end && hasDup; } @@ -45,5 +48,4 @@ namespace aoc2019 return $"{Enumerable.Range(start, end).Count(HasOnePair)}"; } } -} - +} \ No newline at end of file diff --git a/Day5.cs b/Day5.cs index fc360aa..88465db 100644 --- a/Day5.cs +++ b/Day5.cs @@ -5,22 +5,26 @@ namespace aoc2019 { internal sealed class Day5 : Day { - public override int DayNumber => 5; - private readonly IEnumerable tape; + + private int output; + public Day5() { tape = Input.First().Split(',').Select(int.Parse); } - private int output; + public override int DayNumber => 5; + public void RunIntCode(List v, int input) { var i = 0; while (i < v.Count && v[i] != 99) { - int Val(int mode, int val) => - mode != 0 ? val : v[val]; + int Val(int mode, int val) + { + return mode != 0 ? val : v[val]; + } var mode1 = v[i] / 100 % 10; var mode2 = v[i] / 1000; @@ -60,6 +64,7 @@ namespace aoc2019 } } } + public override string Part1() { RunIntCode(tape.ToList(), 1); @@ -72,4 +77,4 @@ namespace aoc2019 return $"{output}"; } } -} +} \ No newline at end of file diff --git a/Day6.cs b/Day6.cs index 50dd605..d92b402 100644 --- a/Day6.cs +++ b/Day6.cs @@ -5,14 +5,15 @@ namespace aoc2019 { internal sealed class Day6 : Day { - public override int DayNumber => 6; - private readonly Dictionary input; + public Day6() { input = Input.ToDictionary(i => i.Split(')')[1], i => i.Split(')')[0]); } + public override int DayNumber => 6; + private List GetParents(string obj) { var res = new List(); @@ -29,11 +30,11 @@ namespace aoc2019 public override string Part2() { - List you = GetParents("YOU"); - List san = GetParents("SAN"); - int common = 1; - for (; you[^common] == san[^common]; common++); + var you = GetParents("YOU"); + var san = GetParents("SAN"); + var common = 1; + for (; you[^common] == san[^common]; common++) ; return $"{you.Count + san.Count - common * 2}"; } } -} +} \ No newline at end of file diff --git a/Day7.cs b/Day7.cs index 7f94e5a..123d075 100644 --- a/Day7.cs +++ b/Day7.cs @@ -1,20 +1,20 @@ -using aoc2019.lib; using System.Collections.Generic; using System.Linq; +using aoc2019.lib; namespace aoc2019 { internal sealed class Day7 : Day { - public override int DayNumber => 7; - private readonly IntCodeVM[] Amplifiers = new IntCodeVM[5]; + public Day7() { for (var i = 0; i < 5; i++) Amplifiers[i] = new IntCodeVM(Input.First()); } - + public override int DayNumber => 7; + public override string Part1() { @@ -67,4 +67,4 @@ namespace aoc2019 return $"{largest}"; } } -} +} \ No newline at end of file diff --git a/Day8.cs b/Day8.cs index 1666544..27182ad 100644 --- a/Day8.cs +++ b/Day8.cs @@ -1,20 +1,21 @@ -using aoc2019.lib; using System; using System.Collections.Generic; using System.Linq; +using aoc2019.lib; namespace aoc2019 { internal sealed class Day8 : Day { - public override int DayNumber => 8; - private readonly List> photo; + public Day8() { photo = Input.First().Chunk(25 * 6).Select(s => s.ToList()).ToList(); } + public override int DayNumber => 8; + public override string Part1() { var l = photo.OrderBy(layer => layer.Count(pixel => pixel == '0')).First(); @@ -36,4 +37,4 @@ namespace aoc2019 .Replace('1', 'x'); } } -} +} \ No newline at end of file diff --git a/Day9.cs b/Day9.cs index c6de017..77e72e1 100644 --- a/Day9.cs +++ b/Day9.cs @@ -1,11 +1,10 @@ -using aoc2019.lib; using System.Linq; +using aoc2019.lib; namespace aoc2019 { internal sealed class Day9 : Day { - public override int DayNumber => 9; private readonly IntCodeVM vm; public Day9() @@ -13,6 +12,8 @@ namespace aoc2019 vm = new IntCodeVM(Input.First()); } + public override int DayNumber => 9; + public override string Part1() { vm.Reset(); @@ -27,4 +28,4 @@ namespace aoc2019 return $"{vm.output.ToDelimitedString(",")}"; } } -} +} \ No newline at end of file diff --git a/Program.cs b/Program.cs index 981804b..4338952 100644 --- a/Program.cs +++ b/Program.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -9,7 +8,7 @@ namespace aoc2019 { private static void Main(string[] args) { - var days = + var days = Assembly.GetExecutingAssembly().GetTypes() .Where(t => t.BaseType == typeof(Day)) .Select(t => (Day) Activator.CreateInstance(t)) @@ -18,7 +17,7 @@ namespace aoc2019 if (args.Length == 1 && int.TryParse(args[0], out var dayNum)) { var day = days.FirstOrDefault(d => d.DayNumber == dayNum); - + if (day != null) day.AllParts(); else @@ -26,11 +25,8 @@ namespace aoc2019 } else { - foreach (var d in days) - { - d.AllParts(); - } + foreach (var d in days) d.AllParts(); } } } -} +} \ No newline at end of file diff --git a/lib/Extensions.cs b/lib/Extensions.cs index 3c81f17..a1ffbcc 100644 --- a/lib/Extensions.cs +++ b/lib/Extensions.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; namespace aoc2019.lib @@ -8,13 +7,13 @@ namespace aoc2019.lib { public static IEnumerable> Permute(this IEnumerable list) { - if (list.Count() == 1) return new[] { list }; + if (list.Count() == 1) return new[] {list}; return list.SelectMany(t => Permute(list.Where(x => !x.Equals(t))), (v, p) => p.Prepend(v)); } public static IEnumerable Chunk(this string str, int chunkSize) { - for (int i = 0; i < str.Length; i += chunkSize) + for (var i = 0; i < str.Length; i += chunkSize) yield return str.Substring(i, chunkSize); } @@ -30,4 +29,4 @@ namespace aoc2019.lib yield return item; } } -} +} \ No newline at end of file diff --git a/lib/IntCodeVM.cs b/lib/IntCodeVM.cs index 472da92..d35444b 100644 --- a/lib/IntCodeVM.cs +++ b/lib/IntCodeVM.cs @@ -6,11 +6,17 @@ namespace aoc2019.lib { public class IntCodeVM { - private long i; - private long relbase; - public long[] memory; + public enum HaltType + { + Terminate, + Waiting + } + private readonly long[] program; + private long i; public Queue input, output; + public long[] memory; + private long relbase; public IntCodeVM(string tape) { @@ -22,11 +28,7 @@ namespace aoc2019.lib output = new Queue(); } - public enum HaltType - { - Terminate, - Waiting - } + public long Result => output.Dequeue(); public void Reset() { @@ -37,8 +39,6 @@ namespace aoc2019.lib output.Clear(); } - public long Result => output.Dequeue(); - public void AddInput(long value) { input.Enqueue(value); @@ -53,7 +53,7 @@ namespace aoc2019.lib { if (addr < 0) addr = 0; if (addr >= memory.Length) - Array.Resize(ref memory, (int)addr + 1); + Array.Resize(ref memory, (int) addr + 1); memory[addr] = value; } @@ -82,9 +82,13 @@ namespace aoc2019.lib var param = MemGet(i + idx); switch (Mode(idx)) { - case 0: MemSet(param, val); break; + case 0: + MemSet(param, val); + break; case 1: throw new Exception("cannot set in immediate mode"); - case 2: MemSet(relbase + param, val); break; + case 2: + MemSet(relbase + param, val); + break; default: throw new Exception("invalid parameter mode"); } } @@ -94,6 +98,7 @@ namespace aoc2019.lib foreach (var s in additionalInput) AddInput(s); return Run(); } + public HaltType Run() { while (i < memory.Length) @@ -103,18 +108,22 @@ namespace aoc2019.lib { case 1: Set(3, Get(1) + Get(2)); - i += 4; break; + i += 4; + break; case 2: Set(3, Get(1) * Get(2)); - i += 4; break; + i += 4; + break; case 3: if (!input.Any()) return HaltType.Waiting; Set(1, input.Dequeue()); - i += 2; break; + i += 2; + break; case 4: output.Enqueue(Get(1)); - i += 2; break; + i += 2; + break; case 5: i = Get(1) == 0 ? i + 3 : Get(2); break; @@ -123,13 +132,16 @@ namespace aoc2019.lib break; case 7: Set(3, Get(1) < Get(2) ? 1 : 0); - i += 4; break; + i += 4; + break; case 8: Set(3, Get(1) == Get(2) ? 1 : 0); - i += 4; break; + i += 4; + break; case 9: relbase += Get(1); - i += 2; break; + i += 2; + break; case 99: return HaltType.Terminate; default: @@ -140,4 +152,4 @@ namespace aoc2019.lib return HaltType.Terminate; } } -} +} \ No newline at end of file