Skip to content

Commit

Permalink
Merging 2016
Browse files Browse the repository at this point in the history
  • Loading branch information
shrugalic committed Nov 19, 2023
2 parents e92196a + fce08af commit fe86e2d
Show file tree
Hide file tree
Showing 33 changed files with 4,559 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
@@ -1 +1 @@
input/day*.txt filter=git-crypt diff=git-crypt
**/input/day*.txt filter=git-crypt diff=git-crypt
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Generated by Cargo
# will have compiled files and executables
target/
**/target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Expand Down
10 changes: 10 additions & 0 deletions 2016/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "advent_of_code_2016"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
md5 = "0.7.0"
rayon = "1.5.1"
21 changes: 21 additions & 0 deletions 2016/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 bOli

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.
2 changes: 2 additions & 0 deletions 2016/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Advent of Code
My solutions to the [Advent of Code 2016](https://adventofcode.com/2016) puzzles.
12 changes: 12 additions & 0 deletions 2016/advent_of_code_2016.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="RUST_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
155 changes: 155 additions & 0 deletions 2016/src/assembunny.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
use std::collections::HashSet;
use Op::*;
use Param::*;

type Register = char;
type Value = isize;

#[derive(Debug, Copy, Clone)]
pub(crate) enum Param {
Register(Register),
Value(Value),
}
impl From<&str> for Param {
fn from(s: &str) -> Self {
if let Ok(number) = s.parse() {
Value(number)
} else {
Register(s.to_char())
}
}
}

#[derive(Debug)]
pub(crate) enum Op {
Cpy(Param, Register),
Inc(Register),
Dec(Register),
Jnz(Param, Param),
// The two ops below are for day 23 only. This is the toggle command
Tgl(Register), // toggle
Nop(Param, Param), // no-op used to store the previous ops parameters
// The op below is for day 25 only
Out(Param), // Transmit the next clock signal value
}
impl From<&str> for Op {
fn from(s: &str) -> Self {
let p: Vec<_> = s.split_ascii_whitespace().collect();
match p[0] {
"cpy" => Cpy(Param::from(p[1]), p[2].to_char()),
"inc" => Inc(p[1].to_char()),
"dec" => Dec(p[1].to_char()),
"jnz" => Jnz(Param::from(p[1]), Param::from(p[2])),
"tgl" => Tgl(p[1].to_char()),
"out" => Out(Param::from(p[1])),
_ => panic!("Invalid op {}", s),
}
}
}

trait ToChar {
fn to_char(&self) -> char;
}
impl ToChar for &str {
fn to_char(&self) -> char {
self.chars().next().unwrap()
}
}

trait ToIndex {
fn to_idx(&self) -> usize;
}
impl ToIndex for char {
fn to_idx(&self) -> usize {
(*self as u8 - b'a') as usize
}
}

#[derive(Debug)]
pub(crate) struct Computer {
code: Vec<Op>,
register: Vec<Value>,
}
impl From<Vec<&str>> for Computer {
fn from(s: Vec<&str>) -> Self {
let code = s.into_iter().map(Op::from).collect();
let register = vec![0; 4];
Computer { code, register }
}
}

impl Computer {
pub(crate) fn run(&mut self) -> isize {
let mut instr_ptr = 0;
let mut prev_output = None;
let mut visited_states = HashSet::new();
while let Some(op) = self.code.get(instr_ptr) {
match op {
Cpy(i, r) => self.register[r.to_idx()] = self.get_value(i),
Inc(r) => self.register[r.to_idx()] += 1,
Dec(r) => self.register[r.to_idx()] -= 1,
Jnz(i, p) => {
if 0 != self.get_value(i) {
let offset = self.get_value(p);
let ip = instr_ptr as isize + offset;
if ip < 0 {
// still out of bounds, but valid for a usize
instr_ptr = self.code.len();
} else {
instr_ptr = ip as usize;
}
continue; // Avoid increasing of instr_ptr below
}
}
// This is for day 23 only
Tgl(r) => {
let offset = self.register[r.to_idx()];
let ip = instr_ptr as isize + offset;
if 0 <= ip && (ip as usize) < self.code.len() {
let op = self.code.get_mut(ip as usize).unwrap();
// println!("old op = {:?}", op);
match op {
Jnz(i, v) => match v {
Register(r) => *op = Cpy(*i, *r),
Value(_) => *op = Nop(*i, *v),
},
Cpy(i, r) => *op = Jnz(*i, Param::Register(*r)),
Nop(i, v) => *op = Jnz(*i, *v),
Inc(r) => *op = Dec(*r),
Dec(r) | Tgl(r) => *op = Inc(*r),
// Day 25 "Out" does not need to be handled for the day 23-only "Tgl"
Out(_) => {}
}
// println!("new op = {:?}", op);
} // else nothing happens if out of bounds
}
Nop(_, _) => {} // Just skip this no-op
Out(p) => {
let curr_output = self.get_value(p);
match (curr_output, prev_output) {
(0, None) | (0, Some(1)) | (1, Some(0)) => prev_output = Some(curr_output),
// Not a sequence of 0, 1, 0, 1, 0, 1, …
(_, _) => return -1, // denotes error
}
// Copy the computer's registers into a set to see if we're in an infinite loop,
// and stop if we are
if !visited_states.insert(format!("{:?}", self.register)) {
return 1; // denotes success
}
}
}
instr_ptr += 1;
}
self.register['a'.to_idx()]
}

fn get_value(&self, p: &Param) -> Value {
match p {
Param::Register(r) => self.register[r.to_idx()],
Param::Value(v) => *v,
}
}
pub(crate) fn set_register(&mut self, r: Register, v: Value) {
self.register[r.to_idx()] = v;
}
}
123 changes: 123 additions & 0 deletions 2016/src/day01.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
use crate::parse;
use std::collections::HashSet;

const INPUT: &str = include_str!("../input/day01.txt");

pub(crate) fn day01_part1() -> usize {
distance_from_origin(&parse(INPUT)[0])
}

pub(crate) fn day01_part2() -> usize {
distance_to_first_location_visited_twice(&parse(INPUT)[0])
}

fn distance_from_origin(input: &str) -> usize {
let (mut x, mut y) = (0isize, 0isize);
let mut dir = Dir::N;
for Step { turn, distance } in input.split(", ").map(Step::from).collect::<Vec<_>>() {
dir.turn(&turn);
match dir {
Dir::N => y -= distance,
Dir::S => y += distance,
Dir::E => x += distance,
Dir::W => x -= distance,
}
}

(x.abs() + y.abs()) as usize
}

fn distance_to_first_location_visited_twice(input: &str) -> usize {
let (mut x, mut y) = (0isize, 0isize);
let mut dir = Dir::N;
let mut visited = HashSet::new();
visited.insert((x, y));
'outer: for Step { turn, distance } in input.split(", ").map(Step::from).collect::<Vec<_>>() {
dir.turn(&turn);
for _ in 0..distance {
match dir {
Dir::N => y -= 1,
Dir::S => y += 1,
Dir::E => x += 1,
Dir::W => x -= 1,
}
if !visited.insert((x, y)) {
break 'outer;
}
}
}

(x.abs() + y.abs()) as usize
}

