From dfddbea84b961505209eede0276f6e47c90c73c7 Mon Sep 17 00:00:00 2001 From: Brandon Scott Date: Mon, 26 Jun 2017 20:19:55 -0500 Subject: [PATCH] Initial commit. --- .gitignore | 883 ++++++++++++++++++++++++++++++++++++++++++++ LICENSE | 23 ++ README.md | 12 + csharp/bscott01.cs | 187 ++++++++++ csharp/bscott02.cs | 127 +++++++ csharp/bscott07.cs | 114 ++++++ csharp/bscott08.cs | 144 ++++++++ csharp/bscott09.cs | 141 +++++++ csharp/bscott10.cs | 219 +++++++++++ csharp/bscott12.cs | 111 ++++++ pascal/bscott06.pas | 117 ++++++ php/bscott03.php | 39 ++ php/bscott04.php | 81 ++++ php/bscott05.php | 54 +++ 14 files changed, 2252 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 csharp/bscott01.cs create mode 100644 csharp/bscott02.cs create mode 100644 csharp/bscott07.cs create mode 100644 csharp/bscott08.cs create mode 100644 csharp/bscott09.cs create mode 100644 csharp/bscott10.cs create mode 100644 csharp/bscott12.cs create mode 100644 pascal/bscott06.pas create mode 100644 php/bscott03.php create mode 100644 php/bscott04.php create mode 100644 php/bscott05.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c7ef96 --- /dev/null +++ b/.gitignore @@ -0,0 +1,883 @@ + +# 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 + +# 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 ### diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e24e3c6 --- /dev/null +++ b/LICENSE @@ -0,0 +1,23 @@ +Individual files may be licensed differently, as noted in those files. + +MIT License + +Copyright (c) 2016 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..53a24e7 --- /dev/null +++ b/README.md @@ -0,0 +1,12 @@ +# Advent of Code 2016 + +## About + +These are my solutions to the Advent of Code 2016. + +## 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. \ No newline at end of file diff --git a/csharp/bscott01.cs b/csharp/bscott01.cs new file mode 100644 index 0000000..0179ae4 --- /dev/null +++ b/csharp/bscott01.cs @@ -0,0 +1,187 @@ +/* + * Advent of Code 2016 + * Day 1 (part 1) + */ +using System; +using System.Collections.Generic; + +namespace adventofcode +{ + enum Direction + { + North, + East, + South, + West + } + enum Side + { + Left = 'L', + Right = 'R' + } + class Instruction + { + public Side Side { get; set; } + public int StepCount { get; set; } + public Instruction(Side side, int stepCount) + { + this.Side = side; + this.StepCount = stepCount; + } + } + class Point + { + public int X { get; set; } + public int Y { get; set; } + public Point(int x, int y) + { + this.X = x; + this.Y = y; + } + } + class bscott01 + { + List instructions = new List(); + + public void ClearInstructions() + { + instructions.Clear(); + } + public bool LoadInstructions(string input) + { + if (input.Length == 0) + return false; + + foreach (string s in input.Split(new char[] { ',' })) + { + string instruction = s.Trim().ToUpper(); + + // Not a valid instruction length + if (instruction.Length < 2) + continue; + + // Not a valid side + if (instruction[0] != 'L' && instruction[0] != 'R') + continue; + + Side side = (Side)instruction[0]; + + int stepCount = 0; + if(!int.TryParse(instruction.Substring(1), out stepCount)) + continue; + + instructions.Add(new Instruction(side, stepCount)); + } + + return instructions.Count > 0; + } + + public int GetDistanceA() + { + int currentX = 0, currentY = 0; + Direction currentDirection = Direction.North; + + foreach (Instruction instruction in instructions) + { + if (instruction.Side == Side.Left) + currentDirection = (int)currentDirection - 1 < 0 ? Direction.West : currentDirection - 1; + else + currentDirection = (int)currentDirection + 1 > 3 ? Direction.North : currentDirection + 1; + + switch(currentDirection) + { + case Direction.North: + currentY += instruction.StepCount; + break; + case Direction.East: + currentX += instruction.StepCount; + break; + case Direction.South: + currentY -= instruction.StepCount; + break; + case Direction.West: + currentX -= instruction.StepCount; + break; + } + } + + return Math.Abs(currentX) + Math.Abs(currentY); + } + public int GetDistanceB() + { + int currentX = 0, currentY = 0; + Direction currentDirection = Direction.North; + List history = new List(); + + foreach (Instruction instruction in instructions) + { + if (instruction.Side == Side.Left) + currentDirection = (int)currentDirection - 1 < 0 ? Direction.West : currentDirection - 1; + else + currentDirection = (int)currentDirection + 1 > 3 ? Direction.North : currentDirection + 1; + + for (int i = 0; i < instruction.StepCount; i++) + { + switch (currentDirection) + { + case Direction.North: + currentY += 1; + break; + case Direction.East: + currentX += 1; + break; + case Direction.South: + currentY -= 1; + break; + case Direction.West: + currentX -= 1; + break; + } + + Point point = new Point(currentX, currentY); + if (history.Find(value => value.X == currentX && value.Y == currentY) != null) + return Math.Abs(currentX) + Math.Abs(currentY); + history.Add(point); + } + } + + return 0; + } + } + + class Program + { + static void Main(string[] args) + { + bscott01 test = new bscott01(); + + // PART 1 + test.ClearInstructions(); + test.LoadInstructions("R2, L3"); + Console.WriteLine("Distance: {0}", test.GetDistanceA()); + + test.ClearInstructions(); + test.LoadInstructions("R2, R2, R2"); + Console.WriteLine("Distance: {0}", test.GetDistanceA()); + + test.ClearInstructions(); + test.LoadInstructions("R5, L5, R5, R3"); + Console.WriteLine("Distance: {0}", test.GetDistanceA()); + + test.ClearInstructions(); + test.LoadInstructions("R3, L2, L2, R4, L1, R2, R3, R4, L2, R4, L2, L5, L1, R5, R2, R2, L1, R4, R1, L5, L3, R4, R3, R1, L1, L5, L4, L2, R5, L3, L4, R3, R1, L3, R1, L3, R3, L4, R2, R5, L190, R2, L3, R47, R4, L3, R78, L1, R3, R190, R4, L3, R4, R2, R5, R3, R4, R3, L1, L4, R3, L4, R1, L4, L5, R3, L3, L4, R1, R2, L4, L3, R3, R3, L2, L5, R1, L4, L1, R5, L5, R1, R5, L4, R2, L2, R1, L5, L4, R4, R4, R3, R2, R3, L1, R4, R5, L2, L5, L4, L1, R4, L4, R4, L4, R1, R5, L1, R1, L5, R5, R1, R1, L3, L1, R4, L1, L4, L4, L3, R1, R4, R1, R1, R2, L5, L2, R4, L1, R3, L5, L2, R5, L4, R5, L5, R3, R4, L3, L3, L2, R2, L5, L5, R3, R4, R3, R4, R3, R1"); + Console.WriteLine("Distance: {0}", test.GetDistanceA()); + + // PART 2 + test.ClearInstructions(); + test.LoadInstructions("R8, R4, R4, R8"); + Console.WriteLine("Distance: {0}", test.GetDistanceB()); + + test.ClearInstructions(); + test.LoadInstructions("R3, L2, L2, R4, L1, R2, R3, R4, L2, R4, L2, L5, L1, R5, R2, R2, L1, R4, R1, L5, L3, R4, R3, R1, L1, L5, L4, L2, R5, L3, L4, R3, R1, L3, R1, L3, R3, L4, R2, R5, L190, R2, L3, R47, R4, L3, R78, L1, R3, R190, R4, L3, R4, R2, R5, R3, R4, R3, L1, L4, R3, L4, R1, L4, L5, R3, L3, L4, R1, R2, L4, L3, R3, R3, L2, L5, R1, L4, L1, R5, L5, R1, R5, L4, R2, L2, R1, L5, L4, R4, R4, R3, R2, R3, L1, R4, R5, L2, L5, L4, L1, R4, L4, R4, L4, R1, R5, L1, R1, L5, R5, R1, R1, L3, L1, R4, L1, L4, L4, L3, R1, R4, R1, R1, R2, L5, L2, R4, L1, R3, L5, L2, R5, L4, R5, L5, R3, R4, L3, L3, L2, R2, L5, L5, R3, R4, R3, R4, R3, R1"); + Console.WriteLine("Distance: {0}", test.GetDistanceB()); + + Console.ReadLine(); + } + } +} diff --git a/csharp/bscott02.cs b/csharp/bscott02.cs new file mode 100644 index 0000000..08a35e2 --- /dev/null +++ b/csharp/bscott02.cs @@ -0,0 +1,127 @@ +/* + * Advent of Code 2016 + * Day 2 (part 1 and 2) + */ +using System; +using System.Text; + +namespace adventofcode +{ + enum KeypadType + { + Exercise01, + Exercise02 + } + + class bscott02 + { + private int x = 1, y = 1; + protected void ResetA() + { + this.x = 1; + this.y = 1; + } + + protected void ResetB() + { + this.x = 0; + this.y = 2; + } + + public string GetCode(string[] input, KeypadType keypadType) + { + StringBuilder outputBuffer = new StringBuilder(); + + if (keypadType == KeypadType.Exercise01) + ResetA(); + else + ResetB(); + + for (int i = 0; i < input.Length; i++) + { + if (keypadType == KeypadType.Exercise01) + outputBuffer.Append(GetDigitA(input[i])); + else + outputBuffer.Append(GetDigitB(input[i])); + } + + return outputBuffer.ToString(); + } + + protected string GetDigitA(string input) + { + for (int i = 0; i < input.Length; i++) + { + switch(input[i]) + { + case 'U': + if (y - 1 > -1) y--; + break; + case 'D': + if (y + 1 < 3) y++; + break; + case 'L': + if (x - 1 > -1) x--; + break; + case 'R': + if (x + 1 < 3) x++; + break; + } + } + return (((y * 3) + x) + 1).ToString(); + } + + protected string GetDigitB(string input) + { + int[][] map = new int[][] + { + new int[] { 0, 0, 1, 0, 0 }, + new int[] { 0, 2, 3, 4, 0 }, + new int[] { 5, 6, 7, 8, 9 }, + new int[] { 0, 10, 11, 12, 0 }, + new int[] { 0, 0, 13, 0, 0 } + }; + + for (int i = 0; i < input.Length; i++) + { + switch (input[i]) + { + case 'U': + if (y - 1 > -1 && map[y - 1][x] != 0) y--; + break; + case 'D': + if (y + 1 < 5 && map[y + 1][x] != 0) y++; + break; + case 'L': + if (x - 1 > -1 && map[y][x - 1] != 0) x--; + break; + case 'R': + if (x + 1 < 5 && map[y][x + 1] != 0) x++; + break; + } + } + return String.Format("{0:X}", map[y][x]); + } + } + + class Program + { + static void Main(string[] args) + { + bscott02 exercise2 = new bscott02(); + + string[] data = new string[] + { + "UUURRRRULRDLRDRRDURDDDLLDLLLULDUDDLDLULUURULRLDLRRLLLRRDRRLDDLLULUDUDDLRDRDUURDLURUURLRULLDDURULRRURDUURLULUUUURDDDDUUDLULRULLLRLLRRRURDLLRLLRRRUURULRDRUUDDDDDLLLRURRURRUURDUURDDRDLULRRLLLDRRRLURRLLURLDRRDDLDLRRLLRDRLLLLDLULDLRRDRRLDDURLULLUDLUDRRDRRLRLULURDRLRLUUUDLRLDLLLURDUDULULDDRUUURLLLDLLDDUDDRURURUDDLUULRDRRRRLDRDDURLUDURDULLDLUDLULDRLRLLRLLLLRURDURLLDRRDRLRUUUUULLLRUDURUDLLLUDLLLLRDLDRDUDRURLUDDUDDURLUUUUDDLLUDLULLLLLDUDLLRLRRDDDULULRLDRLLULDLUDLLURULRDDUURULRDLDLDLRL", + "URUUURDULUDLUUUUDDRRRDRRRLDUDLRDRRDRDDLRUULDLLDUDULLLRLDRDRRLDLDLUUDRUULDUDULDUDURURDDURULDLURULRLULDUDDUULDLLLDDURDDRDDURUULUUDRLDDULDRRRRDURRUDLLLURDDDLRULLRDDRDDDDLUUDRDUULRRRRURULDDDLDDRDRRUDRRURUDRDDLDRRRLLURURUULUUDRDULLDRLRDRRDDURDUDLDRLUDRURDURURULDUUURDUULRRRRRUDLLULDDDRLULDDULUDRRRDDRUDRRDLDLRUULLLLRRDRRLUDRUULRDUDRDRRRDDRLLRUUDRLLLUDUDLULUUDULDRRRRDDRURULDULLURDLLLDUUDLLUDRLDURRRLDDDURUDUDURRULDD", + "LRUDDULLLULRLUDUDUDRLLUUUULLUDLUUUUDULLUURDLLRDUDLRUDRUDDURURRURUDLLLRLDLUDRRRRRRDLUURLRDDDULRRUDRULRDRDDUULRDDLDULDRRRDDLURRURLLLRURDULLRUUUDDUDUURLRLDDUURLRDRRLURLDRLLUUURDRUUDUUUDRLURUUUDLDRRLRLLRRUURULLLRLLDLLLDULDDLDULDLDDRUDURDDURDUDURDLLLRRDDLULLLUDURLUDDLDLUUDRDRUDUUDLLDDLLLLDRDULRDLDULLRUDDUULDUDLDDDRUURLDRRLURRDDRUUDRUDLLDLULLULUDUDURDDRLRDLRLDRLDDRULLLRUDULDRLRLRULLRLLRRRLLRRRDDRULRUURRLLLRULDLUDRRDDLLLUDDUDDDLURLUDRDLURUUDLLDLULURRLLDURUDDDDRLULRDDLRLDDLRLLDDRRLRDUDUUULRRLRULUDURDUDRLRLRUDUDLLRRRRLRRUDUL", + "RULLLLUUUDLLDLLRULLRURRULDDRDLUULDRLLRUDLLRRLRDURLLDUUUUURUUURDLUURRLDDDLRRRRLRULDUDDLURDRRUUDLRRRDLDDUDUDDRUDURURLDULLDLULDLLUDLULRDRLLURRLLDURLDLRDLULUDDULDLDDDDDUURRDRURLDLDULLURDLLDDLLUDLDLDRLRLDLRDRLDLRRUUDRURLUUUDLURUULDUDRDULLDURUDLUUURRRLLDUDUDDUUULLLRUULDLURUDDRLUDRDDLDLLUDUDRRRDDUUULUULLLRLLUURDUUDRUUULULLDLDRUUDURLLUULRLDLUURLLUUDRURDDRLURULDUDUUDRRUUURDULRLDUUDDRURURDRRULDDDRLUDLLUUDURRRLDLRLRDRURLURLLLRLDDLRRLDLDDURDUUDRDRRLDRLULDRLURUUUDDRLLLDDLDURLLLLDRDLDRRUDULURRLULRDRLLUULLRLRDRLLULUURRUDRUDDDLLDURURLURRRDLLDRDLUDRULULULRLDLRRRUUDLULDURLRDRLULRUUURRDDLRUURUDRURUDURURDD", + "DURRDLLLDDLLDLLRLULULLRDLDRRDDRDLRULURRDUUDDRLLDDLDRRLRDUDRULDLRURDUUDRDDLLDRRDRUDUDULLDDDDLDRRRLRLRDRDLURRDDLDDDUUDRDRLLLDLUDDDLUULRDRLLLRLLUULUDDDRLDUUUURULRDDURRDRLUURLUDRLRLLLDDLRDDUULRRRRURDLDDDRLDLDRRLLDRDDUDDUURDLDUUDRDLDLDDULULUDDLRDDRLRLDDLUDLLDRLUDUDDRULLRLDLLRULRUURDDRDRDRURDRRLRDLLUDDRRDRRLDDULLLDLUDRRUDLDULDRURRDURLURRLDLRDLRUDLULUDDRULRLLDUURULURULURRLURRUULRULRRRLRDLULRLRLUDURDDRUUURDRLLRRRDDLDRRRULLDLRDRULDRRLRRDLUDDRDDDUUURRLULLDRRUULULLRRRRLDDRDDLUURLLUDLLDUDLULUULUDLLUUURRRUDDDRLLLRDRUUDUUURDRULURRLRDLLUURLRDURULDRRUDURRDDLDRLDRUUDRLLUDLRRU" + }; + + Console.WriteLine("Exercise 02 - Part 1: {0}", exercise2.GetCode(data, KeypadType.Exercise01)); + Console.WriteLine("Exercise 02 - Part 2: {0}", exercise2.GetCode(data, KeypadType.Exercise02)); + Console.ReadLine(); + } + } +} diff --git a/csharp/bscott07.cs b/csharp/bscott07.cs new file mode 100644 index 0000000..4dd8f52 --- /dev/null +++ b/csharp/bscott07.cs @@ -0,0 +1,114 @@ +/* + * Advent of Code 2016 + * Day 7 (Part 1 and 2) + */ + +using System; +using System.Collections.Generic; +using System.IO; + +namespace adventofcode +{ + class bscott07 + { + public static int GetTLSIPCount(string[] input) + { + int ipCount = 0; + + for (int i = 0; i < input.Length; i++) + { + bool insideBracket = false; + bool hasMirrorSequence = false; + + for (int j = 0; j < input[i].Length - 3; j++) + { + if (input[i][j] == '[') + { + insideBracket = true; + continue; + + } + else if (input[i][j] == ']') + { + insideBracket = false; + continue; + } + + if ((input[i][j] == input[i][j + 3] && input[i][j + 1] == input[i][j + 2]) + && (input[i][j] != input[i][j + 1] && input[i][j + 2] != input[i][j + 3])) + if (insideBracket) + break; + else + hasMirrorSequence = true; + + } + + if (!insideBracket && hasMirrorSequence) + ipCount++; + } + + return ipCount; + } + + public static int GetSSLIPCount(string[] input) + { + int ipCount = 0; + for (int i = 0; i < input.Length; i++) + { + bool insideBracket = false; + List babSequences = new List(); + List abaSequences = new List(); + for (int j = 0; j < input[i].Length - 2; j++) + { + if (input[i][j] == '[') + { + insideBracket = true; + continue; + + } + else if (input[i][j] == ']') + { + insideBracket = false; + continue; + } + + if (insideBracket) + { + if (input[i][j] == input[i][j + 2] && input[i][j] != input[i][j + 1]) + babSequences.Add(input[i].Substring(j + 1, 1) + input[i].Substring(j, 1) + input[i].Substring(j + 1, 1)); // pre flip it + } + else + { + if (input[i][j] == input[i][j + 2] && input[i][j] != input[i][j + 1]) + abaSequences.Add(input[i].Substring(j, 3)); + } + } + if (babSequences.Count > 0 && abaSequences.Count > 0) + { + for (int j = 0; j < abaSequences.Count; j++) + { + if (babSequences.Contains(abaSequences[j])) + { + ipCount++; + break; + } + } + } + } + return ipCount; + } + } + + class Program + { + static void Main(string[] args) + { + string[] input = File.ReadAllLines("input_day07.txt"); + + Console.WriteLine("Part 1 - TLS IP Count: {0}", bscott07.GetTLSIPCount(input)); + Console.WriteLine("Part 2 - SSL IP Count: {0}", bscott07.GetSSLIPCount(input)); + + Console.ReadLine(); + } + } +} diff --git a/csharp/bscott08.cs b/csharp/bscott08.cs new file mode 100644 index 0000000..661f928 --- /dev/null +++ b/csharp/bscott08.cs @@ -0,0 +1,144 @@ +/* + * Advent of Code 2016 + * Day 8 (part 1 and 2) + */ +using System; +using System.IO; + +namespace adventofcode +{ + class bscott08 + { + private int _width, _height; + private byte[] _screenData; + + public bscott08(int width, int height) + { + _width = width; + _height = height; + _screenData = new byte[width * height]; + Clear(); + } + + public void Clear() + { + // clear the screen + for (int i = 0; i < _screenData.Length; i++) + _screenData[i] = (byte)'.'; + } + + public void ProcessInstruction(string instruction) + { + string[] args = instruction.Split(new char[] { ' ' }); + int width = 0, height = 0, x = 0, y = 0, count = 0; + switch (args[0]) + { + case "rect": + string[] dimensions = args[1].Split(new char[] { 'x' }); + int.TryParse(dimensions[0], out width); + int.TryParse(dimensions[1], out height); + Rect(width, height); + break; + + case "rotate": + if (args[1] == "column") + { + int.TryParse(args[2].Substring(2), out x); + int.TryParse(args[4], out count); + RotateColumn(x, count); + } + else + { + int.TryParse(args[2].Substring(2), out y); + int.TryParse(args[4], out count); + RotateRow(y, count); + } + break; + } + } + + private byte GetPixel(int y, int x) + { + return _screenData[(y * _width) + x]; + } + + private void SetPixel(int y, int x, byte value) + { + _screenData[(y * _width) + x] = value; + } + + private void Rect(int width, int height) + { + for (int y = 0; y < height; y++) + for (int x = 0; x < width; x++) + SetPixel(y, x, (byte)'#'); + } + + private void RotateColumn(int x, int count) + { + byte[] tempColumn = new byte[_height]; + // minipulate temp column + for (int y = 0; y < _height; y++) + tempColumn[(y + count) % _height] = GetPixel(y, x); + + for (int y = 0; y < _height; y++) + SetPixel(y, x, tempColumn[y]); + } + + private void RotateRow(int y, int count) + { + byte[] tempRow = new byte[_width]; + + // minipulate temp row + for (int x = 0; x < _width; x++) + tempRow[(x + count) % _width] = GetPixel(y, x); + + for (int x = 0; x < _width; x++) + SetPixel(y, x, tempRow[x]); + } + + public int GetLitPixels() + { + int result = 0; + for (int i = 0; i < _screenData.Length; i++) + if (_screenData[i] != (byte)'.') + result++; + return result; + } + + public void DumpScreen() + { + for (int y = 0; y < _height; y++) + { + for (int x = 0; x < _width; x++) + { + Console.Write((char)GetPixel(y, x)); + } + Console.Write("\n"); + } + Console.Write("\n"); + } + } + + class Program + { + static void Main(string[] args) + { + bscott08 day08 = new bscott08(50, 6); + + string[] input = File.ReadAllLines("input_day08.txt"); + + for (int i = 0; i < input.Length; i++) + day08.ProcessInstruction(input[i]); + + // Part 1 ( don't skim over the instructions >_< ) + Console.WriteLine("Pixels Lit: {0}\n", day08.GetLitPixels()); + + // Part 2 + Console.WriteLine("Screen Dump: "); + day08.DumpScreen(); + + Console.ReadLine(); + } + } +} diff --git a/csharp/bscott09.cs b/csharp/bscott09.cs new file mode 100644 index 0000000..6ee6312 --- /dev/null +++ b/csharp/bscott09.cs @@ -0,0 +1,141 @@ +/* + * Advent of Code 2016 + * Day 9 (part 1 and 2) + */ + +using System; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; + +namespace adventofcode +{ + class bscott09 + { + public static long CalcDecompressedLength(string input, bool recursive = false, int level = 0) + { + long decompressedLength = 0; + MatchCollection matchCollection = Regex.Matches(input, @"\((\d+)x(\d+)\)"); + int lastMatchIndex = 0, nextCmdPosition = 0; + int length = 0, repeatCount = 0; + + // nothing to process + if (matchCollection.Count == 0 || level > 25) + return input.Length; + + // pre-inline data + if (matchCollection[0].Index > 0) + { + nextCmdPosition = matchCollection[0].Index; + decompressedLength += matchCollection[0].Index; + } + + // cycle through detected commands, ignore non-commands, include inline data + foreach (Match m in matchCollection) + { + int.TryParse(m.Groups[1].Value, out length); + int.TryParse(m.Groups[2].Value, out repeatCount); + + if (m.Index >= nextCmdPosition) + { + // inline data + if (m.Index > nextCmdPosition) + decompressedLength += (m.Index - nextCmdPosition); + + string payload = input.Substring(m.Index + m.Length, length); + long payloadLength = recursive ? CalcDecompressedLength(payload, true, level++) : payload.Length; + + decompressedLength += (payloadLength * repeatCount); + lastMatchIndex = m.Index; + nextCmdPosition = (m.Index + m.Length) + length; + } + } + + // trailing inline data + if (lastMatchIndex != nextCmdPosition) + decompressedLength += (input.Length - nextCmdPosition); + + return decompressedLength; + } + + public static string Decompress(string input, bool recursiveDecompress = false, int level = 0, int maxLevel = 25) + { + StringBuilder output = new StringBuilder(); + MatchCollection matchCollection = Regex.Matches(input, @"\((\d+)x(\d+)\)"); + int lastMatchIndex = 0, nextCmdPosition = 0; + int length = 0, repeatCount = 0; + + // nothing to process or the recursion level is too high + if (matchCollection.Count == 0 || level > maxLevel) + return input; + + // pre-inline data + if (matchCollection[0].Index > 0) + { + nextCmdPosition = matchCollection[0].Index; + output.Append(input.Substring(0, matchCollection[0].Index)); + } + + // cycle through detected commands, ignore non-commands, include inline data + foreach (Match m in matchCollection) + { + int.TryParse(m.Groups[1].Value, out length); + int.TryParse(m.Groups[2].Value, out repeatCount); + + if (m.Index >= nextCmdPosition) + { + // inline data + if (m.Index > nextCmdPosition) + output.Append(input.Substring(nextCmdPosition, m.Index - nextCmdPosition)); + + string payload = input.Substring(m.Index + m.Length, length); + if (recursiveDecompress) + payload = Decompress(payload, true, level++); + + for (int i = 0; i < repeatCount; i++) + output.Append(payload); + + lastMatchIndex = m.Index; + nextCmdPosition = (m.Index + m.Length) + length; + } + } + + // trailing inline data + if (lastMatchIndex != nextCmdPosition) + { + output.Append(input.Substring(nextCmdPosition, input.Length - nextCmdPosition)); + } + + return output.ToString(); + } + } + + class Program + { + static void Main(string[] args) + { + Console.WriteLine("Part 1 Example Length: {0}", bscott09.CalcDecompressedLength("ADVENT")); + Console.WriteLine("Part 1 Example Length: {0}", bscott09.CalcDecompressedLength("A(1x5)BC")); + Console.WriteLine("Part 1 Example Length: {0}", bscott09.CalcDecompressedLength("(3x3)XYZ")); + Console.WriteLine("Part 1 Example Length: {0}", bscott09.CalcDecompressedLength("A(2x2)BCD(2x2)EFG")); + Console.WriteLine("Part 1 Example Length: {0}", bscott09.CalcDecompressedLength("(6x1)(1x3)A")); + Console.WriteLine("Part 1 Example Length: {0}", bscott09.CalcDecompressedLength("X(8x2)(3x3)ABCY")); + + Console.WriteLine("Part 1 Example: {0}", bscott09.Decompress("ADVENT")); + Console.WriteLine("Part 1 Example: {0}", bscott09.Decompress("A(1x5)BC")); + Console.WriteLine("Part 1 Example: {0}", bscott09.Decompress("(3x3)XYZ")); + Console.WriteLine("Part 1 Example: {0}", bscott09.Decompress("A(2x2)BCD(2x2)EFG")); + Console.WriteLine("Part 1 Example: {0}", bscott09.Decompress("(6x1)(1x3)A")); + Console.WriteLine("Part 1 Example: {0}", bscott09.Decompress("X(8x2)(3x3)ABCY")); + + // Part 2 + string input = File.ReadAllText("input_day09.txt").Trim(); + Console.WriteLine("Part 1 Length: {0}\n", bscott09.CalcDecompressedLength(input)); + Console.WriteLine("Part 2 Example Length: {0}", bscott09.CalcDecompressedLength("(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN", true)); + + Console.WriteLine("Part 2 Length: {0}\n", bscott09.CalcDecompressedLength(input, true)); + + Console.ReadLine(); + } + } +} diff --git a/csharp/bscott10.cs b/csharp/bscott10.cs new file mode 100644 index 0000000..8aace1a --- /dev/null +++ b/csharp/bscott10.cs @@ -0,0 +1,219 @@ +/* + * Advent of Code 2016 + * Day 10 (part 1 and 2) + */ + +using System; +using System.Collections.Generic; +using System.IO; + +namespace adventofcode +{ + class Bot + { + public int Index { get; } + public int[] Values { get; set; } + public string LowDestination { get; set; } + public int LowDestinationId { get; set; } + public string HighDestination { get; set; } + public int HighDestinationId { get; set; } + public Bot(int index) + { + Index = index; + Values = new int[2] { -1, -1 }; + LowDestination = ""; + LowDestinationId = -1; + HighDestination = ""; + HighDestinationId = -1; + } + + public bool SetValue(int value) + { + if (this.Values[0] == -1) + this.Values[0] = value; + else if (this.Values[1] == -1) + this.Values[1] = value; + else + return false; // both values already set? + + return true; + } + public bool HasBothValues() + { + return this.Values[0] > -1 && this.Values[1] > -1; + } + + public int GetAndClearLowValue() + { + int lowValueIndex = this.Values[0] > this.Values[1] ? 1 : 0; + int lowValue = this.Values[lowValueIndex]; + this.Values[lowValueIndex] = -1; + return lowValue; + } + + public int GetAndClearHighValue() + { + int highValueIndex = this.Values[0] < this.Values[1] ? 1 : 0; + int highValue = this.Values[highValueIndex]; + this.Values[highValueIndex] = -1; + return highValue; + } + + public override string ToString() + { + return String.Format("Bot HasBothValues={0}, LowDestination={1}, LowDestinationId={2}, HighDestination={3}, HighDestinationId={4}", + this.HasBothValues(), this.LowDestination, this.LowDestinationId, this.HighDestination, this.HighDestinationId); + } + } + + class ComparisonLogEntry + { + public int Index { get; set; } + public int ValueA { get; set; } + public int ValueB { get; set; } + + public ComparisonLogEntry(int index, int valueA, int valueB) + { + this.Index = index; + this.ValueA = valueA; + this.ValueB = valueB; + } + } + + class bscott10 + { + private Dictionary bots = new Dictionary(); + private Dictionary outputs = new Dictionary(); + private List comparisonLog = new List(); + + public bscott10() + { + // precreate all the bots and outputs (pointless robots and outputs shouldn't hurt anything right?) + for (int i = 0; i < 1000; i++) + { + bots.Add(i, new Bot(i)); + outputs.Add(i, -1); + } + } + + public Dictionary Outputs + { + get { return outputs; } + } + + public List ComparisonLog + { + get { return comparisonLog; } + } + + public void DumpOutputs() + { + for (int i = 0; i < 1000; i++) + if (outputs[i] != -1) + Console.WriteLine($"Output {i} = {outputs[i]}"); + } + public int PerformActions() + { + int actionsPerformed = 0; + foreach (KeyValuePair bot in bots) + { + Bot pBot = bot.Value; + // we can do something I think.... + if (pBot.HasBothValues()) + { + // this is overkill, but i can't think of a better way to have a public interface to fetch a specific bot by + // what comparisons it did. + comparisonLog.Add(new ComparisonLogEntry(bot.Key, pBot.Values[0], pBot.Values[1])); + + // perform low action + if (pBot.LowDestination == "output") + outputs[pBot.LowDestinationId] = pBot.GetAndClearLowValue(); + else if (pBot.LowDestination == "bot") + bots[pBot.LowDestinationId].SetValue(pBot.GetAndClearLowValue()); + + // perform high action + if (pBot.HighDestination == "output") + outputs[pBot.HighDestinationId] = pBot.GetAndClearHighValue(); + else if (pBot.HighDestination == "bot") + bots[pBot.HighDestinationId].SetValue(pBot.GetAndClearHighValue()); + + actionsPerformed++; + } + } + return actionsPerformed; + } + public void ProcessInstruction(string instruction) + { + string[] args = instruction.Split(new char[] { ' ' }); + + int botId = -1; + int value = -1; + string lowDest = ""; + int lowDestId = -1; + string highDest = ""; + int highDestId = -1; + + if (args[0] == "value") + { + int.TryParse(args[1], out value); + int.TryParse(args[5], out botId); + + // set a value. + bots[botId].SetValue(value); + } + else if (args[0] == "bot") + { + int.TryParse(args[1], out botId); + + lowDest = args[5]; + int.TryParse(args[6], out lowDestId); + + highDest = args[10]; + int.TryParse(args[11], out highDestId); + + bots[botId].LowDestination = lowDest; + bots[botId].LowDestinationId = lowDestId; + bots[botId].HighDestination = highDest; + bots[botId].HighDestinationId = highDestId; + } + } + } + + class Program + { + static void Main(string[] args) + { + bscott10 day10 = new bscott10(); + + string[] input = File.ReadAllLines("input_day10.txt"); + + // first you process everything + for (int i = 0; i < input.Length; i++) + day10.ProcessInstruction(input[i]); + + // then set everything in motion + int actions = day10.PerformActions(); + while (actions > 0) + { + Console.WriteLine($"Performed {actions} actions."); + actions = day10.PerformActions(); + } + + // Part 1 + foreach (ComparisonLogEntry cle in day10.ComparisonLog) + { + if ((cle.ValueA == 61 && cle.ValueB == 17) || + (cle.ValueA == 17 && cle.ValueB == 61)) + { + Console.WriteLine($"Part 1 Answer: Bot {cle.Index}"); + } + } + + // Part 2 + int value = day10.Outputs[0] * day10.Outputs[1] * day10.Outputs[2]; + Console.WriteLine($"Part 2 Answer: {value}"); + + Console.ReadLine(); + } + } +} diff --git a/csharp/bscott12.cs b/csharp/bscott12.cs new file mode 100644 index 0000000..5a2f6c5 --- /dev/null +++ b/csharp/bscott12.cs @@ -0,0 +1,111 @@ +/* + * Advent of Code 2016 + * Day 12 (part 1 and 2) + */ + +using System; +using System.Collections.Generic; +using System.IO; + +namespace adventofcode +{ + class bscott12 + { + private Dictionary registers = new Dictionary(); + private int pc = 0; + + public Dictionary Registers + { + get { return registers; } + } + + + public bscott12() + { + for (char i = 'a'; i <= 'd'; i++) + registers.Add(i.ToString(), 0); + } + + public void Reset() + { + for (char i = 'a'; i <= 'd'; i++) + registers[i.ToString()] = 0; + pc = 0; + } + + public void Process(string[] instructions) + { + while(pc < instructions.Length) + ProcessInstruction(instructions[pc]); + } + + public void ProcessInstruction(string instruction) + { + string[] arguments = instruction.Split(new char[] { ' ' }); + int value = 0; + bool branch = false; + + switch (arguments[0]) + { + case "cpy": + if (arguments[1][0] >= '0' && arguments[1][0] <= '9') + int.TryParse(arguments[1], out value); + else + value = registers[arguments[1]]; + + registers[arguments[2]] = value; + break; + case "inc": + registers[arguments[1]]++; + break; + case "dec": + registers[arguments[1]]--; + break; + case "jnz": + if (arguments[1][0] >= '0' && arguments[1][0] <= '9') + int.TryParse(arguments[1], out value); + else + value = registers[arguments[1]]; + + int jumpOffset = int.Parse(arguments[2]); + if (value != 0) + { + pc = pc + jumpOffset; + branch = true; + } + break; + } + + if(!branch) pc++; + } + } + + class Program + { + static void Main(string[] args) + { + bscott12 day12 = new bscott12(); + + string[] input = File.ReadAllLines("input_day12.txt"); + + // part 1 + day12.Process(input); + Console.Write("Part 1: "); + for (char i = 'a'; i <= 'd'; i++) + Console.Write(i.ToString() + " = " + day12.Registers[i.ToString()] + ", "); + Console.Write("\n"); + + // part 2 + day12.Reset(); + day12.Registers["c"] = 1; + day12.Process(input); + + Console.Write("Part 2: "); + for (char i = 'a'; i <= 'd'; i++) + Console.Write(i.ToString() + " = " + day12.Registers[i.ToString()] + ", "); + Console.Write("\n"); + + Console.ReadLine(); + } + } +} diff --git a/pascal/bscott06.pas b/pascal/bscott06.pas new file mode 100644 index 0000000..ba98156 --- /dev/null +++ b/pascal/bscott06.pas @@ -0,0 +1,117 @@ +{**************************************************************************** + Advent of Code 2016 + Day 6 (part 1 and 2) +****************************************************************************} + +program bscott06; + +{$mode objfpc}{$H+} + +uses + {$IFDEF UNIX}{$IFDEF UseCThreads} + cthreads, + {$ENDIF}{$ENDIF} + Classes, SysUtils, CustApp + { you can add units after this }; + +type + + { TAdventOfCodeDay06 } + + TAdventOfCodeDay06 = class(TCustomApplication) + protected + procedure DoRun; override; + public + constructor Create(TheOwner: TComponent); override; + destructor Destroy; override; + end; + +{ TAdventOfCodeDay06 } + +procedure TAdventOfCodeDay06.DoRun; +var + CharCountArrArray: array [0..7, 'a'..'z'] of Integer; + Password: array [0..7] of Char; + CharCount, I : Integer; + J: Char; + CurrentLine: String; + InputDataFile: text; +begin + + FillChar (CharCountArrArray,SizeOf(CharCountArrArray),0); + FillChar (Password,SizeOf(Password),0); + + AssignFile(InputDataFile, 'day6_input.txt'); + Reset(InputDataFile); + while not eof(InputDataFile) do + begin + readln(InputDataFile, CurrentLine); + + Inc(CharCountArrArray[0, CurrentLine[1]],1); + Inc(CharCountArrArray[1, CurrentLine[2]],1); + Inc(CharCountArrArray[2, CurrentLine[3]],1); + Inc(CharCountArrArray[3, CurrentLine[4]],1); + Inc(CharCountArrArray[4, CurrentLine[5]],1); + Inc(CharCountArrArray[5, CurrentLine[6]],1); + Inc(CharCountArrArray[6, CurrentLine[7]],1); + Inc(CharCountArrArray[7, CurrentLine[8]],1); + end; + CloseFile(InputDataFile); + + for I := 0 to 7 do + begin + CharCount := 0; + for J := 'a' to 'z' do + begin + if CharCount < CharCountArrArray[I, J] then + begin + Password[I] := J; + CharCount := CharCountArrArray[I, J]; + end; + end; + end; + + writeln('Part A Password: ' + Password); + + FillChar (Password,SizeOf(Password),0) ; + for I := 0 to 7 do + begin + CharCount := 0; + for J := 'a' to 'z' do + begin + if (CharCountArrArray[I, J] > 0) and ((CharCount > CharCountArrArray[I, J]) or (CharCount = 0)) then + begin + Password[I] := J; + CharCount := CharCountArrArray[I, J]; + end; + end; + end; + writeln('Part B Password: ' + Password); + + { add your program here } + ReadLn; + + // stop program loop + Terminate; +end; + +constructor TAdventOfCodeDay06.Create(TheOwner: TComponent); +begin + inherited Create(TheOwner); + StopOnException:=True; +end; + +destructor TAdventOfCodeDay06.Destroy; +begin + inherited Destroy; +end; + +var + Application: TAdventOfCodeDay06; +begin + Application:=TAdventOfCodeDay06.Create(nil); + Application.Title:='Advent of Code - Day 6'; + Application.Run; + Application.Free; +end. + diff --git a/php/bscott03.php b/php/bscott03.php new file mode 100644 index 0000000..6f0433f --- /dev/null +++ b/php/bscott03.php @@ -0,0 +1,39 @@ + $c && $a + $c > $b && $b + $c > $a); +} + +$input = file('day3_input.txt'); + +$valid_triangle_count = 0; +foreach($input as $line) { + $args = array_values(array_filter(explode(' ', $line))); + if(isValidTriangle((int)$args[0], (int)$args[1], (int)$args[2])) + $valid_triangle_count++; +} + +echo "Part 1 Count: $valid_triangle_count\n"; + +$valid_triangle_count = 0; +for($i = 0; $i < count($input); $i += 3) { + $args1 = array_values(array_filter(explode(' ', $input[$i+0]))); + $args2 = array_values(array_filter(explode(' ', $input[$i+1]))); + $args3 = array_values(array_filter(explode(' ', $input[$i+2]))); + + if(isValidTriangle((int)$args1[0], (int)$args2[0], (int)$args3[0])) + $valid_triangle_count++; + + if(isValidTriangle((int)$args1[1], (int)$args2[1], (int)$args3[1])) + $valid_triangle_count++; + + if(isValidTriangle((int)$args1[2], (int)$args2[2], (int)$args3[2])) + $valid_triangle_count++; +} + +echo "Part 2 Count: $valid_triangle_count\n"; \ No newline at end of file diff --git a/php/bscott04.php b/php/bscott04.php new file mode 100644 index 0000000..5e18b00 --- /dev/null +++ b/php/bscott04.php @@ -0,0 +1,81 @@ + $output_array[1], + 'sector_id' => $output_array[2], + 'checksum' => $output_array[3] + ); + } + return false; +} + +function generateChecksum($room_name) { + // calculate char occurrences + $char_count_array = count_chars(str_replace('-', '', $room_name), 1); + + // sort by occurrence count + arsort($char_count_array); + + // group chars into occurrence count + $dedupe = array(); + foreach($char_count_array as $char => $occurrence) { + $dedupe[$occurrence][] = $char; + } + + // cross my fingers and hope this actually works + $checksum = ''; + foreach($dedupe as $occurrence => $chars) { + sort($chars); + for($i = 0; $i < count($chars); $i++) { + $checksum .= chr($chars[$i]); + } + } + + // cut off the excess and return + return substr($checksum, 0, 5); +} + +function decryptRoomName($name, $sector_id) { + $key = $sector_id % 26; // this should work right? + $a_start = ord('a'); + $output = ''; + + for($i = 0; $i < strlen($name); $i++) { + $a = ord(substr($name, $i, 1)); + if($a == ord('-')) + $output .= ' '; + else + $output .= chr($a_start + ((($a - $a_start) + $key) % 26)); + } + + return $output; +} + +$input = file('day4_input.txt'); +//$input = array("aaaaa-bbb-z-y-x-123[abxyz]", "a-b-c-d-e-f-g-h-987[abcde]", "not-a-real-room-404[oarel]"); + +// Part 1 +$valid_room_sum = 0; +$valid_rooms = array(); +foreach($input as $line) { + $room_info = extractRoomInfo($line); + $generated_checksum = generateChecksum($room_info['room_name']); + if($generated_checksum == $room_info['checksum']) { + $valid_rooms[] = $room_info; + $valid_room_sum += (int)$room_info['sector_id']; + } +} +echo "valid room sum: $valid_room_sum
\n"; + +// Part 2 +foreach($valid_rooms as $room) { + $decrypted_name = decryptRoomName($room['room_name'], (int)$room['sector_id']); + echo "room name: $decrypted_name, sector: {$room['sector_id']}
\n"; +} diff --git a/php/bscott05.php b/php/bscott05.php new file mode 100644 index 0000000..4cc9d87 --- /dev/null +++ b/php/bscott05.php @@ -0,0 +1,54 @@ += $max) + return $result; + } + + for($i = 0; $i < 1000000000; $i++) { + $hash = md5($salt.$i); + if(substr($hash, 0, 5) === '00000') { + $result[$count++] = $hash; + if($count >= $max) + break; + } + } + + file_put_contents($cache_file, implode("\n", $result)); + return $result; +} + +$puzzle_input = 'reyedfim'; +$hashes = calculateHashes($puzzle_input, 30); + +// Part 1 +$password = ''; +for($i = 0; $i < 8; $i++) { + $password .= substr($hashes[$i], 5, 1); +} +echo "Step 1 Password: $password\n"; + +// Part 2 +$password = array_fill(0, 8, '_'); +for($i = 0; $i < count($hashes); $i++) { + $pos = substr($hashes[$i], 5, 1); + $char = substr($hashes[$i], 6, 1); + if (is_numeric($pos) && (int)$pos < 8 && $password[(int)$pos] === '_') + $password[(int)$pos] = $char; + +} +echo "Step 2 Password: ".implode($password); \ No newline at end of file