Added day2

This commit is contained in:
Ishan Jain 2022-12-31 23:11:32 +05:30
parent dfb79ce0ee
commit a744398d4b
Signed by: ishan
GPG Key ID: 0506DB2A1CC75C27
4 changed files with 1090 additions and 0 deletions

44
src/day2/1.rs Normal file
View File

@ -0,0 +1,44 @@
#![feature(iterator_try_collect)]
#![feature(test)]
extern crate test;
const INPUTS: [&str; 2] = [include_str!("./sample.txt"), include_str!("./input.txt")];
fn parse(input: &'static str) -> Vec<Vec<i64>> {
input
.trim()
.lines()
.map(|line| {
line.splitn(3, 'x')
.map(|num| num.bytes().fold(0, |a, x| (a * 10) + (x - b'0') as i64))
.collect()
})
.collect()
}
fn solution(input: Vec<Vec<i64>>) -> i64 {
input.into_iter().fold(0, |a, c| {
let s1 = c[0] * c[1];
let s2 = c[1] * c[2];
let s3 = c[2] * c[0];
a + 2 * s1 + 2 * s2 + 2 * s3 + s1.min(s2.min(s3))
})
}
fn main() {
for input in INPUTS.iter() {
let output = parse(input);
let output = solution(output);
println!("{output}");
}
}
#[bench]
fn solution_bench(b: &mut test::Bencher) {
b.iter(|| {
let input = parse(INPUTS[1]);
let result = solution(input);
test::black_box(result);
})
}

44
src/day2/2.rs Normal file
View File

@ -0,0 +1,44 @@
#![feature(iterator_try_collect)]
#![feature(test)]
extern crate test;
const INPUTS: [&str; 2] = [include_str!("./sample.txt"), include_str!("./input.txt")];
fn parse(input: &'static str) -> Vec<Vec<i64>> {
input
.trim()
.lines()
.map(|line| {
line.splitn(3, 'x')
.map(|num| num.bytes().fold(0, |a, x| (a * 10) + (x - b'0') as i64))
.collect()
})
.collect()
}
fn solution(input: Vec<Vec<i64>>) -> i64 {
input.into_iter().fold(0, |a, c| {
let s1 = 2 * (c[0] + c[1]);
let s2 = 2 * (c[1] + c[2]);
let s3 = 2 * (c[2] + c[0]);
a + c[0] * c[1] * c[2] + s1.min(s2.min(s3))
})
}
fn main() {
for input in INPUTS.iter() {
let output = parse(input);
let output = solution(output);
println!("{output}");
}
}
#[bench]
fn solution_bench(b: &mut test::Bencher) {
b.iter(|| {
let input = parse(INPUTS[1]);
let result = solution(input);
test::black_box(result);
})
}

1000
src/day2/input.txt Normal file

File diff suppressed because it is too large Load Diff

2
src/day2/sample.txt Normal file
View File

@ -0,0 +1,2 @@
2x3x4
1x1x10