Initial commit

This commit is contained in:
Brandon Scott 2018-12-22 12:50:18 -06:00
commit 8fd936789f
50 changed files with 10484 additions and 0 deletions

885
.gitignore vendored Normal file
View File

@ -0,0 +1,885 @@
# Created by https://www.gitignore.io/api/jetbrains,intellij+iml,eclipse,visualstudio,sublimetext,windows,macos,emacs,vim,linux,c,c++,cmake,python,csharp,java
### Vim ###
# swap
[._]*.s[a-w][a-z]
[._]s[a-w][a-z]
# session
Session.vim
# temporary
.netrwhist
*~
# auto-generated tag files
tags
### JetBrains ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/workspace.xml
.idea/tasks.xml
# Sensitive or high-churn files:
.idea/dataSources/
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml
# Gradle:
.idea/gradle.xml
.idea/libraries
.gradle
# Mongo Explorer plugin:
.idea/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### JetBrains Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
### Eclipse ###
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# Eclipse Core
.project
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# JDT-specific (Eclipse Java Development Tools)
.classpath
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
### Csharp ###
## 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
*.suo
*.user
*.userosscache
*.sln.docstates
*.vcxproj.filters
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp_proj
*.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
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# 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
# TODO: 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
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable 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
# 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
node_modules/
orleans.codegen.cs
# 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
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# 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/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/
### SublimeText ###
# cache files for sublime text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
# workspace files are user-specific
*.sublime-workspace
# project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using SublimeText
# *.sublime-project
# sftp configuration file
sftp-config.json
# Package control specific files
Package Control.last-run
Package Control.ca-list
Package Control.ca-bundle
Package Control.system-ca-bundle
Package Control.cache/
Package Control.ca-certs/
bh_unicode_properties.cache
# Sublime-github package stores a github token in this file
# https://packagecontrol.io/packages/sublime-github
GitHub.sublime-settings
### Windows ###
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
### macOS ###
*.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
### Emacs ###
# -*- mode: gitignore; -*-
\#*\#
/.emacs.desktop
/.emacs.desktop.lock
*.elc
auto-save-list
tramp
.\#*
# Org-mode
.org-id-locations
*_archive
# flymake-mode
*_flymake.*
# eshell files
/eshell/history
/eshell/lastdir
# elpa packages
/elpa/
# reftex files
*.rel
# AUCTeX auto folder
/auto/
# cask packages
.cask/
dist/
# Flycheck
flycheck_*.el
# server auth directory
/server/
# projectiles files
.projectile
# directory configuration
.dir-locals.el
### Intellij+iml ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
# Sensitive or high-churn files:
# Gradle:
# Mongo Explorer plugin:
## File-based project format:
## Plugin-specific files:
# IntelliJ
# mpeltonen/sbt-idea plugin
# JIRA plugin
# Crashlytics plugin (for Android Studio and IntelliJ)
### Intellij+iml Patch ###
# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023
*.iml
modules.xml
.idea/misc.xml
*.ipr
### Linux ###
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### C ###
# Prerequisites
*.d
# Object files
*.o
*.ko
*.elf
# Linker output
*.map
*.exp
# Precompiled Headers
*.gch
# Libraries
*.lib
*.a
*.la
*.lo
# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib
# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
# Debug files
*.dSYM/
*.su
*.idb
# Kernel Module Compile Results
*.mod*
*.cmd
modules.order
Module.symvers
Mkfile.old
dkms.conf
### C++ ###
# Prerequisites
# Compiled Object files
*.slo
# Precompiled Headers
# Compiled Dynamic libraries
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
# Executables
### CMake ###
CMakeCache.txt
CMakeFiles
CMakeScripts
Makefile
cmake_install.cmake
install_manifest.txt
CTestTestfile.cmake
### Python ###
# Byte-compiled / optimized / DLL files
*.py[cod]
*$py.class
# C extensions
# Distribution / packaging
.Python
env/
build/
develop-eggs/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# dotenv
.env
# virtualenv
.venv/
venv/
ENV/
# Spyder project settings
.spyderproject
# Rope project settings
.ropeproject
### Java ###
*.class
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
### VisualStudio ###
## 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
# User-specific files (MonoDevelop/Xamarin Studio)
# Build results
# Visual Studio 2015 cache/options directory
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
# NUNIT
# Build Results of an ATL Project
# .NET Core
# Chutzpah Test files
# Visual C++ cache files
# Visual Studio profiler
# TFS 2012 Local Workspace
# Guidance Automation Toolkit
# ReSharper is a .NET coding add-in
# JustCode is a .NET coding add-in
# TeamCity is a build add-in
# DotCover is a Code Coverage Tool
# Visual Studio code coverage results
# NCrunch
# MightyMoose
# Web workbench (sass)
# Installshield output folder
# DocProject is a documentation generator add-in
# Click-Once directory
# Publish Web Output
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
# 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
# NuGet Packages
# The packages folder can be ignored because of Package Restore
# except build/, which is used as an MSBuild target.
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
# Microsoft Azure Build Output
# Microsoft Azure Emulator
# Windows Store app package directories and files
# Visual Studio cache files
# files ending in .cache can be ignored
# but keep track of directories ending in .cache
# Others
# 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
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
# SQL Server files
# Business Intelligence projects
# Microsoft Fakes
# GhostDoc plugin setting file
# Node.js Tools for Visual Studio
# Visual Studio 6 build log
# Visual Studio 6 workspace options file
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
# Visual Studio LightSwitch build output
# Paket dependency manager
# FAKE - F# Make
# JetBrains Rider
# CodeRush
# Python Tools for Visual Studio (PTVS)
# Cake - Uncomment if you are using it
# tools/
### VisualStudio Patch ###

23
LICENSE Normal file
View File

@ -0,0 +1,23 @@
Individual files may be licensed differently, as noted in those files.
MIT License
Copyright (c) 2017 individual contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

24
README.md Normal file
View File

@ -0,0 +1,24 @@
# Advent of Code 2017
## About
These are my solutions to the Advent of Code 2017.
## Author
Brandon Scott
## What is Advent of Code?
[Advent of Code](https://adventofcode.com/) is an Advent calendar of small programming
puzzles for a variety of skill sets and skill levels that can be solved in any
programming language you like. People use them as a speed contest, interview prep,
company training, university coursework, practice problems, or to challenge
each other.
## License
By default, all code in this project is licensed under the MIT license,
copyright the individual contributor(s). Comments in individual files
may specify an alternate license as chosen by a particular individual
for their code. If not specified, the file is MIT.

48
csharp/BScottDay1.cs Normal file
View File

@ -0,0 +1,48 @@
using System;
using System.IO;
namespace AOC2017
{
class BScottDay1 : BScottSolution
{
public override string Name => "Day 1: Inverse Captcha";
public override void Run()
{
string input = "1122";
Console.WriteLine($"Example 1: {CalculateSumPart1(input)}");
input = "1111";
Console.WriteLine($"Example 2: {CalculateSumPart1(input)}");
input = "1234";
Console.WriteLine($"Example 3: {CalculateSumPart1(input)}");
input = "91212129";
Console.WriteLine($"Example 4: {CalculateSumPart1(input)}");
input = File.ReadAllText("BScottDay1.txt");
Console.WriteLine($"Part 1 Answer: {CalculateSumPart1(input)}");
Console.WriteLine($"Part 2 Answer: {CalculateSumPart2(input)}");
}
static long CalculateSumPart1(string input)
{
long sum = 0;
for (int i = 0; i < input.Length; i++)
if (input[i] == input[(i + 1) % input.Length])
sum += int.Parse(input[i].ToString());
return sum;
}
static long CalculateSumPart2(string input)
{
long sum = 0;
int step = input.Length / 2;
for (int i = 0; i < input.Length; i++)
if (input[i] == input[(i + step) % input.Length])
sum += int.Parse(input[i].ToString());
return sum;
}
}
}

1
csharp/BScottDay1.txt Normal file
View File

@ -0,0 +1 @@
818275977931166178424892653779931342156567268946849597948944469863818248114327524824136924486891794739281668741616818614613222585132742386168687517939432911753846817997473555693821316918473474459788714917665794336753628836231159578734813485687247273288926216976992516314415836985611354682821892793983922755395577592859959966574329787693934242233159947846757279523939217844194346599494858459582798326799512571365294673978955928416955127211624234143497546729348687844317864243859238665326784414349618985832259224761857371389133635711819476969854584123589566163491796442167815899539788237118339218699137497532932492226948892362554937381497389469981346971998271644362944839883953967698665427314592438958181697639594631142991156327257413186621923369632466918836951277519421695264986942261781256412377711245825379412978876134267384793694756732246799739464721215446477972737883445615664755923441441781128933369585655925615257548499628878242122434979197969569971961379367756499884537433839217835728263798431874654317137955175565253555735968376115749641527957935691487965161211853476747758982854811367422656321836839326818976668191525884763294465366151349347633968321457954152621175837754723675485348339261288195865348545793575843874731785852718281311481217515834822185477982342271937155479432673815629144664144538221768992733498856934255518875381672342521819499939835919827166318715849161715775427981485233467222586764392783699273452228728667175488552924399518855743923659815483988899924199449721321589476864161778841352853573584489497263216627369841455165476954483715112127465311353411346132671561568444626828453687183385215975319858714144975174516356117245993696521941589168394574287785233685284294357548156487538175462176268162852746996633977948755296869616778577327951858348313582783675149343562362974553976147259225311183729415381527435926224781181987111454447371894645359797229493458443522549386769845742557644349554641538488252581267341635761715674381775778868374988451463624332123361576518411234438681171864923916896987836734129295354684962897616358722633724198278552339794629939574841672355699222747886785616814449297817352118452284785694551841431869545321438468118

94
csharp/BScottDay10.cs Normal file
View File

@ -0,0 +1,94 @@
using System;
using System.IO;
using System.Text;
namespace AOC2017
{
class BScottDay10 : BScottSolution
{
public override string Name => "Day 10: Knot Hash";
public override void Run()
{
string input = File.ReadAllText("BScottDay10.txt");
Console.WriteLine($"Part 1 Answer: {KnotHashPart1(input)}");
Console.WriteLine($"Part 2 Answer: {KnotHashPart2(input)}");
Console.WriteLine($"Part 2 Example Answer #1 (blank): {KnotHashPart2("")}");
Console.WriteLine($"Part 2 Example Answer #2 (AoC 2017): {KnotHashPart2("AoC 2017")}");
Console.WriteLine($"Part 2 Example Answer #3 (1,2,3): {KnotHashPart2("1,2,3")}");
Console.WriteLine($"Part 2 Example Answer #4 (1,2,4): {KnotHashPart2("1,2,4")}");
}
private int KnotHashPart1(string input)
{
int[] lengths = Array.ConvertAll(input.Split(','), s => int.Parse(s));
byte[] list = new byte[256];
int pos = 0, skipSize = 0;
// initialize list
for (int i = 0; i < list.Length; i++)
list[i] = (byte)i;
for (int i = 0; i < lengths.Length; i++)
{
byte[] buff = new byte[lengths[i]];
for (int j = 0; j < buff.Length; j++)
buff[j] = list[(pos + j) % list.Length];
Array.Reverse(buff);
for (int j = 0; j < buff.Length; j++)
list[(pos + j) % list.Length] = buff[j];
pos += (lengths[i] + skipSize) % list.Length; // wrap around
skipSize++; // increase skip size
}
return list[0] * list[1];
}
private string KnotHashPart2(string input)
{
String suffix = Encoding.ASCII.GetString(new byte[] { 17, 31, 73, 47, 23 });
byte[] lengths = Encoding.ASCII.GetBytes(input + suffix); //string of bytes and add a suffix
byte[] list = new byte[256];
byte[] denseHash = new byte[16];
int pos = 0, skipSize = 0;
// initialize list
for (int i = 0; i < list.Length; i++)
list[i] = (byte)i;
// 64 rounds of fun
for (int x = 0; x < 64; x++)
{
for (int i = 0; i < lengths.Length; i++)
{
byte[] buff = new byte[lengths[i]];
for (int j = 0; j < buff.Length; j++)
buff[j] = list[(pos + j) % list.Length];
Array.Reverse(buff);
for (int j = 0; j < buff.Length; j++)
list[(pos + j) % list.Length] = buff[j];
pos += (lengths[i] + skipSize) % list.Length; // wrap around
skipSize++; // increase skip size
}
}
// do the Xor magic
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 16; j++)
denseHash[i] ^= list[i * 16 + j];
}
return BitConverter.ToString(denseHash).Replace("-", "").ToLower();
}
}
}

1
csharp/BScottDay10.txt Normal file
View File

@ -0,0 +1 @@
94,84,0,79,2,27,81,1,123,93,218,23,103,255,254,243

65
csharp/BScottDay11.cs Normal file
View File

@ -0,0 +1,65 @@
using System;
using System.IO;
namespace AOC2017
{
class BScottDay11 : BScottSolution
{
public override string Name => "Day 11: Hex Ed";
public override void Run()
{
Console.WriteLine($"Part 1 Example Answer #1 (ne,ne,ne):\t\t{CalculateDistances("ne,ne,ne").Item1}");
Console.WriteLine($"Part 1 Example Answer #2 (ne,ne,sw,sw):\t\t{CalculateDistances("ne,ne,sw,sw").Item1}");
Console.WriteLine($"Part 1 Example Answer #3 (ne,ne,s,s):\t\t{CalculateDistances("ne,ne,s,s").Item1}");
Console.WriteLine($"Part 1 Example Answer #4 (se,sw,se,sw,sw):\t{CalculateDistances("se,sw,se,sw,sw").Item1}");
string input = File.ReadAllText("BScottDay11.txt");
Console.WriteLine($"Part 1 Answer:\t{CalculateDistances(input).Item1}");
Console.WriteLine($"Part 2 Answer:\t{CalculateDistances(input).Item2}");
}
private static Tuple<int,int> CalculateDistances(string input)
{
string[] commands = input.Split(',');
int x = 0, y = 0, distance = 0, maxDistance = 0;
foreach (string cmd in commands)
{
switch (cmd)
{
case "n":
y--;
break;
case "s":
y++;
break;
case "ne":
x++;
break;
case "sw":
x--;
break;
case "se":
y++;
x++;
break;
case "nw":
y--;
x--;
break;
}
distance = Math.Max(Math.Abs(y), Math.Max(Math.Abs(x), Math.Abs((x - y) * -1)));
if (distance > maxDistance)
maxDistance = distance;
}
return Tuple.Create(distance,maxDistance);
}
}
}

1
csharp/BScottDay11.txt Normal file

File diff suppressed because one or more lines are too long

95
csharp/BScottDay12.cs Normal file
View File

@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace AOC2017
{
class BScottDay12 : BScottSolution
{
public override string Name => "Day 12: Digital Plumber";
public override void Run()
{
string[] exampleInput = new[] {
"0 <-> 2",
"1 <-> 1",
"2 <-> 0, 3, 4",
"3 <-> 2, 4",
"4 <-> 2, 3, 6",
"5 <-> 6",
"6 <-> 4, 5"
};
Console.WriteLine($"Part 1 Example Answer: {DigitalPlumberPart1(exampleInput)}");
Console.WriteLine($"Part 2 Example Answer: {DigitalPlumberPart2(exampleInput)}");
string[] input = File.ReadAllLines("BScottDay12.txt");
Console.WriteLine($"Part 1 Answer: {DigitalPlumberPart1(input)}");
Console.WriteLine($"Part 2 Answer: {DigitalPlumberPart2(input)}");
}
private int DigitalPlumberPart1(string[] input)
{
Dictionary<int, int[]> programDictionary = ParseInput(input);
List<int> connected = new List<int>();
GetConnectedPrograms(programDictionary, connected, 0, 0);
return connected.Count;
}
private int DigitalPlumberPart2(string[] input)
{
Dictionary<int, int[]> programDictionary = ParseInput(input);
List<int> connected = new List<int>();
int groups = 0;
foreach (var programId in programDictionary.Keys)
{
if (!connected.Contains(programId))
{
GetConnectedPrograms(programDictionary, connected, programId, 0);
groups++;
}
}
return groups;
}
private void GetConnectedPrograms(Dictionary<int, int[]> programDictionary, List<int> connected, int start, int level)
{
// stack overflow protection
if (level > 100)
return;
foreach (var programId in programDictionary[start])
{
if (!connected.Contains(programId))
{
connected.Add(programId);
GetConnectedPrograms(programDictionary, connected, programId, ++level);
}
}
}
private Dictionary<int, int[]> ParseInput(string[] input)
{
Dictionary<int, int[]> programDictionary = new Dictionary<int, int[]>();
Regex regex = new Regex(@"([\d]+) <-> (?:([\d]+)*(?:, )?)*");
for (int i = 0; i < input.Length; i++)
{
Match match = regex.Match(input[i]);
if (match.Success)
{
List<int> programList = new List<int>();
foreach (Capture capture in match.Groups[2].Captures)
programList.Add(int.Parse(capture.Value));
programDictionary.Add(int.Parse(match.Groups[1].Value), programList.ToArray());
}
}
return programDictionary;
}
}
}

2000
csharp/BScottDay12.txt Normal file

File diff suppressed because it is too large Load Diff

92
csharp/BScottDay13.cs Normal file
View File

@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace AOC2017
{
class BScottDay13 : BScottSolution
{
public override string Name => "Day 13: Packet Scanners";
public override void Run()
{
string[] exampleInput = new[] {
"0: 3",
"1: 2",
"4: 4",
"6: 4"
};
Console.WriteLine($"Part 1 Example Answer: {PacketScannerPart1(exampleInput)}");
Console.WriteLine($"Part 2 Example Answer: {PacketScannerPart2(exampleInput)}");
string[] input = File.ReadAllLines("BScottDay13.txt");
Console.WriteLine($"Part 1 Answer: {PacketScannerPart1(input)}");
Console.WriteLine($"Part 2 Answer: {PacketScannerPart2(input)}");
}
private int PacketScannerPart1(string[] input)
{
Dictionary<int, Layer> firewallList = new Dictionary<int, Layer>();
foreach (var layer in input)
{
int[] args = Array.ConvertAll(layer.Split(':'), s => int.Parse(s.Trim()));
firewallList.Add(args[0], new Layer(args[0], args[1]));
}
int totalSeverity = 0;
foreach (int key in firewallList.Keys)
{
if (key % (2 * firewallList[key].Range - 2) == 0)
totalSeverity += firewallList[key].Severity;
}
return totalSeverity;
}
private int PacketScannerPart2(string[] input)
{
Dictionary<int, Layer> firewallList = new Dictionary<int, Layer>();
foreach (var layer in input)
{
int[] args = Array.ConvertAll(layer.Split(':'), s => int.Parse(s.Trim()));
firewallList.Add(args[0], new Layer(args[0], args[1]));
}
for (int delay = 10; delay < int.MaxValue; delay++)
{
bool isCaught = false;
foreach (int key in firewallList.Keys)
{
if ((key + delay) % (2 * firewallList[key].Range - 2) == 0)
{
isCaught = true;
break;
}
}
if (!isCaught)
return delay;
}
return -1;
}
class Layer
{
public int Depth { get; private set; }
public int Range { get; private set; }
public int Severity => Depth * Range;
public Layer(int depth, int range)
{
Depth = depth;
Range = range;
}
}
}
}

43
csharp/BScottDay13.txt Normal file
View File

@ -0,0 +1,43 @@
0: 4
1: 2
2: 3
4: 4
6: 6
8: 5
10: 6
12: 6
14: 6
16: 8
18: 8
20: 9
22: 12
24: 8
26: 8
28: 8
30: 12
32: 12
34: 8
36: 12
38: 10
40: 12
42: 12
44: 10
46: 12
48: 14
50: 12
52: 14
54: 14
56: 12
58: 14
60: 12
62: 14
64: 18
66: 14
68: 14
72: 14
76: 14
82: 14
86: 14
88: 18
90: 14
92: 17

134
csharp/BScottDay14.cs Normal file
View File

@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace AOC2017
{
class BScottDay14 : BScottSolution
{
public override string Name => "Day 14: Disk Defragmentation";
public override void Run()
{
string input = "flqrgnkx";
Console.WriteLine($"Part 1 Example Answer: {DiskDefragmentationPart1(input)}");
Console.WriteLine($"Part 2 Example Answer: {DiskDefragmentationPart2(input)}");
input = "oundnydw";
Console.WriteLine($"Part 1 Answer: {DiskDefragmentationPart1(input)}");
Console.WriteLine($"Part 2 Answer: {DiskDefragmentationPart2(input)}");
}
private int DiskDefragmentationPart1(string input)
{
byte[][] disk = new byte[128][];
for (int i = 0; i < 128; i++)
disk[i] = KnotHash($"{input}-{i}");
int sum = 0;
for (int i = 0; i < 128; i++)
for (int j = 0; j < 128; j++)
sum += disk[i][j];
return sum;
}
private int DiskDefragmentationPart2(string input)
{
byte[][] disk = new byte[128][];
for (int i = 0; i < 128; i++)
disk[i] = KnotHash($"{input}-{i}");
List<Tuple<int, int>> map = new List<Tuple<int, int>>();
for (int i = 0; i < 128; i++)
for (int j = 0; j < 128; j++)
if (disk[i][j] == 1)
map.Add(new Tuple<int, int>(i, j));
int regions = 0;
while (map.Count > 0)
{
FindRegion(map);
regions++;
}
return regions;
}
private void FindRegion(List<Tuple<int, int>> map)
{
Stack<Tuple<int, int>> stack = new Stack<Tuple<int, int>>();
stack.Push(map[map.Count - 1]);
map.RemoveAt(map.Count - 1);
int[,] deltas = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
while (stack.Count > 0)
{
Tuple<int, int> fragment = stack.Pop();
for (int i = 0; i < deltas.GetLength(0); i++)
{
int dy = fragment.Item1 + deltas[i, 0];
int dx = fragment.Item2 + deltas[i, 1];
if (dy < 0 || dy >= 128 || dx < 0 || dy >= 128)
continue;
int index = map.FindIndex(eri => eri.Item1 == dy && eri.Item2 == dx);
if (index != -1)
{
stack.Push(map[index]);
map.RemoveAt(index);
}
}
}
}
// from day 10
private byte[] KnotHash(string input)
{
String suffix = Encoding.ASCII.GetString(new byte[] { 17, 31, 73, 47, 23 });
byte[] lengths = Encoding.ASCII.GetBytes(input + suffix); //string of bytes and add a suffix
byte[] list = new byte[256];
byte[] denseHash = new byte[16];
int pos = 0, skipSize = 0;
// initialize list
for (int i = 0; i < list.Length; i++)
list[i] = (byte)i;
// 64 rounds of fun
for (int x = 0; x < 64; x++)
{
for (int i = 0; i < lengths.Length; i++)
{
byte[] buff = new byte[lengths[i]];
for (int j = 0; j < buff.Length; j++)
buff[j] = list[(pos + j) % list.Length];
for (int j = 0; j < buff.Length; j++)
list[(pos + j) % list.Length] = buff[(buff.Length - 1) - j];
pos += (lengths[i] + skipSize++) % list.Length; // wrap around, increase skipsize
}
}
// do the Xor magic
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 16; j++)
denseHash[i] ^= list[i * 16 + j];
}
byte[] output = new byte[128];
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 8; j++)
output[i * 8 + (7 - j)] = (byte)((denseHash[i] >> j) & 0x1);
}
return output;
}
}
}

61
csharp/BScottDay15.cs Normal file
View File

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
namespace AOC2017
{
class BScottDay15 : BScottSolution
{
public override string Name => "Day 15: Dueling Generators";
public override void Run()
{
int sampleSize = 40000000;
int inputA = 679;
int inputB = 771;
Console.WriteLine($"Part 1 Example Answer: {DuelingGeneratorsPart1(sampleSize, 65, 8921)}");
Console.WriteLine($"Part 1 Answer: {DuelingGeneratorsPart1(sampleSize, inputA, inputB)}");
Console.WriteLine($"Part 2 Example Answer: {DuelingGeneratorsPart2(sampleSize, 65, 8921)}");
Console.WriteLine($"Part 2 Answer: {DuelingGeneratorsPart2(sampleSize, inputA, inputB)}");
}
private int DuelingGeneratorsPart1(int sampleSize, int generatorA, int generatorB)
{
int count = 0;
for (int i = 0; i < sampleSize; i++)
{
generatorA = (int)(((ulong) generatorA * 16807ul) % int.MaxValue);
generatorB = (int)(((ulong) generatorB * 48271ul) % int.MaxValue);
if ((generatorA & 0xffff) == (generatorB & 0xffff))
count++;
}
return count;
}
private int DuelingGeneratorsPart2(int sampleSize, int generatorA, int generatorB)
{
int count = 0;
List<int> cmpA = new List<int>();
List<int> cmpB = new List<int>();
for (int i = 0; i < sampleSize; i++)
{
generatorA = (int)(((ulong)generatorA * 16807ul) % int.MaxValue);
generatorB = (int)(((ulong)generatorB * 48271ul) % int.MaxValue);
if (generatorA % 4 == 0) cmpA.Add(generatorA);
if (generatorB % 8 == 0) cmpB.Add(generatorB);
}
for (int i = 0; i < Math.Min(cmpA.Count, cmpB.Count); i++)
{
if ((cmpA[i] & 0xffff) == (cmpB[i] & 0xffff))
count++;
}
return count;
}
}
}

122
csharp/BScottDay16.cs Normal file
View File

@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace AOC2017
{
class BScottDay16 : BScottSolution
{
public override string Name => "Day 16: Permutation Promenade";
public override void Run()
{
string[] input = File.ReadAllText("BScottDay16.txt").Split(',');
Console.WriteLine($"Part 1 Answer: {PermutationPromenadePart1(input)}");
Console.WriteLine($"Part 2 Answer: {PermutationPromenadePart2(input)}");
}
private string PermutationPromenadePart1(string[] instructions)
{
char[] programs = new char[16];
for (int i = 0; i < programs.Length; i++)
programs[i] = (char)('a' + i);
for (int i = 0; i < instructions.Length; i++)
{
string[] args = instructions[i].Substring(1).Split('/');
int a, b;
char tmp;
switch (instructions[i][0])
{
case 's': // Spin
int startPos = 16 - int.Parse(args[0]);
char[] temp = new char[16];
for (int j = 0; j < temp.Length; j++)
temp[j] = programs[(j + startPos) % temp.Length];
for (int j = 0; j < temp.Length; j++)
programs[j] = temp[j];
break;
case 'x': // Exchange
a = int.Parse(args[0]);
b = int.Parse(args[1]);
tmp = programs[b];
programs[b] = programs[a];
programs[a] = tmp;
break;
case 'p': // Partner
a = Array.IndexOf(programs, args[0][0]);
b = Array.IndexOf(programs, args[1][0]);
tmp = programs[b];
programs[b] = programs[a];
programs[a] = tmp;
break;
}
}
return new String(programs);
}
private string PermutationPromenadePart2(string[] instructions)
{
char[] programs = new char[16];
List<string> cache = new List<string>();
for (int i = 0; i < programs.Length; i++)
programs[i] = (char)('a' + i);
// add initial state to cache
cache.Add(new string(programs));
for (int x = 0; x < 10000; x++)
{
for (int i = 0; i < instructions.Length; i++)
{
string[] args = instructions[i].Substring(1).Split('/');
char tmp;
int a, b;
switch (instructions[i][0])
{
case 's': // Spin
int startPos = 16 - int.Parse(args[0]);
char[] temp = new char[16];
for (int j = 0; j < temp.Length; j++)
temp[j] = programs[(j + startPos) % temp.Length];
for (int j = 0; j < temp.Length; j++)
programs[j] = temp[j];
break;
case 'x': // Exchange
a = int.Parse(args[0]);
b = int.Parse(args[1]);
tmp = programs[b];
programs[b] = programs[a];
programs[a] = tmp;
break;
case 'p': // Partner
a = Array.IndexOf(programs, args[0][0]);
b = Array.IndexOf(programs, args[1][0]);
tmp = programs[b];
programs[b] = programs[a];
programs[a] = tmp;
break;
}
}
// eventually the same sequence will happen again, and when it does you have
// considerably reduced the number of times you actually have to perform the sequence.
string s = new string(programs);
if (cache.Contains(s))
break;
cache.Add(s);
}
return cache[1000000000 % cache.Count];
}
}
}

1
csharp/BScottDay16.txt Normal file

File diff suppressed because one or more lines are too long

51
csharp/BScottDay17.cs Normal file
View File

@ -0,0 +1,51 @@
using System;
namespace AOC2017
{
class BScottDay17 : BScottSolution
{
public override string Name => "Day 17: Spinlock";
public override void Run()
{
int input = 355;
Console.WriteLine($"Part 1 Example Answer: {SpinlockPart1(3, 2017)}");
Console.WriteLine($"Part 1 Answer: {SpinlockPart1(input, 2017)}");
Console.WriteLine($"Part 2 Answer: {SpinlockPart2(input, 50000000)}");
}
private int SpinlockPart1(int input, int count)
{
int pos = 0, size = 1;
int[] buffer = new int[count+1];
for (int i = 0; i < count; i++)
{
pos = (pos + input + 1) % size;
// move everything over 1
for (int j = size - 1; j > pos; j--)
buffer[j + 1] = buffer[j];
// set value, increase size
buffer[pos + 1] = size++;
}
return buffer[Array.IndexOf(buffer, count) + 1];
}
private int SpinlockPart2(int input, int count)
{
int pos = 0, size = 1;
int value = 0;
for (int i = 0; i < count; i++)
{
pos = (pos + input + 1) % size;
if(pos + 1 == 1)
value = size;
size++;
}
return value;
}
}
}

251
csharp/BScottDay18.cs Normal file
View File

@ -0,0 +1,251 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace AOC2017
{
class BScottDay18 : BScottSolution
{
public override string Name => "Day 18: Duet";
public override void Run()
{
string[] exampleInput = new[]
{
"set a 1",
"add a 2",
"mul a a",
"mod a 5",
"snd a",
"set a 0",
"rcv a",
"jgz a -1",
"set a 1",
"jgz a -2"
};
Console.WriteLine($"Part 1 Example Answer: {DuetPart1(exampleInput)}");
string[] exampleInput2 = new[]
{
"snd 1",
"snd 2",
"snd p",
"rcv a",
"rcv b",
"rcv c",
"rcv d"
};
Console.WriteLine($"Part 2 Example Answer: {DuetPart2(exampleInput2)}");
string[] input = File.ReadAllLines("BScottDay18.txt");
Console.WriteLine($"Part 1 Answer: {DuetPart1(input)}");
Console.WriteLine($"Part 2 Answer: {DuetPart2(input)}");
}
private long DuetPart1(string[] instructions)
{
Dictionary<char, long> registers = new Dictionary<char, long>();
// initialize registers
for(char i = 'a'; i <= 'z'; i++)
registers.Add(i,0);
long snd = 0, rcv = 0;
for(int i = 0; i < instructions.Length; i++)
{
string[] args = instructions[i].Split(' ');
long value = 0;
switch (args[0])
{
case "snd":
snd = registers[args[1][0]];
break;
case "set":
if (long.TryParse(args[2], out value))
registers[args[1][0]] = value;
else
registers[args[1][0]] = registers[args[2][0]];
break;
case "add":
if (long.TryParse(args[2], out value))
registers[args[1][0]] += value;
else
registers[args[1][0]] += registers[args[2][0]];
break;
case "mul":
if (long.TryParse(args[2], out value))
registers[args[1][0]] *= value;
else
registers[args[1][0]] *= registers[args[2][0]];
break;
case "mod":
if (long.TryParse(args[2], out value))
registers[args[1][0]] %= value;
else
registers[args[1][0]] %= registers[args[2][0]];
break;
case "rcv":
if (registers[args[1][0]] > 0)
rcv = snd;
break;
case "jgz":
if (!long.TryParse(args[1], out value))
value = registers[args[1][0]];
if (value > 0)
{
if (!long.TryParse(args[2], out value))
value = registers[args[2][0]];
i += (int)(value-1);
}
break;
}
// recover operation ran
if (rcv > 0)
break;
}
return rcv;
}
private long DuetPart2(string[] instructions)
{
Queue<long> programQueue0 = new Queue<long>();
Queue<long> programQueue1 = new Queue<long>();
Program program0 = new Program(0, instructions, programQueue0, programQueue1);
Program program1 = new Program(1, instructions, programQueue1, programQueue0);
while (!program0.Finished && !program1.Finished)
{
program0.RunInstruction();
program1.RunInstruction();
if (program0.PendingReceive && program1.PendingReceive)
break;
}
return program1.SendCount;
}
class Program
{
Dictionary<char, long> registers = new Dictionary<char, long>();
private long pc = 0;
private long sendCount = 0;
private string[] instructions;
private Queue<long> inputQueue;
private Queue<long> outputQueue;
private bool pendingReceive = false;
private bool finished = false;
public bool PendingReceive
{
get { return pendingReceive; }
}
public bool Finished
{
get { return finished; }
}
public long SendCount
{
get { return sendCount; }
}
public Program(int programId, string[] instructions, Queue<long> inputQueue, Queue<long> outputQueue)
{
for (char i = 'a'; i <= 'z'; i++)
this.registers.Add(i, 0);
this.registers['p'] = programId;
this.instructions = instructions;
this.inputQueue = inputQueue;
this.outputQueue = outputQueue;
}
public void RunInstruction()
{
string[] args = instructions[pc].Split(' ');
long value = 0;
switch (args[0])
{
case "snd":
sendCount++;
if (long.TryParse(args[1], out value))
outputQueue.Enqueue(value);
else
outputQueue.Enqueue(registers[args[1][0]]);
break;
case "set":
if (long.TryParse(args[2], out value))
registers[args[1][0]] = value;
else
registers[args[1][0]] = registers[args[2][0]];
break;
case "add":
if (long.TryParse(args[2], out value))
registers[args[1][0]] += value;
else
registers[args[1][0]] += registers[args[2][0]];
break;
case "mul":
if (long.TryParse(args[2], out value))
registers[args[1][0]] *= value;
else
registers[args[1][0]] *= registers[args[2][0]];
break;
case "mod":
if (long.TryParse(args[2], out value))
registers[args[1][0]] %= value;
else
registers[args[1][0]] %= registers[args[2][0]];
break;
case "rcv":
if (inputQueue.Count == 0)
{
pendingReceive = true;
return;
}
registers[args[1][0]] = inputQueue.Dequeue();
break;
case "jgz":
if (!long.TryParse(args[1], out value))
value = registers[args[1][0]];
if (value > 0)
{
if (!long.TryParse(args[2], out value))
value = registers[args[2][0]];
pc += value;
return;
}
break;
}
if (++pc > instructions.Length)
{
finished = true;
return;
}
}
}
}
}

41
csharp/BScottDay18.txt Normal file
View File

@ -0,0 +1,41 @@
set i 31
set a 1
mul p 17
jgz p p
mul a 2
add i -1
jgz i -2
add a -1
set i 127
set p 735
mul p 8505
mod p a
mul p 129749
add p 12345
mod p a
set b p
mod b 10000
snd b
add i -1
jgz i -9
jgz a 3
rcv b
jgz b -1
set f 0
set i 126
rcv a
rcv b
set p a
mul p -1
add p b
jgz p 4
snd a
set a b
jgz 1 3
snd b
set f 1
add i -1
jgz i -11
snd a
jgz f -16
jgz a -19

167
csharp/BScottDay19.cs Normal file
View File

@ -0,0 +1,167 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace AOC2017
{
class BScottDay19 : BScottSolution
{
public override string Name => "Day 19: A Series of Tubes";
public override void Run()
{
string[] input = File.ReadAllLines("BScottDay19.txt");
char[][] map = new char[input.Length][];
for (int i = 0; i < input.Length; i++)
map[i] = input[i].ToCharArray();
Console.WriteLine($"Part 1 Answer: {TubesPart1(map)}");
Console.WriteLine($"Part 2 Answer: {TubesPart2(map)}");
}
private const int NORTH = 0;
private const int EAST = 1;
private const int SOUTH = 2;
private const int WEST = 3;
private string TubesPart1(char[][] map)
{
int currentX = 0, currentY = 0;
int direction = SOUTH;
List<char> letters = new List<char>();
// get entry position
currentY = 0; // first row
currentX = Array.IndexOf(map[currentY], '|');
direction = SOUTH;
if (currentX == -1)
return String.Empty;
while (true)
{
switch (direction)
{
case NORTH:
currentY--;
break;
case EAST:
currentX++;
break;
case SOUTH:
currentY++;
break;
case WEST:
currentX--;
break;
}
if (currentX < 0 || currentY < 0)
break;
char c = map[currentY][currentX];
switch (c)
{
case ' ':
return new string(letters.ToArray());
case '-':
case '|':
break;
case '+':
direction = FindNextDirection(currentX, currentY, direction, map);
break;
default:
letters.Add(c);
break;
}
}
return new string(letters.ToArray());
}
private int TubesPart2(char[][] map)
{
int currentX = 0, currentY = 0;
int direction = SOUTH;
int distance = 1;
// get entry position
currentY = 0; // first row
currentX = Array.IndexOf(map[currentY], '|');
direction = SOUTH;
if (currentX == -1)
return 0;
while (true)
{
switch (direction)
{
case NORTH:
currentY--;
break;
case EAST:
currentX++;
break;
case SOUTH:
currentY++;
break;
case WEST:
currentX--;
break;
}
if (currentX < 0 || currentY < 0)
break;
char c = map[currentY][currentX];
switch (c)
{
case ' ':
return distance;
case '+':
direction = FindNextDirection(currentX, currentY, direction, map);
break;
}
distance++;
}
return distance;
}
private int FindNextDirection(int x, int y, int currentDirection, char[][] map)
{
char north = map[y - 1][x];
char south = map[y + 1][x];
char east = map[y][x + 1];
char west = map[y][x - 1];
switch (currentDirection)
{
case NORTH:
if (east == '-') return EAST;
if (west == '-') return WEST;
break;
case EAST:
if (north == '|') return NORTH;
if (south == '|') return SOUTH;
break;
case SOUTH:
if (east == '-') return EAST;
if (west == '-') return WEST;
break;
case WEST:
if (north == '|') return NORTH;
if (south == '|') return SOUTH;
break;
}
return -1;
}
}
}

201
csharp/BScottDay19.txt Normal file
View File

@ -0,0 +1,201 @@
 |
+-----------------------------------+ +-+ +-------------------------------------------------------------------------------------------+ +-+
| | | | | | | | |
+-----------------+ | +-----+ | +-----+ | | +---------------------------------------------|---+ |
| | | | | | | | | | |
+-------------+ +-+ | | | +---------------+ | | |
| | | | | | | | | | |
+---------------------------------------------------------------------|---------|-----------+ | | +---------------------|-----+
| | | | | | | | | | | | |
| | +-----+ +-------------------+ +-+ +-------------------------------------------------------------------------------------------+
| | | | | | | | | | | | |
| +-------|-------+ | +-|-+ +---|-------------------------------------------------------|---------------------------------------------|---+ |
| | | | | | | | | | | | | | |
| | | | | +-|-----|---------+ +-----------------------------------------------------------------|-------------------------|---+ |
| | | | | | | | | | | | | | | | |
| +-----------------------------|---|---|-----|---|-------------------------------------------+ | +-------------------|-------------------------+ +-+ |
| | | | | | | | | | | | | | | | | | |
| +---------------|-------------|-------|-------------|-----------|-----|-------------------------------------|-----------------------------------|---------------------------+ +-+ |
| | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | +---|---+ +-----------+ +-+
| | | | | | | | | | | | | | | | | | | | |
| | +-------------|---------------------|-------|-----|-----------|-----|---------------------|---------------|---------------|-------+ | | | | |
| | | | | | | | | | | | | | | | | | | | | | |
| +---|-|---------------------------|---------------|---+ | | +---|-----|-----------------+ | | +---|-------------+ | | | | | +-+
| | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | +-------------------+ +-+ | +-----------------------------------+ | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | +---------------|-------------|---------------|-------|---------|-----|-+ | | | | | | | | | +-----------|-------------+ | | |
| | | | | | | | | | | | | | | | P | | | | | | | | | | | |
| | | | | | | | | +-|-------------------------|-|---------------|-|---------|-----------|-------|-------|-----------+ | +-------+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | |
+-------------+ | | | +---------|---------------|-------|-|-----|-----------------|-|-|---+ | | | | | | | | | | +-----+ | +-+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
+-----+ | | | | | | | | +---------------|-----------------|-|-|-------------------------------------------|---|---|---------------------|-------+ |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | +---------------|-------------|---------|-|-----|-------+ | | | | | | +---|-------------+ | | | | | | +-+ | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | +-------|---------------------|---|-+ +---+ |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | +---------|---|-+ | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
+---------------------|-------------|-----|-----|-|-------|-------|---------------|-|-----|-|-----|---------|---|---|-------------|-+ | | | | +---|---|-------------|-----+ | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| +---------+ | | | | | +---|-+ | | | | | | | | | | | | | | | | | +---------|---+ | +---|-+ | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| +-----------------+ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | +-----------|-----|-----|-----|---|-|-----|---------------|-------|-|-----------------------|---------------------+ | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | +-+ | | | | | | | | | | | | | | | | | | | | | | | | | | | | +---|-|-----------|-----+ | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | +---+ | | | | | | | +-----+ | | +-|-+ +-------------|-|---|-----------|-------|---|---+ | | | | | +-+ | | | +---------+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | +-|-|---|---|-|---------------------|-----|-|---------------------|-----------------|-----|---------+ | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | +---+ | | | | | | | | | | | | | | | | | | +-|-------------------|-----------|-+ | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | +-----------------|-------|-----------+ | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | +-----------|-----------------|---|-|-------------+ | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | +-------|-|-|---|-----------------|---------|---------------|-+ | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | +---|-------------|---|-|---|---------------|---|-|-----+ | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | +---------------|-----------|-----|-+ | | | | | | | | | | | | +-|-----------|-------|---|-|-+ | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | +---|-------------------------+ | +-----|-----------|-------|-----------|-|-|-------|---------------|-+ | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | +-------------|---|-------------|-|---|-|---------+ | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | +---------------|-------------|---|-----+ +-------|-------|-----|---------|-----------|---|-|-------------|-|-|-|-----|-------------|-|-|-|-----------|-----|-------+ | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| +---|-+ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | +---|-----|-----|-----------------+ | | | +---------|-+ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | +-+ | | | | | +-----+ | | | | | | | | | | | | | +-|-+ | +-+ | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | +-------|-------------------|-----------|---|------------Y--|-------------|---------------|-----|---|-----|---------|---|-----------+ | | | | | | |
| | | | X | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | +---------|---------------------------------------|-----|-----------|---|---------|-|-----------+ | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | +-+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | +-|-------------------------|-----|-----------|-|-----------|---|-------------|---------|-|---|-|-----------|---------|-|---------------------|-|---------|-------|-----------|-+ |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | +-|---------|-------------|-|-|-------------|---------|-|-----------------|-------+ | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| +-----------|-----------------------|-|---+ | +---------------|-------------|---|-|-+ | | | | | | | +-------|---|-----|-|-+ | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | O | | |
| | | | | | | | | | | | | | | | | | | +-|-----|-----------------|-|---|-+ | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | +---------|-------|-|---|-----------------------|-|-|-|---+ | | | | | | | | | | | | |
| | | | | | | | | | | | R | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | +-|---------|-|---------------|-------------|-+ | | | | | | | +-----|-|-|-|-|-------|-|-|-----------|-|-----|-|---+ | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | +---|-|---+ | +---------|-----------|-----------------|---------|-----------------------|-----|-+ | | | | +---------|---|---+ | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | +-----|---------|-|---------------|-------------|-----------|---|-----|-----------|---------|-|---+ +-+ +-----|-|---------------+ | | | | | |
| | | | | | | | | | | | | | | | | | W | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | +---|-----|-------|---|---+ | +-|-|---|-------|-|-------|-----|-+ | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | +-------+ | | | | | | | +-|---------------------|---|-|-|---|-+ | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | +-------------|-|---|---|-|-------+ | | +-----+ |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | +-|-------|---------|-+ | +---+ | | | +-|-----|---------+ +-|-------------+ | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | +-|-|-------|---------------|-------|-|-----------------|-------------|---|-----|-----------------|-|-|-|-----|-----------|-----|---|---|---|-|-----------|-----|-|-------------------------+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | +-------+ | | | | +-+ +-------|---------|-------------|---|-----------------------|-----|-----|-------|---|-----|-----|---+ | | +---|-+ | | | | | | | | +-------+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | +-----|-------|---+ | | | | | +---+ | | | | | | +---|-|---|-------|---|-----|-|---|---------|-----------+ | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | +-|-------------|-----------|---------------+ +-|-----|-+ +---|-----|---|-|-------------|---|-+ | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | +---------|-------------|-----------------------------------------------|-----|-------|---|-----|-----------|---|-------|-----|-|---|---+ | | | +-|-|---|---|---------------|-+ | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | +-----------------------|-|-|-----------------------|---|-|-----|-----------|-|-----------------------|-|-------+ | | | +-----|---|-|---|---+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | +---+ | | +-|-------------+ | | | | | | | +-----+ | | | | | | | | | | | | | | | | | | | |
| | E | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | +-----------+ | +-+ | | | | | | | | | | | | +-+ | | | | | | | | | | | +---|---|-+ |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | +-----------------------|---|-------|-----|-----------------------------------|-|---------------|-------|-----|---|---------|-|-----------+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| +-|---------|---|---------------------|---|-------|-----------------------+ | | +-------------|---------+ | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | +-----------+ | +-----|-----|---+ | +-|-------|-|-----------------|-|---------|-------|-|-------------------|---|-------+ | +-+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | +-------|---|---------|-|-|---------|-|-|-----|-----|-|-+ | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | +-----|-------------|-------------|-----------|-|-|---|---|---------|---|---------|---|-|-----+ | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | +-----------|-----|-----|---------+ | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | +-----------------------------------------------|-------|---|-----|-----------------------+ | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | +-------------------------------------------------------|-|-------|---+ | | | +-|-----|-------------|-|---|-|---|---------------|-|---|---|-------------|-+ | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | +-|-----------|-----------|-----|---+ | | | | | | | +-----|-|-----------+ | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| +---|---------------------------------|---|-+ +---|---|-|-------|-|-----------|-|-|--H--------|---|-------------------|---|-|-----------------------+ | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | +-----|-|-|-------|-|---------|-|---------|---|---|-------|---|-------------|-----|-------------------|-----|---------|-|-------|-----|-----+ | | | +-|---+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | +-------------+ | | | | +-+ | | | | +-|---|-|-------|---|-------|-|-+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | +---------------------|---|-|-----|-------------|-------------------------------|-|-------------|---------|---------------------------|---+ | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | +-----|-----|-------|---|-----------------|-|---|---|-|-----------------------------------|---------|---|-------|---+ | | | | | +-----+ | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | +-|---------------|-+ | | | +-------|---|-----------|-----------+ | | | +---------|-----|---|-------|-|-+ | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | +-------------|---|-------------+ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | +---------|-|-|-------------------------|-----------------|---|-------|-|-------------|-|-----|---------|-----|---------|---|-------|-+ | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| +-|-|-------|-------|-------------|-------|---+ | | | | +-----------+ | | | | | | | | | | | | | | | | | | | | | +-----+ | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | +-|-----------+ | | | | | | | | | | +-+ | | | | | | | +-|-------+ | | | +-------|---------------|---------|---+ | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | +-----------+ | | | | | | | | | +---|-------------|-----------|-------------|-----------|-|---|---------+ | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | +-|-----+ | | | | | | | | +---------------------|---|-|---|-|---|-------------|-----|---|-----|-------|-|-|---------------|---------------|-----------------|---+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | +-|-------|---|-----------|---------------+ | +---|-|-+ +-+ | | | +-------+ +-+ | | | | | | | +-------+ | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | +-|-|-----------------+ +---+ | | | | | +---|-|---|---------------------|-------|-------------------------------|---|-|-----|---|-------|-+ | | | +---|-----|-+ | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | +-|-----|---------|-------------|-|-------------------------|-|-------------|-------------|---------|-----|-|---|---|-----+ | +-|-+ | | | +---+ | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| +-|-|---|-|---------|-------------|---|-----------|---|-----------|-----------------+ | | | +-|---------+ | | | +-----|-----|-|---|-----------|---|-------|---|-|-----+ | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| +-|-|-+ | | | | +-----|-|-------|---------------------------------|-------|-------+ +---------+ +---|-----|---|-|-|---+ | +---------+ | | | | | +-|---+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| +-|-+ +-----|-------------------------|---|-------+ | | | | +---------|-----+ | | +---------------|---|-------|-------|---|-----------|-------------|-----|---+
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| +---+ | +---------|---------------------|-----------------------|---|---------------|-----|-----------------+ | | +---------+ | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| +-|-|-------|-------+ | | +-----------|---------|-|---|-----------------------|-----|-----------|---------|---|---------|---|-------------------|-------------|-----------+ | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
+---+ | | | +-------------+ +-----------------------|-+ | | +---|---+ +-----------|-------|-----|-----------|-|-------+ +---|-------+ | +-----------+ | |
| | | | | | | | | | | | | | | | | | | | | | |
+---+ +-----------+ | | +---------------+ +-+ +-----------------+ | | +-----------|-------------------+ | | | | |
| | | | | | | | | | | | |
+-----------|-----------------------------------------------------------------|-|-------------|---|-----------------+ +---+ | | | |
| | | | | | | | | | | | |
+-----------+ +-------------------------------------------------------+ +---N +-+ +-----------------------+ +-------------+ +---+

63
csharp/BScottDay2.cs Normal file
View File

@ -0,0 +1,63 @@
using System;
using System.IO;
using System.Linq;
namespace AOC2017
{
class BScottDay2 : BScottSolution
{
public override string Name => "Day 2: Corruption Checksum";
public override void Run()
{
string[] input = File.ReadAllLines("BScottDay2.txt");
Console.WriteLine($"Part 1 Answer: {CalculateChecksumPart1(input)}");
Console.WriteLine($"Part 2 Answer: {CalculateChecksumPart2(input)}");
}
static long CalculateChecksumPart1(string[] rows)
{
long checksum = 0;
for (int i = 0; i < rows.Length; i++)
{
int min = int.MaxValue, max = 0;
int[] cols = Array.ConvertAll(rows[i].Split(new char[] {'\t'}), s => int.Parse(s));
for (int j = 0; j < cols.Length; j++)
{
if (cols[j] < min)
min = cols[j];
if (cols[j] > max)
max = cols[j];
}
checksum += Math.Abs(max - min);
}
return checksum;
}
static long CalculateChecksumPart2(string[] rows)
{
long checksum = 0;
for (int i = 0; i < rows.Length; i++)
{
int value = 0;
int[] cols = Array.ConvertAll(rows[i].Split(new char[] { '\t' }), s => int.Parse(s));
for (int j = 0; j < cols.Length; j++)
{
for (int k = 0; k < cols.Length; k++)
{
if (cols[j] > cols[k] && (cols[j] % cols[k]) == 0)
{
value = cols[j] / cols[k];
break;
}
}
if (value > 0)
break;
}
checksum += value;
}
return checksum;
}
}
}

16
csharp/BScottDay2.txt Normal file
View File

@ -0,0 +1,16 @@
116 1470 2610 179 2161 2690 831 1824 2361 1050 2201 118 145 2275 2625 2333
976 220 1129 553 422 950 332 204 1247 1092 1091 159 174 182 984 713
84 78 773 62 808 83 1125 1110 1184 145 1277 982 338 1182 75 679
3413 3809 3525 2176 141 1045 2342 2183 157 3960 3084 2643 119 108 3366 2131
1312 205 343 616 300 1098 870 1008 1140 1178 90 146 980 202 190 774
4368 3905 3175 4532 3806 1579 4080 259 2542 221 4395 4464 208 3734 234 4225
741 993 1184 285 1062 372 111 118 63 843 325 132 854 105 956 961
85 79 84 2483 858 2209 2268 90 2233 1230 2533 322 338 68 2085 1267
2688 2022 112 130 1185 103 1847 3059 911 107 2066 1788 2687 2633 415 1353
76 169 141 58 161 66 65 225 60 152 62 64 156 199 80 56
220 884 1890 597 3312 593 4259 222 113 2244 3798 4757 216 1127 4400 178
653 369 216 132 276 102 265 889 987 236 239 807 1076 932 84 864
799 739 75 1537 82 228 69 1397 1396 1203 1587 63 313 1718 1375 469
1176 112 1407 136 1482 1534 1384 1202 604 851 190 284 1226 113 114 687
73 1620 81 1137 812 75 1326 1355 1545 1666 1356 1681 1732 85 128 902
571 547 160 237 256 30 496 592 385 576 183 692 192 387 647 233

119
csharp/BScottDay20.cs Normal file
View File

@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace AOC2017
{
class BScottDay20 : BScottSolution
{
public override string Name => "Day 20: Particle Swarm";
public override void Run()
{
string[] input = File.ReadAllLines("BScottDay20.txt");
Console.WriteLine($"Part 1 Answer: {ParticleSwarmPart1(input)}");
Console.WriteLine($"Part 2 Answer: {ParticleSwarmPart2(input)}");
}
private List<Particle> LoadParticles(string[] input)
{
List<Particle> particleList = new List<Particle>();
int index = 0;
foreach (string s in input)
{
string[] args = s.Split(new string[] {", "}, StringSplitOptions.None);
string[] positionArgs = args[0].Substring(3, args[0].Length - 4).Split(',');
string[] velocityArgs = args[1].Substring(3, args[1].Length - 4).Split(',');
string[] accelerationArgs = args[2].Substring(3, args[2].Length - 4).Split(',');
particleList.Add(new Particle(
index++,
new Vector3D(long.Parse(positionArgs[0]), long.Parse(positionArgs[1]), long.Parse(positionArgs[2])),
new Vector3D(long.Parse(velocityArgs[0]), long.Parse(velocityArgs[1]), long.Parse(velocityArgs[2])),
new Vector3D(long.Parse(accelerationArgs[0]), long.Parse(accelerationArgs[1]), long.Parse(accelerationArgs[2]))
));
}
return particleList;
}
private int ParticleSwarmPart1(string[] input)
{
List<Particle> particleList = LoadParticles(input);
for (int i = 0; i < 2000; i++)
{
foreach (Particle p in particleList)
p.Tick();
}
var test = particleList.ToList().OrderBy(p => p.Position.Distance).First();
return test.Index;
}
private int ParticleSwarmPart2(string[] input)
{
List<Particle> particleList = LoadParticles(input);
for (int i = 0; i < 2000; i++)
{
foreach (Particle p in particleList)
p.Tick();
// finds anything that duplicates, removes anything with that position.
particleList.GroupBy(txt => txt.Position.ToString())
.Where(grouping => grouping.Count() > 1)
.ToList()
.ForEach(groupItem => particleList.RemoveAll(item => item.Position.ToString() == groupItem.Key));
}
return particleList.Count;
}
class Vector3D
{
public long X { get; set; }
public long Y { get; set; }
public long Z { get; set; }
public long Distance => Math.Abs(X) + Math.Abs(Y) + Math.Abs(Z);
public override string ToString()
{
return $"{X},{Y},{Z}";
}
public Vector3D(long x, long y, long z)
{
X = x;
Y = y;
Z = z;
}
}
class Particle
{
public int Index { get; private set; }
public Vector3D Position { get; private set; }
public Vector3D Velocity { get; private set; }
public Vector3D Acceleration { get; private set; }
public Particle(int index, Vector3D position, Vector3D velocity, Vector3D acceleration)
{
Index = index;
Position = position;
Velocity = velocity;
Acceleration = acceleration;
}
public void Tick()
{
Velocity.X += Acceleration.X;
Velocity.Y += Acceleration.Y;
Velocity.Z += Acceleration.Z;
Position.X += Velocity.X;
Position.Y += Velocity.Y;
Position.Z += Velocity.Z;
}
}
}
}

1000
csharp/BScottDay20.txt Normal file

File diff suppressed because it is too large Load Diff

186
csharp/BScottDay22.cs Normal file
View File

@ -0,0 +1,186 @@
using System;
using System.IO;
namespace AOC2017
{
class BScottDay22 : BScottSolution
{
public override string Name => "Day 22: Sporifica Virus";
public override void Run()
{
string[] exampleInput = new[]
{
"..#",
"#..",
"..."
};
Console.WriteLine($"Part 1 Example Answer: {SporificaVirusPart1(exampleInput, 10000)}");
Console.WriteLine($"Part 2 Example Answer: {SporificaVirusPart2(exampleInput, 10000000)}");
string[] input = File.ReadAllLines("BScottDay22.txt");
Console.WriteLine($"Part 1 Answer: {SporificaVirusPart1(input, 10000)}");
Console.WriteLine($"Part 2 Answer: {SporificaVirusPart2(input, 10000000)}");
}
private const int NORTH = 0;
private const int EAST = 1;
private const int SOUTH = 2;
private const int WEST = 3;
private const int LEFT = 0;
private const int RIGHT = 1;
private const int REVERSE = 2;
private char[][] CreateGrid(string[] input)
{
int expand = 1000;
int infiniteGridHeight = input.Length * (expand + 1);
int infiniteGridWidth = input[0].Length * (expand + 1);
// create big grid
char[][] grid = new char[infiniteGridHeight][];
for (int i = 0; i < infiniteGridHeight; i++)
grid[i] = new char[infiniteGridWidth];
// initialize big grid
for (int i = 0; i < infiniteGridHeight; i++)
for (int j = 0; j < infiniteGridWidth; j++)
grid[i][j] = '.';
// copy to the center
for (int i = 0; i < input.Length; i++)
for (int j = 0; j < input[0].Length; j++)
grid[i + (input.Length * expand / 2)][j + (input[0].Length * expand / 2)] = input[i][j];
return grid;
}
private int SporificaVirusPart1(string[] input, int bursts)
{
char[][] grid = CreateGrid(input);
int currentX = 0, currentY = 0;
int direction = NORTH;
int infected = 0;
int centerY = (grid.Length / 2);
int centerX = (grid[0].Length / 2);
for (int i = 0; i < bursts; i++)
{
if (grid[centerY + currentY][centerX + currentX] == '.') // Clean
{
direction = FindNextDirection(direction, LEFT);
grid[centerY + currentY][centerX + currentX] = '#';
infected++;
}
else // Infected
{
direction = FindNextDirection(direction, RIGHT);
grid[centerY + currentY][centerX + currentX] = '.';
}
switch (direction)
{
case NORTH:
currentY--;
break;
case EAST:
currentX++;
break;
case SOUTH:
currentY++;
break;
case WEST:
currentX--;
break;
}
}
return infected;
}
private int SporificaVirusPart2(string[] input, int bursts)
{
char[][] grid = CreateGrid(input);
int currentX = 0, currentY = 0;
int direction = NORTH;
int infected = 0;
int centerY = (grid.Length / 2);
int centerX = (grid[0].Length / 2);
for (int i = 0; i < bursts; i++)
{
if (grid[centerY + currentY][centerX + currentX] == '.') // Clean
{
direction = FindNextDirection(direction, LEFT);
grid[centerY + currentY][centerX + currentX] = 'W';
}
else if (grid[centerY + currentY][centerX + currentX] == 'W') // Weakened
{
grid[centerY + currentY][centerX + currentX] = '#';
infected++;
}
else if (grid[centerY + currentY][centerX + currentX] == '#') // Infected
{
direction = FindNextDirection(direction, RIGHT);
grid[centerY + currentY][centerX + currentX] = 'F';
}
else // Flagged
{
direction = FindNextDirection(direction, REVERSE);
grid[centerY + currentY][centerX + currentX] = '.';
}
switch (direction)
{
case NORTH:
currentY--;
break;
case EAST:
currentX++;
break;
case SOUTH:
currentY++;
break;
case WEST:
currentX--;
break;
}
}
return infected;
}
private int FindNextDirection(int currentDirection, int turn)
{
switch (currentDirection)
{
case NORTH:
if (turn == RIGHT) return EAST;
if (turn == LEFT) return WEST;
if (turn == REVERSE) return SOUTH;
break;
case EAST:
if (turn == LEFT) return NORTH;
if (turn == RIGHT) return SOUTH;
if (turn == REVERSE) return WEST;
break;
case SOUTH:
if (turn == LEFT) return EAST;
if (turn == RIGHT) return WEST;
if (turn == REVERSE) return NORTH;
break;
case WEST:
if (turn == RIGHT) return NORTH;
if (turn == LEFT) return SOUTH;
if (turn == REVERSE) return EAST;
break;
}
return -1;
}
}
}

25
csharp/BScottDay22.txt Normal file
View File

@ -0,0 +1,25 @@
#.....##.####.#.#########
.###..#..#..####.##....#.
..#########...###...####.
.##.#.##..#.#..#.#....###
...##....###..#.#..#.###.
###..#...######.####.#.#.
#..###..###..###.###.##..
.#.#.###.#.#...####..#...
##........##.####..##...#
.#.##..#.#....##.##.##..#
###......#..##.####.###.#
....#..###..#######.#...#
#####.....#.##.#..#..####
.#.###.#.###..##.#..####.
..#..##.###...#######....
.#.##.#.#.#.#...###.#.#..
##.###.#.#.###.#......#..
###..##.#...#....#..####.
.#.#.....#..#....##..#..#
#####.#.##..#...##..#....
##..#.#.#.####.#.##...##.
..#..#.#.####...#........
###.###.##.#..#.##.....#.
.##..##.##...#..#..#.#..#
#...####.#.##...#..#.#.##

85
csharp/BScottDay24.cs Normal file
View File

@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace AOC2017
{
class BScottDay24 : BScottSolution
{
private readonly List<Component> _components = new List<Component>();
private uint _maxOverallStrength;
private uint _maxLength;
private uint _maxStrengthAmongLongest;
public override string Name => "Day 24: Electromagnetic Moat";
public override void Run()
{
string[] input = {
"0/2",
"2/2",
"2/3",
"3/4",
"3/5",
"0/1",
"10/1",
"9/10"
};
ProcessInput(input);
Console.WriteLine($"Part 1 Example Answer: {_maxOverallStrength}");
Console.WriteLine($"Part 2 Example Answer: {_maxStrengthAmongLongest}");
ProcessInput(File.ReadAllLines("BScottDay24.txt"));
Console.WriteLine($"Part 1 Answer: {_maxOverallStrength}");
Console.WriteLine($"Part 2 Answer: {_maxStrengthAmongLongest}");
}
private void ProcessInput(string[] input)
{
_components.Clear();
for (int i = 0; i < input.Length; i++)
{
string[] values = input[i].Split('/');
_components.Add(new Component(uint.Parse(values[0]), uint.Parse(values[1]), false));
}
_maxOverallStrength = 0;
_maxLength = 0;
_maxStrengthAmongLongest = 0;
RecursiveComponentScan(0, 0, 0);
}
private void RecursiveComponentScan(uint ports, uint length, uint strength)
{
_maxOverallStrength = Math.Max(strength, _maxOverallStrength);
_maxLength = Math.Max(length, _maxLength);
if (length == _maxLength)
_maxStrengthAmongLongest = Math.Max(strength, _maxStrengthAmongLongest);
foreach (var c in _components)
{
if (c.Used || (c.A != ports && c.B != ports)) continue;
c.Used = true;
RecursiveComponentScan((c.A == ports) ? c.B : c.A, length + 1, strength + c.A + c.B);
c.Used = false;
}
}
class Component
{
public uint A { get; }
public uint B { get; }
public bool Used { get; set; }
public Component(uint a, uint b, bool used)
{
A = a;
B = b;
Used = used;
}
}
}
}

54
csharp/BScottDay24.txt Normal file
View File

@ -0,0 +1,54 @@
48/5
25/10
35/49
34/41
35/35
47/35
34/46
47/23
28/8
27/21
40/11
22/50
48/42
38/17
50/33
13/13
22/33
17/29
50/0
20/47
28/0
42/4
46/22
19/35
17/22
33/37
47/7
35/20
8/36
24/34
6/7
7/43
45/37
21/31
37/26
16/5
11/14
7/23
2/23
3/25
20/20
18/20
19/34
25/46
41/24
0/33
3/7
49/38
47/22
44/15
24/21
10/35
6/21
14/50

