-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.rs
168 lines (153 loc) · 4.78 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
use std::collections::HashMap;
use std::env::args;
use std::fmt::{self, Display, Formatter};
use std::fs::File;
use std::io::{self, BufRead, BufWriter, StdoutLock, Write};
use std::path::Path;
type Dictionary = HashMap<Vec<u8>, Vec<String>, ahash::RandomState>;
#[derive(Debug, Copy, Clone)]
enum WordOrDigit<'a> {
Word(&'a str),
Digit(u8),
}
impl Display for WordOrDigit<'_> {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
WordOrDigit::Word(s) => s.fmt(formatter),
WordOrDigit::Digit(d) => d.fmt(formatter),
}
}
}
#[derive(PartialEq, Eq)]
enum ResultsOption {
Print,
Count(usize),
}
/// Port of Peter Norvig's Lisp solution to the Prechelt phone-encoding problem.
///
/// Even though this is intended as a port, it deviates quite a bit from it
/// due to the very different natures of Lisp and Rust.
fn main() -> io::Result<()> {
// drop itself from args
let mut args = args().skip(1);
let res_opt = args.next().unwrap_or_else(|| "".to_string());
let mut results_opt = match res_opt.as_ref() {
"print" => ResultsOption::Print,
"count" => ResultsOption::Count(0),
_ => panic!("Bad first argument (expected 'print' or 'count')"),
};
let words_file = args.next().unwrap_or_else(|| "tests/words.txt".into());
let input_file = args.next().unwrap_or_else(|| "tests/numbers.txt".into());
let dict = load_dict(words_file)?;
let stdout = io::stdout();
let mut writer = BufWriter::new(stdout.lock());
for line in read_lines(input_file)? {
let num = line?;
let digits: Vec<u8> = num.chars()
.filter(char::is_ascii_digit)
.map(|ch| ch as u8)
.collect();
find_translations(&mut results_opt, &num, &digits, &mut Vec::new(), &dict, &mut writer)?;
}
if let ResultsOption::Count(counter) = results_opt {
println!("{}", counter);
}
Ok(())
}
fn find_translations<'a>(
results_opt: &mut ResultsOption,
num: &str,
digits: &[u8],
words: &mut Vec<WordOrDigit<'a>>,
dict: &'a Dictionary,
writer: &mut BufWriter<StdoutLock>,
) -> io::Result<()> {
if digits.is_empty() {
return handle_solution(results_opt, num, words, writer);
}
let mut found_word = false;
for i in 0..digits.len() {
let (key, rest_of_digits) = digits.split_at(i + 1);
if let Some(found_words) = dict.get(key) {
for word in found_words {
found_word = true;
words.push(WordOrDigit::Word(word));
find_translations(results_opt, num, rest_of_digits, words, dict, writer)?;
words.pop();
}
}
}
if found_word {
return Ok(());
}
let last_is_digit = matches!(words.last(), Some(WordOrDigit::Digit(..)));
if !last_is_digit {
let digit = digits[0] - b'0';
words.push(WordOrDigit::Digit(digit));
find_translations(results_opt, num, &digits[1..], words, dict, writer)?;
words.pop();
}
Ok(())
}
fn handle_solution(
results_opt: &mut ResultsOption,
num: &str,
words: &[WordOrDigit<'_>],
writer: &mut BufWriter<StdoutLock>,
) -> io::Result<()> {
if let ResultsOption::Count(counter) = results_opt {
*counter += 1;
return Ok(())
}
write!(writer, "{}:", num)?;
if words.is_empty() {
writeln!(writer)?;
return Ok(());
}
for word in words {
write!(writer, " {}", word)?;
}
writeln!(writer)?;
Ok(())
}
fn load_dict(words_file: String) -> io::Result<Dictionary> {
let mut dict: Dictionary = HashMap::with_capacity_and_hasher(
100,
ahash::RandomState::default());
for line in read_lines(words_file)? {
let word = line?;
let key = word_to_number(&word);
let words = dict.entry(key).or_default();
words.push(word);
}
Ok(dict)
}
// The output is wrapped in a Result to allow matching on errors
// Returns an Iterator to the Reader of the lines of the file.
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>, {
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
fn word_to_number(word: &str) -> Vec<u8> {
word.chars()
.filter(char::is_ascii_alphabetic)
.map(char_to_digit)
.map(|d| d + b'0')
.collect()
}
fn char_to_digit(ch: char) -> u8 {
match ch.to_ascii_lowercase() {
'e' => 0,
'j' | 'n' | 'q' => 1,
'r' | 'w' | 'x' => 2,
'd' | 's' | 'y' => 3,
'f' | 't' => 4,
'a' | 'm' => 5,
'c' | 'i' | 'v' => 6,
'b' | 'k' | 'u' => 7,
'l' | 'o' | 'p' => 8,
'g' | 'h' | 'z' => 9,
_ => panic!("invalid input: not a digit: {}", ch)
}
}