Tuesday, May 6, 2014

Arrays and Indexers in JRuby



Today's post is about Arrays and Indexers in JRuby. 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 JRuby, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

This is the first post on this series on a language targeting the JVM. Besides the fact that I had the code from a previous post written in (Iron)Ruby, the newly released version of the (J)Ruby plugin for NetBeans IDE (http://plugins.netbeans.org/plugin/38549/?show=true) helped me decide what to publish next.

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.

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.


require "java"

# Console Program  
def main()  
    # Single-dimensional Array(s)  
    print_title("Reverse Array Elements")  
   
    # Declare and Initialize Array of Chars        
    letters = Array.new(5," ")  
    letters[0] = "A"  
    letters[1] = "E"  
    letters[2] = "I"  
    letters[3] = "O"  
    letters[4] = "U"  
   
    print_array(letters)    
    inverse_letters = reverse_char(letters)  
    print_array(inverse_letters)  
  
    print_title("Sort Integer Array Elements")  
    # Declare and Initialize Array of Integers     
    numbers = [10, 8, 3, 1, 5]  
      
    print_array(numbers)         
    ordered_numbers = bubblesort(numbers)     
    print_array(ordered_numbers)  
  
    print_title("Sort String Array Elements")    
   
    # Declare and Initialize and Array of Strings   
    #names = Array.new(5, ["Damian","Rogelio","Carlos","Luis","Daniel"])  
    # or just   
    names = ["Damian",   
      "Rogelio",   
      "Carlos",   
      "Luis",   
      "Daniel"]  
  
    print_array(names)     
    ordered_names = bubblesort(names)     
    print_array(ordered_names)  
  
    # Multi-dimensional Array (Matrix row,column)     
    print_title("Transpose Matrix")     
  
    # for an empty table initialized to 0s  
    # matrix = Array.new(rows,0) { Array.new(cols,0) }  
    matrix = [[6, 4, 24],        
              [1, -9, 8]]  
  
    print_matrix(matrix)  
    transposed_matrix = transpose_matrix(matrix)     
    print_matrix(transposed_matrix)    
   
    # Jagged Array (Array-of-Arrays)     
    print_title("Upper Case Random Array & Graph Number of Elements")     
  
=begin  
# Creating an array of string arrays using the String.Split method     
# instead of initializing it manually as follows:     
#   
# text = [      
#  [ ["word1", "word2, "wordN"],      
#  [ ["word1", "word2, "wordN"],      
#  ...  
#  ]     
#       
# Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"          
=end  
    text = [  
    "Hoy es el dia mas hermoso de nuestra vida, querido Sancho;".split(" "),      
    "los obstaculos mas grandes, nuestras propias indecisiones;".split(" "),      
    "nuestro enemigo mas fuerte, miedo al poderoso y nosotros mismos;".split(" "),      
    "la cosa mas facil, equivocarnos;".split(" "),      
    "la mas destructiva, la mentira y el egoismo;".split(" "),      
    "la peor derrota, el desaliento;".split(" "),      
    "los defectos mas peligrosos, la soberbia y el rencor;".split(" "),      
    "las sensaciones mas gratas, la buena conciencia...".split(" ")  
    ]   
   
    print_jagged_array(text)     
    uppercase_random_array(text)        
    print_jagged_array(text)     
    graph_jagged_array(text)  
  
    # Array Exceptions  
    print_title('Common Array Exceptions')  
      
    print_common_array_exceptions(nil)  
    print_common_array_exceptions(text)    
  
    # Accessing Class Array Elements through Indexer  
    print_title('Alphabets')  
      
    vowels = Alphabet.new(5)  
    vowels[0] = "a"  
    vowels[1] = "e"  
    vowels[2] = "i"  
    vowels[3] = "o"  
    vowels[4] = "u"  
  
    puts "\nVowels={%s}" % [vowels[0],vowels[1],vowels[2],vowels[3],vowels[4]].join(",")  
  
    en = Alphabet.new("abcdefghijklmnopqrstuvwxyz")     
  
    puts "English Alphabet = {%s}" % [en]  
  
    puts "Alphabet Extract en[9..19] = {%s}" % [Alphabet.new(en.slice(9, 10))]  
  
    word1 = [en[6],en[14],en[14],en[3]].join("")  
    word2 = [en[1],en[24],en[4]].join("")     
    word3 = [en[4],en[21],en[4],en[17],en[24],en[14],en[13],en[4]].join("")     
    puts "\n%s %s, %s!\n" % [word1, word2, word3]  
   
    gets  
end  
  
def reverse_char(arr)  
    arr.reverse  
end   
  
def bubblesort(arr)    
    for i in arr.reverse  
        for j in (0..arr.count-2)  
            if arr[j] > arr[j + 1]      
                swap = arr[j]     
                arr[j] = arr[j + 1]     
                arr[j + 1] = swap     
            end      
        end   
    end     
    arr  
end  
  
def transpose_matrix(m)    
=begin  
# Transposing a Matrix 2,3    
#       
#   A =  [6  4 24]T [ 6  1]    
#        [1 -9  8]  [ 4 -9]    
#                [24  8]    
=end  
    transposed = Array.new(m[0].size) { Array.new(m.size) }   
    for i in 0..(m.size-1)     
        for j in 0..(m[0].size-1)     
            transposed[j][i] = m[i][j]  
        end  
    end  
    transposed    
end  
  
def uppercase_random_array(arr)        
    r = java.util.Random.new()
    i = r.nextInt(arr.size)
    for j in 0..(arr[i].size-1)     
        arr[i][j] = arr[i][j].upcase  
    end  
end  
  
def print_array(arr)  
    puts "\nPrint Array Content #{arr.class.name}[#{arr.size}]"  
    for i in 0..(arr.size-1)  
        puts " array [%2s] = %2s" % [i, arr[i]]  
    end  
end  
  
def print_matrix(m)  
    puts "\nPrint Array Content #{m.class.name}[#{m.size}][#{m[0].size}]"  
    for i in 0..(m.size-1)  
        for j in 0..(m[0].size-1)  
            puts " array [%2s,%2s] = %2s" % [i, j, m[i][j]]  
        end  
    end  
    m  
end  
  
def graph_jagged_array(arr)  
=begin  
# When using Arrays, we can use for(each) instead of for by index  
#    for s in arr    
#        for w in s   
#        end  
#    end  
=end   
    puts "\nPrint Text Content #{arr.class.name}"  
    for i in 0..(arr.size-1)    
        line = ""  
        line += "Line %2s|" % (i+1).to_s   
        for j in 0..(arr[i].size-1)     
            line += " * "  
        end              
        line += "(#{arr[i].size})"  
        puts line  
    end  
end  
  
def print_jagged_array(arr)  
    puts "\nPrint Jagged Array Content #{arr.class.name}"  
    for i in 0..(arr.size-1)  
        line = ""  
        for j in 0..(arr[i].size-1)       
            line += " " + arr[i][j]  
        end  
        if line == line.upcase  
            line += " <-- [UPPERCASED]"  
        end  
        puts line  
    end  
end  
  
def print_common_array_exceptions(arr)  
    begin    
        arr.fetch(100)  
    rescue Exception => ex  
      puts "\nException: \n%s\n%s" % [ex.class.name, ex.message]  
    #else  
    #   others  
    end  
end  
  
def print_title(message)     
    puts ""    
    puts ("=" * 54)     
    puts message     
    puts ("=" * 54)  
end       
  
  
class Alphabet  
    # Array Field     
    @letters = []  
  
    # Indexer Get/Set Property  
    def [](idx)  
        @letters[idx]  
    end  
    def []=(idx, value)  
        @letters[idx] = value.upcase  
    end  
      
    # Read-Only Getter  
    def length  
        @letters.size  
    end            
  
    # Constructor/Initializer  
    def initialize(param)    
        if param.class == 1.class  
            @letters = Array.new(param, " ")  
        elsif param.class == "".class  
            @letters = param.upcase.chars.to_a  
        elsif param.class == [].class  
            @letters = param  
        else  
            @letters = nil  
        end  
    end  
  
    # Overridden Method      
    def to_s  
        @letters.join(",")  
    end  
   
    # Method     
    def slice(start, length)  
        @letters[start..start+length-1]  
    end  
  
end  
  
main


The output:



































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

Thursday, March 6, 2014

Arrays and Indexers in F#



Today's post is about Arrays and Indexers in F#. 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 F#, 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.

WARNING! I know that F# is intended to be use in a Functional way, however, my goal is to show its Imperative and OO language features, so it can be compared with other OO languages. Said that, if you know how to do something on the examples below on a Functional way, you are welcome to add them as a comment :)


open System
open System.Text

module FsArrays =
    type Alphabet public (size: int) as this = class    
        // Array Field 
        [<DefaultValue>]
        val mutable private letters: char array 
        do this.letters <- Array.create size ' '
        // Indexer Get/Set Property  
        member public this.Item
            with get(index) = 
                this.letters.[index]
            and set index value = 
                this.letters.[index] <- value.ToString().ToUpper().[0]
        // Read-only Property
        member public this.Length
            with get() = this.letters.Length
        // Constructors  
        new() = new Alphabet(0)
        new(l: string) as this = new Alphabet(l.Length) then 
            this.letters <- l.ToUpper().ToCharArray()
        new(l: char[]) as this = new Alphabet(0) then 
            this.letters <- l
        // Overridden Method  
        override this.ToString() = 
            String.Join(",", [|for c in this.letters -> c.ToString()|])
        // Method
        member public this.Slice(start: int, length: int): char[] = 
            this.letters.[start .. start + length - 1]
    end

    let ReverseChar (arr: char array) : char array = 
        Array.rev arr

    let BubbleSortInt (arr: int array) = 
        let mutable swap = 0
        for i in Array.rev(arr) do
            for j in 0 .. arr.Length - 2 do
                if arr.[j] > arr.[j + 1] then
                    swap <- arr.[j]   
                    arr.[j] <- arr.[j + 1] 
                    arr.[j + 1] <- swap  
        arr  

    let BubbleSortString (arr: string array) = 
        let mutable swap = ""
        for i in Array.rev(arr) do
            for j in 0 .. arr.Length - 2 do
                if arr.[j].[0] > arr.[j + 1].[0] then
                    swap <- arr.[j]   
                    arr.[j] <- arr.[j + 1] 
                    arr.[j + 1] <- swap  
        arr  

    let TransposeMatrix(m: int[,]): int[,] =
        (* Transposing a Matrix 2,3  
            *  
            * A =  [6  4 24]T [ 6  1]  
            *      [1 -9  8]  [ 4 -9] 
            *                 [24  8] 
        *)  
        let transposed = Array2D.zeroCreate<int> (m.GetLength 1) (m.GetLength 0)  
        for i in 0 .. m.GetLength 0 - 1 do
            for j in 0 .. m.GetLength 1 - 1 do
                transposed.[j, i] <- m.[i, j]         
        transposed;  
  
    let UpperCaseRandomArray (arr: string[][]) =         
        let r = new System.Random()
        let i = r.Next (arr.Length - 1)
        for j in 0 .. arr.[i].Length - 1 do 
            arr.[i].[j] <- arr.[i].[j].ToUpper()

    let PrintArrayChar (arr: char array) =
        printfn "\nPrint Array Content %s" 
            (arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"))
        for i in 0 .. arr.Length - 1 do
            printfn " array [%2i] = %2c" i arr.[i] 

    let PrintArrayInt (arr: int array) =
        printfn "\nPrint Array Content %s" 
            (arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"))
        for i in 0 .. arr.Length - 1 do
            printfn " array [%2i] = %2i" i arr.[i] 

    let PrintArrayString (arr: string array) =
        printfn "\nPrint Array Content %s" 
            (arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"))
        for i in 0 .. arr.Length - 1 do
            printfn " array [%2i] = %2s" i arr.[i] 

    let PrintMatrix (m: int[,]) = 
        printfn "\nPrint Matrix Content %s[%i,%i]" 
            (m.GetType().Name.Replace("[,]", "")) (m.GetLength 0) (m.GetLength 1)
        for i in 0 .. m.GetLength 0 - 1 do
            for j in 0 .. m.GetLength 1 - 1 do
                printfn " array [%2i,%2i] = %2i " i j m.[i, j]  

    let GraphJaggedArray (arr: string[][]) =  
        (* When using Arrays, we can use foreach instead of for + index:  
        *  
        * for i in 0 .. m.GetLength 0 - 1 do
        *   for j in 0 .. m.GetLength 1 - 1 do              
        *  
        *)  
        printfn "\nPrint Matrix Content %s" (arr.GetType().Name)
        let mutable lineCount = 1
        for s in arr do
            printf "Line%2i|" lineCount  
            for w in s do  
                printf "%3c" '*'  
            printfn " (%i)" (s.Length)
            lineCount <- lineCount + 1

    let PrintJaggedArray (arr: string[][]) = 
        printfn "\nPrint Jagged Array Content %s" (arr.GetType().Name)  
        for i in 0 .. arr.Length - 1 do
            let line = new StringBuilder()
            for j in 0 .. arr.[i].Length - 1 do
                line.Append (" " + arr.[i].[j]) |> ignore
            if line.ToString() = line.ToString().ToUpper() then
                line.Append " <-- [UPPERCASED]" |> ignore
            printfn "%s" (line.ToString())

    let PrintTitle (message: string) = 
        printfn "\n"
        printfn "%s" ([|for i in 0..54 -> "*"|] |> String.concat "")
        printfn "%s" message
        printfn "%s" ([|for i in 0..54 -> "*"|] |> String.concat "")

    let PrintCommonArrayExceptions (arr: string[][]) =
        try
            arr.[100].[100] <- "hola"
        with
            (*
            | :? IndexOutOfRangeException as ex -> 
            | _ as ex -> 
            *)
            | ex -> 
                printfn "\nException: \n%s\n%s" (ex.GetType().Name) (ex.Message)

    [<EntryPoint>]
    let main argv =       
        // Single-dimensional Array(s)   
        PrintTitle "Reverse Array Elements"

        // Declare and Initialize Array of Chars
        let letters: char array = Array.create 5 ' '
        letters.[0] <- 'A'  
        letters.[1] <- 'E'  
        letters.[2] <- 'I'  
        letters.[3] <- 'O'  
        letters.[4] <- 'U'  

        PrintArrayChar letters
        let inverse_letters = ReverseChar letters   
        PrintArrayChar inverse_letters

        PrintTitle "Sort Integer Array Elements"   
 
        // Declare and Initialize Array of Integers    
        let numbers = [| 10; 8; 3; 1; 5 |]

        PrintArrayInt numbers   
        let ordered_numbers = BubbleSortInt numbers    
        PrintArrayInt ordered_numbers    

        PrintTitle "Sort String Array Elements"
    
        // Declare and Initialize and Array of Strings    
        let names : string array = [|"Damian";    
                "Rogelio";    
                "Carlos";    
                "Luis";   
                "Daniel"|]   

        PrintArrayString names
        let ordered_names = BubbleSortString names
        PrintArrayString ordered_names   

        // Multi-dimensional Array (Matrix row,column)      
        PrintTitle "Transpose Matrix"
    
        // let matrix = Array2D.zeroCreate<int> 2 3
        let matrix = array2D [|[|6; 4; 24|];
                                [|1; -9; 8|]|]    

        PrintMatrix matrix
        let 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: 
        *  
        * let text: string[][] = [|  
        *      [| "word1"; "word2"; "wordN" |];  
        *      [| "word1"; "word2"; "wordM" |];  
        *      ... 
        *      |]
        *  
        * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
        *  
        *)  
        let mutable 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
        PrintJaggedArray text
        GraphJaggedArray text  

        // Array Exceptions  
  
        PrintTitle "Common Array Exceptions"

        PrintCommonArrayExceptions null
        PrintCommonArrayExceptions text  

        // Accessing Class Array Elements through Indexer  
  
        PrintTitle "Alphabets" 

        let vowels = new Alphabet(5)
        vowels.[0] <- 'a'
        vowels.[1] <- 'e'
        vowels.[2] <- 'i'
        vowels.[3] <- 'o'
        vowels.[4] <- 'u'

        printfn "\nVowels = {%s}" (String.Join(",", [|vowels.[0].ToString(); vowels.[1].ToString(); vowels.[2].ToString(); vowels.[3].ToString(); vowels.[4].ToString()|]))
  
        let en = new Alphabet("abcdefghijklmnopqrstuvwxyz")
        printfn "English Alphabet = {%s}" (en.ToString())  
  
        let x = new Alphabet(en.Slice(9, 10))
        printfn "Alphabet Extract en[9..19] = {%s}" (x.ToString())

        let word1 = String.Join("", [|en.[6].ToString(); en.[14].ToString(); en.[14].ToString(); en.[3].ToString()|])
        let word2 = String.Join("", [|en.[1].ToString(); en.[24].ToString(); en.[4].ToString()|])  
        let word3 = String.Join("", [|en.[4].ToString(); en.[21].ToString(); en.[4].ToString(); en.[17].ToString(); en.[24].ToString(); en.[14].ToString(); en.[13].ToString(); en.[4].ToString()|])  
  
        printfn "\n%s %s, %s!\n" word1 word2 word3

        Console.Read() |> ignore
        0 // Return


The output:






















































































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

Thursday, February 27, 2014

Arrays and Indexers in IronRuby



Today's post is about Arrays and Indexers in IronRuby. 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 IronRuby, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

This is the last of the .NET dynamic languages. I'm considering to stop writing about it because the project seems to be dead with no updates since 13/03/11)... will see, probably this will be the last post about it if no news, fortunately, there is still JRuby.

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 JRuby, later on, 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.


require "mscorlib" 
include System

# Console Program
def main()
    # Single-dimensional Array(s)
    print_title("Reverse Array Elements")
 
    # Declare and Initialize Array of Chars      
    letters = Array.new(5," ")
    letters[0] = "A"
    letters[1] = "E"
    letters[2] = "I"
    letters[3] = "O"
    letters[4] = "U"
 
    print_array(letters)  
    inverse_letters = reverse_char(letters)
    print_array(inverse_letters)

    print_title("Sort Integer Array Elements")
    # Declare and Initialize Array of Integers   
    numbers = [10, 8, 3, 1, 5]
    
    print_array(numbers)       
    ordered_numbers = bubblesort(numbers)   
    print_array(ordered_numbers)

    print_title("Sort String Array Elements")  
 
    # Declare and Initialize and Array of Strings 
    #names = Array.new(5, ["Damian","Rogelio","Carlos","Luis","Daniel"])
    # or just 
    names = ["Damian", 
      "Rogelio", 
      "Carlos", 
      "Luis", 
      "Daniel"]

    print_array(names)   
    ordered_names = bubblesort(names)   
    print_array(ordered_names)

    # Multi-dimensional Array (Matrix row,column)   
    print_title("Transpose Matrix")   

    # for an empty table initialized to 0s
    # matrix = Array.new(rows,0) { Array.new(cols,0) }
    matrix = [[6, 4, 24],      
              [1, -9, 8]]

    print_matrix(matrix)
    transposed_matrix = transpose_matrix(matrix)   
    print_matrix(transposed_matrix)  
 
    # Jagged Array (Array-of-Arrays)   
    print_title("Upper Case Random Array & Graph Number of Elements")   

=begin
# Creating an array of string arrays using the String.Split method   
# instead of initializing it manually as follows:   
# 
# text = [    
#  [ ["word1", "word2, "wordN"],    
#  [ ["word1", "word2, "wordN"],    
#  ...
#  ]   
#     
# Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"        
=end
    text = [
    "Hoy es el dia mas hermoso de nuestra vida, querido Sancho;".split(" "),    
    "los obstaculos mas grandes, nuestras propias indecisiones;".split(" "),    
    "nuestro enemigo mas fuerte, miedo al poderoso y nosotros mismos;".split(" "),    
    "la cosa mas facil, equivocarnos;".split(" "),    
    "la mas destructiva, la mentira y el egoismo;".split(" "),    
    "la peor derrota, el desaliento;".split(" "),    
    "los defectos mas peligrosos, la soberbia y el rencor;".split(" "),    
    "las sensaciones mas gratas, la buena conciencia...".split(" ")
    ] 
 
    print_jagged_array(text)   
    uppercase_random_array(text)      
    print_jagged_array(text)   
    graph_jagged_array(text)

    # Array Exceptions
    print_title('Common Array Exceptions')
    
    print_common_array_exceptions(nil)
    print_common_array_exceptions(text)  

    # Accessing Class Array Elements through Indexer
    print_title('Alphabets')
    
    vowels = Alphabet.new(5)
    vowels[0] = "a"
    vowels[1] = "e"
    vowels[2] = "i"
    vowels[3] = "o"
    vowels[4] = "u"

    puts "\nVowels={%s}" % [vowels[0],vowels[1],vowels[2],vowels[3],vowels[4]].join(",")

    en = Alphabet.new("abcdefghijklmnopqrstuvwxyz")   

    puts "English Alphabet = {%s}" % [en]

    puts "Alphabet Extract en[9..19] = {%s}" % [Alphabet.new(en.slice(9, 10))]

    word1 = [en[6],en[14],en[14],en[3]].join("")
    word2 = [en[1],en[24],en[4]].join("")   
    word3 = [en[4],en[21],en[4],en[17],en[24],en[14],en[13],en[4]].join("")   

    puts "\n%s %s, %s!\n" % [word1, word2, word3]
 
    gets
end

def reverse_char(arr)
    arr.reverse
end 

def bubblesort(arr)  
    for i in arr.reverse
        for j in (0..arr.count-2)
            if arr[j] > arr[j + 1]    
                swap = arr[j]   
                arr[j] = arr[j + 1]   
                arr[j + 1] = swap   
            end    
        end 
    end   
    arr
end

def transpose_matrix(m)  
=begin
# Transposing a Matrix 2,3  
#     
#   A =  [6  4 24]T [ 6  1]  
#        [1 -9  8]  [ 4 -9]  
#                [24  8]  
=end
    transposed = Array.new(m[0].size) { Array.new(m.size) } 
    for i in 0..(m.size-1)   
        for j in 0..(m[0].size-1)   
            transposed[j][i] = m[i][j]
        end
    end
    transposed  
end

def uppercase_random_array(arr)      
    r = System::Random.new
    i = r.next(arr.size)
    for j in 0..(arr[i].size-1)   
        arr[i][j] = arr[i][j].upcase
    end
end

def print_array(arr)
    puts "\nPrint Array Content #{arr.GetType().Name}[#{arr.size}]"
    for i in 0..(arr.size-1)
        puts " array [%2s] = %2s" % [i, arr[i]]
    end
end

def print_matrix(m)
    puts "\nPrint Array Content #{m.GetType().Name}[#{m.size}][#{m[0].size}]"
    for i in 0..(m.size-1)
        for j in 0..(m[0].size-1)
            puts " array [%2s,%2s] = %2s" % [i, j, m[i][j]]
        end
    end
    m
end

def graph_jagged_array(arr)
=begin
# When using Arrays, we can use for(each) instead of for by index
#    for s in arr  
#        for w in s 
#        end
#    end
=end 
    puts "\nPrint Text Content #{arr.GetType().Name}"
    for i in 0..(arr.size-1)  
        line = ""
        line += "Line %2s|" % (i+1).to_s 
        for j in 0..(arr[i].size-1)   
            line += " * "
        end            
        line += "(#{arr[i].size})"
        puts line
    end
end

def print_jagged_array(arr)
    puts "\nPrint Jagged Array Content #{arr.GetType().Name}"
    for i in 0..(arr.size-1)
        line = ""
        for j in 0..(arr[i].size-1)     
            line += " " + arr[i][j]
        end
        if line == line.upcase
            line += " <-- [UPPERCASED]"
        end
        puts line
    end
end

def print_common_array_exceptions(arr)
    begin  
        arr.fetch(100)
    rescue Exception => ex
        puts "\nException: \n%s\n%s" % [ex.GetType().Name, ex.message]
    #else
    #   others
    end
end

def print_title(message)   
    puts ""  
    puts ("=" * 54)   
    puts message   
    puts ("=" * 54)
end     


class Alphabet
    # Array Field   
    @letters = []

    # Indexer Get/Set Property
    def [](idx)
        @letters[idx]
    end
    def []=(idx, value)
        @letters[idx] = value.upcase
    end
    
    # Read-Only Getter
    def length
        @letters.size
    end          

    # Constructor/Initializer
    def initialize(param)  
        if param.class == 1.class
            @letters = Array.new(param, " ")
        elsif param.class == "".class
            @letters = param.upcase.chars.to_a
        elsif param.class == [].class
            @letters = param
        else
            @letters = nil
        end
    end

    # Overridden Method    
    def to_s
        @letters.join(",")
    end
 
    # Method   
    def slice(start, length)
        @letters[start..start+length-1]
    end

end

main


The output:






















































































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

Tuesday, February 25, 2014

Arrays and Indexers in IronPython



Today's post is about Arrays and Indexers in IronPython. 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 IronPython, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

This is the second post of a dynamic language. As with Phalanger's version of the program, code structure changed slightly from previous posts. Besides that, because you normally don't use Arrays per se in Python (except for numerical arrays when better performance is required), it is more practical to use Python's List object instead of .NET's System.Array, which can definitely be used in IronPython, specially when you need to inter operate with other CLS languages. You can even initialize a System.Array with a Python List like this: System.Array[int]([1, 2, 3]).

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 Boo (or Cobra or Jython later on) 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.


import clr
clr.AddReference("System")
import System
from System import Random
 
# Console Program   
def main():   
    # Single-dimensional Array(s)   
    printtitle('Reverse Array Elements'); 

    # Declare and Initialize Array (Python List) of Chars   
    # or letters = list('AEIOU')
    # or letters = 5 * [' ']      
    letters = list(' ' * 5) # letters = []
    letters[0] = 'A'        # letters.append('A')
    letters[1] = 'E'        # letters.append('E')
    letters[2] = 'I'        # letters.append('I')
    letters[3] = 'O'        # letters.append('O')
    letters[4] = 'U'        # letters.append('U')
    
    printarray(letters)
    inverse_letters = reversechar(letters)
    printarray(inverse_letters)

    printtitle('Sort Integer Array Elements')
    # Declare and Initialize Array of Integers   
    numbers = [10, 8, 3, 1, 5]
    
    printarray(numbers)   
    ordered_numbers = bubblesort(numbers)   
    printarray(ordered_numbers)

    printtitle('Sort String Array Elements')  

    # Declare and Initialize and Array of Strings   
    names = ['Damian', 'Rogelio', 'Carlos', 'Luis', 'Daniel']

    printarray(names)   
    ordered_names = bubblesort(names)   
    printarray(ordered_names)

    # Multi-dimensional Array (Matrix row,column)   
    printtitle('Transpose Matrix')   

    matrix = [[6, 4, 24],      
              [1, -9, 8]]

    printmatrix(matrix)
    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, "wordN"],    
        ...
    ]   
     
    Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"        
    '''
    text = [
    'Hoy es el dia mas hermoso de nuestra vida, querido Sancho;'.split(' '),    
    'los obstaculos mas grandes, nuestras propias indecisiones;'.split(' '),    
    'nuestro enemigo mas fuerte, miedo al poderoso y nosotros mismos;'.split(' '),    
    'la cosa mas facil, equivocarnos;'.split(' '),    
    'la mas destructiva, la mentira y el egoismo;'.split(' '),    
    'la peor derrota, el desaliento;'.split(' '),    
    'los defectos mas peligrosos, la soberbia y el rencor;'.split(' '),    
    'las sensaciones mas gratas, la buena conciencia...'.split(' ')
    ]

    printjaggedarray(text)   
    uppercaserandomarray(text)   
    printjaggedarray(text)   
    graphjaggedarray(text)

    # Array Exceptions
    printtitle('Common Array Exceptions')
    
    printcommonarrayexceptions(None)   
    printcommonarrayexceptions(text)  

    # Accessing Class Array Elements through Indexer
    printtitle('Alphabets')  
    
    vowels = Alphabet(5)
    vowels[0] = 'a'
    vowels[1] = 'e'
    vowels[2] = 'i'
    vowels[3] = 'o'
    vowels[4] = 'u'

    print '\nVowels = {%s}' % ','.join([vowels[0],vowels[1],vowels[2],vowels[3],vowels[4]])

    en = Alphabet('abcdefghijklmnopqrstuvwxyz')   
    print 'English Alphabet = {%s}' % (str(en))

    print 'Alphabet Extract en[9..19] = {%s}' % (str(Alphabet(en.slice(9, 10))))
   
    word1 = ''.join([en[6], en[14], en[14], en[3]])
    word2 = ''.join([en[1], en[24], en[4]])   
    word3 = ''.join([en[4], en[21], en[4], en[17], en[24], en[14], en[13], en[4]])   
    print "\n%s %s, %s!\n" % (word1, word2, word3)  

    raw_input()

def reversechar(arr):
    return list(reversed(arr))
    # or 
    # return arr[::-1]
    # or 
    # reversedarr = [], i = 0
    # for j in range(len(arr) - 1,-1,-1):
    #   reversedarr[i] = arr[j]
    # return reversedarr
    #

def bubblesort(arr):
    for i in reversed(arr):   
        for j in range(len(arr) - 1):   
            if arr[j] > arr[j + 1]:   
                swap = arr[j]   
                arr[j] = arr[j + 1]   
                arr[j + 1] = swap   
    return arr

def transposematrix(m):   
    ''' Transposing a Matrix 2,3  
     
     A =  [6  4 24]T [ 6  1]  
          [1 -9  8]  [ 4 -9]  
                     [24  8]  
    '''
    transposed = [len(m)*[0] for i in range(len(m[0]))]
    for i in range(len(m)):   
        for j in range(len(m[0])):   
        transposed[j][i] = m[i][j]
    return transposed  

def uppercaserandomarray(arr):   
    r = Random()   
    i = r.Next(len(arr))   
    for j in range(len(arr[i])):
        arr[i][j] = arr[i][j].upper()

def printarray(arr):
    print '\nPrint Array Content ' + arr.GetType().Name.Replace(']', str(len(arr)) + ']')
    for i in range(len(arr)):   
        print ' array [{0:2}'.format(i) + '] = {0:2}'.format(arr[i])

def printmatrix(m):   
    print '\nPrint Matrix Content ' + m.GetType().Name + '[' + str(len(m)) + ',' + str(len(m[0])) + ']'
    for i in range(len(m)):   
        for j in range(len(m[0])):   
            print ' array [{0:2},{1:2}] = {2:2} '.format(i, j, m[i][j])

def graphjaggedarray(arr):   
    '''When using Arrays, we can use for(each) instead of for by index:
    for s as (string) in arr:  
        for w as string in s: 
    ''' 
    print '\nPrint Text Content ' + arr.GetType().Name  
    for i in range(len(arr)):   
        line = ''
        line += 'Line{0:2}|'.format(i+1)
        for j in range(len(arr[i])):   
            line += '{0:3}'.format('*')   
        line += '(' + str(len(arr[i])) + ')'
        print line
        

def printjaggedarray(arr):
    print '\nPrint Jagged Array Content ' + arr.GetType().Name
    for i in range(len(arr)):
        line = ''
        for j in range(len(arr[i])):      
            line += ' ' + arr[i][j]
        if line == line.upper():
            line += ' <-- [UPPERCASED]'
        print line

def printcommonarrayexceptions(arr):
    try:
        arr[100][100] = 'hola'     
    except System.Exception as ex:
        print '\nException: \n%s\n%s' % (ex.GetType().Name, ex.Message)
    #except:
    #else:

def printtitle(message):    
    print ''  
    print '=' * 54   
    print message   
    print '=' * 54 


class Alphabet:
    # Array Field   
    _letters = []
    
    # Indexer Get/Set Property
    def __getitem__(self, idx):
        return self._letters[idx]
    def __setitem__(self, idx, value):
        self._letters[idx] = str(value).upper()
    
    # Read-Only Property
    def get_Length(self):
        return len(self._letters)   
    Length = property(fget=get_Length)

    # Constructor
    def __init__(self, param=None):           
        if type(param) == type(1):
            self._letters = list(' ' * param)
        elif type(param) == type(''):
            self._letters = list(str(param).upper())
        elif type(param) == type([]):
            self._letters = param
        else:
            self._letters = None

    # Overridden Method    
    def __str__(self):
        return ','.join(self._letters)

    # Method   
    def slice(self, start, length):
        return self._letters[start:start+length]

if __name__ == '__main__':
    main()


The output:






















































































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