Created
August 26, 2023 08:26
-
-
Save mtimkovich/75beab092b697ef07cb1526cf317b185 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashMap; | |
use std::env; | |
use std::fs::File; | |
use std::io::{self, prelude::*, BufReader}; | |
use std::process; | |
fn tokenize(letters: &str) -> HashMap<char, u8> { | |
let mut map = HashMap::new(); | |
for c in letters.chars() { | |
*map.entry(c).or_default() += 1; | |
} | |
map | |
} | |
fn is_token_subset(big: &HashMap<char, u8>, small: &HashMap<char, u8>) -> bool { | |
for (c, count) in small { | |
match big.get(c) { | |
Some(big_count) => { | |
if big_count < count { | |
return false; | |
} | |
} | |
None => return false, | |
}; | |
} | |
true | |
} | |
fn solve(search: &str) -> io::Result<Vec<String>> { | |
let mut solutions = Vec::new(); | |
let search = tokenize(search); | |
let file = File::open("dictionary.txt")?; | |
let reader = BufReader::new(file); | |
for line in reader.lines() { | |
let word = line?; | |
let tokens = tokenize(&word); | |
if is_token_subset(&search, &tokens) { | |
solutions.push(word); | |
} | |
} | |
solutions.sort_by(|a, b| a.len().partial_cmp(&b.len()).unwrap()); | |
Ok(solutions) | |
} | |
fn main() -> io::Result<()> { | |
let letters = match env::args().nth(1) { | |
Some(s) => s.to_lowercase(), | |
None => { | |
eprintln!("letters are required"); | |
process::exit(1); | |
} | |
}; | |
let solutions = solve(&letters)?; | |
for word in solutions.iter().rev().take(10) { | |
println!("{}: {}", word.len(), word); | |
} | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment