Thursday, September 8, 2016

Arrays and Indexers in PowerShell



Today's post is about Arrays and Indexers in PowerShell. Here below you will find a very easy to follow program, that demonstrate arrays and indexer, by implementing some simple tasks that will make you grasp the idea of those 2 features real quick. The main goal of this post, is not really teaching arrays because, come on, you probably already know "all" about them, in fact, it is more to show you how you do that in PowerShell, in this case, compared to all other ~22 languages on future posts, which essentially, is the real aim behind this blog.

By the way, if you missed my most recent post, "New Series - Arrays and Indexers", check it out. It has more details about the following program, and a bunch of definitions for the concepts used on this, and the following, posts. Or you can check my previous posts about arrays in C# and C++ just to compare.

I encourage you to copy the code below and try it yourself, normally, all programs you find in this blog are source code complete, just paste it on your IDE and run it.

There is room for improvement of the code, using generics is one example, but Generics, Collections, lambdas, etc. will have their own "series" of posts.

NOTE:
PowerShell provides two different types of arrays, PowerShell [array] objects and typed arrays [type[]]. In PowerShell array objects, a script can dynamically add and remove elements, and elements can be of any data type. In typed arrays, which are dense, the size is fixed, and elements must be the same type as the base type of the array, the least are coming from .NET types, specially multi-dimensional arrays.

I chose to use the Typed Arrays (and all other variables as well) to keep it closer to the previous posts. I used [array] for jagged arrays [array[]], and for function/method parameter even though [object[]] should also work also.


function ReverseChar($arr) {
    [char[]] $reversed = @(1..$arr.length)
    #[array]::Reverse($reversed)  <-- better to use this but for demo purposes I did it with a for 2 indexes
  
    for ($i, $j = 0, ($arr.length - 1); $j -ge 0; $i++, $j--) {
        $reversed[$i] = $arr[$j] 
    }
    return $reversed
}

function BubbleSort([array]$arr) {  
    $swap = 0  
    for ($i = ($arr.Length - 1); $i -gt 0; $i--) {  
        for ($j = 0; $j -lt $i; $j++) {  
            if ($arr[$j] -gt $arr[$j + 1]) {     
                $swap = $arr[$j]
                $arr[$j] = $arr[$j + 1]                
                $arr[$j + 1] = $swap                  
            }  
        }  
    }  
    return $arr  
}  

function TransposeMatrix([int[,]]$m) {  
    <# Transposing a Matrix 2,3  
        *  
        * A =  [6  4 24]T [ 6  1]  
        *      [1 -9  8]  [ 4 -9] 
        *                 [24  8] 
    #>
    [int[,]]$transposed = [int[,]]::new(
        $m.GetUpperBound(1) + 1,
        $m.GetUpperBound(0) + 1)
    
    for ($i = 0; $i -le $m.GetUpperBound(0); $i++) {  
        for ($j = 0; $j -le $m.GetUpperBound(1); $j++) {                          
            $transposed[$j,$i] = $m[$i,$j]
        }  
    } 
    return ,$transposed  # use comma operator to avoid unroll
}  

function UpperCaseRandomArray([array[]]$arr)  
{  
    #$r = new-object [System.Random]
    #$i = $r.Next(0, ($arr.Length - 1))
    $i = get-random -minimum -0 -maximum ($arr.Length - 1)
    for ($j = 0; $j -lt $arr[$i].Count; $j++) {
        $arr[$i][$j] = $arr[$i][$j].ToUpper()
    }
    return $arr
}  

function PrintArray([array]$arr) {
    if(!$arr) { $arr=@() }
    Write-Host("`nPrint Array Content $($arr.GetType().Name) [$($arr.Length)]")

    for ($i=0; $i -lt $arr.Length; $i++) {    
        Write-Host(" array [$($i.ToString().PadLeft(2))] = $($arr[$i].ToString().PadLeft(2))")
    }
}

