Skip to content

Instantly share code, notes, and snippets.

@huseyinyilmaz
Created October 28, 2019 05:39
Show Gist options
  • Save huseyinyilmaz/9b16466f8ad4d69aa840ce7460482715 to your computer and use it in GitHub Desktop.
Save huseyinyilmaz/9b16466f8ad4d69aa840ce7460482715 to your computer and use it in GitHub Desktop.
rust experiments
/*
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded.
For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.
You can assume that the messages are decodable. For example, '001' is not allowed.
*/
use std::collections::HashMap;
use std::rc;
fn count_times<'a>(msg: &'a str, cache: &'a HashMap<&'a str, i32>) -> i32 {
match cache.get(msg) {
Some(result) => *result,
None => {
let len = msg.len();
let result = match len {
0 => 1,
1 => if &msg[..1] == "0" { 0 } else { 1 },
_ => {
let mut total = 0;
let mut val: i32 = msg[..1].parse().unwrap();
if val > 0 {
total += count_times(&msg[1..], &cache);
}
val = msg[..2].parse().unwrap();
if 0 < val && val <= 26 {
total += count_times(&msg[2..], &cache);
}
total
}
};
cache.clone().insert(msg, result);
result
}
}
}
fn main() {
let msg = String::from("111");
let cache = rc::Rc::new(HashMap::new());
println!("{:?}", count_times(&msg, &cache));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment