{{announcement.body}}
{{announcement.title}}

Day 6 of 30 Ruby Coding Challenge: Factorial Numbers Ugly Version

DZone 's Guide to

Day 6 of 30 Ruby Coding Challenge: Factorial Numbers Ugly Version

Day 6 of 30 - Ruby Coding Challenges in 30 Days. We're going to explore how to calculate Factorial Numbers in Ruby. This will be the ugly version that will be refactored later

· Web Dev Zone ·
Free Resource

Hey folks!

In today’s post, which is the written version of the Youtube video, we’ll explore how to calculate Factorial Numbers in Ruby. I know that you have heard about that before, but just a refresh:

Fancy Factorial Definition

The factorial of a number N is the product of all positive integers less then or equal to N

We indicate a factorial with an exclamation mark, 5! For example,

Real-life:

Factorial of 5! is 5*4*3*2*1=120

which gives us the following pattern

Factorial of 5! is 5*(5-1)*(5-2)*(5-3)*(5-4)

a little bit more generic:

Factorial of N! is N*(N-1)*(N-2)**…**1

Great! We’re on the same page.

It’s time to code!

Algorithm Version 1... As Usual, Ugly

As usual, we’ll take the following steps:

  • Problem definition.
  • First algorithm version to get the job done, which usually is ugly.
  • Later, we’ll refactor the code a little bit more.
  • Then, we’ll create the final version, which should have a decent code design :).
Ruby
 


The code is pretty simple

  • We receive a number N (let’s say 5).
  • We create a while loop, going from 5 to 1.
  • For each iteration, we decrement the argument number until it reaches 1.
  • For each iteration, we multiply the previous result with the current number - 1, following the Factorial pattern.

Why does this code is not that great?

  • We’re mutating (fancy word for changing) the argument number.
  • We have to control the loop by ourselves, which is not that readable.
  • It’s too complex for something that should be simpler.

However, the goal was reached! It gets the job done.

In the next video, we’ll explore a version a lit bit more readable, therefore, more maintainable and beautiful :)


Don’t forget to keep in touch and say hi Alex

Twitter Youtube Instagram Linkedin GitHub

Topics:
algorithm, algorithm analysis, coding, functional programing, programmer, programming, rails, ruby, tutorial, tutorial for beginners

Published at DZone with permission of Alexandre Gama . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}