function PrintMatrix([int[,]]$m) {  
    Write-Host ("`nPrint Matrix Content {0}[{0},{0}]" -f 
        $m.GetType().Name.Replace("[,]", ""),
        ($m.GetUpperBound(0) + 1), 
        ($m.GetUpperBound(1) + 1))
            
    for ($i = 0; $i -le $m.GetUpperBound(0); $i++) {
        for ($j = 0; $j -le $m.GetUpperBound(1); $j++) {
            Write-Host (" array [{0,2},{1,2}] = {2,2} " -f $i, $j, $m[$i,$j]) 
        }
    }
}  

function GraphJaggedArray([Array[]]$arr) {  
    <# When using Arrays, we can use foreach operator instead of for:  
        *  
        * for ($i = 0; $i -lt $arr.Length; $i++) 
        *   for ($j = 0; $j -lt $arr.Length; $j++)
        *  
        #> 
    Write-Host ("Print Text Content $($arr.GetType().Name)`n")  
    $lineCount = 1 
    foreach ($s in $arr) {  
        Write-Host -NoNewline ("Line{0,2}|" -f $lineCount)  
        foreach ($_ in $s) {  
            Write-Host -NoNewline ("{0,3}" -f '*')  
        }  
        Write-Host (" ($($s.Length))")
        $lineCount++ 
    }  
}

function PrintJaggedArray([array[]]$arr) {          
    Write-Host ("`nPrint Jagged Array Content $($arr.GetType().Name)")  
    for ($i = 0; $i -lt $arr.Count; $i++) {  
        $line = [System.Text.StringBuilder]::new()
        for ($j = 0; $j -lt $arr[$i].Count; $j++) {
            [void]$line.Append(" ")
            [void]$line.Append($arr[$i][$j].ToString())
        }
        if (($line.ToString()) -ceq ($line.ToString().ToUpper())) {
            [void]$line.Append(" <-- [UPPERCASED]")
        }
        Write-Host $line
    }  
}    


function PrintCommonArrayExceptions($arr) {      
    try {  

        if ($arr -eq $null) {             
            $arr[100] = "hola" 
        }
        elseif ($arr[0] -eq $null) {            
            $arr[100] = "hola"
        } 
        elseif ($arr[100] -eq $null) {            
            $arr[100][100] = "hola"
        }                   

        #throw [System.NullReferenceException]::new("")
        #throw [System.Exception]::new("")        
                            
    } 
    catch [System.Management.Automation.RuntimeException]{
        Write-Host ("`nException: `n$($_.Exception.GetType().FullName)`n$($_.Exception.Message)")          
    }
    catch [System.NullReferenceException],[System.IndexOutOfRangeException] {
        Write-Host ("`nException: `n$($_.Exception.GetType().FullName)`n$($_.Exception.Message)")  
    }               
    catch [Exception] {
        # pass
    }
    catch {
        # pass
    }
    finally {
        # pass
    }
}  

function PrintTitle([String]$message) {
    Write-Host 
    Write-Host ("=" * 55)
    Write-Host ($message)
    Write-Host ("=" * 55)
}

class Alphabet {
    # Array Field  
    hidden [char[]]$letters = @()     

    # No indexer support. 
    # Getter/Setter Method instead. 
    [char] GetItem([int]$index) {    
        return $this.letters[$index]
    } 

    [void] SetItem([int]$index, [char]$value) {
        $this.letters[$index] = [char]::ToUpper($value)
    }

    # "Read-Only Property"
    [int] Length() {    
        return $this.letters.Length
    } 

    # Constructors  
    Alphabet([int]$size) {
        $this.letters = @(,' ' * $size)
    }

    Alphabet([string]$list) {
        $this.letters = $list.ToUpper().ToCharArray()
    }

    Alphabet([char[]]$list) {
        $this.letters = $list
    }

    # Overridden Method  
    [string] ToString() {       
        return [String]::Join(",", $this.letters)
    }

    # Method 
    [char[]] Slice([int]$start, [int]$length) {
        [char[]]$result = @(,' ' * $length)
        for ($i, $j = 0, $start 
             $i -lt $length
             $i++, $j++) {  
            $result[$i] = $this.letters[$j]
        }  
        return $result
    }
}