enum Turn {
L,
R,
}

struct Step {
turn: Turn,
distance: isize,
}
impl From<&str> for Step {
fn from(s: &str) -> Self {
let distance = s[1..].parse().unwrap();
let turn = if s.starts_with('R') { Turn::R } else { Turn::L };
Step { turn, distance }
}
}

enum Dir {
N,
E,
S,
W,
}
impl Dir {
fn turn(&mut self, turn: &Turn) {
*self = match turn {
Turn::L => match self {
Dir::N => Dir::W,
Dir::E => Dir::N,
Dir::S => Dir::E,
Dir::W => Dir::S,
},
Turn::R => match self {
Dir::N => Dir::E,
Dir::E => Dir::S,
Dir::S => Dir::W,
Dir::W => Dir::N,
},
};
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn part1_examples() {
assert_eq!(5, distance_from_origin("R2, L3"));
assert_eq!(2, distance_from_origin("R2, R2, R2"));
assert_eq!(12, distance_from_origin("R5, L5, R5, R3"));
}

#[test]
fn part1() {
assert_eq!(230, day01_part1());
}

#[test]
fn part2_examples() {
assert_eq!(
4,
distance_to_first_location_visited_twice("R8, R4, R4, R8")
);
}

#[test]
fn part2() {
assert_eq!(154, day01_part2());
}
}
Loading

0 comments on commit fe86e2d

Please sign in to comment.