diff --git a/solutions/rust/run-length-encoding/4/Cargo.toml b/solutions/rust/run-length-encoding/4/Cargo.toml new file mode 100644 index 0000000..838424e --- /dev/null +++ b/solutions/rust/run-length-encoding/4/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "run_length_encoding" +version = "0.1.0" +edition = "2024" + +# Not all libraries from crates.io are available in Exercism's test runner. +# The full list of available libraries is here: +# https://github.com/exercism/rust-test-runner/blob/main/local-registry/Cargo.toml +[dependencies] diff --git a/solutions/rust/run-length-encoding/4/src/lib.rs b/solutions/rust/run-length-encoding/4/src/lib.rs new file mode 100644 index 0000000..4966f69 --- /dev/null +++ b/solutions/rust/run-length-encoding/4/src/lib.rs @@ -0,0 +1,57 @@ +#[allow(dead_code)] +pub fn encode(source: &str) -> String { + let mut encoded_str = String::new(); + if source.is_empty() {return encoded_str} + let chars_list:Vec = source.chars().collect(); + let list_len = chars_list.len(); + let mut prev_ch:char = chars_list[0]; + let mut count:u32 = 1; + for i in 1..=list_len { + let ch = if i < list_len { + chars_list[i] + }else { + '0' + }; + if prev_ch == ch { + count += 1; + }else { + if count > 1 { + let count_ch = count.to_string(); + encoded_str.push_str(&count_ch); + } + encoded_str.push(prev_ch); + count = 1; + prev_ch = ch; + } + } + encoded_str +} + +#[allow(dead_code)] +pub fn decode(source: &str) -> String { + let mut decoded_str = String::new(); + let chars_list:Vec = source.chars().collect(); + let mut i= 0usize; + while i < chars_list.len() { + let ch = chars_list[i]; + if ch.is_ascii_digit() { + let mut count = String::new(); + get_letter_count(&mut i, &chars_list, &mut count); + let mut repeated_str = chars_list[i].to_string(); + repeated_str = repeated_str.repeat(count.parse::().unwrap()); + decoded_str.push_str(&repeated_str); + }else { + decoded_str.push(ch); + } + i += 1 + } + decoded_str +} + +fn get_letter_count(index:&mut usize, list:&Vec, count:&mut String) { + if let Some(_ch) = list[*index].to_digit(10) { + count.push(list[*index]); + *index += 1; + get_letter_count(index, list, count); + } +} \ No newline at end of file