rs-01-rle
1.000
Challenge · difficulty 1/5
# Run-length encoding
Implement the library file **`src/lib.rs`** exposing:
```rust
pub fn run_length_encode(input: &str) -> String
```
Encode consecutive runs of the same character as `<char><count>`. A single character still
gets a count of `1`.
- `run_length_encode("aaabbc")` → `"a3b2c1"`
- `run_length_encode("")` → `""`
- `run_length_encode("abc")` → `"a1b1c1"`
Tests live in `tests/` and call it as `challenge::run_length_encode`.
tests/rle.rs
use challenge::run_length_encode;
#[test]
fn basic_runs() {
assert_eq!(run_length_encode("aaabbc"), "a3b2c1");
}
#[test]
fn empty() {
assert_eq!(run_length_encode(""), "");
}
#[test]
fn all_singles() {
assert_eq!(run_length_encode("abc"), "a1b1c1");
}
Proposed solution
```rust
pub fn run_length_encode(input: &str) -> String {
let mut result = String::new();
let mut chars = input.chars();
if let Some(mut current) = chars.next() {
let mut count = 1;
for c in chars {
if c == current {
count += 1;
} else {
result.push(current);
result.push_str(&count.to_string());
current = c;
count = 1;
}
}
result.push(current);
result.push_str(&count.to_string());
}
result
}
```Test output (stdout)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
running 3 tests
...
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s