# Single-dimensional Array(s)
printTitle("Reverse Array Elements")

# Declare and Initialize Array of Chars
[char[]] $letters = @(1..5)
$letters[0] = 'A'  
$letters[1] = 'E'  
$letters[2] = 'I'
$letters[3] = 'O'
$letters[4] = 'U'

# untyped arrays or an array of type [array] are all System.Object[]  
# typed arrays need an explicit type [int[]], [string[]], or even [Object[]]

PrintArray($letters)
$inverse_letters = ReverseChar($letters)
PrintArray($inverse_letters)

PrintTitle("Sort Integer Array Elements")

# Declare and Initialize Array of Integers
[int[]]$numbers = @(10, 8, 3, 1, 5)
PrintArray($numbers)
[int[]]$ordered_numbers = [int[]](BubbleSort($numbers))
PrintArray($ordered_numbers)

PrintTitle("Sort String Array Elements")

# Declare and Initialize and Array of Strings
[string[]]$names = @(
    "Damian",
    "Rogelio",
    "Carlos",
    "Luis",
    "Daniel"
)
PrintArray($names)
[string[]]$ordered_names = BubbleSort($names)
PrintArray($ordered_names) 


# Multi-dimensional Array (Matrix row,column)  
# To declare a multi-dimensional array in PowerShell 
            
PrintTitle("Transpose Matrix");  
            
<# Matrix row=2,col=3 
    * A =  [6  4 24] 
    *      [1 -9  8] 
    * #>
# $matrix = New-Object 'int[,]' 2,3
$matrix = [int[,]]::new(2,3)
$matrix[0,0], $matrix[0,1], $matrix[0,2] = 6, 4,24
$matrix[1,0], $matrix[1,1], $matrix[1,2] = 1,-9, 8 

PrintMatrix($matrix)  
[int[,]]$transposed_matrix = TransposeMatrix($matrix)
PrintMatrix($transposed_matrix)

# Jagged Array (Array-of-Arrays)
            
PrintTitle("Upper Case Random Array & Graph Number of Elements")
            
<#              
    * Creating an array of string arrays using the String.Split method 
    * instead of initializing it manually as follows: 
    *  
    * $text = @(  
    *      ,( "word1", "word2", "wordN" )
    *      ,( "word1", "word2", "wordM" )  
    *      ... 
    *      ) 
    *  
    * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
    *  
 #>  

[array[]]$text = @(   
  ,("Hoy es el día más hermoso de nuestra vida, querido Sancho;".Split(' '))  
  ,("los obstáculos más grandes, nuestras propias indecisiones;".Split(' '))  
  ,("nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;".Split(' '))
  ,("la cosa más fácil, equivocarnos;".Split(' '))
  ,("la más destructiva, la mentira y el egoísmo;".Split(' '))
  ,("la peor derrota, el desaliento;".Split(' '))
  ,("los defectos más peligrosos, la soberbia y el rencor;".Split(' '))
  ,("las sensaciones más gratas, la buena conciencia...".Split(' '))
)          

PrintJaggedArray($text)
UpperCaseRandomArray($text) > $null
PrintJaggedArray($text)
GraphJaggedArray($text)

# Array Exceptions  
            
PrintTitle("Common Array Exceptions")
            
PrintCommonArrayExceptions($null)  
PrintCommonArrayExceptions(@())
PrintCommonArrayExceptions($text)  
                  
# Accessing Class Array Elements through "Indexer" Getter/Setter    
PrintTitle('Alphabets');  

[Alphabet]$vowels = [Alphabet]::new(5)  
$vowels.setitem(0, 'a')  
$vowels.setitem(1, 'e')  
$vowels.setitem(2, 'i')  
$vowels.setitem(3, 'o')  
$vowels.setitem(4, 'u')  

Write-Host ("`nVowels = {" + [String]::Join(',', 
    $vowels.getitem(0), $vowels.getitem(1), $vowels.getitem(2), 
    $vowels.getitem(3), $vowels.getItem(4)) + "}")

[Alphabet]$en = [Alphabet]::new('abcdefghijklmnopqrstuvwxyz')
Write-Host ('English Alphabet = {' + $en.ToString() + "}")

Write-Host ('Alphabet Extract en[9..19] = {' + 
            ([Alphabet]::new($en.slice(9, 10))).tostring() + '}')
  

$word1 = [String]::Join("", $en.getItem(6), $en.getitem(14), 
                            $en.getitem(14), $en.getitem(3))
$word2 = [String]::Join("", $en.getitem(1), $en.getitem(24), 
                            $en.getitem(4), $en.getitem(4))
$word3 = [String]::Join("", $en.getitem(4), $en.getitem(21), 
                            $en.getitem(4), $en.getitem(17),
                            $en.getitem(24), $en.getitem(14), 
                            $en.getitem(13), $en.getitem(4))

Write-Host ("`n$word1 $word2, $word3!")

Read-Host


The output:






















































































VoilĂ , that's it. Next post in the following days.

Friday, September 2, 2016

Factorial and Fibonacci in PowerShell



Here below a little program in PowerShell that implements 2 classes. 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 methods are not static. And finally the script part that instantiates and executes the script program.

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 System.Numerics.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 PowerShell 
Add-Type -Path "C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Numerics.dll"

# Instance Class (No static modifier at class level)
class StaticFiborial {
    # Static Field  
    hidden static [String] $className
    # Static Constructor  
    static StaticFiborial() {  
        [StaticFiborial]::className = "Static Constructor"
        Write-Host ([StaticFiborial]::className)
    }  
    # Static Method - Factorial Recursive  
    static [System.Numerics.BigInteger] FactorialR([Int] $n) {  
        if ($n -eq 1) {
            return 1 #[System.Numerics.BigInteger]::One  
        } else {
            return $n * [StaticFiborial]::FactorialR($n - 1)
        }
    }
    # Static Method - Factorial Imperative   
    static [System.Numerics.BigInteger] FactorialI([Int] $n) {
        $res = [System.Numerics.BigInteger]::One
        for($i = $n
            $i -ge 1
            $i--) {
            #$res = [System.Numerics.BigInteger]::Multiply($res, [System.Numerics.BigInteger]::new($i))
            $res *= $i
        }        
        return $res
    }
    # Static Method - Fibonacci Recursive  
    static [System.Numerics.BigInteger] FibonacciR([Int] $n) {  
        if ($n -lt 2) {
            return 1 #[System.Numerics.BigInteger]::One  
        } else {            
            return [StaticFiborial]::FibonacciR($n - 1) + [StaticFiborial]::FibonacciR($n - 2)
        }
    }
    # Static Method - Fibonacci Imperative  
    static [System.Numerics.BigInteger] FibonacciI([Int] $n) {  
        [long] $pre = 1
        [long] $cur = 1
        [long] $tmp = 0
        for ($i = 2; $i -le $n; $i++) {  
            $tmp = $cur + $pre
            $pre = $cur  
            $cur = $tmp  
        }  
        return $cur 
    }
    # Static Method - Benchmarking Algorithms 
    static [void] BenchmarkAlgorithm([Int] $algorithm, [int[]] $values) {
        $timer = [System.Diagnostics.Stopwatch]::new()
        $i = 0
        $testValue = 0
        $facTimeResult = [System.Numerics.BigInteger]::Zero
        $fibTimeResult = 0

        # "Switch" Flow Constrol Statement          
        switch ($algorithm) {          
            1 {
                Write-Host "`nFactorial Imperative:"
                # "For" Loop Statement
                for($i = 0; $i -lt $values.Length; $i++) {
                    $testValue = $values[$i]
                    # Taking Time   
                    $timer.Start()
                    $facTimeResult = [StaticFiborial]::FactorialI($testValue)
                    $timer.Stop()
                    # Getting Time    
                    Write-Host (" ({0}) = {1}" -f $testValue, $timer.Elapsed)
                }                
            }
            2 {
                Write-Host "`nFactorial Recursive:"      
                # "While" Loop Statement          
                while ($i -lt $values.Length) { 
                    $testValue = $values[$i]
                    # Taking Time   
                    $timer.Start()
                    $facTimeResult = [StaticFiborial]::FactorialR($testValue)
                    $timer.Stop()
                    # Getting Time    
                    Write-Host (" ({0}) = {1}" -f $testValue, $timer.Elapsed)
                    $i++                
                }                          
            }
            3 {
                Write-Host "`nFibonacci Imperative:"      
                # "Do-While" Loop Statement           
                do {
                    $testValue = $values[$i]
                    # Taking Time   
                    $timer.Start()
                    $fibTimeResult = [StaticFiborial]::FibonacciI($testValue)
                    $timer.Stop()
                    # Getting Time    
                    Write-Host (" ({0}) = {1}" -f $testValue, $timer.Elapsed)
                    $i++                
                } while ($i -lt $values.Length)                       
            }
            4 {
                Write-Host "`nFibonacci Recursive:"
                # "For" Loop Statement
                foreach ($testValue in $values) {                    
                    # Taking Time   
                    $timer.Start()
                    $fibTimeResult = [StaticFiborial]::FibonacciR($testValue)
                    $timer.Stop()
                    # Getting Time    
                    Write-Host (" ({0}) = {1}" -f $testValue, $timer.Elapsed)
                }                
            }
            default {   
                echo "DONG!`n"                
            }
        }
    }
}


# Instance Class
class InstanceFiborial {
    # Instance Field
    hidden [string] $className
    # Instance Constructor
    InstanceFiborial() {
        $this.className = "Instance Constructor"
        Write-Host $this.className
    }
    # Instance Method - Factorial Recursive
    [System.Numerics.BigInteger] FactorialR([int] $n) {
        # Calling Static Method
        return [StaticFiborial]::FactorialR($n)
    }
    # Instance Method - Factorial Imperative
    [System.Numerics.BigInteger] FactorialI([int] $n) {
        # Calling Static Method
        return [StaticFiborial]::FactorialI($n)
    }
    # Instance Method - Fibonacci Recursive
    [long] FibonacciR([int] $n) {
        # Calling Static Method
        return [StaticFiborial]::FibonacciR($n)
    }
    # Instance Method - Factorial Imperative
    [long] FibonacciI([int] $n) {
        # Calling Static Method
        return [StaticFiborial]::FibonacciI($n)
    }
}


Write-Host "`nInstance Class (with static methods)"
# Calling Static Methods
# Instantiation needed. Calling method directly from the class

Write-Host ("FacImp(5) = {0}" -f [StaticFiborial]::FactorialI(5))
Write-Host ("FacRec(5) = {0}" -f [StaticFiborial]::FactorialR(5))
Write-Host ("FibImp(11)= {0}" -f [StaticFiborial]::FibonacciI(11))
Write-Host ("FibRec(11)= {0}" -f [StaticFiborial]::FibonacciR(11))

Write-Host "`nInstance Class"
# Calling Instance Class and Methods 
# Need to instantiate before using. Calling method from instantiated object

$ff = [InstanceFiborial]::new()
# or
# $ff = New-Object InstanceFiborial

Write-Host ("FacImp(5) = {0}" -f $ff.FactorialI(5))
Write-Host ("FacRec(5) = {0}" -f $ff.FactorialR(5))
Write-Host ("FibImp(11)= {0}" -f $ff.FibonacciI(11))
Write-Host ("FibRec(11)= {0}" -f $ff.FibonacciR(11))


