diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..6797bed --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,36 @@ +use clap::{Parser, Subcommand}; + +#[derive(Parser, Debug)] +#[command(version, about, long_about = None)] +pub(crate) struct Args { + #[command(subcommand)] + pub(crate) command: Commands, +} + +#[derive(Subcommand, Debug)] +pub(crate) enum Commands { + /// Tools to solve the wordle + Solve { + /// Contains these letters + #[arg(short, long)] + r#in: Option, + + /// Has these position, as a regex, use ^start, end$ and wor.d extensively + #[arg(short, long)] + pos: Option, + + /// Doesnt contains these letters + #[arg(short, long)] + out: Option, + }, + /// Tools to calculate best words for a wordle + Calculate { + /// Number of guesses targetted + #[arg(short, long)] + number: Option, + + /// How many branches to try, warning exponential solving time + #[arg(short, long, default_value_t = 5)] + depth: usize, + }, +} diff --git a/src/main.rs b/src/main.rs index 413fda3..7157aa0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,291 +3,86 @@ // Letter frequency as weight // find better weight // #![allow(dead_code)] +use crate::cli::Args; +use crate::solver::backtrack_best; +use crate::word_representation::TotalScore; use clap::Parser; use regex::Regex; -use std::fmt::Display; -#[derive(Parser, Debug)] -#[command(version, about, long_about = None)] -struct Args { - /// Number of guesses targetted - #[arg(short, long)] - number: Option, +mod cli; +mod solver; +mod word_representation; - /// Contains these letters - #[arg(short, long)] - r#in: Option, - - /// Has these position, as a regex, use ^start, end$ and wor.d extensively - #[arg(short, long)] - pos: Option, - - /// Depth of the trying process - #[arg(short, long, default_value_t = 5)] - depth: usize, - - /// Doesnt contains these letters - #[arg(short, long)] - out: Option, -} - -#[derive(Debug, Eq, PartialEq, Clone)] -struct Word { - origin: String, - // hash: u64, - weight: isize, -} - -impl Word { - fn set_weight(&mut self, weights: &Weightlist) { - self.weight = 0; - let mut found = vec![]; - self.origin.chars().for_each(|c| { - if !found.contains(&c) { - self.weight += weights.getchar(c); - found.push(c); - } - }); - } -} -impl From<&str> for Word { - fn from(value: &str) -> Self { - Self { - origin: value.to_owned(), - weight: 0, - } - } -} - -impl Ord for Word { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.weight.cmp(&other.weight) - } -} -impl PartialOrd for Word { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -#[derive(Debug, Clone)] -struct Weightlist { - weights: Vec, -} - -impl Weightlist { - fn new() -> Self { - Self { - weights: vec![0; 26], - } - } - fn addweight(&mut self, c: char) { - self.weights[c as usize - 'a' as usize] += 1; - } - fn setweight(&mut self, c: char, val: isize) { - self.weights[c as usize - 'a' as usize] = val; - } - - #[allow(dead_code)] - fn getid(&self, id: usize) -> isize { - self.weights[id] - } - fn getchar(&self, c: char) -> isize { - self.weights[c as usize - 'a' as usize] - } - - fn remove_word(&mut self, guess: &Word) { - let mut found = vec![]; - for letter in guess.origin.chars() { - if !found.contains(&letter) { - self.setweight(letter, -200); - found.push(letter) - } - } - } -} - -fn load_words() -> Vec { - String::from_utf8_lossy(include_bytes!("../wordlists/final.txt")) - .split("\n") - .map(|s| s.into()) - .collect() -} -// fn read_list(path: &str) -> Vec { -// read_to_string(path) -// .unwrap() -// .split("\n") -// .map(|s| s.into()) -// .collect() -// } - -#[derive(Debug, Clone)] -struct Wordlist { - inner: Vec, -} - -impl Display for Wordlist { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let o = self - .inner - .iter() - .map(|w| w.origin.clone()) - .collect::>() - .join(", "); - write!(f, "{o}") - } -} -impl Wordlist { - fn new(inner: Vec) -> Self { - Self { inner } - } - - fn make_weights(&self) -> Weightlist { - let mut weights = Weightlist::new(); - self.inner.iter().for_each(|w| { - let mut found = Vec::new(); - w.origin.chars().for_each(|c| { - if !found.contains(&c) { - weights.addweight(c); - found.push(c); - } - }); - }); - weights - } - - fn sort(&mut self) { - self.inner.sort(); - } - - fn update_weights(&mut self, weights: &Weightlist) { - self.inner.iter_mut().for_each(|w| w.set_weight(weights)); - } - - fn guess(&self, arg: usize) -> Word { - self.inner.iter().nth_back(arg).unwrap().clone() - } -} - -#[derive(Default, Debug, Eq, PartialEq, Clone)] -struct TotalScore { - score: isize, - words: Vec, -} -impl TotalScore { - fn add(&mut self, mut best_implied_score: TotalScore) { - self.score += best_implied_score.score; - self.words.append(&mut best_implied_score.words); - } -} -impl Ord for TotalScore { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - match self.score.cmp(&other.score) { - std::cmp::Ordering::Equal => { - if let (Some(w1), Some(w2)) = (self.words.last(), other.words.last()) { - w1.cmp(w2) - } else { - std::cmp::Ordering::Equal - } - } - a => a, - } - } -} - -impl PartialOrd for TotalScore { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -fn backtrack_best( - origin_list: &Wordlist, - origin_weights: &Weightlist, - mut total_score: TotalScore, - letter_depth: usize, - guess_depth: usize, -) -> TotalScore { - if letter_depth == 0 { - TotalScore::default() - } else { - // println!("Starts new track: TS[{:?}]", &total_score); - // Sort original data - let mut list = origin_list.clone(); - let weights = origin_weights.clone(); - list.update_weights(&weights); - list.sort(); - - // Pick n bests word, backtrack their score and return the best of the best results - let mut list_guesses = Vec::new(); - for i in 0..guess_depth { - let guess = list.guess(i); - // println!("Guess: {:?}", guess); - let mut weights = origin_weights.clone(); - weights.remove_word(&guess); - // Backtrack the implied scores - let bb = backtrack_best( - &list, - &weights, - total_score.clone(), - letter_depth - 1, - guess_depth, - ); - let mut v = bb.words.clone(); - v.push(guess.clone()); - list_guesses.push(TotalScore { - score: bb.score + guess.weight, - words: v, - }); - } - list_guesses.sort(); - // println!("List guesses {:#?}", list_guesses); - let best_implied_score = list_guesses.last().unwrap().clone(); - // println!("best impl: {:?}", best_implied_score); - total_score.add(best_implied_score); - // println!("best added: {:?}", total_score); - total_score - } -} -fn main() { - let wl = Wordlist::new(load_words()); +fn main_dispatch(args: Args) { + let wl = word_representation::Wordlist::new(word_representation::load_words()); let weights = wl.make_weights(); - let args = Args::parse(); - if let Some(number) = args.number { - println!( - "Best {}: {:#?}", - number, - backtrack_best(&wl, &weights, TotalScore::default(), number, args.depth) - ); + match args.command { + cli::Commands::Solve { + r#in: contains, + pos, + out: not_contains, + } => { + dispatch_solve(wl, contains, pos, not_contains); + } + cli::Commands::Calculate { number, depth } => { + dispatch_calculate(wl, weights, number, depth); + } } - if let Some(with) = args.r#in { - let mut list = Wordlist::new( - wl.inner +} + +fn dispatch_solve( + wl: word_representation::Wordlist, + with: Option, + pos: Option, + without: Option, +) { + let mut list = word_representation::Wordlist::new(wl.inner); + if let Some(with) = with { + list = word_representation::Wordlist::new( + list.inner .into_iter() .filter(|w| with.chars().all(|c| w.origin.contains(c))) .collect(), ); - if let Some(without) = args.out { - list = Wordlist::new( - list.inner - .into_iter() - .filter(|w| without.chars().all(|c| !w.origin.contains(c))) - .collect(), - ); - } - - if let Some(pos) = args.pos { - list = Wordlist::new( - list.inner - .into_iter() - .filter(|w| { - let re = Regex::new(&pos).unwrap(); - re.is_match(&w.origin) - }) - .collect(), - ) - } - println!("{list}"); } + if let Some(without) = without { + list = word_representation::Wordlist::new( + list.inner + .into_iter() + .filter(|w| without.chars().all(|c| !w.origin.contains(c))) + .collect(), + ); + } + if let Some(pos) = pos { + list = word_representation::Wordlist::new( + list.inner + .into_iter() + .filter(|w| { + let re = Regex::new(&pos).unwrap(); + re.is_match(&w.origin) + }) + .collect(), + ) + } + println!("{list}"); +} + +fn dispatch_calculate( + wl: word_representation::Wordlist, + weights: word_representation::Weightlist, + number: Option, + depth: usize, +) { + let number = number.unwrap_or(3); + println!( + "Best {}: {:#?}", + number, + backtrack_best(&wl, &weights, TotalScore::default(), number, depth) + ); +} + +fn main() { + let args = Args::parse(); + main_dispatch(args); } diff --git a/src/solver.rs b/src/solver.rs new file mode 100644 index 0000000..b6e7338 --- /dev/null +++ b/src/solver.rs @@ -0,0 +1,50 @@ +use crate::word_representation; + +pub(crate) fn backtrack_best( + origin_list: &word_representation::Wordlist, + origin_weights: &word_representation::Weightlist, + mut total_score: word_representation::TotalScore, + letter_depth: usize, + guess_depth: usize, +) -> word_representation::TotalScore { + if letter_depth == 0 { + word_representation::TotalScore::default() + } else { + // println!("Starts new track: TS[{:?}]", &total_score); + // Sort original data + let mut list = origin_list.clone(); + let weights = origin_weights.clone(); + list.update_weights(&weights); + list.sort(); + + // Pick n bests word, backtrack their score and return the best of the best results + let mut list_guesses = Vec::new(); + for i in 0..guess_depth { + let guess = list.guess(i); + // println!("Guess: {:?}", guess); + let mut weights = origin_weights.clone(); + weights.remove_word(&guess); + // Backtrack the implied scores + let bb = backtrack_best( + &list, + &weights, + total_score.clone(), + letter_depth - 1, + guess_depth, + ); + let mut v = bb.words.clone(); + v.push(guess.clone()); + list_guesses.push(word_representation::TotalScore { + score: bb.score + guess.weight, + words: v, + }); + } + list_guesses.sort(); + // println!("List guesses {:#?}", list_guesses); + let best_implied_score = list_guesses.last().unwrap().clone(); + // println!("best impl: {:?}", best_implied_score); + total_score.add(best_implied_score); + // println!("best added: {:?}", total_score); + total_score + } +} diff --git a/src/word_representation.rs b/src/word_representation.rs new file mode 100644 index 0000000..b0394ca --- /dev/null +++ b/src/word_representation.rs @@ -0,0 +1,169 @@ +use std::fmt::Display; + +#[derive(Debug, Eq, PartialEq, Clone)] +pub(crate) struct Word { + pub(crate) origin: String, + // hash: u64, + pub(crate) weight: isize, +} + +impl Word { + pub(crate) fn set_weight(&mut self, weights: &Weightlist) { + self.weight = 0; + let mut found = vec![]; + self.origin.chars().for_each(|c| { + if !found.contains(&c) { + self.weight += weights.getchar(c); + found.push(c); + } + }); + } +} + +impl From<&str> for Word { + fn from(value: &str) -> Self { + Self { + origin: value.to_owned(), + weight: 0, + } + } +} + +impl Ord for Word { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.weight.cmp(&other.weight) + } +} + +impl PartialOrd for Word { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +#[derive(Debug, Clone)] +pub(crate) struct Weightlist { + pub(crate) weights: Vec, +} + +impl Weightlist { + pub(crate) fn new() -> Self { + Self { + weights: vec![0; 26], + } + } + pub(crate) fn addweight(&mut self, c: char) { + self.weights[c as usize - 'a' as usize] += 1; + } + pub(crate) fn setweight(&mut self, c: char, val: isize) { + self.weights[c as usize - 'a' as usize] = val; + } + + #[allow(dead_code)] + pub(crate) fn getid(&self, id: usize) -> isize { + self.weights[id] + } + pub(crate) fn getchar(&self, c: char) -> isize { + self.weights[c as usize - 'a' as usize] + } + + pub(crate) fn remove_word(&mut self, guess: &Word) { + let mut found = vec![]; + for letter in guess.origin.chars() { + if !found.contains(&letter) { + self.setweight(letter, -200); + found.push(letter) + } + } + } +} + +pub(crate) fn load_words() -> Vec { + String::from_utf8_lossy(include_bytes!("../wordlists/final.txt")) + .split("\n") + .map(|s| s.into()) + .collect() +} + +#[derive(Debug, Clone)] +pub(crate) struct Wordlist { + pub(crate) inner: Vec, +} + +impl Display for Wordlist { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let o = self + .inner + .iter() + .map(|w| w.origin.clone()) + .collect::>() + .join(", "); + write!(f, "{o}") + } +} + +impl Wordlist { + pub(crate) fn new(inner: Vec) -> Self { + Self { inner } + } + + pub(crate) fn make_weights(&self) -> Weightlist { + let mut weights = Weightlist::new(); + self.inner.iter().for_each(|w| { + let mut found = Vec::new(); + w.origin.chars().for_each(|c| { + if !found.contains(&c) { + weights.addweight(c); + found.push(c); + } + }); + }); + weights + } + + pub(crate) fn sort(&mut self) { + self.inner.sort(); + } + + pub(crate) fn update_weights(&mut self, weights: &Weightlist) { + self.inner.iter_mut().for_each(|w| w.set_weight(weights)); + } + + pub(crate) fn guess(&self, arg: usize) -> Word { + self.inner.iter().nth_back(arg).unwrap().clone() + } +} + +#[derive(Default, Debug, Eq, PartialEq, Clone)] +pub(crate) struct TotalScore { + pub(crate) score: isize, + pub(crate) words: Vec, +} + +impl TotalScore { + pub(crate) fn add(&mut self, mut best_implied_score: TotalScore) { + self.score += best_implied_score.score; + self.words.append(&mut best_implied_score.words); + } +} + +impl Ord for TotalScore { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + match self.score.cmp(&other.score) { + std::cmp::Ordering::Equal => { + if let (Some(w1), Some(w2)) = (self.words.last(), other.words.last()) { + w1.cmp(w2) + } else { + std::cmp::Ordering::Equal + } + } + a => a, + } + } +} + +impl PartialOrd for TotalScore { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +}