Skip to content

Commit

Permalink
2017
Browse files Browse the repository at this point in the history
  • Loading branch information
rene-d committed Feb 4, 2024
1 parent 1080e92 commit 5840012
Show file tree
Hide file tree
Showing 4 changed files with 136 additions and 9 deletions.
16 changes: 15 additions & 1 deletion 2017/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
# http://adventofcode.com/2017

[workspace]
members = ["day1", "day2", "day8", "day10", "day11", "day13", "day14", "day15", "day16", "day17", "day18", "day23"]
members = [
"day1",
"day2",
"day5",
"day8",
"day10",
"day11",
"day13",
"day14",
"day15",
"day16",
"day17",
"day18",
"day23",
]

resolver = "2"
11 changes: 11 additions & 0 deletions 2017/day5/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "day5"
version = "0.1.0"
edition = "2021"

[dependencies]
aoc = { path = "../../aoc" }

[[bin]]
name = "day5"
path = "day5.rs"
90 changes: 90 additions & 0 deletions 2017/day5/day5.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
//! [Day 5: A Maze of Twisty Trampolines, All Alike](https://adventofcode.com/2017/day/5)
struct Puzzle {
jumps: Vec<i32>,
}

impl Puzzle {
fn new() -> Puzzle {
Puzzle { jumps: vec![] }
}

/// Get the puzzle input.
fn configure(&mut self, path: &str) {
let data = std::fs::read_to_string(path).unwrap();

self.jumps = data.lines().map(|s| s.parse().unwrap()).collect();
}

/// Solve part one.
fn part1(&self) -> u32 {
let mut jumps = self.jumps.clone();
let length = i32::try_from(jumps.len()).unwrap();
let mut offset = 0;
let mut n = 0;

while 0 <= offset && offset < length {
let index = usize::try_from(offset).unwrap();

let jump = jumps[index];
jumps[index] += 1;

offset += jump;
n += 1;
}

n
}

/// Solve part two.
fn part2(&self) -> u32 {
let mut jumps = self.jumps.clone();
let length = i32::try_from(jumps.len()).unwrap();
let mut offset = 0;
let mut n = 0;

while 0 <= offset && offset < length {
let index = usize::try_from(offset).unwrap();

let jump = jumps[index];
if jump >= 3 {
jumps[index] -= 1;
} else {
jumps[index] += 1;
}

offset += jump;
n += 1;
}

n
}
}

fn main() {
let args = aoc::parse_args();
let mut puzzle = Puzzle::new();
puzzle.configure(args.path.as_str());
println!("{}", puzzle.part1());
println!("{}", puzzle.part2());
}

/// Test from puzzle input
#[cfg(test)]
mod test {
use super::*;

#[test]
fn test01() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part1(), 5);
}

#[test]
fn test02() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part2(), 10);
}
}
28 changes: 20 additions & 8 deletions scripts/runall.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
from datetime import timedelta, datetime
from operator import itemgetter
from pathlib import Path
from zlib import crc32

# from zlib import crc32
import sqlite3
import shutil
import hashlib

RED = "\033[91m"
GREEN = "\033[92m"
Expand Down Expand Up @@ -151,8 +153,10 @@ def run(
# under macOS, the first launch of a Rust program is slower (why ???)
subprocess.call(cmd + ["--help"], stdout=subprocess.DEVNULL)

cmd.append(file.absolute().as_posix())

start = time.time_ns()
out = subprocess.run(cmd + [file.absolute()], stdout=subprocess.PIPE)
out = subprocess.run(cmd, stdout=subprocess.PIPE)
elapsed = time.time_ns() - start
answers = " ".join(out.stdout.decode().strip().split("\n"))

Expand All @@ -172,7 +176,8 @@ def run(
result = {"elapsed": elapsed, "status": status, "answers": answers}

with Path("run.log").open("at") as f:
line = f"{datetime.now()} {lang} {cmd} {file.absolute()} {elapsed} {status} '{solution or ''}' '{answers}'"
line = f"{datetime.now()} {lang} {cmd} {elapsed} {status} '{solution or ''}' '{answers}'"
line = line.replace(Path(__file__).parent.parent.as_posix() + "/", "")
print(line, file=f)

return result
Expand Down Expand Up @@ -219,7 +224,7 @@ def build_all(filter_year: int):
make(year, src, f"day{day}_cpp", "c++ -std=c++17")


def load_data(filter_year, filter_user):
def load_data(filter_year, filter_user, filter_yearday):
inputs = defaultdict(dict)
solutions = defaultdict(dict)

Expand All @@ -241,13 +246,18 @@ def load_data(filter_year, filter_user):
if filter_year != 0 and year != filter_year:
continue

if filter_yearday and f"{year}:{day}" in filter_yearday:
continue

key = f"{year}:{day}:{user}"

e = check_cache(key, f, "inputs", ("crc32",))
if e:
crc = e["crc32"]
else:
crc = hex(crc32(f.read_bytes().strip()) & 0xFFFFFFFF)
# crc = hex(crc32(f.read_bytes().strip()) & 0xFFFFFFFF)
crc = hashlib.sha256(f.read_bytes().strip()).hexdigest()

update_cache(key, f, "inputs", {"crc32": crc})

if crc not in inputs[year, day]:
Expand Down Expand Up @@ -430,13 +440,15 @@ def install_venv(interpreter: Path):


def main():
parser = argparse.ArgumentParser()
parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=28))

parser.add_argument("--venv", type=Path, help="install virtual environment")
parser.add_argument("-l", "--language", type=str, action="append", metavar="LANG", help="filter by language")
parser.add_argument("-x", "--exclude", type=str, action="append", metavar="Y:D", help="exclude day")
parser.add_argument("-r", "--refresh", action="store_true", help="relaunch solutions")
parser.add_argument("-n", "--dry-run", action="store_true", help="do not run")
parser.add_argument("--no-build", action="store_true", help="do not build")
parser.add_argument("-u", "--user", dest="filter_user", type=str, help="filter by user id")
parser.add_argument("-u", "--user", dest="filter_user", metavar="USER", type=str, help="filter by user id")
parser.add_argument("n", type=int, nargs="*", help="filter by year or year/day")

args = parser.parse_args()
Expand All @@ -459,7 +471,7 @@ def main():

languages = get_languages(args.language)

inputs, sols = load_data(filter_year, args.filter_user)
inputs, sols = load_data(filter_year, args.filter_user, args.exclude)

for year in range(2015, 2024):
if filter_year != 0 and year != filter_year:
Expand Down

0 comments on commit 5840012

Please sign in to comment.