# Create a (generic) list of integer values to test
# From 5 to 50 by 5
$values = @()
for($i = 5; $i -le 50; $i += 5) {
    $values += $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
Read-Host 


And the Output is:














































Printing the Factorial and Fibonacci Series
Add-Type -Path "C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Numerics.dll"

class Fiborial {

    # Using a StringBuilder as a list of string elements
    static [String] GetFactorialSeries([int] $n) {
        # Create the String that will hold the list
        $series = [System.Text.StringBuilder]::new()
        # We begin by concatenating the number you want to calculate
        # in the following format: "!# ="
        [void]$series.Append("!")
        [void]$series.Append($n)
        [void]$series.Append(" = ")
        # We iterate backwards through the elements of the series
        for($i = $n; $i -le $n -and $i -gt 0; $i--) {        
            # and append it to the list
            [void]$series.Append($i)
            if ($i -gt 1) {
                [void]$series.Append(" * ")
            }
            else {
                [void]$series.Append(" = ") 
            }
        }
        # Get the result from the Factorial Method
        # and append it to the end of the list
        [void]$series.Append([Fiborial]::Factorial($n))
        # return the list as a string        

        return $series.ToString()
    }

    # Using a StringBuilder as a list of string elements
    static [String] GetFibonnaciSeries([int] $n) {
        # Create the String that will hold the list
        $series = New-Object -TypeName "System.Text.StringBuilder"
        # We begin by concatenating the first 3 values which
        # are always constant
        [void]$series.Append("0, 1, 1")
        # Then we calculate the Fibonacci of each element
        # and add append it to the list
        for ($i = 2
             $i -le $n
             $i++) {
            if ($i -lt $n) {
                [void]$series.Append(", ")
            }
            else {
                [void]$series.Append(" = ")
            }
                
            [void]$series.Append([Fiborial]::Fibonacci($i))
        }
        # return the list as a string
        return $series.ToString()
    }

    static [System.Numerics.BigInteger] Factorial([Int] $n) {  
        if ($n -eq 1) {
            return [System.Numerics.BigInteger]::One  
        } else {
            return $n * [Fiborial]::Factorial($n - 1)
        }
    }

    static [System.Numerics.BigInteger] Fibonacci([Int] $n) {  
        if ($n -lt 2) {
            return [System.Numerics.BigInteger]::One  
        } else {            
            return [Fiborial]::Fibonacci($n - 1) + [Fiborial]::Fibonacci($n - 2)
        }
    }
}


echo ("Printing Factorial Series")
echo ([Fiborial]::GetFactorialSeries(5))
echo ([Fiborial]::GetFactorialSeries(7))
echo ([Fiborial]::GetFactorialSeries(9))
echo ([Fiborial]::GetFactorialSeries(11))
echo ([Fiborial]::GetFactorialSeries(40))

Write-Host  ("Printing Fibonacci Series")
Write-Host  ([Fiborial]::GetFibonnaciSeries(5))
Write-Host  ([Fiborial]::GetFibonnaciSeries(7))
Write-Host  ([Fiborial]::GetFibonnaciSeries(9))
Write-Host  ([Fiborial]::GetFibonnaciSeries(11))
Write-Host  ([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, constructors, methods, etc.

   
Add-Type -Path "C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Numerics.dll"

# Instance Class  
class Fiborial {

    # Instance Field  
    hidden [int] $instanceCount  
    # Static Field  
    hidden static [int] $staticCount          
    # Instance Read-Only Property/Getter  
    # Within instance members, you can always use    
    # the "this" reference pointer to access your (instance) members.  
    [int] GetInstanceCount() {  
        return $this.instanceCount
    }  
    # Static Read-Only Property/Getter  
    # As with Static Methods, you cannot reference your class members  
    # with the "this" reference pointer since static members are not  
    # instantiated.
    static [int] GetStaticCount() {  
        return [Fiborial]::staticCount
    }  
    # Instance Constructor 
    Fiborial() {    
        $this.instanceCount = 0
        Write-Host ("Instance Constructor $($this.instanceCount)`n")
    }    
    # Static Constructor  
    static Fiborial() {
        [Fiborial]::staticCount = 0
        Write-Host ("Static Constructor $([Fiborial]::staticCount)`n")
    }
    # Instance Method  
    [void] Factorial([int] $n)  
    {    
        $this.instanceCount++  
        Write-Host ("Factorial($n)`n") 
    }  
    # Static Method  
    static [void] Fibonacci([int] $n)   
    {      
        [Fiborial]::staticCount++
        Write-Host ("Fibonacci($n)`n")  
    }      
}

# Calling Static Constructor/Initializer and Methods  
# No need to instantiate  
[Fiborial]::Fibonacci(5)              
  
# Calling Instance Constructor and Methods  
# Instance required  
$fib = [Fiborial]::new()
$fib.Factorial(5)  

[Fiborial]::Fibonacci(15)              
$fib.Factorial(5)  

# Calling Instance Constructor and Methods  
# for a second object  
$fib2 = [Fiborial]::new()  
$fib2.Factorial(5)

# Calling Static Method  
Write-Host ("Static Count = $([Fiborial]::GetStaticCount())")  
# Calling Instance Property of object 1 and 2  
Write-Host ("Instance 1 Count = $($fib.GetInstanceCount())")
Write-Host ("Instance 2 Count = $($fib2.GetInstanceCount())")  
  
Read-Host 


And the Output is:


















Factorial using System.Int64, System.Double, System.Numerics.BigInteger

The Factorial of numbers over 20 are massive!
For instance: !40 = 815915283247897734345611269596115894272000000000!
Because of this, the previous version of this program was giving the "wrong" result
!40 = -70609262346240000 when using "long" (System.Int64) type, but it was not until I did the Fiborial version in VB.NET that I realized about this faulty code, because instead of giving me a wrong value, VB.NET, JScript.NET, Boo execution thrown an Overflow Exception when using the "Long/long" (System.Int64) type.

My first idea was to use ulong and ULong, but both failed for "big" numbers. I then used Double (double floating point) type and got no more exception/wrong result. The result of the factorial was now correct !40 = 1.1962222086548E+56, but still I wanted to show the Integer value of it, so I did some research and found that there is a new System.Numerics.BigInteger class in the .NET Framework 4.0. Adding the reference to the project and using this new class as the return type of the Factorial methods, I was able to get the result I was expecting.
!40 = 815915283247897734345611269596115894272000000000

What I also found was that using different types change the time the algorithm takes to finish:
System.Int64 < System.Double < System.Numerics.BigInteger
Almost by double!

To illustrate what I just said, lets have a look at the following code and the output we get.



NOTE: you need to manually add a reference to the System.Numerics.dll assembly to your project so you can add it to your code.

And the Output is:




























































Tuesday, November 17, 2015

PowerShell - Basics by Example



To continue with the Basics by Example. today's version of the post written in PowerShell Enjoy!

You can copy and paste the code below in your favorite IDE/Editor, I use PowerShell ISE, and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.

Beware that this is using the class keyword introduced on PowerShell version 5.0. If you're on Windows 10, you must have it already, otherwise you will need to download the Windows Management Framework 5.0 Production Preview . You can check your current version using the following command:






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/2010/08/new-series-languages-basics-by-example.html 



Greetings Program - Verbose
# PowerShell Basics

# Greeting Class  
class Greet {
    # Fields and Auto-Properties (PowerShell doesn't differentiate between fields & properties)
    [String] $message = ""
    [String] $name = ""
    [Int] $loopMessage = 0
    # Set-Property method 
    [void] setMessage([String] $value) {
        $this.message = $this.Capitalize($value)
    }
    [void] setName([String] $value) {
        $this.name = $this.Capitalize($value)
    }
    # Constructor 
    Greet() {
        $this.message = ""
        $this.name = ""
        $this.loopMessage = 1
    }
    # Overloaded Constructor  
    Greet([String] $message, [String] $name, [String] $loopMessage) {
        $this.message = $message
        $this.name = $name
        $this.loopMessage = $loopMessage
    }
    # Method 1
    [String] Capitalize([String] $val) {
        if ($val.Length -eq 0) {  
            return ""
        } else {
            return (Get-Culture).TextInfo.ToTitleCase($val)            
        }
        #Write-Host ("Hello {0}!`n" -f $this.name)
    }    
    # Method 2    
    [void] Salute() {
        # "for" statement (no need of ; if linebreak used) 
        for ($i = 0; $i -lt $this.loopMessage; $i++) {  
            Write-Host ("{0} {1}!" -f $this.message, $this.name)
        }  
    }  
    # Overloaded Method 2.1  
    [void] Salute([String] $message, [String] $name, [String] $loopMessage) {
        $i = 0
        # "while" statement  
        while ($i -lt $loopMessage) {  
            Write-Host ("{0} {1}!" -f $this.Capitalize($message), $this.Capitalize($name))
            $i++
        }       
    }  
    # Overloaded Method 2.2  
    [void] Salute([String] $name) {
        $dtNow = Get-Date
        switch -regex ($dtNow.Hour) {
            "^(10|11|[6-9])" {$this.message = "good morning,";break} 
            "^(1[2-7])" {$this.message = "good afternoon,";break} 
            "^(1[8-9]|2[0-2])" {$this.message = "good evening,";break}             
            "^(23|[0-5])" { $this.message = "good night,";break} 
            default {$this.message ="huh?"}
        }
        Write-Host ("{0} {1}!" -f $this.Capitalize($this.message), $this.Capitalize($name))
    }
}

# Console Program  

# Define object of type Greet and Instantiate. Call Constructor  
$g = [Greet]::new()
# Call Set (Methods)Properties and Property (PS is case-insensitive)
$g.setMessage("hello")
$g.setName("world")
$g.LoopMessage = 5 
# Call Method 2  
$g.Salute()  
# Call Overloaded Method 2.1 and Get Properties  
$g.Salute($g.Message, "powershell", $g.LoopMessage)
# Call Overloaded Method 2.2  
$g.Salute("carlos")
              
# Stop and Exit  
Read-Host "Press any key to exit..."

Greetings Program - Minimal

And the Output is:





Thursday, November 12, 2015

OO Hello World - PowerShell



The Hello World in PowerShell is finally here!

"Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework." Its been around for ~8 years (2006), but it is until now, with the release of version 5.0, that they finally introduce classes as a built-in feature of the language.

Now that the language have classes, properties, methods, constructors, static members, inheritance and so, we can compare its syntax with all other languages on this blog.

By the way, you can see my previous post here: http://carlosqt.blogspot.com/2010/06/oo-hello-world.html where I give some details on WHY these "OO Hello World series" samples.

Version 1 (Minimal):
The minimum you need to type to get your program compiled and running.
class Greet {
    [String] $name;
    Greet([String] $name) {
        $this.name = ([String]$name[0]).ToUpper() + $name.Substring(1);
    }
    [void] Salute() {
        Write-Host ("Hello {0}!`n" -f $this.name)
    }    
}

$g = [Greet]::new("World")
$g.Salute()

Version 2 (Verbose):
Explicitly adding instructions and keywords that are optional to the compiler.
class Greet {
    [String] $name;
    Greet([String] $name) {
        $this.name = ([String]$name[0]).ToUpper() + $name.Substring(1);
    }
    [void] Salute() {
        Write-Host ("Hello {0}!`n" -f $this.name)
    }    
}

$g = [Greet]::new("World")
$g.Salute()



Both version are completely similar.

The Program Output:









PowerShell Info:
“PowerShell is an automation platform and scripting language for Windows and Windows Server that allows you to simplify the management of your systems. Unlike other text-based shells, PowerShell harnesses the power of the .NET Framework, providing rich objects and a massive set of built-in functionality for taking control of your Windows environments. ” Taken from: https://msdn.microsoft.com/en-us/mt173057.aspx

Appeared:
2006
Current Version:
Developed by:
Microsoft
Creator:
Jeffrey Snover, Bruce Payette, James Truher
Influenced by:
C# and Perl, Tcl, Cmd
Predecessor Language
~WSH (VBScript, JScript)
Predecessor Appeared
1998
Predecessor Creator
Microsoft
Runtime Target:
CLR 4.x
Latest Framework Target:
CLR 4.x
Mono Target:
No
Allows Unmanaged Code:

Source Code Extension:
".ps1", "ps*"
Keywords:
35
Case Sensitive:
No
Free Version Available:
Yes
Open Source:
No
Standard:
No
Latest IDE Support:
PowerShell ISE
Language Reference:
More Info: