Compare commits

...

2 Commits

Author SHA1 Message Date
Bryce Allen 97ed63735a day1: add rust impl, example data
3 years ago
Bryce Allen 1658b63ef0 day1: don't keep calories array
3 years ago

2
.gitignore vendored

@ -24,3 +24,5 @@ docs/site/
# environment.
Manifest.toml
target
Cargo.lock

@ -0,0 +1,8 @@
[package]
name = "day1"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

@ -7,23 +7,23 @@ println("infile = ", infile)
N = parse(Int64, Ns)
max_calories = zeros(Int64, N)
elf_calories = zeros(Int64, 1)
elf_calories = 0
i = 1
io = open(infile, "r")
for line in eachline(io)
global i, max_calories, max_elf_idx, elf_calories
if length(line) == 0
if elf_calories[i] > max_calories[1]
max_calories[1] = elf_calories[i]
if elf_calories > max_calories[1]
max_calories[1] = elf_calories
sort!(max_calories)
end
i += 1
push!(elf_calories, 0)
elf_calories = 0
continue
end
snack_calories = parse(Int64, line)
elf_calories[i] += snack_calories
elf_calories += snack_calories
end
println(max_calories)

@ -0,0 +1,14 @@
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

@ -0,0 +1,62 @@
// From rust by example
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
fn aoc_day1(path : &str, n : i64) -> i64 {
let mut max_calories : [i64; 3] = [0, 0, 0];
let mut calories : i64 = 0;
if let Ok(lines) = read_lines(path) {
for line in lines {
if let Ok(scalories) = line {
println!("{}", scalories);
println!("[{}, {}, {}]", max_calories[0], max_calories[1], max_calories[2]);
if scalories.len() == 0 {
if calories > max_calories[0] {
max_calories[0] = calories;
max_calories.sort();
}
calories = 0;
} else {
let snack_calories = scalories.parse::<i64>().unwrap();
calories += snack_calories;
}
}
}
// eof
if calories > max_calories[0] {
max_calories[0] = calories;
max_calories.sort();
}
}
if n == 1 {
return max_calories[2];
} else {
return max_calories.iter().sum();
}
}
// The output is wrapped in a Result to allow matching on errors
// Returns an Iterator to the Reader of the lines of the file.
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>, {
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
fn main() {
aoc_day1("day1input.txt", 1);
}
#[test]
fn day1input() {
assert_eq!(aoc_day1("day1input.txt", 1), 69206);
assert_eq!(aoc_day1("day1input.txt", 3), 197400);
}
#[test]
fn example() {
assert_eq!(aoc_day1("example.txt", 1), 24000);
assert_eq!(aoc_day1("example.txt", 3), 45000);
}
Loading…
Cancel
Save