Run-length encoding: Difference between revisions

Content added Content deleted
m (→‎{{header|Ruby}}: alternate solutino)
Line 877: Line 877:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>def encode(s)
<lang ruby>def encode(string)
s.scan(/(.)(\1*)/).collect do |matchgroups|
string.scan(/(.)(\1*)/).collect do |matchgroups|
char, repeat = matchgroups
char, repeat = matchgroups
[char, 1 + repeat.length]
[char, 1 + repeat.length]
Line 884: Line 884:
end
end


def decode(e)
def decode(encoding)
e.inject("") do |decoded, pair|
encoding.inject("") do |decoding, pair|
char, length = pair
char, length = pair
decoded << char * length
decoding << char * length
end
end
end
end


orig = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
orig = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
encoded = encode(orig) # => [["W", 12], ["B", 1], ["W", 12], ["B", 3], ["W", 24], ["B", 1], ["W", 14]]
enc = encode(orig) # => [["W", 12], ["B", 1], ["W", 12], ["B", 3], ["W", 24], ["B", 1], ["W", 14]]
decoded = decode(encoded)
dec = decode(enc)
puts "success!" if decoded == orig</lang>
puts "success!" if dec == orig</lang>

This usage also seems to be idiomatic, and perhaps less cryptic:
<lang ruby>def encode(string)
encoding = []
for char, repeat in string.scan(/(.)(\1*)/)
encoding << [char, 1 + repeat.length]
end
encoding
end

def decode(encoding)
decoding = ""
for char, length in encoding
decoding << char * length
end
decoding
end</lang>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==