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");
}
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.
Proposed solution
```rust
pub fn run_length_encode(input: &str) -> String {
let mut result = String::new();
if input.is_empty() {
return result;
}
let mut chars = input.chars().peekable();
while let Some(current_char) = chars.next() {
let mut count = 1;
while chars.peek() == Some(¤t_char) {
chars.next();
count += 1;
}
result.push(current_char);
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