128
csharp/BScottDay25.cs Normal file
View File

@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace AOC2017
{
class BScottDay25 : BScottSolution
{
public override string Name => "Day 25: The Halting Problem";
public override void Run()
{
TuringMachine machine = new TuringMachine(File.ReadAllLines("BScottDay25.txt"));
Console.WriteLine($"Part 1 Answer: {machine.RunPart1()}");
}
}
enum InstructionType
{
Write,
Move,
Continue
}
class State
{
public string Id { get; set; }
public Dictionary<int, List<Instruction>> ConditionActions { get; set; }
public State(string id)
{
Id = id;
ConditionActions = new Dictionary<int, List<Instruction>>();
}
}
class Instruction
{
public InstructionType InstructionType { get; set; }
public object Value { get; set; }
public Instruction(InstructionType instructionType, object value)
{
InstructionType = instructionType;
Value = value;
}
}
class TuringMachine
{
private readonly Dictionary<string, State> _states = new Dictionary<string, State>();
private readonly string _initialState = "";
private readonly long _checksumSteps = 0;
public TuringMachine(string[] input)
{
State currentState = null;
int currentCondition = -1;
for (int i = 0; i < input.Length; i++)
{
if(input[i].Trim().Length == 0)
continue;
string[] args = input[i].Trim().Replace(".", "").Replace(":", "").Split(' ');
if (args[0] == "Begin")
{
_initialState = args[3].Substring(0, 1);
}
else if (args[0] == "Perform")
{
_checksumSteps = int.Parse(args[5]);
}
else if (args[0] == "In")
{
if (currentState != null)
_states.Add(currentState.Id, currentState);
currentState = new State(args[2]);
}
else if (args[0] == "If")
{
currentCondition = int.Parse(args[5]);
currentState?.ConditionActions.Add(currentCondition, new List<Instruction>());
}
else if (args[0] == "-")
{
if (args[1] == "Write")
currentState?.ConditionActions[currentCondition].Add(new Instruction(InstructionType.Write, int.Parse(args[4])));
else if (args[1] == "Move")
currentState?.ConditionActions[currentCondition].Add(new Instruction(InstructionType.Move, args[6]));
else if (args[1] == "Continue")
currentState?.ConditionActions[currentCondition].Add(new Instruction(InstructionType.Continue, args[4]));
}
}
// add final state
if (currentState != null)
_states.Add(currentState.Id, currentState);
}
public long RunPart1()
{
int[] tape = new int[_checksumSteps];
int pos = tape.Length / 2;
string state = _initialState;
for (int i = 0; i < _checksumSteps; i++)
{
int value = tape[pos];
for (int j = 0; j < _states[state].ConditionActions[value].Count; j++)
{
switch (_states[state].ConditionActions[value][j].InstructionType)
{
case InstructionType.Move:
pos += ((string)_states[state].ConditionActions[value][j].Value == "left" ? -1 : 1);
break;
case InstructionType.Write:
tape[pos] = (int)_states[state].ConditionActions[value][j].Value;
break;
case InstructionType.Continue:
state = (string) _states[state].ConditionActions[value][j].Value;
break;
}
}
}
return tape.Sum();
}
}
}

62
csharp/BScottDay25.txt Normal file
View File

@ -0,0 +1,62 @@
Begin in state A.
Perform a diagnostic checksum after 12656374 steps.
In state A:
If the current value is 0:
- Write the value 1.
- Move one slot to the right.
- Continue with state B.
If the current value is 1:
- Write the value 0.
- Move one slot to the left.
- Continue with state C.
In state B:
If the current value is 0:
- Write the value 1.
- Move one slot to the left.
- Continue with state A.
If the current value is 1:
- Write the value 1.
- Move one slot to the left.
- Continue with state D.
In state C:
If the current value is 0:
- Write the value 1.
- Move one slot to the right.
- Continue with state D.
If the current value is 1:
- Write the value 0.
- Move one slot to the right.
- Continue with state C.
In state D:
If the current value is 0:
- Write the value 0.
- Move one slot to the left.
- Continue with state B.
If the current value is 1:
- Write the value 0.
- Move one slot to the right.
- Continue with state E.
In state E:
If the current value is 0:
- Write the value 1.
- Move one slot to the right.
- Continue with state C.
If the current value is 1:
- Write the value 1.
- Move one slot to the left.
- Continue with state F.
In state F:
If the current value is 0:
- Write the value 1.
- Move one slot to the left.
- Continue with state E.
If the current value is 1:
- Write the value 1.
- Move one slot to the right.
- Continue with state A.

108
csharp/BScottDay3.cs Normal file
View File

@ -0,0 +1,108 @@
using System;
namespace AOC2017
{
class BScottDay3 : BScottSolution
{
public override string Name => "Day 3: Spiral Memory";
public override void Run()
{
Console.WriteLine($"Part 1 Example Answer #1 (1): {SpiralMemoryPart1(1)}");
Console.WriteLine($"Part 1 Example Answer #2 (12): {SpiralMemoryPart1(12)}");
Console.WriteLine($"Part 1 Example Answer #3 (23): {SpiralMemoryPart1(23)}");
Console.WriteLine($"Part 1 Example Answer #4 (1024): {SpiralMemoryPart1(1024)}");
int value = 325489; // Puzzle Input
Console.WriteLine($"Part 1 Answer: {SpiralMemoryPart1(value)}");
Console.WriteLine($"Part 2 Answer: {SpiralMemoryPart2(value)}");
}
static int SpiralMemoryPart1(int value)
{
Point position = GetPosition(value);
return Math.Abs(position.X) + Math.Abs(position.Y);
}
// Unfortunatly I can't take credit for solving this. This was ported and optimized slightly from a C function posted to github.
// Included this just for the sake of completion.
// Source: https://github.com/vesche/adventofcode-2017/blob/master/day03.c
// Integer Sequence: https://oeis.org/A141481/b141481.txt
static int SpiralMemoryPart2(int value)
{
int x = 0, y = 0, dx = 0, dy = -1;
int[,] array = new int[1000, 3];
int[,] coords = new int[,] { { 1, 0 }, { 1, -1 }, { 0, -1 }, { -1, -1 }, { -1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 } };
for (int step = 0; step < 1000; step++)
{
int total = 0;
for (int i = 0; i < 1000; i++)
{
int tx = array[i, 0];
int ty = array[i, 1];
for (int j = 0; j < 8; j++)
{
if ((x + coords[j, 0] == tx) && (y + coords[j, 1] == ty))
total += array[i, 2];
}
}
array[step, 0] = x;
array[step, 1] = y;
array[step, 2] = (x == 0 && y == 0) ? 1 : total;
if (total > value)
return total;
if ((x == y) || ((x < 0) && (x == -y)) || ((x > 0) && (x == 1 - y)))
{
int dxtmp = dx;
dx = -dy;
dy = dxtmp;
}
x += dx;
y += dy;
}
return -1;
}
// Inverse ulam spiral coords
static Point GetPosition(int n)
{
double k = Math.Ceiling((Math.Sqrt(n) - 1) / 2);
double t = 2 * k + 1;
double m = Math.Pow(t, 2);
t = t - 1;
if (n >= m - t)
return new Point((int)(k - (m - n)), (int)-k);
m = m - t;
if (n >= m - t)
return new Point((int)-k, (int)(-k + (m - n)));
m = m - t;
if (n >= m - t)
return new Point((int)(-k + (m - n)), (int)k);
return new Point((int)k, (int)(k - (m - n - t)));
}
struct Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y)
{
this.X = x;
this.Y = y;
}
}
}
}

44
csharp/BScottDay4.cs Normal file
View File

@ -0,0 +1,44 @@
using System;
using System.Linq;
using System.IO;
namespace AOC2017
{
class BScottDay4 : BScottSolution
{
public override string Name => "Day 4: High-Entropy Passphrases";
public override void Run()
{
string[] input = File.ReadAllLines("BScottDay4.txt");
Console.WriteLine($"Part 1 Answer: {GetValidPassPhrasesPart1(input)}");
Console.WriteLine($"Part 2 Answer: {GetValidPassPhrasesPart2(input)}");
}
static int GetValidPassPhrasesPart1(string[] input)
{
int count = 0;
for (int i = 0; i < input.Length; i++)
{
string[] passStrings = input[i].Split(new char[] {' '});
string[] distinctStrings = passStrings.Distinct().ToArray();
if (passStrings.Length == distinctStrings.Length)
count++;
}
return count;
}
static int GetValidPassPhrasesPart2(string[] input)
{
int count = 0;
for (int i = 0; i < input.Length; i++)
{
string[] passStrings = Array.ConvertAll(input[i].Split(new char[] { ' ' }), s => string.Concat(s.OrderBy(c => c)));
string[] distinctStrings = passStrings.Distinct().ToArray();
if (passStrings.Length == distinctStrings.Length)
count++;
}
return count;
}
}
}

512
csharp/BScottDay4.txt Normal file
View File

