Skip to content

Instantly share code, notes, and snippets.

@fcracker79
Created June 29, 2019 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcracker79/763a45d7d6d097c6af76d6057a34eef9 to your computer and use it in GitHub Desktop.
Save fcracker79/763a45d7d6d097c6af76d6057a34eef9 to your computer and use it in GitHub Desktop.
RustHero Rustlab Florence 2019
use std::str;
struct ReadLoud<'a> {
current_element: Option<u32>,
numbers_iterator: str::Chars<'a>,
next_elements: Vec<u32>
}
impl <'a> ReadLoud<'a> {
fn new(number: &str) -> ReadLoud {
ReadLoud{current_element: None, numbers_iterator: number.chars(), next_elements: Vec::new()}
}
}
impl <'a> Iterator for ReadLoud<'a> {
type Item = u32;
fn next(&mut self) -> Option<u32> {
match self.next_elements.pop() {
Some(x) => Some(x),
None => {
let cur_element = match self.current_element {
Some(x) => {
Some(x)
}
None => {
self.numbers_iterator.next()?.to_digit(10)
}
};
self.current_element = None;
match cur_element {
None => {
None
},
Some(x) => {
let mut counter = 1;
loop {
let c_char = self.numbers_iterator.next();
if let None = c_char {
break;
}
let c : Option<u32> = c_char?.to_digit(10);
if let None::<u32> = c {
break;
}
if c == Some(x) {
counter += 1;
} else {
self.next_elements.push(x);
self.current_element = c;
return Some(counter);
}
}
self.next_elements.push(x);
return Some(counter);
}
}
}
}
}
}
fn read_loud(val: &str) -> String {
return ReadLoud::new(val).map(|x| x.to_string()).collect::<Vec<String>>().join("");
}
fn main() {
println!("Hello world");
}
#[test]
fn test1() {
assert_eq!("11", read_loud("1"));
}
#[test]
fn test12() {
assert_eq!("1112", read_loud("12"));
}
#[test]
fn test31() {
assert_eq!("1311", read_loud("31"));
}
#[test]
fn test3211() {
assert_eq!("131221", read_loud("3211"));
}
#[test]
fn test111223() {
assert_eq!("312213", read_loud("111223"));
}
#[test]
fn test_40_times() {
let mut x = String::from("22164224441");
for _ in 0..40 {
x = read_loud(&x);
}
assert_eq!(453420, x.chars().count());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment