update gitignore and run resharper cleanup
continuous-integration/drone/push Build is failing Details

This commit is contained in:
Ben Harris 2020-12-02 00:36:24 -05:00
parent 00c3b51b89
commit 36bb28af87
Signed by: ben
GPG Key ID: 4E0AF802FFF7960C
21 changed files with 735 additions and 335 deletions

436
.gitignore vendored
View File

@ -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

3
Day.cs
View File

@ -8,6 +8,7 @@ namespace aoc2019
public abstract class Day
{
public abstract int DayNumber { get; }
public virtual IEnumerable<string> Input =>
File.ReadLines($"input/day{DayNumber}.in");
@ -33,4 +34,4 @@ namespace aoc2019
public abstract string Part1();
public abstract string Part2();
}
}
}

23
Day1.cs
View File

@ -5,15 +5,20 @@ namespace aoc2019
{
internal sealed class Day1 : Day
{
public override int DayNumber => 1;
private readonly IEnumerable<int> 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)}";
}
}
}
}

View File

@ -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();
}
}
}
}

View File

@ -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
}
}
}
}

123
Day12.cs
View File

@ -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<Position> moons;
private readonly List<Position> startingPositions;
private readonly List<Position> 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<Position> siblings;
public Position(IList<int> moon)
{
x = moon[0];
y = moon[1];
z = moon[2];
dx = 0; dy = 0; dz = 0;
}
public void SetSiblings(List<Position> positions)
{
siblings = positions.Where(p => p != this).ToList();
}
public override string ToString() =>
$"pos=<x={x}, y={y}, z={z}> vel=<x={dx}, y={dy}, z={dz}>";
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<Position> siblings;
public int x, y, z;
public Position(IList<int> 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<Position> positions)
{
siblings = positions.Where(p => p != this).ToList();
}
public override string ToString()
{
return $"pos=<x={x}, y={y}, z={z}> vel=<x={dx}, y={dy}, z={dz}>";
}
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;
}
}
}
}
}

View File

@ -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<long> 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)]}";
}
}
}
}

View File

@ -6,48 +6,18 @@ namespace aoc2019
{
internal sealed class Day14 : Day
{
public override int DayNumber => 14;
private Dictionary<string, long> available;
private readonly Dictionary<string, Reaction> reactions;
private struct Component
private Dictionary<string, long> 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<string, long> { { "ORE", long.MaxValue } };
available = new Dictionary<string, long> {{"ORE", long.MaxValue}};
Consume("FUEL", 1);
return $"{long.MaxValue - available["ORE"]}";
}
public override string Part2()
{
available = new Dictionary<string, long> {{"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]
};
}
}
}
}
}
}

View File

@ -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<string, long>? available;
private readonly Dictionary<string, Reaction>? 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<string, long> { { "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 "";
}
}
}
}

View File

@ -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 "";
}
}
}
}

17
Day2.cs
View File

@ -5,18 +5,20 @@ namespace aoc2019
{
internal sealed class Day2 : Day
{
public override int DayNumber => 2;
private readonly IEnumerable<int> 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;
}
}
}
}

22
Day3.cs
View File

@ -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<Dictionary<(int, int), int>> 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;
}
}
}
}

18
Day4.cs
View File

@ -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)}";
}
}
}
}

17
Day5.cs
View File

@ -5,22 +5,26 @@ namespace aoc2019
{
internal sealed class Day5 : Day
{
public override int DayNumber => 5;
private readonly IEnumerable<int> 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<int> 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}";
}
}
}
}

15
Day6.cs
View File

@ -5,14 +5,15 @@ namespace aoc2019
{
internal sealed class Day6 : Day
{
public override int DayNumber => 6;
private readonly Dictionary<string, string> input;
public Day6()
{
input = Input.ToDictionary(i => i.Split(')')[1], i => i.Split(')')[0]);
}
public override int DayNumber => 6;
private List<string> GetParents(string obj)
{
var res = new List<string>();
@ -29,11 +30,11 @@ namespace aoc2019
public override string Part2()
{
List<string> you = GetParents("YOU");
List<string> 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}";
}
}
}
}

10
Day7.cs
View File

@ -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}";
}
}
}
}

View File

@ -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<List<char>> 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');
}
}
}
}

View File

@ -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(",")}";
}
}
}
}

View File

@ -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();
}
}
}
}
}

View File

@ -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<IEnumerable<T>> Permute<T>(this IEnumerable<T> 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<string> 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;
}
}
}
}

View File

@ -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<long> input, output;
public long[] memory;
private long relbase;
public IntCodeVM(string tape)
{
@ -22,11 +28,7 @@ namespace aoc2019.lib
output = new Queue<long>();
}
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;
}
}
}
}