Initial upload
This commit is contained in:
34
julia/run-length-encoding/run-length-encoding.jl
Normal file
34
julia/run-length-encoding/run-length-encoding.jl
Normal file
@@ -0,0 +1,34 @@
|
||||
function encode(s)
|
||||
ch = nothing
|
||||
cnt = 1
|
||||
result = ""
|
||||
for c ∈ s
|
||||
if ch ≡ nothing
|
||||
ch = c
|
||||
continue
|
||||
end
|
||||
if ch == c
|
||||
cnt += 1
|
||||
else
|
||||
result *= cnt > 1 ? "$cnt$ch" : "$ch"
|
||||
ch = c
|
||||
cnt = 1
|
||||
end
|
||||
end
|
||||
if ch ≢ nothing
|
||||
result *= cnt > 1 ? "$cnt$ch" : "$ch"
|
||||
end
|
||||
result
|
||||
end
|
||||
|
||||
|
||||
|
||||
function decode(s)
|
||||
items = collect(eachmatch(r"(\d+)?(.)", s))
|
||||
result = ""
|
||||
for item ∈ items
|
||||
cnt = parse(Int, (item[1] ≡ nothing) ? "1" : item[1])
|
||||
result *= item[2]^cnt
|
||||
end
|
||||
result
|
||||
end
|
||||
Reference in New Issue
Block a user