Wednesday, February 8, 2012

Factorial and Fibonacci in Fantom



Here below a little program in Fantom that implements 2 classes (in fact, they are 3 + an extra utility Stopwatch class from my previous post http://carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.html). There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the Fibonacci and the Factorial algorithms in two ways, one Recursive (using recursion) and the other Imperative (using loops and states). The second class is just an instance class that does the same thing, but its there just to show the difference between static and instance classes, and finally the third one (which will not appear in other languages) is the Program class which has the static execution method "main".

You can also find 3 more little examples at the bottom. One prints out the Factorial's Series and Fibonacci's Series, the second one just shows a class that mixes both: static and instance members, and finally the third one that uses different return types (including java.math.BigInteger) for the Factorial method to compare the timing and result.

As with the previous posts, you can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you some more basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2011/01/new-series-factorial-and-fibonacci.html 


The Fiborial Program

// Factorial and Fibonacci in Fantom

using [java] com.carlosqt.util::Stopwatch
using [java] java.math::BigInteger

// static is not a valid class modifier
// Instanced Class
class StaticFiborial 
{
  // (Constant) Static Field  - Static fields must be const - this ensures thread safety  
  private const static Str className
  // Class/Static Constructor/Initializer
  // It is permissible to have multiple static initializers; they run in order of declaration
  static 
  {      
    className = "Static Constructor"  
    echo(className)  
  }
  // Static Method - Factorial Recursive
  static BigInteger factorialR(Int n)      
  {      
    if (n == 1)      
      return BigInteger.ONE  
    else      
      return BigInteger.valueOf(n).multiply(factorialR(n - 1))  
  }
  // Static Method - Factorial Imperative      
  static BigInteger factorialI(Int n)      
  {      
    BigInteger res := BigInteger.ONE  
    for (i := n; i >= 1; i--)      
    {                      
      res = res.multiply(BigInteger.valueOf(i))  
    }      
    return res  
  }
  // Static Method - Fibonacci Recursive      
  static Int fibonacciR(Int n)      
  {      
    if (n < 2)      
      return 1  
    else      
      return fibonacciR(n - 1) + fibonacciR(n - 2)  
  }      
  // Static Method - Fibonacci Imperative      
  static Int fibonacciI(Int n)      
  {                  
    Int pre := 1  
    Int cur := 1  
    Int tmp := 0   
    for (i := 2; i <= n; i++)  
    {      
      tmp = cur + pre  
      pre = cur  
      cur = tmp  
    }      
    return cur    
  }          
  // Class/Static Method - Benchmarking Algorithms      
  static Void benchmarkAlgorithm(Int algorithm, List values)      
  {                  
    Stopwatch timer := Stopwatch()  
    Int testValue := 0 
    BigInteger facTimeResult := BigInteger.ZERO  
    Int fibTimeResult := 0
    // "Switch" Flow Control Statement
    switch (algorithm)    
    {    
      case 1:    
        echo("\nFactorial Imperative:")    
        // "For" Loop Statement    
        for (i := 0; i < values.size; i++)    
        {                            
          testValue = values.get(i)    
          // Taking Time    
          timer.start()    
          facTimeResult = factorialI(testValue)    
          timer.stop()
          // Getting Time    
          echo(" ($testValue) = ${timer.getElapsed()}")    
        }
      case 2:    
        echo("\nFactorial Recursive:")    
        // "While" Loop Statement
        Int i := 0
        while (i < values.size)    
        {                            
          testValue = values.get(i)   
          // Taking Time    
          timer.start()    
          facTimeResult = factorialR(testValue)
          timer.stop()
          // Getting Time    
          echo(" ($testValue) = ${timer.getElapsed()}")    
          i++
        }    
      case 3:    
        echo("\nFibonacci Imperative:")    
        // "While" Loop Statement
        Int i := 0
        while (i < values.size)    
        {
          testValue = values.get(i)    
          // Taking Time    
          timer.start()    
          fibTimeResult = fibonacciI(testValue)    
          timer.stop()    
          // Getting Time    
          echo(" ($testValue) = ${timer.getElapsed()}")    
          i++    
        }    
      case 4:    
        echo("\nFibonacci Recursive:")      
        // "For" Loop Statement    
        for (i := 0; i < values.size; i++)    
        {    
          testValue = values.get(i)
          // Taking Time    
          timer.start()    
          fibTimeResult = fibonacciR(testValue)   
          timer.stop()   
          // Getting Time    
          echo(" ($testValue) = ${timer.getElapsed()}")    
        }    
        default:    
          echo("DONG!")    
    }                    
  }
}


// Instance Class      
class InstanceFiborial      
{      
  // Instance Field      
  private Str className  
  // Instance Constructor      
  new make()      
  {      
      this.className = "Instance Constructor"  
      echo(this.className)  
  }      
  // Instance Method - Factorial Recursive      
  BigInteger factorialR(Int n)      
  {      
      // Calling Static Method      
      return StaticFiborial.factorialR(n)  
  }      
  // Instance Method - Factorial Imperative      
  BigInteger factorialI(Int n)
  {      
      // Calling Static Method      
      return StaticFiborial.factorialI(n)      
  }      
  // Instance Method - Fibonacci Recursive  
  Int fibonacciR(Int n)  
  {      
      // Calling Static Method      
      return StaticFiborial.fibonacciR(n)  
  }      
  // Instance Method - Factorial Imperative      
  Int fibonacciI(Int n)  
  {      
      // Calling Static Method      
      return StaticFiborial.fibonacciI(n)  
  }      
}    

// Console Program  
public class FiborialApp    
{    
  public static Void main()    
  {
    echo("\nStatic Class")      
    // Calling Static Class and Methods  
    // No instantiation needed. Calling method directly from the class      
    echo("FacImp(5) = ${StaticFiborial.factorialI(5)}")  
    echo("FacRec(5) = ${StaticFiborial.factorialR(5)}")     
    echo("FibImp(11)= ${StaticFiborial.fibonacciI(11)}")      
    echo("FibRec(11)= ${StaticFiborial.fibonacciR(11)}")  
      
    echo("\nInstance Class")      
    // Calling Instance Class and Methods       
    // Need to instantiate before using. Calling method from instantiated object      
    InstanceFiborial ff := InstanceFiborial.make()  
    echo("FacImp(5) = ${ff.factorialI(5)}")  
    echo("FacRec(5) = ${ff.factorialR(5)}")  
    echo("FibImp(11)= ${ff.fibonacciI(11)}")  
    echo("FibRec(11)= ${ff.fibonacciR(11)}")  
      
    // Create a list of integer values to test  
    // From 5 to 50 by 5      
    Int[] values := Int[,]  
    for(i := 5; i <= 50; i += 5)
        values.add(i)
            
    // Benchmarking Fibonacci                           
    // 1 = Factorial Imperative                  
    StaticFiborial.benchmarkAlgorithm(1, values)  
    // 2 = Factorial Recursive      
    StaticFiborial.benchmarkAlgorithm(2, values)  
      
    // Benchmarking Factorial                  
    // 3 = Fibonacci Imperative      
    StaticFiborial.benchmarkAlgorithm(3, values)  
    // 4 = Fibonacci Recursive      
    StaticFiborial.benchmarkAlgorithm(4, values) 
    
    // Stop and exit      
    echo("Press any key to exit...")  
    console := Env.cur  
    userInput := console.in.readLine  
  }
}

And the Output is:




















































Printing the Factorial and Fibonacci Series
using [java] java.math::BigInteger    
using [java] java.lang::StringBuffer  
    
class Fiborial
{    
  // Using a StringBuffer as a list of string elements
  // because of the following compile error: 
  // Ambiguous call append(sys::Str) FiborialSeries.fan ... Fantom Problem
  // I had to use StringBuffer.apend(s, 0, s.length) instead of just StringBuffer.apend(CharSequence s) 
  static Str getFactorialSeries(Int n)    
  {    
    // Create the String that will hold the list    
    StringBuffer series := StringBuffer()  
    // We begin by concatenating the number you want to calculate    
    // in the following format: "!# ="    
    series.append("!", 0, "!".size)  
    series.append(n.toStr, 0, n.toStr.size)  
    series.append(" = ", 0, 3)
    // We iterate backwards through the elements of the series    
    for (i := n; i <= n && i > 0; i--)   
    {
      // and append it to the list    
      series.append(i.toStr, 0, i.toStr.size)
      if (i > 1)  
        series.append(" * ", 0, 3)  
      else     
        series.append(" = ", 0, 3)
    }  
    // Get the result from the Factorial Method    
    // and append it to the end of the list
    Str fac := factorial(n).toStr
    series.append(fac, 0, fac.size)    
    // return the list as a string    
    return series.toStr  
  }    
  
  // Using a StringBuffer as a list of string elements    
  static Str getFibonnaciSeries(Int n)    
  {    
    // Create the String that will hold the list    
    StringBuffer series := StringBuffer()    
    // We begin by concatenating the first 3 values which    
    // are always constant    
    series.append("0, 1, 1", 0, 7)  
    // Then we calculate the Fibonacci of each element    
    // and add append it to the list
    Str fib := ""
    for (i := 2; i <= n; i++)
    {    
      if (i < n)    
        series.append(", ", 0, 2)
      else    
        series.append(" = ", 0, 3)
      
      fib = fibonacci(i).toStr
      series.append(fib, 0, fib.size)  
    }    
    // return the list as a string    
    return series.toStr
  }    
  
  static BigInteger factorial(Int n)    
  {    
    if (n == 1)      
      return BigInteger.ONE
    else      
      return BigInteger.valueOf(n).multiply(factorial(n - 1))  
  }            
  
  static Int fibonacci(Int n)    
  {    
    if (n < 2)
      return 1  
    else      
      return fibonacci(n - 1) + fibonacci(n - 2)  
  }       
}    
  
// Console Program  
public class FiborialSeriesApp    
{    
  public static Void main()    
  {  
    // Printing Factorial Series    
    echo("")  
    echo(Fiborial.getFactorialSeries(5))   
    echo(Fiborial.getFactorialSeries(7)) 
    echo(Fiborial.getFactorialSeries(9)) 
    echo(Fiborial.getFactorialSeries(11)) 
    echo(Fiborial.getFactorialSeries(40))  
    // Printing Fibonacci Series    
    echo("")  
    echo(Fiborial.getFibonnaciSeries(5)) 
    echo(Fiborial.getFibonnaciSeries(7)) 
    echo(Fiborial.getFibonnaciSeries(9)) 
    echo(Fiborial.getFibonnaciSeries(11))  
    echo(Fiborial.getFibonnaciSeries(40)) 
  }
}

And the Output is:


















Mixing Instance and Static Members in the same Class

Instance classes can contain both, instance and static members such as: fields, getters, constructors/initializers, methods, etc.

// Instance Class  
class Fiborial
{  
  // Instance Field  
  private Int instanceCount  
  // Static Field
  // Static field 'staticCount' must be const
  private const static Int staticCount
  // Instance Read-Only Property   
  Int InstanceCount
  {
    get { return &instanceCount }  
  }  
  // Static Fields need to be const. A static const cannot have getter
  // using Static Read-Only Getter instead  
  // As with Static Methods, you cannot reference your class members  
  // with the "this" reference pointer since static members are not  
  // instantiated.  
  /*static Int StaticCount
  {    
    get { return &staticCount }    
  }*/
  static Int getStaticCount() 
  {
    return staticCount
  }
  // Instance Constructor  
  new make() 
  {  
    this.instanceCount = 0  
    echo("\nInstance Constructor ${this.instanceCount}")  
  }  
  // Static Constructor
  // Static constructors are methods executed to initialize the class itself. 
  // They are typically used to initialize static fields.
  static  
  {    
    staticCount = 0    
    echo("\nStatic Constructor $staticCount")
  }      
  // Instance Method  
  Void factorial(Int n) 
  {  
    this.instanceCount += 1  
    echo("\nFactorial($n)")  
  }  
  // Static Method  
  static Void fibonacci(Int n) 
  {  
    // Error: 
    // Cannot set const static field 'staticCount' outside of static initializer 
    // (static constructor) so we cannot increment staticCount
    // staticCount += 1  
    echo("\nFibonacci($n)")  
  }  
}

public class FiborialExtrasApp    
{    
  public static Void main()    
  {  
    // Calling Static Constructor and Methods  
    // No need to instantiate  
    Fiborial.fibonacci(5)  
      
    // Calling Instance Constructor and Methods  
    // Instance required  
    Fiborial fib := Fiborial()  
    fib.factorial(5)  
      
    Fiborial.fibonacci(15)  
    fib.factorial(5)  
      
    // Calling Instance Constructor and Methods  
    // for a second object  
    Fiborial fib2 := Fiborial()
    fib2.factorial(5)
      
    echo("")  
    // Calling Static Property  
    echo("Static Count = ${Fiborial.getStaticCount}")  
    // Calling Instance Property of object 1 and 2  
    echo("Instance 1 Count = ${fib.InstanceCount}")  
    echo("Instance 2 Count = ${fib2.InstanceCount}")   
  }
}

And the Output is:

























Factorial using java.lang.Long/sys::Int, java.lang.Double/sys::Float, java.math.BigInteger


using [java] com.carlosqt.util::Stopwatch
using [java] java.math::BigInteger

public class FiborialTypesApp    
{    
  public static Void main()    
  {     
    Stopwatch timer := Stopwatch()    
    Int facIntResult := 0
    Float facDblResult := 0f    
    BigInteger facBigResult := BigInteger.ZERO 
    
    echo("\nFactorial using Int64")  
    // Benchmark Factorial using Int64    
    for (i := 5; i <= 50; i += 5)    
    {    
      timer.start
      facIntResult = factorialInt64(i)    
      timer.stop    
      echo(" ($i) = ${timer.getElapsed} : $facIntResult")  
    }    
    echo("\nFactorial using Float/Double")
    // Benchmark Factorial using Double    
    for (i := 5; i <= 50; i += 5)    
    {    
      timer.start    
      facDblResult = factorialDouble(i)    
      timer.stop                
      echo(" ($i) = ${timer.getElapsed} : $facDblResult")  
    }    
    echo("\nFactorial using BigInteger")    
    // Benchmark Factorial using BigInteger    
    for (i := 5; i <= 50; i += 5)    
    {    
      timer.start();    
      facBigResult = factorialBigInteger(i);    
      timer.stop();    
      echo(" ($i) = ${timer.getElapsed} : $facBigResult")
    }            
  }  
      
  // Int64 Factorial    
  static Int factorialInt64(Int n)    
  {    
    if (n == 1)    
      return 1
    else    
      return n * factorialInt64(n - 1)  
  }  
    
  // Float Factorial  
  static Float factorialDouble(Int n)    
  {    
    if (n == 1)    
      return 1f
    else    
      return n * factorialDouble(n - 1)  
  }  
    
  // BigInteger Factorial   
  static BigInteger factorialBigInteger(Int n)    
  {    
    if (n == 1)    
      return BigInteger.ONE  
    else    
      return BigInteger.valueOf(n).multiply(factorialBigInteger(n - 1))
  }
}

And the Output is:



Sunday, February 5, 2012

Factorial and Fibonacci in Gosu



Here below a little program in Gosu that implements 2 classes (in fact, they are 3 + an extra utility Stopwatch class from my previous post http://carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.html). There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the Fibonacci and the Factorial algorithms in two ways, one Recursive (using recursion) and the other Imperative (using loops and states). The second class is just an instance class that does the same thing, but its there just to show the difference between static and instance classes, and finally the third one (which will not appear in other languages) is the Program class which has the static execution method "main".

You can also find 3 more little examples at the bottom. One prints out the Factorial's Series and Fibonacci's Series, the second one just shows a class that mixes both: static and instance members, and finally the third one that uses different return types (including java.math.BigInteger) for the Factorial method to compare the timing and result.

As with the previous posts, you can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you some more basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2011/01/new-series-factorial-and-fibonacci.html 


The Fiborial Program

// Factorial and Fibonacci in Gosu
package com.series
uses com.series.Stopwatch
uses java.math.BigInteger
uses java.util.Scanner
uses java.lang.System

// static class
static class StaticFiborial {
  // Static Field
  private static var className: String = "Static Constructor"
  //  no available static constructor support
  // you can initialize your static fields instead
  /*static construct() {  // error: constructors cannot be static
    className = "Static Constructor";
    print(className)
  }*/
  // Static Method - Factorial Recursive
  static function factorialR( n : int ) : BigInteger {
    if (n == 1) {
      return BigInteger.ONE
    }
    else {
      return BigInteger.valueOf(n).multiply(factorialR(n - 1))
    }
  }
  // Class/Static Method - Factorial Imperative
  static function factorialI( n : int ) : BigInteger {
    var res = BigInteger.ONE
    while (n > 1) {
      res = res.multiply(BigInteger.valueOf(n))
      n -= 1
    }
    return res
  }
  // Static Method - Fibonacci Recursive
  static function fibonacciR( n : int ) : long {
    if (n < 2) {
      return 1
    }
    else {
      return fibonacciR(n - 1) + fibonacciR(n - 2)
    }
  }
  // Static Method - Fibonacci Imperative
  static function fibonacciI( n : int ) : long {
    var pre : long = 1
    var cur : long = 1
    var tmp : long = 0
    for ( i in 2..n ) {
      tmp = cur + pre
      pre = cur
      cur = tmp
    }
    return cur
  }
  // Static Method - Benchmarking Algorithms
  static function benchmarkAlgorithm( algorithm : int, values : List<int>) {
    var timer = new Stopwatch()
    var testValue = 0
    var facTimeResult : BigInteger = BigInteger.ZERO
    var fibTimeResult : long = 0
    // "Switch" Flow Control Statement
    switch (algorithm)
    {
      case 1:
          print("\nFactorial Imperative:")
          // "For" Loop Statement
          for (i in 0..values.size()-1) {
            testValue = values.get(i).intValue()
            // Taking Time
            timer.start()
            facTimeResult = factorialI(testValue)
            timer.stop()
            // Getting Time
            print(" (${testValue}) = ${timer.getElapsed()}")
          }
          break
      case 2:
          print("\nFactorial Recursive:")
          // "While" Loop Statement
          var i = 0
          while ( i < values.size() ) {
            testValue = values.get(i).intValue()
            // Taking Time
            timer.start()
            facTimeResult = factorialR(testValue)
            timer.stop()
            // Getting Time
            print(" (${testValue}) = ${timer.getElapsed()}")
            i++
          }
          break
      case 3:
          print("\nFibonacci Imperative:")
          // "Do-While" Loop Statement
          var i = 0
          do {
            testValue = values.get(i).intValue()
            // Taking Time
            timer.start()
            fibTimeResult = fibonacciI(testValue)
            timer.stop()
            // Getting Time
            print(" (${testValue}) = ${timer.getElapsed()}")
            i++
          } while (i < values.size());
          break
      case 4:
          print("\nFibonacci Recursive:")
          // "For Each" Loop Statement
          for (item in values) {
            testValue = item
            // Taking Time
            timer.start()
            facTimeResult = fibonacciR(testValue)
            timer.stop()
            // Getting Time
            print(" (${testValue}) = ${timer.getElapsed()}")
          }
          break
    }
  }
}

// Instance Class
class InstanceFiborial {
  // Instance Field
  private var className : String
  // Instance Constructor
  construct() {
    this.className = "Instance Constructor"
    print(this.className)
  }
  // Instance Method - Factorial Recursive
  function factorialR( n : int ) : BigInteger {
    // Calling Static Method
    return StaticFiborial.factorialR(n)
  }
  // Instance Method - Factorial Imperative
  function factorialI( n : int ) : BigInteger {
    // Calling Static Method
    return StaticFiborial.factorialI(n)
  }
  // Instance Method - Fibonacci Recursive
  function fibonacciR( n : int ) : long {
    // Calling Static Method
    return StaticFiborial.fibonacciR(n)
  }
  // Instance Method - Factorial Imperative
  function fibonacciI( n : int ) : long {
    // Calling Static Method
    return StaticFiborial.fibonacciI(n)
  }
}

// Console Program
print("Static Class")
//Calling Static Class and Methods
//No instantiation needed. Calling method directly from the class
print("FacImp(5) = " + StaticFiborial.factorialI(5))
print("FacRec(5) = " + StaticFiborial.factorialR(5))
print("FibImp(11)= " + StaticFiborial.fibonacciI(11))
print("FibRec(11)= " + StaticFiborial.fibonacciR(11))

print("\nInstance Class")
//Calling Instance Class and Methods
//Need to instantiate before using. Calling method from instantiated object
var ff = new InstanceFiborial()
print("FacImp(5) = ${ff.factorialI(5)}")
print("FacRec(5) = ${ff.factorialR(5)}")
print("FibImp(11)= ${ff.fibonacciI(11)}")
print("FibRec(11)= ${ff.fibonacciR(11)}")

//Create a (generic) list of values to test
//From 5 to 50 by 5
var values = new List<int>()
var i = 5
while (i < 55) {
  values.add(i)
  i+=5
}

// Benchmarking Fibonacci
// 1 = Factorial Imperative
StaticFiborial.benchmarkAlgorithm(1, values)
// 2 = Factorial Recursive
StaticFiborial.benchmarkAlgorithm(2, values)

// Benchmarking Factorial
// 3 = Fibonacci Imperative
StaticFiborial.benchmarkAlgorithm(3, values)
// 4 = Fibonacci Recursive
StaticFiborial.benchmarkAlgorithm(4, values)

// Stop and exit
var sin = new Scanner(System.in)
var line = sin.nextLine()
sin.close()

And the Output is:























































Printing the Factorial and Fibonacci Series
package com.series
uses java.math.BigInteger
uses java.lang.StringBuffer

static class Fiborial {
  // Using a StringBuffer as a list of string elements
  static function getFactorialSeries( n : int ) : String {
    // Create the String that will hold the list
    var series = new StringBuffer()
    // We begin by concatenating the number you want to calculate
    // in the following format: "!# ="
    series.append("!")
    series.append(n)
    series.append(" = ")
    // We iterate backwards through the elements of the series
    for (i in n..0){
      // and append it to the list
      series.append(i)
      if (i > 1)
        series.append(" * ")
      else
        series.append(" = ")
    }
    // Get the result from the Factorial Method
    // and append it to the end of the list
    series.append(factorial(n).toString())
    // return the list as a string
    return series.toString()
  }

  // Using a StringBuffer as a list of string elements
  static function getFibonnaciSeries( n : int ) : String {
    // Create the String that will hold the list
    var series = new StringBuffer()
    // We begin by concatenating the first 3 values which
    // are always constant
    series.append("0, 1, 1")
    // Then we calculate the Fibonacci of each element
    // and add append it to the list
    for (i in 2..n) {
      if (i < n)
        series.append(", ")
      else
        series.append(" = ")
      series.append(fibonacci(i))
    }
    // return the list as a string
    return series.toString()
  }

  static function factorial( n : int  ) : BigInteger {
    if (n == 1)
      return BigInteger.ONE
    else
      return BigInteger.valueOf(n).multiply(factorial(n - 1))
  }

  static function fibonacci( n : int ) : long {
    if (n < 2)
      return 1
    else
      return fibonacci(n - 1) + fibonacci(n - 2)
  }
}

// Printing Factorial Series
print("")
print(Fiborial.getFactorialSeries(5))
print(Fiborial.getFactorialSeries(7))
print(Fiborial.getFactorialSeries(9))
print(Fiborial.getFactorialSeries(11))
print(Fiborial.getFactorialSeries(40))
// Printing Fibonacci Series
print("")
print(Fiborial.getFibonnaciSeries(5))
print(Fiborial.getFibonnaciSeries(7))
print(Fiborial.getFibonnaciSeries(9))
print(Fiborial.getFibonnaciSeries(11))
print(Fiborial.getFibonnaciSeries(40))

And the Output is:


















Mixing Instance and Static Members in the same Class

Instance classes can contain both, instance and static members such as: fields, properties, constructors/initializers, methods, etc.

// Fiborial.gs
package com.series

// Instance Class
class Fiborial {
  // Instance Field
  private var _instanceCount : int
  // Static Field - no static constructor so it needs to be initialized here
  private static var _staticCount : int = 0
  // Instance Read-Only Property
  // Within instance members, you can always use
  // the "this" reference pointer to access your (instance) members.
  property get InstanceCount() : int {
    return this._instanceCount
  }
  // Static Read-Only Getter
  // As with Static Methods, you cannot reference your class members
  // with the "this" reference pointer since static members are not
  // instantiated.
  static property get StaticCount() : int {
    return _staticCount
  }
  // Instance Constructor
  construct() {
    this._instanceCount = 0
    print("\nInstance Constructor ${this.instanceCount}")
  }
  // Static Constructor
  // not supported in Gosu. Constructor cannot be static.
  /*static construct() {
    staticCount = 0;
    print("\nStatic Constructor $staticCount")
  }
  */
  // Instance Method
  function factorial( n : int ) {
    this._instanceCount += 1
    print("\nFactorial(${n})")
  }
  // Static Method
  static function fibonacci( n : int ) {
    _staticCount += 1
    print("\nFibonacci(${n})")
  }
}
// FiborialExtrasApp.gsp
package com.series

// Calling Static Constructor and Methods
// No need to instantiate
Fiborial.fibonacci(5)

// Calling Instance Constructor and Methods
// Instance required
var fib = new Fiborial()
fib.factorial(5)

Fiborial.fibonacci(15)
fib.factorial(5)

// Calling Instance Constructor and Methods
// for a second object
var fib2 = new Fiborial()
fib2.factorial(5)

print("")
// Calling Static Property
print("Static Count = ${Fiborial.getStaticCount()}")
// Calling Instance Property of object 1 and 2
print("Instance 1 Count = ${fib.getInstanceCount()}")
print("Instance 2 Count = ${fib2.getInstanceCount()}")

And the Output is:

























Factorial using java.lang.Long, java.lang.Double, java.math.BigInteger


package com.series
uses java.math.BigInteger
uses com.series.Stopwatch

// Long Factorial
function factorialInt64( n : int ) : long
{
  if (n == 1)
    return 1
  else
    return n * factorialInt64(n - 1)
}

// Double Factorial
function factorialDouble( n : int ) : double
{
  if (n == 1)
    return 1
  else
    return n * factorialDouble(n - 1)
}

// BigInteger Factorial
function factorialBigInteger( n : int ) : BigInteger
{
  if (n == 1)
    return BigInteger.ONE
  else
    return BigInteger.valueOf(n).multiply(factorialBigInteger(n - 1))
}

var timer = new Stopwatch()
var facIntResult : long = 0
var facDblResult : double = 0
var facBigResult = BigInteger.ZERO

print("\nFactorial using Int64")
// Benchmark Factorial using Int64
var i = 5
while (i < 55) {
  timer.start()
  facIntResult = factorialInt64(i)
  timer.stop()
  print(" (${i}) = ${timer.getElapsed()} : ${facIntResult}")
  i += 5
}
print("\nFactorial using Double")
// Benchmark Factorial using Double
i = 5
while (i < 55) {
  timer.start()
  facDblResult = factorialDouble(i)
  timer.stop()
  print(" (${i}) = ${timer.getElapsed()} : ${facDblResult}")
  i += 5
}
print("\nFactorial using BigInteger")
// Benchmark Factorial using BigInteger
i = 5
while (i < 55) {
  timer.start()
  facBigResult = factorialBigInteger(i)
  timer.stop()
  print(" (${i}) = ${timer.getElapsed()} : ${facBigResult}")
  i += 5
}

And the Output is:



Friday, January 20, 2012

Factorial and Fibonacci in Groovy



Here below a little program in Groovy that implements 2 classes (in fact, they are 3 + an extra utility Stopwatch class from my previous post http://carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.html). There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the Fibonacci and the Factorial algorithms in two ways, one Recursive (using recursion) and the other Imperative (using loops and states). The second class is just an instance class that does the same thing, but its there just to show the difference between static and instance classes, and finally the third one (which will not appear in other languages) is the Program class which has the static execution method "main".

You can also find 3 more little examples at the bottom. One prints out the Factorial's Series and Fibonacci's Series, the second one just shows a class that mixes both: static and instance members, and finally the third one that uses different return types (including java.math.BigInteger) for the Factorial method to compare the timing and result.

As with the previous posts, you can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you some more basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2011/01/new-series-factorial-and-fibonacci.html 


The Fiborial Program

// Factorial and Fibonacci in Groovy  
package com.series  
import java.math.BigInteger  
  
// Instance Class  
class StaticFiborial    
{      
    // Static Field      
    private static className  
    // Class/Static Constructor/Initializer    
    static    
    {      
        className = "Static Constructor"  
        println className  
    }      
    // Class/Static Method - Factorial Recursive      
    static factorialR(int n)      
    {      
        if (n == 1)      
            return BigInteger.ONE  
        else      
            return n * factorialR(n - 1)  
    }      
    // Class/Static Method - Factorial Imperative      
    static factorialI(int n)      
    {      
        def res = BigInteger.ONE  
        for (int i = n; i >= 1; i--)      
        {                      
            res *= i  
        }      
        return res  
    }      
    // Class/Static Method - Fibonacci Recursive      
    static fibonacciR(int n)      
    {      
        if (n < 2)      
            return 1  
        else      
            return fibonacciR(n - 1) + fibonacciR(n - 2)  
    }      
    // Class/Static Method - Fibonacci Imperative      
    static fibonacciI(int n)      
    {                  
        def pre, cur, tmp = 0  
        pre = cur = 1          
        for (i in 2..n)  
        {      
            tmp = cur + pre  
            pre = cur  
            cur = tmp  
        }      
        return cur    
    }          
    // Class/Static Method - Benchmarking Algorithms      
    static benchmarkAlgorithm(algorithm, values)      
    {                  
        def timer = new Stopwatch()  
        def i, testValue  
        def facTimeResult = BigInteger.ZERO  
        def fibTimeResult = 0  
        i = testValue = 0              
              
        // "Switch" Flow Control Statement      
        switch (algorithm)      
        {      
            case 1:      
                println "\nFactorial Imperative:"  
                // "For" Loop Statement      
                for (i = 0; i < values.size(); i++)      
                {                              
                    testValue = ((Integer)values.get(i)).intValue()  
                    // Taking Time      
                    timer.start()  
                    facTimeResult = factorialI(testValue)  
                    timer.stop()      
                    // Getting Time      
                    println " ($testValue) = ${timer.getElapsed()}"  
                }                          
                break      
            case 2:      
                println "\nFactorial Recursive:"  
                // "While" Loop Statement      
                while (i < values.size())      
                {                              
                    testValue = ((Integer)values.get(i)).intValue()  
                    // Taking Time      
                    timer.start()  
                    facTimeResult = factorialR(testValue)  
                    timer.stop()  
                    // Getting Time      
                    println " ($testValue) = ${timer.getElapsed()}"  
                    i++  
                }      
                break     
            case 3:      
                println "\nFibonacci Imperative:"  
                // "For" Loop Statement      
                for (j in 0..values.size()-1)  
                {   
                    testValue = ((Integer)values.get(j)).intValue()  
                    // Taking Time  
                    timer.start()  
                    fibTimeResult = fibonacciI(testValue)  
                    timer.stop()  
                    // Getting Time      
                    println " ($testValue) = ${timer.getElapsed()}"                      
                }                  
                break  
            case 4:      
                println "\nFibonacci Recursive:"  
                // "For Each" Loop Statement                      
                for (item in values)  
                {      
                    testValue = item  
                    // Taking Time      
                    timer.start()    
                    fibTimeResult = fibonacciR(testValue)  
                    timer.stop()  
                    // Getting Time  
                    println " ($testValue) = ${timer.getElapsed()}"  
                }   
                break  
            default:      
                println "DONG!"  
                break  
        }   
    }      
}  
  
// Instance Class      
class InstanceFiborial      
{      
    // Instance Field      
    private def className  
    // Instance Constructor      
    def InstanceFiborial()      
    {      
        this.className = "Instance Constructor"  
        println this.className  
    }      
    // Instance Method - Factorial Recursive      
    def factorialR(n)      
    {      
        // Calling Static Method      
        return StaticFiborial.factorialR(n)  
    }      
    // Instance Method - Factorial Imperative      
    def factorialI(n)      
    {      
        // Calling Static Method      
        return StaticFiborial.factorialI(n)      
    }      
    // Instance Method - Fibonacci Recursive  
    def fibonacciR(n)      
    {      
        // Calling Static Method      
        return StaticFiborial.fibonacciR(n)  
    }      
    // Instance Method - Factorial Imperative      
    def fibonacciI(n)      
    {      
        // Calling Static Method      
        return StaticFiborial.fibonacciI(n)  
    }      
}    
  
  
println "\nStatic Class"      
// Calling Static Class and Methods  
// No instantiation needed. Calling method directly from the class      
println "FacImp(5) = ${StaticFiborial.factorialI(5)}"  
println "FacRec(5) = ${StaticFiborial.factorialR(5)}"      
println "FibImp(11)= ${StaticFiborial.fibonacciI(11)}"      
println "FibRec(11)= ${StaticFiborial.fibonacciR(11)}"  
  
println "\nInstance Class"      
// Calling Instance Class and Methods       
// Need to instantiate before using. Calling method from instantiated object      
def ff = new InstanceFiborial()  
println "FacImp(5) = ${ff.factorialI(5)}"  
println "FacRec(5) = ${ff.factorialR(5)}"  
println "FibImp(11)= ${ff.fibonacciI(11)}"  
println "FibRec(11)= ${ff.fibonacciR(11)}"  
  
// Create a list of integer values to test  
// From 5 to 50 by 5      
def values = []  
5.step(55, 5) {  
    values.add(it)  
}  
  
// Benchmarking Fibonacci                           
// 1 = Factorial Imperative                  
StaticFiborial.benchmarkAlgorithm(1, values)  
// 2 = Factorial Recursive      
StaticFiborial.benchmarkAlgorithm(2, values)  
  
// Benchmarking Factorial                  
// 3 = Fibonacci Imperative      
StaticFiborial.benchmarkAlgorithm(3, values)  
// 4 = Fibonacci Recursive      
StaticFiborial.benchmarkAlgorithm(4, values)  
  
// Stop and exit      
println "Press any key to exit..."    
def sin = new Scanner(System.in)    
def line = sin.nextLine()    
sin.close()

And the Output is:























































Printing the Factorial and Fibonacci Series
package com.series  
import java.math.BigInteger    
import java.lang.StringBuffer  
    
class Fiborial    
{    
    // Using a StringBuffer as a list of string elements    
    static getFactorialSeries(n)    
    {    
        // Create the String that will hold the list    
        def series = new StringBuffer()  
        // We begin by concatenating the number you want to calculate    
        // in the following format: "!# ="    
        series.append("!")  
        series.append(n)  
        series.append(" = ")  
        // We iterate backwards through the elements of the series    
        for (i in n..0)  
        {    
            // and append it to the list    
            series.append(i)  
            if (i > 1)  
                series.append(" * ")  
            else     
                series.append(" = ")  
        }  
        // Get the result from the Factorial Method    
        // and append it to the end of the list    
        series.append(factorial(n))    
        // return the list as a string    
        return series
    }    
    
    // Using a StringBuffer as a list of string elements    
    static getFibonnaciSeries(n)    
    {    
        // Create the String that will hold the list    
        def series = new StringBuffer();    
        // We begin by concatenating the first 3 values which    
        // are always constant    
        series.append("0, 1, 1")  
        // Then we calculate the Fibonacci of each element    
        // and add append it to the list    
        for (i in 2..n)  
        {    
            if (i < n)    
                series.append(", ")  
            else    
                series.append(" = ")  
                
            series.append(fibonacci(i))  
        }    
        // return the list as a string    
        return series    
    }    
    
    static factorial(n)    
    {    
        if (n == 1)      
            return BigInteger.ONE  
        else      
            return n * factorial(n - 1)  
    }            
    
    static fibonacci(n)    
    {    
        if (n < 2)      
            return 1  
        else      
            return fibonacci(n - 1) + fibonacci(n - 2)  
    }       
}    
  
  
// Printing Factorial Series    
println ""
println Fiborial.getFactorialSeries(5)    
println Fiborial.getFactorialSeries(7)  
println Fiborial.getFactorialSeries(9)  
println Fiborial.getFactorialSeries(11)  
println Fiborial.getFactorialSeries(40)  
// Printing Fibonacci Series    
println ""  
println Fiborial.getFibonnaciSeries(5)  
println Fiborial.getFibonnaciSeries(7)  
println Fiborial.getFibonnaciSeries(9)  
println Fiborial.getFibonnaciSeries(11)  
println Fiborial.getFibonnaciSeries(40)

And the Output is:
















Mixing Instance and Static Members in the same Class

Instance classes can contain both, instance and static members such as: fields, getters/setters, constructors/initializers, methods, etc.

package com.series

// Instance Class    
class Fiborial    
{    
    // Instance Field    
    private def instanceCount    
    // Static Field    
    private static staticCount
    // Instance Read-Only Getter    
    // Within instance members, you can always use      
    // the "this" reference pointer to access your (instance) members.    
    def getInstanceCount()  
    {    
        return this.instanceCount     
    }    
    // Static Read-Only Getter        
    // As with Static Methods, you cannot reference your class members    
    // with the "this" reference pointer since static members are not    
    // instantiated.            
    static getStaticCount()  
    {    
        return staticCount    
    }    
    // Instance Constructor    
    def Fiborial()    
    {    
        this.instanceCount = 0
        println "\nInstance Constructor ${this.instanceCount}"
    }    
    // Static Constructor    
    static
    {    
        staticCount = 0;    
        println "\nStatic Constructor $staticCount"    
    }    
  
    // Instance Method    
    def factorial(n)    
    {    
        this.instanceCount += 1
        println "\nFactorial($n)"
    }    
  
    // Static Method    
    static fibonacci(n)    
    {    
        staticCount += 1    
        println "\nFibonacci($n)"
    }                    
}  

// Calling Static Constructor and Methods    
// No need to instantiate    
Fiborial.fibonacci(5)

// Calling Instance Constructor and Methods
// Instance required    
def fib = new Fiborial()
fib.factorial(5)           

Fiborial.fibonacci(15)
fib.factorial(5)

// Calling Instance Constructor and Methods    
// for a second object    
def fib2 = new Fiborial()
fib2.factorial(5)

println ""
// Calling Static Property    
println "Static Count = ${Fiborial.getStaticCount()}}"
// Calling Instance Property of object 1 and 2    
println "Instance 1 Count = ${fib.getInstanceCount()}"
println "Instance 2 Count = ${fib2.getInstanceCount()}"

And the Output is:



















Factorial using java.lang.Long, java.lang.Double, java.math.BigInteger


package com.series    
import java.math.BigInteger  
      
// Long Factorial      
long factorialInt64(n)      
{      
    if (n == 1)      
        return 1    
    else      
        return n * factorialInt64(n - 1)    
}    
  
// Double Factorial    
double factorialDouble(n)      
{      
    if (n == 1)      
        return 1  
    else      
        return n * factorialDouble(n - 1)  
}    
  
// BigInteger Factorial     
BigInteger factorialBigInteger(n)      
{      
    if (n == 1)      
        return BigInteger.ONE  
    else      
        return n * factorialBigInteger(n - 1)
}    
  
def timer = new Stopwatch()  
long facIntResult = 0     
double facDblResult = 0  
def facBigResult = BigInteger.ZERO      
  
println "\nFactorial using Int64"  
// Benchmark Factorial using Int64      
for (i in (5..50).step(5)) {      
    timer.start()  
    facIntResult = factorialInt64(i)  
    timer.stop()      
    println " ($i) = ${timer.getElapsed()} : ${facIntResult}"    
}      
println "\nFactorial using Double"  
// Benchmark Factorial using Double      
for (i in (5..50).step(5)) {      
    timer.start()  
    facDblResult = factorialDouble(i)  
    timer.stop()  
    println " ($i) = ${timer.getElapsed()} : ${facDblResult}"  
}      
println "\nFactorial using BigInteger"  
// Benchmark Factorial using BigInteger      
for (i in (5..50).step(5)) {      
    timer.start()  
    facBigResult = factorialBigInteger(i)  
    timer.stop()  
    println " ($i) = ${timer.getElapsed()} : ${facBigResult}"              
}

And the Output is:


Tuesday, January 10, 2012

Misc


Hi Everyone! Happy and successful 2012 to all of you!

Last couple of months I haven't been active on this blog, I had a busy end of year plus December  holidays on where I hardly touched the keyboard :) anyway, I have noticed, thanks to google analytics, that many people had visited this blog from all around the world since I created it (2009-Today) (see below).




Note: The number of visits from Belgium is not real... that is more because I visit it often hehe.

Now, to me, this means that I have some public, and that what I'm doing is not meaningless so, this year, I will try to become more active and continue adding more code examples on the current languages and the new ones that appeared during last year and the ones that will show up this year.

So, here are my priorities concerning this blog:

  1. Finilize the "Factorial and Fibonacci Series" in Groovy, Gosu, Zonnon, Fantom
  2. Adding Xtend, Ceylon (and Kotlin once released) to the blog posts "OO Hello World", "Basics by Example" and  "Factorial and Fibonacci Series"
  3. I'm still considering including Oxygene (ObjectPascal/Delphi for the JVM) as a separate language. Since it is exactly the same than Delphi Prism (aka Embarcadero Prism)... I think I won't do it.
  4. JavaFX Script was deprecated as a language on 2011. I won't post about it any more.
  5. Will continue updating the Languages Page with the latest releases and languages.


VoilĂ ! that's it!

Regards!
Carlos