Created
March 2, 2017 14:08
-
-
Save nsmaciej/b584bf4ac689dd49403fb9a636283a2a to your computer and use it in GitHub Desktop.
Scrabble solver in Rust
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::io::{self, BufReader}; | |
use std::fs::File; | |
use std::cmp::Ord; | |
use std::io::prelude::*; | |
fn main() { | |
// Read the input | |
let mut word = String::new(); | |
print!("Enter your letters: "); | |
io::stdout().flush().unwrap(); | |
io::stdin().read_line(&mut word).expect("could not read stdin"); | |
// Sort the input word | |
let mut word: Vec<_> = word.trim().chars().collect(); | |
word.sort(); | |
// Read the file | |
let mut answers = Vec::new(); | |
let file = File::open("dictionary.txt").expect("could not read dictionary"); | |
'main: for check in BufReader::new(file).lines().map(Result::unwrap) { | |
let mut at = 0; | |
let mut cs: Vec<_> = check.chars().collect(); | |
cs.sort(); | |
'next_letter: for c in cs { | |
// We must have enough letters, since sorted just seek forward | |
while at < word.len() && word[at] <= c { | |
at += 1; | |
if word[at - 1] == c { | |
continue 'next_letter; | |
} | |
} | |
// We didn't hit next_letter for all letters, next word | |
continue 'main; | |
} | |
answers.push(check); | |
} | |
// Sort by length and output first 10 | |
println!("\nHere are the top 10 suggestions:\n"); | |
answers.sort_by(|a, b| a.len().cmp(&b.len()).reverse()); | |
for answer in answers.iter().take(10) { | |
println!("{}", answer); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment