day1 reimpl

1.20x speedup
master
Avril 4 years ago
parent 4a26755270
commit 2c45829d63
Signed by: flanchan
GPG Key ID: 284488987C31F630

3
.gitignore vendored

@ -1,3 +1,6 @@
input*
part1*
part2*
*.lock
target/

@ -0,0 +1,12 @@
[package]
name = "day1"
version = "0.1.0"
authors = ["Avril <flanchan@cumallover.me>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[features]
big = []
[dependencies]

@ -0,0 +1,37 @@
use std::{
io::{
self, BufRead, BufReader, Write,
},
fs,
error,
};
fn gen_input<W: Write+?Sized, R: BufRead>(output: &mut W, lines: R, const_name: &str) -> io::Result<()> {
eprint!("Generating {}... ", const_name);
writeln!(output, "pub const {}: &[u64] = &[", const_name)?;
for line in lines.lines()
{
writeln!(output, " {},", line?)?;
}
output.write_all(b"];\n")?;
eprintln!("OK");
Ok(())
}
fn main() -> Result<(), Box<dyn error::Error>>{
let mut output = fs::OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open("./src/input.rs").expect("Couldn't open output");
gen_input(&mut output, BufReader::new(fs::OpenOptions::new()
.read(true)
.open("../input").expect("Couldn't open input")), "INPUT")?;
gen_input(&mut output, BufReader::new(fs::OpenOptions::new()
.read(true)
.open("../input-big").expect("Couldn't open big input")), "INPUT_BIG")?;
Ok(())
}

@ -0,0 +1,37 @@
use std::collections::HashMap;
#[allow(dead_code)]
mod input;
#[cfg(feature="big")]
use input::INPUT_BIG as INPUT;
#[cfg(not(feature="big"))]
use input::INPUT;
#[cfg(not(feature="big"))] const TARGET: u64 = 2020;
#[cfg(feature="big")] const TARGET: u64 = 99920044;
// O(n^2)
fn main() {
let deficits: HashMap<u64, usize> = (0..)
.zip(INPUT.iter().copied())
.filter_map(|(i, x)| TARGET.checked_sub(x).map(|x| (x, i)))
.collect();
//eprintln!("calculated deficits: {}", deficits.len());
for (i, ix) in (0..).zip(INPUT.iter().copied())
{
for jx in INPUT[i..].iter().copied().skip(1)
{
let sum = ix+jx;
if let Some(&idx) = deficits.get(&sum)
{
//eprintln!("solution found?");
println!("{}", if let Some(x) = INPUT[idx].checked_mul(ix).map(|x| x.checked_mul(jx)).flatten()
{ x } else { continue; });
return;
}
}
}
//panic!("no solution");
}
Loading…
Cancel
Save