// ============================================================================ // Run-length encoding — compress repeated characters // ============================================================================ // // "aaabbc" -> "a3b2c1". Decoding walks the encoded string reading a letter // followed by its digit-run count. Demonstrates per-char scanning, run // counting, and reconstructing a string by repetition. // // Run: soma run run_length.cell --signal encode "aaabbbcccd" cell RunLength { face { signal encode(s: String) -> String signal decode(s: String) -> String } on encode(s: String) { if len(s) == 0 { return "" } let out = "" let prev = s[0] let count = 1 for i in range(1, len(s)) { let c = s[i] if c == prev { count = count + 1 } else { out = out + prev + to_string(count) prev = c count = 1 } } return out + prev + to_string(count) } on decode(s: String) { let out = "" let i = 0 let n = len(s) while i < n { let ch = s[i] i = i + 1 // read the digit run that follows let num = "" while i < n && s[i] >= "0" && s[i] <= "9" { num = num + s[i] i = i + 1 } let reps = to_int(num) for j in range(0, reps) { out = out + ch } } return out } } cell test RunLengthTest { rules { assert encode("aaabbbcccd") == "a3b3c3d1" assert encode("") == "" assert encode("x") == "x1" assert decode("a3b3c3d1") == "aaabbbcccd" assert decode(encode("wwwwwwwwwwaa")) == "wwwwwwwwwwaa" } }