notes/school/intro-crypto/uebung/01/u01/src/main.rs

73 lines
1.9 KiB
Rust
Raw Normal View History

2018-10-13 13:23:37 +02:00
extern crate countmap;
use countmap::CountMap;
use std::{
2018-10-15 10:38:22 +02:00
collections::HashMap,
2018-10-13 13:23:37 +02:00
fs::File,
io::{BufRead, BufReader},
2018-10-15 10:38:22 +02:00
path::Path,
2018-10-13 13:23:37 +02:00
};
fn count() {
let args: Vec<_> = std::env::args().collect();
2018-10-15 10:38:22 +02:00
let file = &args[1];
2018-10-13 13:23:37 +02:00
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,
2018-10-15 10:38:22 +02:00
f64::from(v) / f64::from(sum)
2018-10-13 13:23:37 +02:00
)
});
println!("sum &\\text{{:}}& {}", sum);
}
2018-10-15 10:38:22 +02:00
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)
}
2018-10-13 13:23:37 +02:00
fn main() {
2018-10-15 10:38:22 +02:00
count();
2018-10-13 13:23:37 +02:00
let args: Vec<_> = std::env::args().collect();
2018-10-15 10:38:22 +02:00
let target = &args[1];
let map = create_map(&args[2]).unwrap();
let read = BufReader::new(File::open(target).unwrap());
2018-10-13 13:23:37 +02:00
for line in read.lines() {
if let Ok(line) = line {
let s: String = line
.chars()
2018-10-15 10:38:22 +02:00
.map(|c| map.get(&c).cloned().unwrap_or(c))
.collect();
2018-10-13 13:23:37 +02:00
println!("{}", s);
}
}
}