Skip to content

Instantly share code, notes, and snippets.

@jthemphill
Created December 9, 2021 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jthemphill/b4e42f12b1b78dd2757669d5f400cbd7 to your computer and use it in GitHub Desktop.
Save jthemphill/b4e42f12b1b78dd2757669d5f400cbd7 to your computer and use it in GitHub Desktop.
use rayon::prelude::*;
use std::io::BufRead;
fn edit_distance(s1: &str, s2: &str) -> usize {
if s1.len() > s2.len() {
return edit_distance(s2, s1);
}
let mut distances: Vec<usize> = (0..=s1.len()).collect();
for (i2, c2) in s2.chars().enumerate() {
let mut distances_ = vec![i2 + 1];
for (i1, c1) in s1.chars().enumerate() {
if c1 == c2 {
distances_.push(distances[i1]);
} else {
distances_.push(
1 + distances[i1]
.min(distances[i1 + 1])
.min(distances_[distances_.len() - 1]),
);
}
}
distances = distances_;
}
distances[distances.len() - 1]
}
fn main() {
let mut argv = std::env::args();
argv.next();
let needed_distance: usize = argv.next().unwrap().parse().unwrap();
let clues: Vec<String> = argv.collect();
let dict: Vec<String> = std::io::stdin()
.lock()
.lines()
.flat_map(|word| word.into_iter())
.map(|word| word.trim().to_lowercase())
.collect();
for word in dict
.into_par_iter()
.filter(|word| {
clues
.iter()
.all(|clue| edit_distance(clue, &word) == needed_distance)
})
.collect::<Vec<String>>()
.into_iter()
{
println!("Found a word! {}", word);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment