Tuesday, November 19, 2013

Arrays and Indexers in Cobra



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


use System.Text

namespace CobraArrays

class Program is public
    shared   
        def main
            # Single-dimensional Array(s)  
            .printTitle("Reverse Array Elements")
            
            # Declare and initialize Array of Chars 
            letters as char[] = char[](5)
            letters[0] = c'A'  
            letters[1] = c'E'  
            letters[2] = c'I'  
            letters[3] = c'O'  
            letters[4] = c'U'
            
            .printArrayChar(letters)  
            inverse_letters as char[] = .reverseChar(letters)  
            .printArrayChar(inverse_letters)
        
            .printTitle("Sort Integer Array Elements")  

            # Declare and Initialize Array of Integers  
            numbers as int[] = @[10, 8, 3, 1, 5]
            .printArrayInt(numbers)  
            ordered_numbers as int[] = .bubblesortInt(numbers)  
            .printArrayInt(ordered_numbers)  

            .printTitle("Sort String Array Elements")  

            # Declare and Initialize and Array of Strings  
            names as String[] = @[   
                'Damian', 
                'Rogelio',   
                'Carlos', 
                'Luis', 
                'Daniel'  
            ]  
            .printArrayString(names)  
            ordered_names as String[] = .bubblesortString(names)  
            .printArrayString(ordered_names)  

            # Multi-dimensional Array (Matrix row,column) 
            # Cobra does not support multi-dimensional arrays syntax            
            # using List<of List<of Type>> instead
            .printTitle("Transpose Matrix")  

            /# Matrix row=2,col=3   
            # A =  [6  4 24]   
            #      [1 -9  8]   
            #/               
            matrix as List<of List<of int>> = [[6, 4, 24],
                                                [1, -9, 8]]            

            .printMatrix(matrix)  
            transposed_matrix as List<of List<of int>> = .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 as String[] = @[   
            #      @[ 'word1', 'word2', 'wordN' ],   
            #      @[ 'word1', 'word2', 'wordM' ],   
            #      ...  
            #      ]  
            #   
            # Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"  
            #   
            #/  
            text = [ _
            "Hoy es el día más hermoso de nuestra vida, querido Sancho;".split(c' '),   
            "los obstáculos más grandes, nuestras propias indecisiones;".split(c' '),
            "nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;".split(c' '),
            "la cosa más fácil, equivocarnos;".split(c' '),
            "la más destructiva, la mentira y el egoísmo;".split(c' '),
            "la peor derrota, el desaliento;".split(c' '),
            "los defectos más peligrosos, la soberbia y el rencor;".split(c' '),
            "las sensaciones más gratas, la buena conciencia...".split(c' ')
            ]
            
            .printJaggedArray(text)  
            /#
            .uppercaserandomArray(text)  
            #/
            .printJaggedArray(text)  
            .graphJaggedArray(text)  
            
            # Array Exceptions  
            .printTitle("Common Array Exceptions")  

            .printCommonArrayExceptions(nil)  
            .printCommonArrayExceptions(text)  

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

            print "\nVowels = {" + [vowels[0], vowels[1], vowels[2], 
                                vowels[3], vowels[4]].join(",") + "}"  

            en as Alphabet = Alphabet("abcdefghijklmnopqrstuvwxyz")  
            print "English Alphabet = {[en.toString]}"  

            print "Alphabet Extract en\[9..19\] = {[Alphabet(en.slice(9, 10))]}"

            word1 as String = [en[6], en[14], en[14], en[3]].join('')  
            word2 as String = [en[1], en[24], en[4]].join('')
            word3 as String = [en[4], en[21], en[4], en[17], en[24],   
                                en[14], en[13], en[4]].join('')
            print "\n[word1] [word2], [word3]!"  

            Console.read
        
        def reverseChar(arr as char[]) as char[]
            reversed as char[] = char[](arr.length)  
            i as int = 0  
            for j in arr.length-1:-1:-1
                reversed[i] = arr[j]  
                i += 1
            return reversed
            
        def bubblesortInt(arr as int[]) as int[]  
            swap as int = 0  
            for i in arr.length-1:-1:-1  
                for j in arr.length-1
                    if arr[j] > arr[j + 1]
                        swap = arr[j]  
                        arr[j] = arr[j + 1]  
                        arr[j + 1] = swap  
            return arr 
            
        def bubblesortString(arr as String[]) as String[]
            swap as String = ""  
            for i in arr.length-1:-1:-1  
                for j in arr.length-1
                    if arr[j][0] > arr[j + 1][0]
                        swap = arr[j]  
                        arr[j] = arr[j + 1]  
                        arr[j + 1] = swap  
            return arr 
        
        def transposeMatrix(m as List<of List<of int>>) as List<of List<of int>>
            /# Transposing a Matrix 2,3   
            #   
            # A =  [6  4 24]T [ 6  1]   
            #      [1 -9  8]  [ 4 -9]  
            #                 [24  8]  
            #/ 
            transposed = [[0]] # to get [int] instead of [object]
            transposed.clear
            for i in 0:m[0].count
                transposed.add([0]) # same here
                transposed[i].clear
                for j in 0:m.count    
                    transposed[i].add(m[j][i])
            return transposed        
        
        def printArrayChar(arr as char[]) 
            print "\nPrint Array Content " + arr.getType.name.replace(']', _
                arr.length.toString + ']')
            for i in arr.length
                print " array " + String.format("[[{0,2}]] = {1,2}", i, arr[i])
                
        def printArrayInt(arr as int[]) 
            print "\nPrint Array Content " + arr.getType.name.replace(']', _
                arr.length.toString + ']')
            for i in arr.length
                print " array " + String.format("[[{0,2}]] = {1,2}", i, arr[i])
        
        def printArrayString(arr as String[]) 
            print "\nPrint Array Content " + arr.getType.name.replace(']', _
                arr.length.toString + ']')
            for i in arr.length
                print " array " + String.format("[[{0,2}]] = {1,2}", i, arr[i])
        
        def printMatrix(m as List<of List<of int>>)
            print "\nPrint Matrix Content " + m.getType.name 
            for i in 0:m.count 
                for j in 0:m[0].count  
                    print " array " + String.format("[[{0,2},{1,2}]] = {2,2} " _ 
                        , i, j, m[i][j])
        
        def graphJaggedArray(arr as List<of String[]?>)  
            /# When using Arrays, we can use for(each) instead of for by index:         
            #    
            # for s in arr: 
            #   for w as String in s 
            #    
            #/  
            print "\nPrint Text Content [arr.getType.name]"  
            for i in arr.count  
                Console.write("Line{0,2}|", i+1)
                for j in arr[i].length  
                    Console.write("{0,3}", "*")
                print " ([arr[i].length.toString])"  
        
        def printJaggedArray(arr as List<of String[]?>)  
            line as StringBuilder?      
            print "\nPrint Jagged Array Content [arr.getType.name]"
            for i in arr.count
                line = StringBuilder() 
                for j in arr[i].length
                    line.append(" " + arr[i][j])
                if line.toString == line.toString.toUpper  
                    line.append(r" <-- [UPPERCASED]")  
                print line.toString
        
        def printCommonArrayExceptions(arr as List<of String[]?>?)  
            try  
                arr[100][100] = "hola"    
            catch ex as Exception      
                print "\nException: \n[ex.getType.name]\n[ex.message]"  
        
        def printTitle(message as String) 
            print ""
            print "======================================================"
            print message
            print "======================================================"
    
class Alphabet is public
    # Array Field
    var _letters as char[]? is private
    
    # Indexer Get/Set Property  
    pro [index as int] as char is public
        get
            return _letters[index]
        set
            _letters[index] = value.toUpper
            
    # Read-Only Property  
    get length as int is public
        return _letters.length
    
    # Constructors
    cue init(size as int) is public  
        base.init  
        _letters = char[](size)
    
    cue init(list as String) is public
        base.init
        _letters = list.toUpper.toCharArray
    
    cue init(list as char[]) is public
        base.init
        _letters = list
    
    # Overridden Method    
    def toString as String is override
        return "" + _letters.join(',')

    # Method 
    def slice(start as int, length as int) as char[]?
        return _letters[start:start+length]


The output:






















































































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