Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
rene-d committed Feb 5, 2024
1 parent 94d2f33 commit 03afcdc
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 51 deletions.
16 changes: 8 additions & 8 deletions 2016/day9/day9.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ fn main() {
}

/// Do part 1 of the puzzle
fn part1(data: &str) -> usize {
data.split('\n').fold(0, |acc, line| acc + expand_v1(line).len())
fn part1(data: &str) -> u64 {
data.split('\n').fold(0, |acc, line| acc + expand_v1(line).len() as u64)
}

/// Do part 2 of the puzzle
fn part2(data: &str) -> usize {
fn part2(data: &str) -> u64 {
data.split('\n').fold(0, |acc, line| acc + expand_v2(line))
}

Expand Down Expand Up @@ -53,12 +53,12 @@ fn expand_v1(s: &str) -> String {
}

/// ``expand_v2`` returns the length of expanded string according to the format v2.
fn expand_v2(s: &str) -> usize {
fn expand_v2(s: &str) -> u64 {
expand(s, 2)
}

/// ``expand`` returns the length of the expanded string (v1 or v2).
fn expand(s: &str, version: u8) -> usize {
fn expand(s: &str, version: u8) -> u64 {
let mut new_len = 0;
let mut chars = s.chars();

Expand All @@ -76,13 +76,13 @@ fn expand(s: &str, version: u8) -> usize {
.by_ref()
.take_while(|c| *c != ')')
.collect::<String>()
.parse::<usize>()
.parse::<u64>()
.unwrap();

let taken = chars.by_ref().take(take);

let count = if version == 1 {
taken.count()
taken.count() as u64
} else {
expand(taken.collect::<String>().as_str(), version)
};
Expand All @@ -101,7 +101,7 @@ fn expand(s: &str, version: u8) -> usize {
fn test_expand_v1() {
fn test_v1(s: &str, expected: &str) {
assert_eq!(expand_v1(s), expected);
assert_eq!(expand(s, 1), expected.len());
assert_eq!(expand(s, 1), expected.len() as u64);
}
test_v1("ADVENT", "ADVENT");
test_v1("A(1x5)BC", "ABBBBBC");
Expand Down
22 changes: 11 additions & 11 deletions 2023/day11/day11.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
//! [Day 11: Cosmic Expansion](https://adventofcode.com/2023/day/11)
struct Puzzle {
galaxies: Vec<(usize, usize)>,
empty_rows: Vec<usize>,
empty_cols: Vec<usize>,
galaxies: Vec<(u64, u64)>,
empty_rows: Vec<u64>,
empty_cols: Vec<u64>,
}

impl Puzzle {
Expand All @@ -21,9 +21,9 @@ impl Puzzle {

let mut grid = vec![];

for (y, line) in data.lines().enumerate() {
for (line, y) in data.lines().zip(0..) {
let row: Vec<_> = line.chars().collect();
for (x, &c) in row.iter().enumerate() {
for (&c, x) in row.iter().zip(0..) {
if c == '#' {
self.galaxies.push((x, y));
}
Expand All @@ -38,12 +38,12 @@ impl Puzzle {

for x in 0..grid[0].len() {
if (0..grid.len()).all(|y| grid[y][x] == '.') {
self.empty_cols.push(x);
self.empty_cols.push(x as u64);
}
}
}

fn solve(&self, expansion_factor: usize) -> usize {
fn solve(&self, expansion_factor: u64) -> u64 {
let expansion_factor = expansion_factor - 1;
let mut result = 0;
for (i, &(x1, y1)) in self.galaxies.iter().enumerate() {
Expand All @@ -55,15 +55,15 @@ impl Puzzle {
.empty_cols
.iter()
.filter(|&&col| x1.min(x2) <= col && col <= x1.max(x2))
.count()
.count() as u64
* expansion_factor;

// expand empty spaces vertically
distance += self
.empty_rows
.iter()
.filter(|&&row| y1.min(y2) <= row && row <= y1.max(y2))
.count()
.count() as u64
* expansion_factor;

result += distance;
Expand All @@ -74,12 +74,12 @@ impl Puzzle {
}

/// Solve part one.
fn part1(&self) -> usize {
fn part1(&self) -> u64 {
self.solve(2)
}

/// Solve part two.
fn part2(&self) -> usize {
fn part2(&self) -> u64 {
self.solve(1_000_000)
}
}
Expand Down
12 changes: 6 additions & 6 deletions 2023/day21/day21.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ impl Puzzle {
self.garden[usize::try_from(i).unwrap()]
}

fn count(&self, n: i32) -> usize {
fn count(&self, n: i32) -> u64 {
// nota: still not really optimized, could probably memoize something
let mut p = HashSet::new();
p.insert((self.start_x, self.start_y));
Expand Down Expand Up @@ -116,10 +116,10 @@ impl Puzzle {
p = np;
}

p.len()
p.len() as u64
}

fn big_count(&self, n: i32) -> usize {
fn big_count(&self, n: i32) -> u64 {
// the step count curve is parabolic
let (t, x0) = n.div_rem(&self.n);

Expand All @@ -138,18 +138,18 @@ impl Puzzle {
let a = y2 - 2 * y1 + y0;
let b = y1 - y0;

let t = usize::try_from(t).unwrap();
let t = u64::try_from(t).unwrap();

a * t * (t - 1) / 2 + b * t + y0
}

/// Solve part one.
fn part1(&self) -> usize {
fn part1(&self) -> u64 {
self.count(64)
}

/// Solve part two.
fn part2(&self) -> usize {
fn part2(&self) -> u64 {
self.big_count(26_501_365)
}
}
Expand Down
12 changes: 6 additions & 6 deletions 2023/day8/day8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use num::Integer;
use std::collections::HashMap;

fn lcm(values: &Vec<usize>) -> usize {
fn lcm(values: &Vec<u64>) -> u64 {
let mut m = 1;
for x in values {
m = m.lcm(x);
Expand Down Expand Up @@ -44,7 +44,7 @@ impl Puzzle {
}
}

fn solve(&self, part1: bool) -> usize {
fn solve(&self, part1: bool) -> u64 {
let start = u32::from_str_radix(if part1 { "AAA" } else { "A" }, 36).unwrap();
let stop = u32::from_str_radix(if part1 { "ZZZ" } else { "Z" }, 36).unwrap();
let mask = if part1 { 36 * 36 * 36 } else { 36 };
Expand Down Expand Up @@ -81,10 +81,10 @@ impl Puzzle {
*node = new_node;

if new_node % mask == stop {
z.insert(i, n);
z.insert(i, n as u64);

if z.len() == size {
let z = z.values().copied().collect::<Vec<usize>>();
let z: Vec<_> = z.values().copied().collect();
return lcm(&z);
}
}
Expand All @@ -93,12 +93,12 @@ impl Puzzle {
}

/// Solve part one.
fn part1(&self) -> usize {
fn part1(&self) -> u64 {
self.solve(true)
}

/// Solve part two.
fn part2(&self) -> usize {
fn part2(&self) -> u64 {
self.solve(false)
}
}
Expand Down
52 changes: 32 additions & 20 deletions scripts/runall.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,28 +199,33 @@ def make(year: Path, source: Path, dest: Path, cmd: str):
subprocess.check_call(cmdline, shell=True)


def build_all(filter_year: int):
def build_all(filter_year: int, filter_lang: t.Iterable[str]):
for year in range(2015, 2024):
if filter_year != 0 and year != filter_year:
continue
year = Path(str(year))
if not year.is_dir():
continue
m = year / "Cargo.toml"
if year.is_dir() and m.is_file():
print(f"{FEINT}{ITALIC}cargo build {m}{RESET}", end=f"{CLEAR_EOL}{CR}")
subprocess.check_call(["cargo", "build", "--manifest-path", m, "--release", "--quiet"])

if not filter_lang or "rust" in filter_lang:
m = year / "Cargo.toml"
if year.is_dir() and m.is_file():
print(f"{FEINT}{ITALIC}cargo build {m}{RESET}", end=f"{CLEAR_EOL}{CR}")
subprocess.check_call(["cargo", "build", "--manifest-path", m, "--release", "--quiet"])

for day in range(1, 26):
src = year / f"day{day}" / f"day{day}.c"
if src.is_file():
print(f"{FEINT}{ITALIC}compile {src}{RESET}", end=f"{CLEAR_EOL}{CR}")
make(year, src, f"day{day}_c", "cc -std=c11")

src = year / f"day{day}" / f"day{day}.cpp"
if src.is_file():
print(f"{FEINT}{ITALIC}compile {src}{RESET}", end=f"{CLEAR_EOL}{CR}")
make(year, src, f"day{day}_cpp", "c++ -std=c++17")
if not filter_lang or "c" in filter_lang:
src = year / f"day{day}" / f"day{day}.c"
if src.is_file():
print(f"{FEINT}{ITALIC}compile {src}{RESET}", end=f"{CLEAR_EOL}{CR}")
make(year, src, f"day{day}_c", "cc -std=c11")

if not filter_lang or "c++" in filter_lang:
src = year / f"day{day}" / f"day{day}.cpp"
if src.is_file():
print(f"{FEINT}{ITALIC}compile {src}{RESET}", end=f"{CLEAR_EOL}{CR}")
make(year, src, f"day{day}_cpp", "c++ -std=c++17")


def load_data(filter_year, filter_user, filter_yearday):
Expand Down Expand Up @@ -366,7 +371,6 @@ def run_day(


def get_languages(filter_lang: t.Iterable[str]) -> t.Dict[str, t.Tuple[str, t.Union[str, None]]]:
filter_lang = set(map(str.casefold, filter_lang or ()))

languages = {}
for lang, v in LANGUAGES.items():
Expand All @@ -377,6 +381,16 @@ def get_languages(filter_lang: t.Iterable[str]) -> t.Dict[str, t.Tuple[str, t.Un

if "/" not in interpreter and "\\" not in interpreter:
interpreter = shutil.which(interpreter)
if not interpreter:
continue

if lang == "Python":
hexversion = int(
subprocess.check_output([interpreter, "-c", "import sys;print(sys.hexversion)"]).decode()
)
if hexversion < 0x30A0000: # 3.10.x
continue

languages[lang2] = (v, interpreter)
else:
interpreter = Path(interpreter).expanduser().absolute()
Expand Down Expand Up @@ -458,7 +472,9 @@ def main():
if args.venv:
return install_venv(args.venv)

languages = get_languages(args.language)
filter_lang = set(map(str.casefold, args.language or ()))

languages = get_languages(filter_lang)

args.exclude = args.exclude or []
if args.no_slow:
Expand All @@ -471,16 +487,12 @@ def main():
" -x 2022:15"
" -x 2023:5 -x 2023:10 -x 2023:23".split()
)
if args.no_64:
args.exclude.extend(
" -x 2016:9 -x 2016:15" " -x 2022:11 -x 2022:20" " -x 2020:23" " -x 2023:8 -x 2023:11 -x 2023:21"
)

filter_year = 0 if len(args.n) == 0 else int(args.n.pop(0))
filter_day = set(args.n)

if not args.no_build:
build_all(filter_year)
build_all(filter_year, filter_lang)
print(end=f"{CR}{CLEAR_EOL}")

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

0 comments on commit 03afcdc

Please sign in to comment.