@ -0,0 +1,512 @@
pphsv ojtou brvhsj cer ntfhlra udeh ccgtyzc zoyzmh jum lugbnk
vxjnf fzqitnj uyfck blnl impo kxoow nngd worcm bdesehw
caibh nfuk kfnu llfdbz uxjty yxjut jcea
qiho qif eupwww avyglnj nxzotsu hio lws
xjty usocjsh pivk qnknunc yjcgh bwya djw zpyr
ycfmfe mgq sjiomg nfzjul bjwkmgu yvsnvgj dcjupu wzz blmn
rdowgbt vpwfdoi blzl laghnk gsa vhnpo cztxzlb rtz hvwonhb eciju pfjtbo
bqs bqs dbutvgf mmzb izpyud rap izpyud xlzeb mnj hjncs
xpu vwp nujcos piu irindir tpmfd umtvlm gznu
sfpuxar qcnbte omouazv cnh uaxspfr sepolf rusafpx
xbmaf iceyqqq sabpt gliexel muubepe qqiyqce fmrcc eazk obkeonl fmccr kgk
apg gbycwe gap pag
gagv saqbk lwtllc wnhzz khxsjc
lgc alen rlmsp anel gcbvg
bujlaz rks rlqf deknmee yrp
scqvl weusbc bgvaz vgg cjwsfno vqy zbq aqy tvf bgzav
hbki vei fxdwljs myjuba elbsib pvy xxjxgi dtgv
linzaeu qbwdke fdg pykw
qvtdd aco aav bpu mvkcuc kjfj japgfki jfdl gem hog bdzsiea
wpbigkb lzhwba jssjkn qvb kmwu qddv
iny osyvqnt tumunzb torq bdeneg wywank poza ipp iggorw
tuko mhdbsf vmjdop jomaqpj rcdsud hmgspr lsas nzmwc
cirkjq nmjuu xtgejv gtexvj vjcmtqq unjmu
xsdmezq xvqjvqp exhygy qahju hvd qadmdh lok
wvvys kax rohrrar rwhnvi lhnmefp lsktouy bxilosp
wayf diobnl zvu obnidl oibnld
cewil ygsf ffzp ruxhu vah lnvwt aef lnnjc kgkb gxtlx feko
uti epphrin pywths cpzzh csjei nczhamy gayxmb bdcytq xkx fgmt
qvzyuwi dwo swkw bwjdrn dasgd ijgw vzabaop yefyhmc wgij
dyg sugrf vid etz weyqg nyntx dwfgwm khon hnzzzn xfyra
ofbh bdrsk rdrjj elaxvk jrjdr
msxau rsocvx zxdda mxz lknl
qktaywx dirpdbf unqnd wbrwkuu fvmqwl emxr big
xwz kvsydc ayokjyy qiah omw neo htltxx fxhwqwj colqvbb sxmo ephfkex
ncjxoaf fwjkc czmhv ylg axcjofn dvj bzqjku opvcr jiwzucg vmhzc
gmmnrt zqar twdwrg qiwwki fcbr lixm hjdwwe moiva
roinlxg cxeezve whannk cxeezve pyoj boweioy cpkgxsz
qkct qso xlb xyy aellfet rzt cbboow devfb nih fhbfxzi
qyc ltxia alixt atilx xtgrv
svruz ufvo rvesnxv dik vzurs jjg idk
xeudhrg hudn cilo ljplosb
kpb oyzvywx vldko qhfkwod bkeutk zqcqug pbriu wqocos
qkngzfy whobyri aze jvipdty ocirbep icqwc
kzxxlab sjr zhymws xkbx
nnxs gkwtld dwhkry snuibq dtdl aicug bhtlfzp qzk jctos
regvro mxcq hqof yraucxi jhkol iuxineo pbtnk rfjwc szgjpr ndqqj vfgm
yqrfox xoqrfy utbryu utubyr
jdubjt wqrl wnk rlqw nwiq pnbn qinw uaff ftdo htfrav
rum mur umr tij ovbahl losao imawwpb wadhww tbteyqc
napxd kzeiqcp ppgqucm xkityt frq hugrp gjgtt gmuqppc zwqme
xyuzs ysch howlzgu dkqppbs nvbiz mks mtxv vivouex uvawq
ffe lfsn nlq mpulheq ikcfo wdtz cnwsbph zkib muu
bqkxav wtecb lxwdhr kqbavx aqxvbk
czwswqx ldkxapd pfwd bdkkj iqohla cwosw ihqpd pcc ckhabbn
foiip hau rbqiyhh htm omeubgh symh evfcqg
lqx xlq rsgf izu esetis
npsrkdj fvulgkw eovw mzr uobcze azb tij ihoer ehori jit wknsqhm
gnrksh xwggt oosi bpnmhx qqaa mpmryu jhzyz
yad gbexqcr gbexqcr gbexqcr
ldca xxhznn twyy ytwy zhxnnx xfmpi
floioot kfyh dhibv ezyznar sfg sfg ezyznar
cinioim iiocmin ypla aypl
mhwcjbz dftuqsy wswop eizbf ptsd
ehx mlh nfxgfkz uuw xftmn ptlkbo vsnyo ttwce
oexvf orcg cncnkfk comvhl
lqewsj lyulrcl efixd qvd fhznqnz yvrkwyi xmhgc vzbp
dmr wrxqh thcm giomp rtvl ssc gwq rbklw hcmt fjvud
teozhb dmzwfv qkq pvcqfqq
hvlebc qqmg repxk zwrjdx ztruwb such tyligs ybg
psa rqznokd lgc jstqres yiqt mbiody xazb xjuk dtb
lea ncm rnh myzqzwm
wjml eums ueflvbr cjpgnl qduunu zfxaai jwlm lprzzg vrn ttetyr sume
uwkgeu uiahd plyewgi vveo nwhsitz mcitc uvk zsxehgs sewl
lnbdrka sgtivn sozzq mgd vhxfnlr twrfpk
gadphmk mbx lmlbrf tsnehnr lawdpm fnima gxgl
umty vrn dpow fsnnpjv fsnvnjp nnsvpjf cioaio
euu uue zeskmtk hob stekkzm
ypqpri qwdju ypriqp iprqyp jnoxqa
lkppi ingfxw wlulvp yhwrli nxwigf oyuhq ggfslx
kdd ypvr pyvr waw vyrp khqq mamxca bapq gobfm
iuq upvdpv zxef bfwns lmq lxswr kpsqo pwde iaaou nsw udy
lgzo nil ovgrmt omgtrv jrqp pqrj lit
uumyu iiakfj gvdtzz qbux yxn ejs dvlts
hcm ghutxq zswi tmyhqef hgxtuq
shkhkdk kad seubeax kdl mzu
cpykgr skx rfhpor xsk moyhlai ogv ophfrr dxipuuh
beyw jvrre opodn zdoajhx fhg ijs drczy drczy hjungq
jrzieja gfg yzdn yxm wshibsn fgg
xtylh vxscmvp rfymq uzhpyea spxcmvv dlni msj yxhlt
eov awql miv miv eov
mmvrfbg fjiyf hvqz zpuqmbf fszyuz ldfgni wemfjl fjjpl rbnpy rfb
ppzpeh nam ntv xnchtyk hja hpepzp foj bibvx nmmdlff bsrkp
qiy qiy umhlnh qiy
tyds oepk wae tdsy sdty
ukawr rkwau ghtjhm axy
wtbjiv btjivw ewaf hwk ttq
kdpun myve sqv rhvpy fnjwt puw ujhf thsp nkdadqr
vyw wkkpdpy xlgz lmmcuve ncuq lmotk
pmsfw vxd jpe qxlyasx ejp gwuv
pmgyndm ezofbvx nicbwrw kwnlj yjvnas fdpkfo mqcsyhn pyjpf fbexvzo vkftm erl
trmwvk rywuzoz hbidea kicohfz heidab deaibh
sogf govd dknpk vxrvk rlm vwhjk
xnxbfmw wguzrhd zbmkz piwppa mkbzz xvwrdgy flusfqb
cgduq hbnwr xfx mrejb ckw zkbaihf cloow cwk wuvthv iwqctx
vugx qbucd gxuv ocb cob
ilmet fbelxxz qratdfn unoj hbc duv srmikz
vnzuw zgpbqgf uzm thysyxd dinfh bgvr olungg ksd dsetwqz hpg
omagsf zpr coa kknx bzithq pewp flvoz xiiq weojqr wpep
aagj gcglqt gqcglt xbfx dhdx lbx
pljq plxuscw ilh wfk lhi hli fouieyw
hvnh zvm aqy dzitirm veq ctux
lglhs aqibdii hjbn cfgc qrg pnbntcx owoks ebz
jozngde lwne mbo omb fnyzvvj gndozje
bbdgc igtdj uhahgp sqduko
uuspedu fgnspm ewc slly jbs chl heanm abqijx kadvgxu
akfsft skna kusjqr rkqujs
erc vrljpu lruvjp lpvjur
iors hcdr fsqtcj vop vmn dtqnz tov oscjlw cdrh ctfjsq lrnts
fxp mczo sjlcxa mzoc jmsq hcxybow dmrr bcoxhyw
aac ewraerq odmxpz aac aac
zzio zebmxa szeej poordr gmi owwnnh xfx rzrab lfey jesze
akc yyoj vqod drtne
joxhvyf ymasnbr omouvq isxdrr
qyi ayrkzu jsk vqvvno jkkuxi zufnnwu mrsszdf
ocqi htfb tzjna cdt wkzhynm eergf
yokzugl usyuqu qvotq uweqyow lygkzuo kpmqmb uglyzok
glvshl imqv jrv xlpnsy gcg psj irtiamg wkl
bjcpc nvyloa dkkan efj okubpc cxlowm eone kmpny
cyxqys nmuaftv gqxj gtvsc
beouh dioxiah kizdy hyi cozrray rave fqxmxmj gdm
frjz amrsat lxvhzj azhevtu vxlzhj
zwmnrk sbk txzrcsj sbk oosgfej cvh zuthibi onvwd sbk nhwpzq
gzamt vraw kuk ugayl lyaug bww rwav ijah
bdjirxg vifjr rhbxpa oao yrhjxoi pbn
navb umesiys yhix phuhu aekkciu nlnsiq wjf idqdwp
cmhw rsu urs ziprlfe
kyhxitv cgty bnwjyq cygt sgjn pdab imarvhg yjbnqw
axaa ejancv yau njpc jvwy bpft kwjvg qzrbvtm diu njpc bpft
ambj upe rmqr yudbiqf krudp pqyf
tnb mobnpv vep ohxoc cyip wxyccfo jrbi rwsws kls zlv oohxc
fjh dmb hlbq bqc jhf kax suz fjjg rkpc
wjnn byfirm goeyh xtjmdka
tgyfxx hefpxln mveobqr yeo ftfn srt vim vlcu hevoi xtaaff
imyql xotcl poql rlueapq bkwykm hlalk bkwykm
gkec zff hbmtq rjxjbcf arerlu pvz cdaqi nijmhv uodwjh
mpctof mopftc ksfbat sbkatf
nvdd jub bvi kyggdbx nwtiok gjt mgsm dbhsn rzibgjm dvdn eqi
ysd iirp dfgzza wiyeoou ysd ispkv bcqg wwzqgq xphse
ntq ivposb gsd ezl tlkztp lez qyurp vxsmg dgs
wijs rydbj onm usiyqzb hwrol giusanb kewukl yziuqbs doojam nom
lfacyy xwwast truqtt tzneimn uxsydc ktu eqyaj ndszak
ffleooc kikif fohgop aucy moubqxu
iaxc pnwexdl ncy vmwm xrqoi wpgftq rofx utyzjuf stdxq twpgfq
ppmlp etsvi cjdx poly ynx vfxpslg mqjo qnpsage flpsxvg jwsxiqt
lbyhnb kflrpeq ssoti webxr embbjd kbnx ubzqco
khhc vwuqzb ebocbko rwmonkz edfqn hzh qhncoq gbwdi wjeg ocwow
ghzhd kcxblp lzwkkr gzhdh umk pblcxk
wyajtw jiff ouylv sni lwhlrg avqjiis igzx wbl lhrwgl
glhh kaxha tqii hwzx rgic kaxha rgyidmt qdgxfl ynjc oibfij
bapj bix rjniw ynbql idlvnmt wynpzbl zlpuoix kvn kakwys
aldpxxu iojxp rif xbyqtr jffdvy qnrq tqwsdiu
ulssco ktbymjw bfj zhkg zgc ctyri
ilrmq wfahcgk mrlqi bguad inj
cjzc rekuy ifr wfkg sple
cvjkp qbmumnp mprg ltmwxxh zpemtyb ozzssfd ksu mgrp
nvc sxp mpkxz bhlctq hguaa yrdkm iwsgfg qjssh gobbies hucdh
jdxrjw qmo qmo vobhnu
dnjib wtjp rfdjqdj skpvrb vkwevb kxxovp
fzi kicta zkuvr rfaawv ehklq cfdjsyb tukahwr zkuvr kicta ouq
aba ytdguk gqmpn hvxabff hvxabff dckj
fna wxyqhxd hvy khsu yypoyy lvvue medheua gim slf drdbeh ikihf
jquz wwo wwo ghlz jrbvb jrbvb
jwzvkl yjw ouwla yjw ouwla
zsvlgyf rzqbtj qygynem ukdgjm lbsyh tmdzp fbcaim eymzr
pvw sbs dvsa plmepl pwv ayxk vpw dwt
inayadn pnti yzhxk azga gxq aznbciu gjnmyqm
isgf ndqmk beyqq ebyqq srtzxo aiiw oqfuwp uoqwfp buejctv pxbk
pzl irv tzvzdb wcy eszm ybwiw ycw riizifd iybww
btpu cua azzqffy owcr
ofwq sqlpzat lozdxlc aevjmpc lcolzxd wbbysn qwfo vcrx gdzgi
dbpfmxu ydsxwl ijn svxtop csep ldqeog ffye zcrl soh aclw
wyiyyhv vyhiywy obgi hiyywvy
ddvaoc lhv spurn rgxyy onjw illvn yryxg xyyrg
vid wdttqq kajr myip
wolqlue phlunpt dcmmkfm sgxk dmmckmf sfng jlbsntq dxp
zmneyho fswj xdgsjc oefwjdi htgxvbd tgqrq xodoa
ynw bygqdnh hhmnkuw cojqrke qszzdjo orskwq mdfae asabn
vvpm vkj pcxghao caoxphg axhblxb vvmp
txox nzy eqn zgir dytsi girz ffa ugjjbzj brob fll
kbz pukqbd fiwmuh umwihf bkz dvz
vgs vejs vejs vejs mbkyjjy
viqmnmu bitkyw nddnk dknnd cldnpp hipub plcdpn fdzzpb mmyomn
ndylnfx gozlrx ngptk rnpteb wtacx xmtcjy xldha
fey doyxis ampmtr ycqh syw cqhlj hnngx
dijf nac tvkq ayo akbj lzmngdm wfxpn bpyvrf cvdqpa
zsofz lhho hgat wqskga mnt
mylwm zxsd omzpa waz hcrr lxmpq jsw sqtwak pzoma
rwhgsgt ysdq ztihici mpwcawv alkqg wsxiwx
snldn bcb anjdv cbb awsscc cqxult hjmjew mcycb fdpdg sesrh
kukrqm fawafz qdim wyobtqx bnvjnqg dcvqxta yptr nnpu ughldqp duo zafwaf
knb yjqb bscpnt nzg sqeu zkahna ttuf nsbtpc ixwit vucwj idix
bfqyx xlnpc ijrxu zkqi kjxtahr fgag orusms adi bfqyx bfqyx
dqddc ncbv bvfk hefikb dqddc hqjl otpx zfiu
ntkv qunrzx eztzure ctt rjo bkdt znvd jwdf gqhf mmhrzgt
zeavm hkbf rawqwuf pis dojlkt vnjhmi uvk cufmn qginezd xyut
hnidzk chlctc yst pepd dxntbxg vqk daxfpmu wshyddl
jgd vesqgo bdyqy igl ahstdm wjtd lrtkjsv tjsj sccxbih esn gkkzj
iisiswh jll rhlaf jqwwgfa wmhyo izva vrg zjkak nlxxfer rvhx
mkrkd jlqtpy ukstro ktuors wsj ynqpbp kpiyxzv nxeiwg xpzvkiy
jbr gnct fwklekg cmfqnm ctn gqobrs kwht
pztmjs yiffc kfhsblx yiffc yiffc
biezil iiezbl bzeiil smocoju
viiigm gmmmk yeiv dxzogro qsmzsur hukzwjn lcle syo mdj uruf rxfseu
extchsd adeff ouikoj fyaclr rwwvqsd dooe tcxheds zrdqqhm fdoxv kbxi tlcj
aycnydq qlxhka zoi shplo qll
bfry lbwckm ltq rbfy gpn vojp ruj dpxcve geq
svtvfwh lca lac qia vhwsftv nookdfz xgjiaf yvcdlt
aspgqym fryuzhx bbydf tbn bwutsc fqgi zij lmxhog qnmse
rbb gsys volnas onvlas lonasv vwjdso lnteapy
got iauk kficn jvfuy yvoe jcxwui hyamqx mke mwh jcxwui hyamqx
avutfi ggmha dkopc kothnnb syoi xsd wjedywy
oziejyz yzeijoz hnthyn knj juuq qujtp kgq bymlnlf yicf
zsejuy dybeap hvowmvn okxb yoi epadby cnzjk xfwprzc
lacg iiix fblhxvf nrkkol lnafzw qspzsn gvdy ipj zub uouseo
evukwkh ycjxxc lptwmf pmd izxdsos zrkavf pgjoy zwokg mpjiej
vqw ijwoy eaw wvq svmcq ccxi nyub ynlq eqornax uprt pygfe
plue okbbm btvm gba kutn jacjx ysqt lvx pcxxu qcf
pyw ffjfudq bvk hsdwdva fjnivhf odbmw krpgrj
hziesm bxa dceiwt tmvivjk snl fkh dahsxyx kqlhak lurtk
xss sswyxrg yqff dbkx kbxd mpzbmnl bzplnmm
uvz pjm ilrol pmj uzct ztcu brhkv
heiz jcn syjt zfvlvaq aflvqvz amcjh rxnitw
cxl nxvrn vjnz aewtr cxtko nnvcp ltptd adpxt zvjn fntklj
aymmm tuirj hzngq zhbh paqs kvpfo aqsp kmo acprw sabrso kdqmp
ndqjspv mmhp pndjsvq rti usm
ije oad mvelyg jadz ekm dao zdcmv
qwww tmwmdbb oxxfoza rgmf eonku brh gcgiuoi ojscn
fjedeek ohlax fiydku rbnxpg wfivg cdgs
axwbni hojye mwfe oyqknxp whdgfy ihku mbhr gagnz hehagxj
hibautd blnayq lnayqb gepml mgpel qunw
ircx oeb kujtip zbu ebo cmmn
upyqvot wbponp hnn vav avv tvrky omm
yzqsnf agbfsw dbxoya sfnqzy hqrxek qsnyzf oagyerm xxhukm
xzvk mvcwz oujr hell hoe xexa dqlpqt xdqz ucola hsvv tcmybhl
skldxr mzyol ybzyzd jnnxb rxncdy nkpwy fwlnsw omylz oiwieu fshv ngvha
jkwqf yxrox hejfoq orxyx
rijken xiwf mawqcfu erinjk jsi yyg mmu mdkfqb
ornjes krp eornjs enjros pyqp nnwwjl
wzd uqqo kyeli tikdle aykdjog uiz rbpnw mjxezf ihiz rlgyg
cjm ajqgvkz kfgyy dmczlc mjc kxcm zctyqgh ymsk jwhqfd czpqgan
vxkzvco owo qogj uyictoj kfr pyoo ejrru npluynx bvv jhhzu kuciwc
eqk pcsly kelu arzgoe trfo fotr cuaax
lagonw qvcssqz sdoklh uvovi sfrkmd hnvafj ltg wfjj
viwbkm hpwe kzzwrbr axjtlq mznin wwpjg unlwur
nuzorgo qfoz ydisca qxdfutv hzg
nqgge tobtt hjocx ntyqyi rxzkynw wrnxzyk ciscy trjt ottbt
yuii srawx gljxe eteogz kcu jlgxe tjik ktsnp agudqok jwol vfnyv
vgicg dhnrmxz sjhozy hlalx rutwq
nyoyoje kco hoyam hoyam tta iflud amh gdxcsj vqr fvsqcgv
xdmbtph ueen cskerl rxjvpdc
nricn addljzg obq rikez igq bxygkmv qmgojou uheubk qor
snzd ztusvr vrstzu mceddga hgu
vvrbfjg mcdhmsf ldtwl otuna gmjurrx jgrurxm rxmurjg yrioq
iotkvo sftfvn vvoit lllju xvlg rdsb ywmdf mzxigu kzq
sgqw gqsw lqfu wgqs xpiwou jurgucd azq wgaqpm
ijntzi chlnfj yjqatz hjflcn vys ofq oqf oadthe jrfw
mmc motjo vcwmod rpaszfk zgkkua bpja vjb htrk
bpfvvka kmger mnvvfl hakudy yfprdoo mvnlfv rgmek evnwg
mykpu juavkn cecdvi aszbi lxm hmps oaqoif
fshizd fsdzhi lvcq hhpb eavwno auqlwz rpv owcdojx amsmf qgnddd
pohmcn hlcxk qsesxh rncr
fgyrsis ldem avxmnh frpodq oefzn
plfpu qdyojz xdrzrjy kpv abkh fge bbnotvp liikmcu czvwl oyh
ovha muitw pzy edfjoo fhsxuh dliyruc dikcd cqem ywfy
exyry jtzqn tscr qbtxno cikk poqgr tnjzq eofe sxea anlikep kick
zcie purpw dmhhms bcdo prwup uprpw wfejgjd
kwtjc cmixp dodfwj hcgmmat pkeyspo ubnl ajxvj ffkh xvw
nvlgq oduus psufiqg lrwpn dleftn xtllqvf usgz
liarf sczsf sczsf wky qtzq qvve qvve
cit vtjsh jrhkyvi txj urmq hppx
rhblmxn rhblmxn lkgow dylurwc beyk gfcewxj ehpl disoe tjbjy lkgow
nbkrm jvk ffux ars agns bebic jzjfm kmnbr gptvtsa ufxf
hrlvup jaz tafyr qcgq wkd fiz bgsrx jmtcvo qkbvj
eontk djf tiafrng mtwat puainel nyjoh meynxbf eqdw
aspvmbx tgzuszm fpj xkl nzpr fjp vnomk byx sbtov tnu utn
ldyww gwmiddv hwyh gcgsdit gtgdisc suufl xsw dlwyw
sye dgbd wyf ixqzthx dgdb esy
nsdgera fqz xwbdgui ngdgbcd bcn qrdxml cwcmxws tncm mqsodj cqgk
estayas cocmbpv cdcf vygtswo aplwa estayas
ndc ndc wntr sfls sfls
gse svv esmi lcdii lnr kemrk gnk ildic blnqy wvn
mwlpm awkr sxsudub yauwww hnktbog fpnqc nmxoq yoparu tqjpkug nbipft
czwnkk hrodtmx yyzpil ooqjb cvxzfh
kwa wak gipak gsgrw
jyy fja jjk kuvoqdy urqx
doyu chgn gvtxi qjdigvy kxr dizwrjc sll zenl yyblj
epxeqih kfi hlog pakk kkiidrh hiufw wuhif baqzxzi bgcd phi jzjdxjp
hllhyad sodc nyrtfe kygof hyyqi txddqg wcwxvnt ewqmj wwv
vxymuoe caat diqwbo vfruxdf sqniefn hetcbl nvtttu ouesb
yvoez pvthzc tdowuci wjijicn fhpmq kfobag yctdwj
xaugkb rprkg tidpx pjk tpwwm pbcfhr wmwpt sfynrl iouaw zbnyu
auakc culuxg bffg rodyhea ixlmtfb jdurl szoa
xgona fjzho buh khbvti ddh mgj ptgaqps
dqldupd udpldqd poku gfgpcg zsvk grvk kntx jih uwvxdvq sivk
mwdnq wmqdn uzto mdqnw
alvfm qxqo thwru xqqo jilnsgs rnonk fwntuby ogbha
gvxlxyf cdpv khvpka kgt gshlaa tenb
mtgvvxh mrjrsd truk rrerzx tujweaz
ozepw gsqkr rtmmc cmrtm
spnthg xhlzuu xwcrxz aqqejhh bpzh
ectdftk rgp mkp vxp pevriz wkgfkaw vfygj peg gep wjn
bksbu ywsszf tsbrps vxicr hfustju ynnlbo
sio urbvf ujezjk vkyc ukjezj bvrfu qwwgqmw uqfekvx bzipxus qfumwh
druru kycweog ycmef rjyy fkgp
rmf ifbip rsztco coju wlr bfbmsug lwr bsufbgm nwmp
jjuxtyd yif rkldsvu binq spepa mfg aszm
ghilaau ncm sgbavz omzeotz azukf bgjw zqzo gjbw pld
gtog iqheik budeu guvljmi
qqlj jqql ttk xcxu
cfq cfq kpagib dxfxufw hhksbjh gpcp
xkeax acnia jjubfc mhot uxlhh gnkj pavta rciondm rkquh xudqian
wqhqzg psqh rnnc uujlgq
hpjpaoa maa rdndl xewqj nmagwx xewqj hxuyvou xziv rdndl fbxmbz hmfwghy
dtwnrca hbfcptw qrmvat sdatx les zwizogq
bodiwzg sgoas fsf wgkrn zgbdowi wfkz
ngcsg grtao wcfxpyl gngcs fxwycpl fkpt
txvngo vxngot tkoap zqjc qzcj oeruix myh ihgdfik qtt
rxeh fcbnoo rxeh lve wvoc pmnxej dlcbrh rztt noibg
zyvq lwxqu oyjv bvidmf wxuql
wzc zcw czw dnhkvrg nzslrf
cfgl uwhxu qnsfmt tgyabes mqnq nkitq hmcvxlt qqmn yzmb uomqp
lwziur hgmdmv zuvipkp vir apr gfaq zeo dunat mqgafzg
prq pqkr xlrw njf ncqni kgpoma cmtklv
jwfuc poz opz fuple
fgleub lcgnifu lkwo kftbc onvwvdx lukpod xgmh rnj
rwqvv ezjmoni llq ekd cdvv kzcci gzsj vuipv fnw
rtnua gbnzg kqtogns iozzwc kjpzz kiiurey yzlvzx cpy xrue
fexcjmw ebwssx ewbcgwd uwolou nfdhic vupiykn jss djoo xftbkgo
idf ipvmez qyevwd wfsjxja dif dig
szpbtsa bssaztp sptzasb qppgz odur cpmn wpmg
pxn zjmq rbnr azwstzm mln upaqyty nxp oge nlm
bfaryqv hag phtvh ypi
epeeog lip zqio wuehlnb bau sbd dsb
xbrrp sej agrqnpa aarpnqg bnwyi jbn
uqmsvd asmuyy czxviw pznnmvc
sddwmek wnaea iwphupk sabo
cingdks ksh mtyip zltgafm dflkcd wbdnqup uokm gmxpyd libz svv akce
qge ewv dkabkmb xcpi nrkmsu mkmb djvamg mhhrwjh
krjt etfhm bxzatw zdkvz ehov seyxbw mkiirs plzoplu sogmwb wodfcle
qwea adibdp emo homrd pjcrhlc eqaw kqsrp rphjlcc
gajzo nwjg qxjra jztcnir ijvjwez avxb afz zyywqz kcszgh elmlkfh
lbz ozia bctf bumoji anhil rta xvit
ejybire ypjl qevak fzalx mlh qxlei zib
xmzas kwojjz ntrnrw nbmxlv mdgxs xjhxg suo zdcrxl qkujisz pxmu
eezyd unrtm wyu vhufvto rpb isfcy ygh hgy
nszvbzv ebtt memrsva ebtt qwcaq bhbas pvzfbov ppjbdy nszvbzv jabvrp
rlo zbmi lugvu yeby
tfcd tvl faaq mnural nyarh xnxk ctdf bodz
vwdrhc gub bgu fpcovx rcvwhd jukwsue
aekrhi lpknnrh bett tkib ioqrap igwnst aekrhi lhha
acg mknhazp pcgjuk tajplv
masq fyjkn agq qhxbbl qga npzj fme xtihic rntisg iqv aqg
ipagh fjth mswztpi iexd cocojy vhqrla joe wrsrmw
njztu tsh auqrxca zpp
jctn webxi haq irrr qox irrr webxi
reaw axmnvd voakf lnz ftbxfh zjyxzl pryfjpv sistgb pov mshs
gsy ctsngl ptmnyx vpjx zpvtori pfu ioycdrq
aobdtlj osdnrth sgqe geqs qegs
oamrlxk ygbb rkamoxl nztl sarbmtj yqupjt plu sbtarmj vpa rxea
yvhgp yznko epwpza gqrsod rilukp cglhomj wnaplu ugvdko qdr
cggztg ajw gggzct ubmiefj kpa
rel lvasbh kobm mdnzla pwnyj ehep gzx nhjdnsg rxa
qaz gook rplqwh vsht
dhe aneq ivrn awekad ckcbt zsqca ehd rvni oulwfuu
oxgzzow wntz tkqaoi oxgzzow lwkdpgy lhd aekjasp tkqaoi dnhaw
alxghco cpanoa onjh hyeyebe whxn zfu zozbll gojn
zdqulsa dlqsazu zqudals sfedw
rydtrsv rrtvysd fvyza drdgh lsfzt blnxr cnxe tslzf iijyds ylcxn
cczea nxx kwol kopaza wuvr cyvoo whlicv
zbmrwdq tlzbevx jwzpsc uvkwpd bmss rbzblj
jogx jgi gji hypmtkg ijg oscjv
flkoqja kwmrqv wzehel fvmcfap mkwqvr ivwxg jqfwdvo hweezl
vgjg nzucho nuohcz ggvj tmxci
fqaqx zeybhtg bxeic lftuqp wzuerz sww qfltxk
keiy myrvp blkxcg lncqmsu diittlg fqrf digrel cpwrk ipan dkxb bymlzo
owm irygdz pyhj mow wmo
noul pbvvt zcv ueqyjl zhetlw lpjfhli
felvwb wdykz kyibdz haq qkouj vuav oztyqh
dyxo njcr hcuk ysrr pucw qbajztc
ooyaz pmt hqwu gjx tmp tpm pwz
lyhzajz dfot avyifo kdwka pwypcep kyyw tirlku zdpjmft
aexle hfxo dacwvcy xsiotyg cifq ibupshj aktt rzvf pgafj
pxubhw ibpm jxtxg iwnssf osbpj
exmtfyx blbfg emrunru zkuhoi lfzn zrj unmcece phuppi
icomb rmy mvsqqkh zwjubz lumq wekx
cmdgs gsr pfhqx pfhqx cmdgs pga
rpyf jejc adaiou dutv imbenyu dqw zhebjhu pryf vtxs yprf
cxj roprjn rqoh qacagru snxd
rczvi hfpl luc yowgj nvavlhw vjudkmv dwu teq
klwc cktzh ksnvswl nsgeu xyohp mhs fxnjhm fwrcg rdeadkx cim
ounvb vzqje ujctzzk iyy vxck ebtvbqr uswsmcr jveqz qejzv jmi pboq
lwffygh mqsh vnnj ufz qhms gqfuxo lurzmu
buf psdluck gapwoo wgll sbfavbc lljfvzx cdgo rpt sfvabcb
svefr kubbri fervs nboi zkvq
jwr vtc zkcpzb kczbzp cdned pzbzkc wigjuak fszgweu odflfek
vwdqm khnnj plokjg vnce venc vecn yzxtgb
tawl yrhoz tawl yrhoz
vvehsl kdhzgme rix rcs btm pxnlsps vlhesv sxpnslp yqjtool
eqpyw kpmkcyw wqhglxg ajfzo hbd qvmhy nhokah iisqvad kxuyd fxek
jsz txhwhah hxt djnvl srylveu pxp dzmmn epek tzs
joyzql jqczueb rtdyw fyc fjirfyn tjcalz joyzql fyc
pjrmiz xwnmwns kcqjuut zfgxhdr octwn kqppg zhfgxrd wmwnnxs
ema yqxqs aljjo ajloj wozb
urgmhiz epqj vhhaxdm ptlsvig qzbmm cumbho lkg gyzmg eaopyzf ncfy mqe
ijvwvo oszkees ugvyk hjdj ftip itfp
ylfw qutzdj mgqp cyjss yzsdqqi iykvs fyor sthyqp mrjtzee hgo zwqbtgk
bkfkns gco bykzc mje dwmkrwt ljegqor yxjxp oaleuu
xeltq ggyqis aud frtyxhx iwz wiz fwoxz fozxw
zdu nwduqsa nced iphaaxo
bqjj oah ezd brhgxrc pmkz kdog exw
ihatt hck iepn egemprp wrz wzcuo xjzeaa wku ivjvihh
cwkuof bmj qmxd qbtms zgdei bsqmt ssndhw eeenku lcsqy bvvodr
tek zsgytci vgoun kwwu
jcxvp ijxc buqgix uil zfoku
ggndshq bmjeo yqaxtik blspz yofh edaroy
ipvtxh ouye elln dllvx iqza nhwf zyfw pvlky
iydcx gvarm gvarm wegmiy
sfjd liiflle mulboe qywzs tzbns trojl pad mnfcrhb sltb
gthqj jvpsof jwlfyeg jwhlfj
qckv umzrge gnzc mnr xde
gvgxmhv txnait taxint ius iboqdj
vsfex kbpvsby qembkb efxvs vhflzvm eaazg dyg bbmekq
wxpfk xwfpk xwkpf cjsyi
knzg eefq feqe seppop ttxz qnqfn atgsy cch mkjlbwt uyhct
quzw jbiw miqehe qvf jyipqh kzcjxyh
teuvzf tdtwoi pcuafa cwgjk ccur lgmqv jpjdkk efrnw uloqn dpkjkj lwloeph
yaffjy xntstsv gygq sxttvsn tvnstxs
cvbmdf pfrfkna wupv van iocb hsiyke obspj ytyfkl hbsqtij hkcw
oeddmnu koso mdodeun ybe mhjbmwy ubejz soko yxvuv
nylhy ylnyh olb vcdik
gsp ilba llnu jjk urbvuma qzypf bkceotg ezxq hyvjngf
tfnegyq rue waeif tfnegyq mvqm
wvgnsk cpd oib wrdfaz kohwgkc kzzig hogkwck gkizz
fecuuyp yfq bvanvxb cjeqwf unw dccr qzh zqu voakj
utoazh bjuq kmhcre izmny mirorsy twnl jyoc
fnnpd dmr ccgu eqgewc zuqivf
kkxiba qdabuen oikaz dnuywmm
aogud adugo uzcglpj lucv dgoua mdsqa mvrg
lymhv sof hvyml mlvhy nit
chu bwxp xpbw ghaix seklnc ola zofnrwt uch
wtt abob vblijtd oabb qjws
uozrpw kgf gxidxm uehdr fta pqakkrq atf fat woaolk
gaee voshd ghlyy emvzlkg cmcgk tuwlsj jwtsul znrta mjieqph glker
qiugxas gkg cbzmoz kahs obzzcm
puz omcokz gjc heuqb
dgndhb wid wdi scwnrjf juaisgo eivaw hgdndb
mgcrd hnqg pkpeb vprxcp
atlcnzp fyp cpkivxi bzj ypf cqpt bysu
pnd jiitmzs csw mxnpck vxutdrs ivipzy cws xiegsy qut
txlk avcvbuu hnq yyriq ajyswd urgiwc
qgiqut gvblizs giqnfrk tty mvoj wpikl giqnfrk bkdpndu xztmxn hsmqxf
llthg zjslki wilj rcyfois bavz hrqxn
ytbw hlkl vip skycogy ejiirhx
ndmtg bthlbw lsoq cvlvo sqol sqlo bppl sdkbls dtpyzrq vgm
psm xpj xjp lqi spm gqirw aglpj
htg fcchvyt xffev szdu lieadft
nbjo qohgzu vofg vvild dbtyi pdolxn plnoao jxze xlpbxj brajzg
urpp jjv lihmvp ivkwdqr sesyp ypbry qok sesyp ivkwdqr was
yinepzv qvnzdtf apv ucxo bdioo juga hjfsyl hmowo avc
dmiv tplae iiuiaxx tpale pyzkc
giwhst mpexd byfyc swuzkc
yydkwp xuu vjya kav ujmcxy qrtp zvlk
lsvdyn tkw qxu omvlc wwmfvov mrgcoov dhpu tfair hupd zbx njzgwtw
zuz rsxc xsrc gdwwf nycsv zzu kcu
unlvzv jerqqgm nozma ykbflj qihqkx
pctffo begf ivrvy ezru mvqt waocq
tubtuk gxkc ikgw bjrird kxjebbh sbjyc yafkd khqajmt aclpmf gqfo yrpf
rdt vrxa fyudo myeosb ursflwk
wbjras edlbwdp ctobtw jbvtvcd xjgoo cmunxm mjtbpi klovx bypmsab unc
xckml uztr htublq vilabvr jdiwus qejxur evfw qqm
tzqq tzqq wkb wkb
dgmg ljzc dgmg mbmco cgze qsap jccvot uors iiq
rwvac woylk dmn teorprx nyuvz hcwwxlj lvej drbjo asjgq
ljen tpfl vixcivr guaf lnje waim jlen
djgaa janhi adudm yzv zkcb xqw fgvrz
kpkjoon ggzx skp rqcsw xgzg zgxg jtf ghc
rtnyxo qixfd nphekk mouzk gny fpzquw qgywx rpr gqydze
gawdlv vrivoof rte iyp gaih sfzplm
csojx wzojode uzy qulr lylmb guvtkwv
ovxj aamms ftxo ebckdqw wqvsdci jwfqxks jafrcrn yyomrot
qnu jqwr ywudxk qpsez rdc kiyfz iiecf dthxjjb bown
typ zxcvjo rip acjhl paaab qhqipg xkguye sbxy pomkvn
ofvaegv hgak oafevgv hkemar rqkha grklnsp msvkkku rekahm bxmjnw
ahoihju sdyn phi uhz lupbx
lavt jef klmq oqyfpf kis nazul ymezxek xpla fxyrfnt
nwnagwy hvpjqfg sgm ungfstr gso owqqxjh
hey hye ipyrt qxmthg jth wpbr hxgmtq cvfkfux qykdzhk movcfnl vxyoc
zsras abnrj fgaczuk ssazr xzf cnxu gns wnqqy dwjh szars
uhb zanlvh lvdotkb xekl kcofo
lhx iccy ibkjw ciykxaj imsx ehamqlz iwzapxc rhaltv
pofit owmpqej vwrobh jvox gdqehss yyxd styu tfkm fiotp
ecz mdpoqsv mdpoqsv yxx rexok hcfll yvury hdhcfu juhkvpt rspnfj hxvgdir
ohed mtigaoe eodh agmiteo
vjvv hfco cppbxtw hawsjxz ovlsq qgs risgwhg auhj
togivgg czrtvw ccz wzvtrc bse lsk
ndc ndc lrfi iyleol nchx jxpv xdcsfmp nnx wtvq pih tgc
hzpf sur zhfp klfmhx lbuidp xiqimnf
qddpdk trfxpip pnsowj hidgvnf prur rsrautp aamykfm fysqjmq xwzjane mbmtxhf oqctt
lfd eops govslp ultbye vrqai hcjkcf snpape
cbok koumkad otpozb pqcs emilpe wpcyvxd bock
spjb xkkak anuvk ejoklh nyerw bsjp zxuq vcwitnd xxtjmjg zfgq xkpf
juo pmiyoh xxk myphio ogfyf dovlmwm moevao qqxidn

