Skip to content

Instantly share code, notes, and snippets.

@saxxi
Created August 16, 2015 11:29
Show Gist options
  • Select an option

  • Save saxxi/6ca18bec12f7aa58b611 to your computer and use it in GitHub Desktop.

Select an option

Save saxxi/6ca18bec12f7aa58b611 to your computer and use it in GitHub Desktop.

Revisions

  1. saxxi created this gist Aug 16, 2015.
    65 changes: 65 additions & 0 deletions sum_digits.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,65 @@
    # Sum all the digits

    # Write a program that takes a positive number as an input.
    # The program should take every single digit of this number,
    # and sum them until only a 1 digit number is left.

    # Example input: 31337

    # Output: 8 (because 3+1+3+3+7=17 and 1+7=8)

    # Please add a benchmark for your solution.

    # Usage
    # > SumDigit.run 912931241291293124129129312412

    require 'inline'

    class SumDigit

    def self.run_with_each_char(number) # 1st
    while number > 9 do
    sum = 0
    number.to_s.each_char { |c| sum += c.to_i }
    number = sum
    end
    number
    end

    def self.run_with_split(number) # 2nd
    while number > 9 do
    sum = 0
    number.to_s.split('').each { |c| sum += c.to_i }
    number = sum
    end
    number
    end

    def self.run_with_mod(number) # 3rd
    while number > 9 do
    sum = 0
    while number > 0 do
    sum += number % 10
    number /= 10
    end

    number = sum
    end
    number
    end

    class << self
    alias :run :run_with_each_char
    end

    end

    require 'benchmark'

    test_number = 912923124541291293130241291290332124453534412745985591342932112041291209312411529720129312412349082109120942834938750395063473621032432480357565234

    Benchmark.bm do |x|
    x.report { SumDigit.run_with_each_char test_number }
    x.report { SumDigit.run_with_split test_number }
    x.report { SumDigit.run_with_mod test_number }
    end