Skip to content

Commit

Permalink
custom parse to i32
Browse files Browse the repository at this point in the history
  • Loading branch information
RagnarGrootKoerkamp committed Jan 3, 2024
1 parent 9971993 commit 1fd779a
Showing 1 changed file with 45 additions and 17 deletions.
62 changes: 45 additions & 17 deletions src/main.rs
Expand Up @@ -3,31 +3,62 @@ use std::{collections::HashMap, env::args, io::Read};

struct Record {
count: u32,
min: f32,
max: f32,
sum: f32,
min: V,
max: V,
sum: V,
}

impl Record {
fn default() -> Self {
Self {
count: 0,
min: 1000.0,
max: -1000.0,
sum: 0.0,
min: i32::MAX,
max: i32::MIN,
sum: 0,
}
}
fn add(&mut self, value: f32) {
fn add(&mut self, value: V) {
self.count += 1;
self.sum += value;
self.min = self.min.min(value);
self.max = self.max.max(value);
}
fn avg(&self) -> f32 {
self.sum / self.count as f32
fn avg(&self) -> V {
self.sum / self.count as V
}
}

type V = i32;

fn parse(mut s: &[u8]) -> V {
let neg = if s[0] == b'-' {
s = &s[1..];
true
} else {
false
};
// s = abc.d
let (a, b, c, d) = match s {
[c, b'.', d] => (0, 0, c - b'0', d - b'0'),
[b, c, b'.', d] => (0, b - b'0', c - b'0', d - b'0'),
[a, b, c, b'.', d] => (a - b'0', b - b'0', c - b'0', d - b'0'),
[c] => (0, 0, 0, c - b'0'),
[b, c] => (0, b - b'0', c - b'0', 0),
[a, b, c] => (a - b'0', b - b'0', c - b'0', 0),
_ => panic!("Unknown patters {:?}", std::str::from_utf8(s).unwrap()),
};
let v = a as V * 1000 + b as V * 100 + c as V * 10 + d as V;
if neg {
-v
} else {
v
}
}

fn format(v: V) -> String {
format!("{:.1}", v as f64 / 10.0)
}

fn main() {
let filename = args().nth(1).unwrap_or("measurements.txt".to_string());
let mut data = vec![];
Expand All @@ -39,21 +70,18 @@ fn main() {
let mut h = HashMap::new();
for line in data.split(|&c| c == b'\n') {
let (name, value) = line.split_once(|&c| c == b';').unwrap();
let value = unsafe { std::str::from_utf8_unchecked(value) }
.parse::<f32>()
.unwrap();
h.entry(name).or_insert(Record::default()).add(value);
h.entry(name).or_insert(Record::default()).add(parse(value));
}

let mut v = h.into_iter().collect::<Vec<_>>();
v.sort_unstable_by_key(|p| p.0);
for (name, r) in &v {
println!(
"{}: {:.1}/{:.1}/{:.1}",
"{}: {}/{}/{}",
std::str::from_utf8(name).unwrap(),
r.min,
r.avg(),
r.max
format(r.min),
format(r.avg()),
format(r.max)
);
}
eprintln!("Num records: {}", v.len());
Expand Down

0 comments on commit 1fd779a

Please sign in to comment.