Skip to content

Instantly share code, notes, and snippets.

@mtimkovich
Created August 26, 2023 08:26
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 mtimkovich/75beab092b697ef07cb1526cf317b185 to your computer and use it in GitHub Desktop.
Save mtimkovich/75beab092b697ef07cb1526cf317b185 to your computer and use it in GitHub Desktop.
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