Skip to content

Commit

Permalink
Use hashbrown for day01
Browse files Browse the repository at this point in the history
  • Loading branch information
sd2k committed Feb 11, 2019
1 parent 7d4af5d commit c53a818
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 8 deletions.
3 changes: 3 additions & 0 deletions day01/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ version = "0.1.0"
authors = ["Ben Sully <ben@bsull.io>"]
edition = "2018"

[dependencies]
hashbrown = "*"

[dev-dependencies]
criterion = "0.2"

Expand Down
8 changes: 7 additions & 1 deletion day01/benches/bench.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
use criterion::{criterion_group, criterion_main, Criterion};
use day01::{part2_functional, part2_imperative};
use day01::{part1, part2_functional, part2_imperative};

fn part1_benchmark(c: &mut Criterion) {
let input: Vec<&str> = include_str!("../../input/2018/day1.txt").lines().collect();
c.bench_function("part1", move |b| b.iter(|| part1(&input)));
}

fn part2_functional_benchmark(c: &mut Criterion) {
let input: Vec<&str> = include_str!("../../input/2018/day1.txt").lines().collect();
Expand All @@ -17,6 +22,7 @@ fn part2_imperative_benchmark(c: &mut Criterion) {

criterion_group!(
benches,
part1_benchmark,
part2_functional_benchmark,
part2_imperative_benchmark
);
Expand Down
14 changes: 7 additions & 7 deletions day01/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
use std::collections::HashSet;
use hashbrown::HashSet;

fn parse_element(el: &str) -> i64 {
el.trim_left_matches('+').parse().unwrap()
fn parse_element(el: &str) -> i32 {
el.parse().unwrap()
}

pub fn part1(input: &[&str]) -> i64 {
pub fn part1(input: &[&str]) -> i32 {
input.iter().map(|el| parse_element(el)).sum()
}

pub fn part2_functional(input: &[&str]) -> i64 {
pub fn part2_functional(input: &[&str]) -> i32 {
let mut seen = HashSet::new();
seen.insert(0);
let err: Result<_, i64> = input.iter().cycle().try_fold(0, |acc, &x| {
let err: Result<_, i32> = input.iter().cycle().try_fold(0, |acc, &x| {
let new = acc + parse_element(x);
if seen.contains(&new) {
return Err(new);
Expand All @@ -23,7 +23,7 @@ pub fn part2_functional(input: &[&str]) -> i64 {
return err.err().unwrap();
}

pub fn part2_imperative(input: &[&str]) -> i64 {
pub fn part2_imperative(input: &[&str]) -> i32 {
let mut current = 0;
let mut seen = HashSet::new();
seen.insert(current);
Expand Down

0 comments on commit c53a818

Please sign in to comment.