24 lines
722 B
Mojo
24 lines
722 B
Mojo
# probe: run-length encoding a string
|
|
# status: the expected output is Programming+'s interpreter's prediction; corpus.py verify confirms or refutes it on godbolt
|
|
# expect-stdout: aaabccdddd -> 3a1b2c4d
|
|
# expect-stdout: abc -> 1a1b1c
|
|
# expect-stdout: ->
|
|
# expect-stdout: zzzzzzzzzz -> 10z
|
|
def encode(s: String) -> String:
|
|
var out = String("")
|
|
var n = s.count_codepoints()
|
|
var i = 0
|
|
while i < n:
|
|
var c = String(s[codepoint=i])
|
|
var run = 1
|
|
while i + run < n and String(s[codepoint=i + run]) == c:
|
|
run += 1
|
|
out += String(run) + c
|
|
i += run
|
|
return out
|
|
|
|
|
|
def main():
|
|
for s in ["aaabccdddd", "abc", "", "zzzzzzzzzz"]:
|
|
print(s, "->", encode(s))
|