Tuesday, November 4, 2014

Using Scala Recursion Functions For Permutation Calculation

Permutation is an ordered combination - how many possible ordered combination.

There are 2 types of Permutation:


  1. Permutation with Repeat is Allowed

    Permutation Lock is an example of Repeat Allowed.

    There are 10 numbers to choose from (0,1,...9) and we choose 3 of them.

    10 x 10 x 10 = 1000 permutation


    Formula: nwhere n is the number of things to choose from, and r 
    is number of times
  2. Permutation with No Repeat



    A good example is lottery which number can not be repeat.

    There are 3 numbers to choose from (1,2 and 3) and we choose 3 of them.

    3 x 2 x 1 = 6 permutation

    Formula: Without repetition our choices get reduced each time.

But how do we write that mathematically? Answer: we use the "factorial function".
I am going to use recursion method to write factorial function. This program accepts 2 integer inputs (Number of things to choose from and Number of times to choose) and calculate how many permutation (possible combination) with not repeat.

object Permutations {
  def main(args: Array[String]) {
    print("How many lottery number? ")
    val num1 = readInt()
    println()
    print("How many lottery  number to pick? ")
    val num2 = readInt()
    println("Total Permutation: " + factorial(num1,num2).toString)
  }
  
  def factorial(x: BigInt, y: BigInt) : BigInt = {
    if (y > 1)
      x * factorial( x - 1, y - 1)
    else
      x
  }
}








  1. Tips: Remember to has exist call on recursive function to avoid unstopped loop


No comments:

Post a Comment