45
csharp/BScottDay5.cs Normal file
View File

@ -0,0 +1,45 @@
using System;
using System.IO;
namespace AOC2017
{
class BScottDay5 : BScottSolution
{
public override string Name => "Day 5: A Maze of Twisty Trampolines, All Alike";
public override void Run()
{
string[] input = File.ReadAllLines("BScottDay5.txt");
Console.WriteLine($"Part 1 Answer: {RunCpuPart1(input)}");
Console.WriteLine($"Part 2 Answer: {RunCpuPart2(input)}");
}
static int RunCpuPart1(string[] input)
{
int[] instructions = Array.ConvertAll(input, s => int.Parse(s));
int count = 0, pc = 0;
do
{
count++;
pc = pc + instructions[pc]++;
} while (pc < instructions.Length);
return count;
}
static int RunCpuPart2(string[] input)
{
int[] instructions = Array.ConvertAll(input, s => int.Parse(s));
int count = 0, pc = 0;
do
{
count++;
pc = pc + (instructions[pc] >= 3 ? instructions[pc]-- : instructions[pc]++);
} while (pc < instructions.Length);
return count;
}
}
}

1056
csharp/BScottDay5.txt Normal file

File diff suppressed because it is too large Load Diff

70
csharp/BScottDay6.cs Normal file
View File

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace AOC2017
{
class BScottDay6 : BScottSolution
{
public override string Name => "Day 6: Memory Reallocation";
public override void Run()
{
string input = File.ReadAllText("BScottDay6.txt");
int[] banks = Array.ConvertAll(input.Split(new char[] { '\t' }), s => int.Parse(s));
RedistributeMemoryResult redistributeMemoryResult = RedistributeMemory(banks);
Console.WriteLine($"Part 1 Answer: {redistributeMemoryResult.ReallocCount}");
Console.WriteLine($"Part 2 Answer: {redistributeMemoryResult.RepeatLoopCount}");
}
static RedistributeMemoryResult RedistributeMemory(int[] banks)
{
bool done = false;
int index = Array.IndexOf(banks, banks.Max()); // find largest bank
int reallocBlocks = banks[index];
int reallocCount = 0, repeatLoopCount =0;
Dictionary<string, int> uniqueList = new Dictionary<string, int>();
banks[index] = 0;
do
{
for (int i = 0; i < reallocBlocks; i++)
{
index++;
banks[index % banks.Length]++;
}
string banksString = string.Join(",", banks);
if (uniqueList.ContainsKey(banksString))
{
repeatLoopCount = reallocCount - uniqueList[banksString];
done = true;
}
else
{
uniqueList.Add(banksString, reallocCount);
index = Array.IndexOf(banks, banks.Max()); // find largest bank
reallocBlocks = banks[index];
banks[index] = 0;
}
reallocCount++;
} while (!done);
return new RedistributeMemoryResult(reallocCount, repeatLoopCount);
}
class RedistributeMemoryResult
{
public int ReallocCount { get; private set; }
public int RepeatLoopCount { get; private set; }
public RedistributeMemoryResult(int reallocCount, int repeatLoopCount)
{
ReallocCount = reallocCount;
RepeatLoopCount = repeatLoopCount;
}
}
}
}

