From 5707ec957dc98a3ccf5d98a8023bbc694b751437 Mon Sep 17 00:00:00 2001 From: Valentin Brandl Date: Mon, 15 Oct 2018 10:38:22 +0200 Subject: [PATCH] Improve helper code --- school/intro-crypto/uebung/01/u01/map | 28 +++++++++ school/intro-crypto/uebung/01/u01/src/main.rs | 61 ++++++++----------- 2 files changed, 54 insertions(+), 35 deletions(-) create mode 100644 school/intro-crypto/uebung/01/u01/map diff --git a/school/intro-crypto/uebung/01/u01/map b/school/intro-crypto/uebung/01/u01/map new file mode 100644 index 0000000..eef332c --- /dev/null +++ b/school/intro-crypto/uebung/01/u01/map @@ -0,0 +1,28 @@ +Af +Bä +Cg +Dj +Eö +Fx +Gn +Ji +Km +Lc +Mß +Nv +Od +Pr +Qa +Rl +Se +Tü +Uh +Vz +Wt +Xw +Yp +Zs +Äo +Öb +Üu +ßk diff --git a/school/intro-crypto/uebung/01/u01/src/main.rs b/school/intro-crypto/uebung/01/u01/src/main.rs index f694f4b..93d3a5e 100644 --- a/school/intro-crypto/uebung/01/u01/src/main.rs +++ b/school/intro-crypto/uebung/01/u01/src/main.rs @@ -2,13 +2,15 @@ extern crate countmap; use countmap::CountMap; use std::{ + collections::HashMap, fs::File, io::{BufRead, BufReader}, + path::Path, }; fn count() { let args: Vec<_> = std::env::args().collect(); - let file = args.get(1).unwrap(); + let file = &args[1]; let mut map: CountMap = CountMap::new(); let read = BufReader::new(File::open(file).unwrap()); for line in read.lines() { @@ -30,51 +32,40 @@ fn count() { "{} &\\text{{:}}& {:3} \\to{{}} {:.2} \\\\", k, v, - v as f64 / sum as f64 + f64::from(v) / f64::from(sum) ) }); println!("sum &\\text{{:}}& {}", sum); } +fn create_map>(path: P) -> std::io::Result> { + let read = BufReader::new(File::open(path)?); + let mut map = HashMap::new(); + for line in read.lines() { + if let Ok(line) = line { + let chars: Vec = line.chars().collect(); + if chars.len() != 2 { + eprintln!("Invalid line {}", line); + } else { + map.insert(chars[0], chars[1]); + } + } + } + Ok(map) +} + fn main() { + count(); let args: Vec<_> = std::env::args().collect(); - let file = args.get(1).unwrap(); - let read = BufReader::new(File::open(file).unwrap()); + let target = &args[1]; + let map = create_map(&args[2]).unwrap(); + let read = BufReader::new(File::open(target).unwrap()); for line in read.lines() { if let Ok(line) = line { let s: String = line .chars() - .map(|c| match c { - 'A' => 'f', - 'B' => 'ä', - 'C' => 'g', - 'D' => 'j', - 'E' => 'ö', - 'F' => 'x', - 'G' => 'n', - 'J' => 'i', - 'K' => 'm', - 'L' => 'c', - 'M' => 'ß', - 'N' => 'v', - 'O' => 'd', - 'P' => 'r', - 'Q' => 'a', - 'R' => 'l', - 'S' => 'e', - 'T' => 'ü', - 'U' => 'h', - 'V' => 'z', - 'W' => 't', - 'X' => 'w', - 'Y' => 'p', - 'Z' => 's', - 'Ä' => 'o', - 'Ö' => 'b', - 'Ü' => 'u', - 'ß' => 'k', - c => c, - }).collect(); + .map(|c| map.get(&c).cloned().unwrap_or(c)) + .collect(); println!("{}", s); } }