Created
November 29, 2021 16:45
-
-
Save wperron/0e1cc6c00fef7e92dba85782407e85af to your computer and use it in GitHub Desktop.
Find all permutations of letters given a phone number
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 lazy_static::lazy_static; | |
use std::collections::HashMap; | |
lazy_static! { | |
static ref NUM_MAP: HashMap<char, Vec<char>> = { | |
let mut m = HashMap::new(); | |
m.insert('2', vec!['a', 'b', 'c']); | |
m.insert('3', vec!['d', 'e', 'f']); | |
m.insert('4', vec!['g', 'h', 'i']); | |
m.insert('5', vec!['j', 'k', 'l']); | |
m.insert('6', vec!['m', 'n', 'o']); | |
m.insert('7', vec!['p', 'q', 'r', 's']); | |
m.insert('8', vec!['t', 'u', 'v']); | |
m.insert('9', vec!['w', 'x', 'y', 'z']); | |
m | |
}; | |
} | |
fn main() { | |
println!("{:?}", phone_letter(String::from("23"))) | |
} | |
fn phone_letter(num: String) -> Vec<String> { | |
let mut permuts = vec![String::from("")]; | |
for c in num.chars() { | |
let mut tmp: Vec<String> = vec![]; | |
for p in permuts.into_iter() { | |
let options = NUM_MAP.get(&c).map_or(vec![], |v| v.to_owned()); | |
for i in options { | |
let mut copy = p.clone(); | |
copy.push(i); | |
tmp.push(copy); | |
} | |
} | |
permuts = tmp; | |
} | |
permuts | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment