Skip to content

Instantly share code, notes, and snippets.

@epitron
Last active December 30, 2015 01:49
Show Gist options
  • Save epitron/7758166 to your computer and use it in GitHub Desktop.
Save epitron/7758166 to your computer and use it in GitHub Desktop.
Run-length encoding
def rle_regexp(s)
s.scan(/(.)(\1*)/).map {|c, extra| [c, extra.size+1] }
end
def rle_each_char(s)
result = []
last = nil
count = 0
s.each_char do |c|
if c != last and last != nil
result << [last, count]
count = 0
end
last = c
count += 1
end
result << [last, count] if count > 0
result
end
def rle_each_cons(s)
result = []
count = 0
(s.chars + [nil]).each_cons(2) do |a,b|
count += 1
if a != b
result << [a, count]
count = 0
end
end
result
end
#################################################################################
require 'epitools'
benchmarks = {
"Very repeated string" => "a"*50000 + "b"*20000 + "c"*9000,
"No repeats" => "abc"*50000
}
benchmarks.each do |name, str|
puts "##### #{name} ##################################"
bench(
10,
rle_regexp: proc { rle_regexp(str) },
rle_each_char: proc { rle_each_char(str) },
rle_each_cons: proc { rle_each_cons(str) }
)
end
##### Very repeated string ##################################
user system total real
rle_regexp 0.020000 0.000000 0.020000 ( 0.029349)
rle_each_char 0.190000 0.000000 0.190000 ( 0.193324)
rle_each_cons 0.370000 0.010000 0.380000 ( 0.373018)
##### No repeats ##################################
user system total real
rle_regexp 1.410000 0.000000 1.410000 ( 1.420607)
rle_each_char 1.050000 0.000000 1.050000 ( 1.074731)
rle_each_cons 0.890000 0.010000 0.900000 ( 0.905797)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment