Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Exercism: Armstrong Numbers (Ruby)

Exercism: Armstrong Numbers (Ruby)

A presentation outlining my solution to the Exercism Armstrong Numbers problem in Ruby (https://exercism.io/tracks/ruby/exercises/armstrong-numbers).

Presented at the Sydney Ruby on Rails meetup on 10 September 2019.

Presentation slide deck markdown and speaker notes (useable in Deckset 2):
https://github.com/paulfioravanti/presentations/tree/master/exercism_ruby_armstrong_numbers

Paul Fioravanti

September 10, 2019
Tweet

More Decks by Paul Fioravanti

Other Decks in Programming

Transcript

  1. Armstrong Numbers ✅ 153 = 1^3 + 5^3 + 3^3

    = 153 ❌ 154 != 1^3 + 5^3 + 4^3 = 190
  2. Armstrong Numbers ! Get the number of digits ! Calculate

    the power of each digit ! Sum all the powers
  3. Sum Powers module ArmstrongNumbers module_function def include?(number) sum = number

    .digits .then(&method(:sum_powers)) sum == number end end
  4. Sum Powers module ArmstrongNumbers module_function # ... def sum_powers(digits) digits

    .each .with_object(digits.length) end private_class_method :sum_powers end
  5. Sum Powers module ArmstrongNumbers module_function # ... def sum_powers(digits) digits

    .each .with_object(digits.length) .sum(&method(:power)) end private_class_method :sum_powers end
  6. Calculate Power of Each Digit module ArmstrongNumbers module_function # ...

    def power((digit, length)) digit**length end private_class_method :power end
  7. module ArmstrongNumbers module_function def include?(number) sum = number .digits .then(&method(:sum_powers))

    sum == number end def sum_powers(digits) digits .each .with_object(digits.length) .sum(&method(:power)) end private_class_method :sum_powers def power((digit, length)) digit**length end private_class_method :power end
  8. module ArmstrongNumbers module_function def include?(number) digits = number.digits length =

    digits.length number == digits.sum { |digit| digit**length } end end
  9. BONUS FACTOIDS! ! Number of Armstrong numbers is finite !

    Only 88 Armstrong numbers in Base 10