Skip to content

Instantly share code, notes, and snippets.

@Alex-Swann
Created March 20, 2016 20:07
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 Alex-Swann/766f7e540c02e0f8b7f2 to your computer and use it in GitHub Desktop.
Save Alex-Swann/766f7e540c02e0f8b7f2 to your computer and use it in GitHub Desktop.
Counts total number of increasing/decreasing numbers to powers of 10
require 'benchmark'
def total_nums x
return 0 if x == nil
return 1 if x == 0
1.upto(10 ** x).count do |i|
s = i.to_s.chars
t = s.sort
s == t || s == t.reverse
end
end
def total_nums2(x)
xf, nf, tf = (1..x).inject(1, :*), (1..9).inject(1, :*), (1..(x + 9)).inject(1, :*)
( ((x + 10) * tf) /xf/nf/10) + (tf/xf/nf) - (10 * x) - 1
end
Benchmark.bm do |x|
x.report { puts total_nums(6) }
x.report { puts total_nums2(6) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment