Finish set 1.

This commit is contained in:
2022-04-11 20:13:53 -04:00
parent 6cc8ed65d0
commit 415baedd78
3 changed files with 237 additions and 0 deletions

View File

@@ -10,4 +10,5 @@ fn main() {
set1::challenge5();
set1::challenge6();
set1::challenge7();
set1::challenge8();
}

View File

@@ -171,3 +171,35 @@ pub fn challenge7() {
let partial_msg = result[..20].to_string();
println!("[okay] Challenge 7: {}...", partial_msg);
}
pub fn challenge8() {
fn read(path: &str) -> Vec<Bytes> {
let file = std::fs::File::open(path).unwrap();
let br = BufReader::new(file);
br.lines()
.map(|line| Bytes::from_hex(&line.unwrap()))
.collect()
}
fn rate(Bytes(v): &Bytes, size: usize) -> u32 {
let mut rating = 0;
let chunks: Vec<&[u8]> = v.chunks(size).collect();
for i in 0..chunks.len() {
for j in (i + 1)..chunks.len() {
rating += Bytes::hemming(&Bytes(chunks[i].to_vec()), &Bytes(chunks[j].to_vec()));
}
}
rating
}
let bytes_vector = read("data/8.txt");
let ratings: Vec<u32> = bytes_vector.iter().map(|b| rate(&b, 16)).collect();
let min_rating = ratings.iter().min().unwrap();
let index = ratings.iter().position(|e| e == min_rating).unwrap();
let average = ratings.iter().sum::<u32>() as f32 / ratings.len() as f32;
let partial_cipher = bytes_vector[index].to_hex()[..10].to_string();
println!(
"[okay] Challenge 8: Cipher {} [{}...] with rating {} (average = {}) is the solution.",
index, partial_cipher, min_rating, average
);
}