notes/school/intro-crypto/uebung/01/u01/src/main.rs
2018-10-15 10:38:22 +02:00

73 lines
1.9 KiB
Rust

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[1];
let mut map: CountMap<char, u32> = CountMap::new();
let read = BufReader::new(File::open(file).unwrap());
for line in read.lines() {
if let Ok(line) = line {
line.chars().filter(|c| c.is_alphabetic()).for_each(|c| {
map.insert_or_increment(c);
});
}
}
let sum: u32 = map
.iter()
.filter(|(k, _)| k.is_alphabetic())
.map(|(_, v)| v)
.sum();
let mut vec: Vec<_> = map.into_iter().collect();
vec.sort_unstable();
vec.into_iter().for_each(|(k, v)| {
println!(
"{} &\\text{{:}}& {:3} \\to{{}} {:.2} \\\\",
k,
v,
f64::from(v) / f64::from(sum)
)
});
println!("sum &\\text{{:}}& {}", sum);
}
fn create_map<P: AsRef<Path>>(path: P) -> std::io::Result<HashMap<char, char>> {
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<char> = 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 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| map.get(&c).cloned().unwrap_or(c))
.collect();
println!("{}", s);
}
}
}