Skip to content

Instantly share code, notes, and snippets.

@kaityo256
Created September 26, 2017 00:58
Show Gist options
  • Save kaityo256/9c2add14cc908b5d94d32e3be069e56c to your computer and use it in GitHub Desktop.
Save kaityo256/9c2add14cc908b5d94d32e3be069e56c to your computer and use it in GitHub Desktop.
Convert string so that 0<->9, 1<->8, ..., and 4<->5.
require 'benchmark'
# Convert string so that 0<->9, 1<->8, ..., and 4<->5.
# For example, from "8253593637" to "1746406362"
def use_each_char(input)
input.each do |s|
r = "0"*s.length
s.each_char.with_index do |c,i|
r[i] = (105 - c.ord).chr
end
end
end
def use_each_byte(input)
input.each do |s|
r = "0"*s.length
s.each_byte.with_index do |c,i|
r[i] = (105 - c).chr
end
end
end
def use_map_join(input)
input.each do |s|
r = s.each_byte.to_a.map{|v| (105 - v).chr}.join("")
end
end
srand(1)
input = Array.new(100) do
s = ""
10000.times do
s << (rand*10).to_i.to_s
end
s
end
r1 = Benchmark.realtime do
use_each_char(input)
end
r2 = Benchmark.realtime do
use_each_byte(input)
end
r3 = Benchmark.realtime do
use_map_join(input)
end
puts "each_char #{r1} [sec]" # => each_char 0.8496029999805614 [sec]
puts "each_byte #{r2} [sec]" # => each_byte 0.7626579999923706 [sec]
puts "map_join #{r3} [sec]" # => map_join 0.2027799999341368 [sec]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment