Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active December 21, 2015 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/6245044 to your computer and use it in GitHub Desktop.
Save havenwood/6245044 to your computer and use it in GitHub Desktop.
Convert a Ruby Integer into an Array of digits.
##
# Looking at benchmark derivatives of:
# http://gistflow.com/posts/873-integer-to-array-of-digits-with-ruby
#
require 'benchmark'
require 'benchmark/ips'
module Test
class << self
def divmod(d)
base, last_digit = d.divmod(10)
digits = [last_digit]
while base > 9 do
base, last_digit = base.divmod(10)
digits = digits.insert(0, last_digit)
end
digits.insert(0, base)
end
def divmod_reverse(d)
digits = []
while d > 9 do
d, last_digit = d.divmod(10)
digits << last_digit
end
digits << d
digits.reverse
end
def mikdie(d)
digits = []
until d == 0 do
d, last_digit = d.divmod(10)
digits << last_digit
end
digits.reverse
end
def each_char_map(d)
d.to_s.each_char.map(&:to_i)
end
def chars_map(d)
d.to_s.chars.map(&:to_i)
end
def chars_map_bang(d)
d.to_s.chars.map!(&:to_i)
end
end
end
Benchmark.ips do |r|
N = 123_456_789_123_456_789_123_456_789
Test.methods(false).each do |method|
r.report(method.to_s) do
Test.send(method, N)
end
end
end
# >> Calculating -------------------------------------
# >> divmod 7915 i/100ms
# >> divmod_reverse 9702 i/100ms
# >> mikdie 9684 i/100ms
# >> each_char_map 9983 i/100ms
# >> chars_map 10446 i/100ms
# >> chars_map_bang 11363 i/100ms
# >> -------------------------------------------------
# >> divmod 105944.7 (±26.7%) i/s - 498645 in 5.034317s
# >> divmod_reverse 142615.2 (±41.0%) i/s - 591822 in 5.002818s
# >> mikdie 142368.9 (±40.8%) i/s - 600408 in 5.048888s
# >> each_char_map 128670.1 (±24.5%) i/s - 598980 in 5.015994s
# >> chars_map 137758.9 (±27.9%) i/s - 637206 in 5.051835s
# >> chars_map_bang 148910.0 (±23.9%) i/s - 693143 in 5.001251s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment