Browse Source

refined regex workup

move from for loop to chained iterators
format output to match tests
regex
Jim Infield 3 years ago
parent
commit
9bea5bc12c
  1. 58
      src/main.rs

58
src/main.rs

@ -16,7 +16,7 @@ fn main() {
println!(); println!();
let test = "01|15|59, 1|47|16.35, 1|20|30, 1|43|03";
let test = args[0];
let hms = Regex::new(r"(\d\d?)\|(\d\d)\|(\d\d)").unwrap(); let hms = Regex::new(r"(\d\d?)\|(\d\d)\|(\d\d)").unwrap();
let csv = Regex::new(r", ").unwrap(); let csv = Regex::new(r", ").unwrap();
@ -25,40 +25,34 @@ fn main() {
m.unwrap().as_str().parse::<usize>().unwrap() m.unwrap().as_str().parse::<usize>().unwrap()
}; };
let mut vec = vec![];
for cap in hms.captures_iter(test) {
let mut col = cap.iter().skip(1)
.map(|e| parse_int(e)).collect::<Vec<usize>>();
vec.push(col[0] * 3600 + col[1] * 60 + col[2]);
}
let median = |v: Vec<usize>| {
if v.len() % 2 == 1 {
v[v.len()/2 + 1]
} else {
(v[v.len()/2] + v[v.len()/2 + 1])/2
}
let mut vec =
hms.captures_iter(test)
.map(|cap|
cap.iter().skip(1)
.map(parse_int)
.collect::<Vec<usize>>()
.chunks(3)
.map(|c| (c[0],c[1],c[2]))
.map(|(h,m,s)| h*3600 + m*60 +s)
.sum())
.collect::<Vec<usize>>();
vec.sort_unstable();
let (len, tot) = (vec.len(), vec.iter().sum::<usize>());
let (avg, mid, rng) = (tot/len, len/2, vec[len-1] - vec[0]);
let med = if len % 2 == 1 { vec[mid] }
else { (vec[mid-1] + vec[mid]) / 2 };
let time = |s| {
format!("{:02}|{:02}|{:02}", s/3600, s%3600/60, s%60)
}; };
vec.sort();
let len = vec.len();
let tot = vec.iter().sum();
let mut list = vec![
( "Total", tot ),
( "Range", vec[len-1] - vec[0] ),
( "Mean", tot/len ),
( "Median", median(vec) )
];
println!("\n{}", test);
println!("Range: {} Average: {} Median: {}",
time(rng), time(avg), time(med)
);
for i in list {
print!(" {}: {:02}|{:02}|{:02}",
i.0, i.1/3600, i.1%3600/60, i.1%60
);
}
println!("\n"); println!("\n");
} }

Loading…
Cancel
Save