1
csharp/BScottDay6.txt Normal file
View File

@ -0,0 +1 @@
10 3 15 10 5 15 5 15 9 2 5 8 5 2 3 6

147
csharp/BScottDay7.cs Normal file
View File

@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
namespace AOC2017
{
class BScottDay7 : BScottSolution
{
public override string Name => "Day 7: Recursive Circus";
public override void Run()
{
// Sample Problem
string[] input = File.ReadAllLines("BScottDay7Sample.txt");
Node rootNode = ProcessList(input);
Console.WriteLine($"Part 1 Example Answer: {rootNode.Name}");
int weightDifference = FindWeightDifference(rootNode);
Node badProgram = FindBadProgram(rootNode);
Console.WriteLine("Part 2 Example Answer: " + (badProgram.Weight + weightDifference));
// Main problem
input = File.ReadAllLines("BScottDay7.txt");
rootNode = ProcessList(input);
Console.WriteLine($"Part 1 Answer: {rootNode.Name}");
// I have no idea if this convoluted solution will work for other inputs,
// but it's printing out the right answer and I am too tired and fed up with this
// problem to care if it's not perfect.
weightDifference = FindWeightDifference(rootNode);
badProgram = FindBadProgram(rootNode);
Console.WriteLine("Part 2 Answer: " + (badProgram.Weight + weightDifference));
}
static Node ProcessList(string[] input)
{
List<string> removalList = new List<string>();
Dictionary<string, Node> nodeList = new Dictionary<string, Node>();
Regex regex = new Regex(@"([a-z]+) \((\d+)\)(?: -> )?(?:([a-z]+)*(?:, )?)*");
for (int i = 0; i < input.Length; i++)
{
Match match = regex.Match(input[i]);
if (match.Success)
{
// create a new node
Node node = new Node(match.Groups[1].Value, int.Parse(match.Groups[2].Value));
// add any sub items
if (match.Groups[3].Captures.Count > 0)
{
foreach (Capture capture in match.Groups[3].Captures)
{
node.ChildNames.Add(capture.Value);
}
}
nodeList.Add(match.Groups[1].Value, node);
}
}
foreach (KeyValuePair<string, Node> kvpNode in nodeList)
{
if (kvpNode.Value.ChildNames.Count > 0)
{
foreach (string s in kvpNode.Value.ChildNames)
{
if (nodeList.ContainsKey(s))
{
kvpNode.Value.ChildNodes.Add(nodeList[s]);
removalList.Add(s); // a list of nodes to remove from dictionary
}
}
}
}
// Remove everything from root colllection that was a child node of something else.
// This should leave just 1 node remaining which is the root node.
foreach (string key in removalList)
nodeList.Remove(key);
return nodeList.First().Value; // hopefully this is the fully populated root node...
}
static int GetWeight(Node parentNode)
{
if (parentNode.ChildNodes.Count == 0)
return parentNode.Weight;
int weight = parentNode.Weight;
foreach (Node t in parentNode.ChildNodes)
weight += GetWeight(t);
return weight;
}
/// <summary>
/// Finds the weight difference of the inbalance
/// </summary>
/// <param name="rootNode">The root node of the entire stack</param>
/// <returns>The weight difference of the offending program.</returns>
static int FindWeightDifference(Node rootNode)
{
int[] weights = new int[rootNode.ChildNodes.Count];
for (int i = 0; i < rootNode.ChildNodes.Count; i++)
weights[i] = GetWeight(rootNode.ChildNodes[i]);
List<int> result = weights.GroupBy(i => i).OrderBy(g => g.Count()).Select(g => g.Key).ToList();
return result.Last() - result.First();
}
static Node FindBadProgram(Node parentNode)
{
// only find nodes that have at least 3 children to compare
if(parentNode.ChildNodes.Count >= 3) {
int[] weights = new int[parentNode.ChildNodes.Count];
// calulate the weights
for (int i = 0; i < parentNode.ChildNodes.Count; i++)
weights[i] = GetWeight(parentNode.ChildNodes[i]);
// find the least common weight
int result = weights.GroupBy(i => i).OrderBy(g => g.Count()).Select(g => g.Key).ToList().First();
Node nextNode = parentNode.ChildNodes[Array.IndexOf(weights, result)];
if (nextNode.ChildNodes.Count > 0)
{
// dig into the node with the uncommon weight
return FindBadProgram(parentNode.ChildNodes[Array.IndexOf(weights, result)]);
}
}
return parentNode;
}
class Node
{
public string Name { get; set; }
public int Weight { get; set; }
public List<Node> ChildNodes { get; set; }
public List<string> ChildNames { get; set; }
public Node(string name, int weight)
{
Name = name;
Weight = weight;
ChildNodes = new List<Node>();
ChildNames = new List<string>();
}
}
}
}

1039
csharp/BScottDay7.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,13 @@
pbga (66)
xhth (57)
ebii (61)
havc (66)
ktlj (57)
fwft (72) -> ktlj, cntj, xhth
qoyq (66)
padx (45) -> pbga, havc, qoyq
tknk (41) -> ugml, padx, fwft
jptl (61)
ugml (68) -> gyxo, ebii, jptl
gyxo (61)
cntj (57)

103
csharp/BScottDay8.cs Normal file
View File

@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace AOC2017
{
class BScottDay8 : BScottSolution
{
public override string Name => "Day 8: I Heard You Like Registers";
private const int ARG_REG = 0;
private const int ARG_OP = 1;
private const int ARG_VALUE = 2;
private const int ARG_KEYWORD = 3;
private const int ARG_COND_REG = 4;
private const int ARG_COND = 5;
private const int ARG_COND_VAL = 6;
public override void Run()
{
string[] example = new string[]
{
"b inc 5 if a > 1",
"a inc 1 if b < 5",
"c dec -10 if a >= 1",
"c inc -20 if c == 10"
};
Tuple<int, int> exampleResult = RunCpu(example);
Console.WriteLine($"Part 1 Example Answer: {exampleResult.Item1}");
Console.WriteLine($"Part 2 Example Answer: {exampleResult.Item2}");
string[] input = File.ReadAllLines("BScottDay8.txt");
Tuple<int, int> result = RunCpu(input);
Console.WriteLine($"Part 1 Answer: {result.Item1}");
Console.WriteLine($"Part 2 Answer: {result.Item2}");
}
static Tuple<int,int> RunCpu(string[] input)
{
int highestValue = 0;
Dictionary<string, int> r = new Dictionary<string, int>();
for (int i = 0; i < input.Length; i++)
{
string[] args = input[i].Split(' ');
// create any missing registers
if(!r.ContainsKey(args[ARG_REG]))
r.Add(args[ARG_REG], 0);
if (!r.ContainsKey(args[ARG_COND_REG]))
r.Add(args[ARG_COND_REG], 0);
// evaluate the condition
int x = r[args[ARG_COND_REG]];
int y = int.Parse(args[ARG_COND_VAL]);
bool cond = false;
switch (args[ARG_COND])
{
case ">":
cond = x > y;
break;
case ">=":
cond = x >= y;
break;
case "==":
cond = x == y;
break;
case "<=":
cond = x <= y;
break;
case "<":
cond = x < y;
break;
case "!=":
cond = x != y;
break;
}
// execute the operation if the condition is met
if (cond)
{
switch (args[ARG_OP])
{
case "inc":
r[args[ARG_REG]] += int.Parse(args[ARG_VALUE]);
break;
case "dec":
r[args[ARG_REG]] -= int.Parse(args[ARG_VALUE]);
break;
}
// keep track of the highest register
if (r[args[ARG_REG]] > highestValue)
highestValue = r[args[ARG_REG]];
}
}
return Tuple.Create(r.OrderByDescending(x => x.Value).First().Value, highestValue);
}
}
}

1000
csharp/BScottDay8.txt Normal file

File diff suppressed because it is too large Load Diff

65
csharp/BScottDay9.cs Normal file
View File

@ -0,0 +1,65 @@
using System;
using System.IO;
using System.Text;
namespace AOC2017
{
class BScottDay9 : BScottSolution
{
public override string Name => "Day 9: Stream Processing";
public override void Run()
{
string input = File.ReadAllText("BScottDay9.txt");
Tuple<int, int> processStreamResult = ProcessStream(input);
Console.WriteLine($"Part 1 Answer: {processStreamResult.Item1}");
Console.WriteLine($"Part 2 Answer: {processStreamResult.Item2}");
}
static Tuple<int, int> ProcessStream(string input)
{
int total = 0, nestingLevel = 0;
Tuple<int, string> filterGarbageResult = FilterGarbage(input);
int filteredCount = filterGarbageResult.Item1;
string filteredInput = filterGarbageResult.Item2;
for (int i = 0; i < filteredInput.Length; i++)
{
if (filteredInput[i] == '{')
nestingLevel++;
else if (filteredInput[i] == '}')
total += nestingLevel--;
}
return Tuple.Create(total, filteredCount);
}
static Tuple<int, string> FilterGarbage(string input)
{
bool inGarbage = false;
StringBuilder filteredInput = new StringBuilder(input.Length);
int filteredCount = 0;
// filter out garbage
for (int i = 0; i < input.Length; i++)
{
if (!inGarbage && input[i] == '<')
inGarbage = true;
else if (input[i] == '>')
inGarbage = false;
else if (input[i] == '!')
i++;
else
{
if (!inGarbage)
filteredInput.Append(input[i]);
else
filteredCount++;
}
}
return Tuple.Create(filteredCount, filteredInput.ToString());
}
}
}

1
csharp/BScottDay9.txt Normal file

File diff suppressed because one or more lines are too long

29
csharp/BScottProgram.cs Normal file
View File

@ -0,0 +1,29 @@
using System;
using System.Reflection;
namespace AOC2017
{
class BScottProgram
{
static void Main(string[] args)
{
// Find all classes inheriting from BScottSolution, create an instance, and execute Run method.
foreach (Type t in Assembly.GetAssembly(typeof(BScottSolution)).GetTypes())
{
if (t.IsSubclassOf(typeof(BScottSolution)))
{
BScottSolution solution = Activator.CreateInstance(t) as BScottSolution;
Console.WriteLine("-----------------------------------------------------------");
Console.WriteLine(solution.Name);
Console.WriteLine("-----------------------------------------------------------");
solution.Run();
Console.WriteLine();
}
}
Console.ReadLine();
}
}
}

15
csharp/BScottSolution.cs Normal file
View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AOC2017
{
abstract class BScottSolution
{
public abstract string Name { get; }
public abstract void Run();
}
}

65
python/BScottDay23.py Normal file
View File

@ -0,0 +1,65 @@
import math
class Coprocessor:
def __init__(self, instructions):
self.instructions = instructions
self.pc = 0
self.finished = False
self.registers = dict.fromkeys(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], 0)
def value(self, input_reg):
if input_reg.isalpha():
return self.registers[input_reg]
else:
return int(input_reg)
def is_prime(self, x):
prime = False
if x > 1:
prime = True
k = 2
n = math.sqrt(x)
while k <= n and prime == True:
if x % k == 0:
prime = False
k += 1
return prime
def part1(self):
mul_count = 0
while not self.finished:
args = self.instructions[self.pc].split(' ')
if args[0] == 'set':
self.registers[args[1]] = self.value(args[2])
elif args[0] == 'sub':
self.registers[args[1]] -= self.value(args[2])
elif args[0] == 'mul':
self.registers[args[1]] *= self.value(args[2])
mul_count += 1
elif args[0] == 'jnz':
if self.value(args[1]) != 0:
self.pc += self.value(args[2]) - 1
self.pc += 1
if self.pc >= len(self.instructions) or self.pc < 0:
self.finished = True
return mul_count
def part2(self):
primecount = 0
start = int(self.instructions[0].split(' ')[2]) * 100 + 100000
for i in range(start, start + 17000 + 1, 17):
if not self.is_prime(i):
primecount += 1
return primecount
with open("BScottDay23.txt") as f:
instructions = f.read().splitlines()
solution = Coprocessor(instructions)
print('Part 1 Answer: ' + str(solution.part1()))
print('Part 2 Answer: ' + str(solution.part2()))

32
python/BScottDay23.txt Normal file
View File

@ -0,0 +1,32 @@
set b 67
set c b
jnz a 2
jnz 1 5
mul b 100
sub b -100000
set c b
sub c -17000
set f 1
set d 2
set e 2
set g d
mul g e
sub g b
jnz g 2
set f 0
sub e -1
set g e
sub g b
jnz g -8
sub d -1
set g d
sub g b
jnz g -13
jnz f 2
sub h -1
set g b
sub g c
jnz g 2
jnz 1 3
sub b -17
jnz 1 -23