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.

Sunday, October 27, 2013

Arrays and Indexers in Phalanger



Today's post is about Arrays and Indexers in Phalanger (PHP). 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 Phalanger (PHP), 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 of a "dynamic" language implemented for the DLR. You will notice that the code structure its slightly different from previous posts. Besides that, because Phalanger is PHP, it is definitely better to use PHP's array type instead of System\Array, implemented in Phalanger as PhpArray which at the end, stores the data as a Dictionary<object,object>.

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.


<?php
namespace PhpArrays 
{    
    use System as S;
    use System\Console;
    use System\Random;
    use System\Text as T;
    
    class Program
    {
        static function Main()
        {            
            /* 
             * An array in PHP is actually an ordered map.
             * implements arrays as Phpp.Runtime.PhpArray class 
             * that internally implements a Dictionary<object,object>.
            */
            
            // Single-dimensional Array(s)  
            self::printTitle("Reverse Array Elements");
            
            // Declare and Initialize Array of Chars  
            $letters = array();  
            $letters[0] = "A";  
            $letters[1] = "E";  
            $letters[2] = "I";  
            $letters[3] = "O";  
            $letters[4] = "U"; 
            
            //print_r($letters);
            self::printArray($letters);
            $inverse_letters = self::reverseChar($letters);  
            self::printArray($inverse_letters);  
            
            self::printTitle("Sort Integer Array Elements");  
            
            // Declare and Initialize Array of Integers   
            $numbers = array ( 10, 8, 3, 1, 5 );  
            self::printArray($numbers);  
            $ordered_numbers = self::bubbleSort($numbers);  
            self::printArray($ordered_numbers);  
            
            self::printTitle("Sort String Array Elements");  
            
            // Declare and Initialize and Array of Strings  
            $names = array (                       
                    "Damian",   
                    "Rogelio",  
                    "Carlos",   
                    "Luis",                       
                    "Daniel"  
                );  
            self::printArray($names);  
            $ordered_names = self::bubbleSort($names);  
            self::printArray($ordered_names);  
            
            // Multi-dimensional Array (Matrix row,column)  
            // in PHP they are the same as Jagged Arrays or "array of arrays"
            
            self::printTitle("Transpose Matrix");  
            
            /* Matrix row=2,col=3 
             * A =  [6  4 24] 
             *      [1 -9  8] 
             */  
            $matrix = array ( array ( 6, 4, 24 ),   
                              array ( 1, -9, 8 ));  
            self::printMatrix($matrix);  
            $transposed_matrix = self::transposeMatrix($matrix);  
            self::printMatrix($transposed_matrix);  
            
            // Jagged Array (Array-of-Arrays)         
            
            self::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 = array (  
             *      array ( "word1", "word2", "wordN" ),  
             *      array ( "word1", "word2", "wordM" ),  
             *      ... 
             *      ); 
             *  
             * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
             *  
             */  
            // using php function explode (split also works)
            $text = array (   
            \explode(" ", "Hoy es el día más hermoso de nuestra vida, querido Sancho;"),  
            \explode(" ", "los obstáculos más grandes, nuestras propias indecisiones;"),  
            \explode(" ", "nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;"),  
            \explode(" ", "la cosa más fácil, equivocarnos;"),
            \explode(" ", "la más destructiva, la mentira y el egoísmo;"),
            \explode(" ", "la peor derrota, el desaliento;"),
            \explode(" ", "los defectos más peligrosos, la soberbia y el rencor;"),
            \explode(" ", "las sensaciones más gratas, la buena conciencia...")
            );          
            //print_r ($text);
            self::printJaggedArray($text);  
            $text = self::upperCaseRandomArray($text);  // param not by reference
            self::printJaggedArray($text);  
            self::graphJaggedArray($text);  
            
            // Array Exceptions  
            
            self::printTitle("Common Array Exceptions");  
            
            self::printCommonArrayExceptions(NULL);  
            self::printCommonArrayExceptions($text);  
            
            // Accessing Class Array Elements through Indexer  
            
            self::printTitle("Alphabets");  
            
            $vowels = new Alphabet(5);  
            $vowels[0] = 'a';  
            $vowels[1] = 'e';  
            $vowels[2] = 'i';  
            $vowels[3] = 'o';  
            $vowels[4] = 'u';  
            
            //print_r ($vowels);
            
            echo "\nVowels = {" 
                . \implode(",", array($vowels[0], $vowels[1], $vowels[2], $vowels[3], $vowels[4])) 
                . "}\n";                  
            
            $en = new Alphabet("abcdefghijklmnopqrstuvwxyz");  
            echo "English Alphabet = {{$en}}\n";  
  
            echo "Alphabet Extract en[9..19] = {"
                . new Alphabet($en->slice(9, 10))  
                . "}\n";
            
            $word1 = \implode("", array ($en[6], $en[14], $en[14], $en[3]));  
            $word2 = \implode("", array ($en[1], $en[24], $en[4]));  
            $word3 = \implode("", array ($en[4], $en[21], $en[4], $en[17],  
                                         $en[24], $en[14], $en[13], $en[4]));  
  
            echo "\n$word1 $word2, $word3!\n";
  
            \fgets(STDIN);

            return 0;
        }
        
        static function reverseChar($arr)
        {              
            $reversed = array();  
            for ($i = 0, $j = \count($arr) - 1; $j >= 0; $i++, $j--)  
            {
                $reversed[$i] = $arr[$j]; 
            }
            return $reversed;  
            // or: return \array_reverse($arr);
        }  
        
        static function bubbleSort($arr)  
        {  
            $swap = 0;  
            for ($i = \count($arr) - 1; $i > 0; $i--)  
            {  
                for ($j = 0; $j < $i; $j++)  
                {  
                    // if ($arr[$j][0] > $arr[$j + 1][0])  
                    if (\is_numeric($arr[$j]) ? 
                        $arr[$j] > $arr[$j + 1] : 
                        $arr[$j][0] > $arr[$j + 1][0])  
                    {  
                        $swap = $arr[$j];  
                        $arr[$j] = $arr[$j + 1];  
                        $arr[$j + 1] = $swap;  
                    }  
                }  
            }  
            return $arr;  
        }  
                                    
        static function transposeMatrix($m)  
        {  
            /* Transposing a Matrix 2,3  
             *  
             * A =  [6  4 24]T [ 6  1]  
             *      [1 -9  8]  [ 4 -9] 
             *                 [24  8] 
             */
            $transposed = array();  
            for ($i = 0; $i < \count($m); $i++)  
            {  
                for ($j = 0; $j < \count($m[0]); $j++)  
                {  
                    $transposed[$j][$i] = $m[$i][$j];                  
                }  
            }  
            return $transposed;  
        }  
        
        static function upperCaseRandomArray($arr)  
        {  
            $r = new Random();  
            $i = $r->Next(0, \count($arr) - 1);  
            for ($j = 0; $j < \count($arr[$i]); $j++)  
            {
                $arr[$i][$j] = \strtoupper($arr[$i][$j]);  
            }
            return $arr;
        }  
        
        static function printArray($arr)  
        {  
            echo "\nPrint Array Content " . $arr->GetType()->Name . "\n";
            
            for ($i = 0; $i < \count($arr); $i++)  
            {
                Console::WriteLine(" array [{0,2}] = {1,2} ", $i, $arr[$i]);          
            }
        }  
        
        static function printMatrix($m)  
        {  
            echo "\nPrint Matrix Content " . $m->GetType()->Name 
            . "[" . \count($m) . "," . \count($m[0]) . "]\n";        
            
            for ($i = 0; $i < \count($m); $i++)  
            {
                for ($j = 0; $j < \count($m[0]); $j++)  
                {
                    Console::WriteLine(" array [{0,2},{1,2}] = {2,2} ", $i, $j, $m[$i][$j]);  
                }
            }
        }  
        
        static function graphJaggedArray($arr)  
        {  
            /* When using Arrays, we can use foreach instead of for:  
             *  
             * for (int i = 0; i <= arr.Length - 1; i++) 
             *   for (int j = 0; j <= arr.Length - 1; j++)                 
             *  
             */  
            echo "\nPrint Text Content " . $arr->GetType()->Name . "\n";  
            $lineCount = 1;  
            foreach ($arr as $s)  
            {  
                Console::Write("Line{0,2}|", $lineCount);  
                foreach ($s as $w)  
                {  
                    Console::Write("{0,3}", '*');  
                }  
                echo " (" . \count($s) . ")\n";  
                $lineCount++;  
            }  
        }  
        
        static function printJaggedArray($arr)  
        {          
            echo "\nPrint Jagged Array Content " . $arr->GetType()->Name . "\n";  
            for ($i = 0; $i < \count($arr); $i++)  
            {  
                $line = new T\StringBuilder();  
                for ($j = 0; $j < \count($arr[$i]); $j++)
                {
                    $line->Append(" " . $arr[$i][$j]);  
                }
                if ($line->ToString() == \strtoupper($line->ToString()))  
                {
                    $line->Append(" <-- [UPPERCASED]");  
                }
                echo $line . "\n";  
            }  
        }  

        static function printCommonArrayExceptions($arr)  
        {  
            // there is a bug throwing System\Exception(s) in Phalanger.
            // but apparently it has been quickly fixed after reported.
            try  
            {  
                /* Throwing System\Exception(s) do not get caught in
                 * the catch, instead they give an error message and 
                 * continue executing. i.e.
                 * throw new S\NullReferenceException("");                    
                 * throw new S\Exception("");
                */
                
                if (\is_null($arr))
                {
                    throw new \ErrorException(
                        "Object reference not set to an instance of an object.", 
                        0, \E_ERROR);                    
                }
                if (!isset($arr[100][100]))
                {
                    throw new \OutOfRangeException(
                        "Index was outside the bounds of the array.", 0);
                }      
            }  
            catch (\OutOfRangeException $ex)  
            {  
                echo "\nException: OutOfRangeException\n" . 
                    $ex->getMessage() . "\n";  
            } 
            catch (\ErrorException $ex)  
            {  
                echo "\nException: ErrorException " .
                    $ex->getSeverity() . "\n" . $ex->getMessage() . "\n";                
            }             
            /*catch (S\Exception $ex)
            {
                echo "\nException: ", "Exception", 
                    $ex->getMessage(), "\n";  
            }*/
        }  
        
        static function printTitle(string $message)
        {
            echo "\n";
            echo \str_repeat("=", 54) . "\n";
            echo $message . "\n";
            echo \str_repeat("=", 54) . "\n";
        }
    }

    [\Export]    
    class Alphabet implements \ArrayAccess   
    {    
        // Array Field
        private $letters = array();
        
        // Indexer Get/Set methods
        // Implementing ArrayAccess methods
        public function offsetSet($offset, $value) {
            if (\is_null($offset)) 
            {
                $this->letters[] = $value;
            } else 
            {
                $this->letters[$offset] = \strtoupper($value);
            }
        }
        public function offsetExists($offset) {
            return isset($this->letters[$offset]);
        }
        public function offsetUnset($offset) {
            unset($this->letters[$offset]);
        }
        public function offsetGet($offset) {
            return isset($this->letters[$offset]) ? $this->letters[$offset] : NULL;
        }
        
        // Read-Only Property  
        public function getLength()
        {  
            return \count($this->letters); 
        }  
        
        // Constructor 
        // No Overloaded Constructors support in (PHP) Phalanger 
        public function __construct($param = NULL)    
        {   
            // int $size
            if(\is_numeric($param))
            {
                $this->letters = \array_pad($this->letters, $size, ' '); 
            }
            // string $list
            else if(\is_string($param))
            {
                $this->letters = \str_split(\strtoupper($param));
            }
            // array $list
            else if(\is_array($param))
            {
                $this->letters = $param;
            }
            else 
            {
                $this->letters = NULL;
            }
        }    
        
        // Overridden Method
        public function __toString()    
        {    
            return \join(",", $this->letters); 
        }
        
        // Method  
        public function slice($start, $length)  
        {  
            return \array_slice($this->letters, $start, $length);              
        }  
    }    
}
?>


The output:






















































































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

Tuesday, October 22, 2013

Arrays and Indexers in Nemerle



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


using Nemerle.IO;
using System;
using System.Console;
using System.Text;

namespace NsArrays
{  
    module Program
    {
        Main() : void
        {
            // Single-dimensional Array(s)  
            PrintTitle("Reverse Array Elements");  
            
            // Declare and Initialize Array of Chars  
            def letters : array[char] = array(5);  
            letters[0] = 'A';  
            letters[1] = 'E';  
            letters[2] = 'I';  
            letters[3] = 'O';  
            letters[4] = 'U';  
            
            PrintArrayChar(letters); 
            def inverse_letters : array[char] = ReverseChar(letters);  
            PrintArrayChar(inverse_letters);  
            
            PrintTitle("Sort Integer Array Elements");  
  
            // Declare and Initialize Array of Integers   
            def numbers : array[int] = array [10, 8, 3, 1, 5];
            PrintArrayInt(numbers);
            def ordered_numbers : array[int] = BubbleSortInt(numbers);  
            PrintArrayInt(ordered_numbers);  
  
            PrintTitle("Sort String Array Elements");  
  
            // Declare and Initialize and Array of Strings   
            def names : array[string] = array[
                    "Damian",   
                    "Rogelio",  
                    "Carlos",   
                    "Luis",                       
                    "Daniel"  
                ];
            
            PrintArrayString(names);  
            def ordered_names : array[string] = BubbleSortString(names);  
            PrintArrayString(ordered_names);  
  
            // Multi-dimensional Array (Matrix row,column)  
  
            PrintTitle("Transpose Matrix");  
  
            /* Matrix row=2,col=3 
             * A =  [6  4 24] 
             *      [1 -9  8] 
            */
            def matrix : array[2,int] = array.[2][[ 6, 4, 24 ],   
                                                  [ 1, -9, 8 ]];
            
            PrintMatrix(matrix);  
            def transposed_matrix : array[2,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: 
             *  
             * def text : array[array[string]] = array[ 
             *      array[ "word1", "word2", "wordN" ],  
             *      array[ "word1", "word2", "wordM" ],  
             *      ... 
             *      ]; 
             *  
             * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
             *  
             */           
            def text : array[array[string]] = array[   
            "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");  
  
            def vowels : Alphabet = Alphabet(5);  
            vowels[0] = 'a';  
            vowels[1] = 'e';  
            vowels[2] = 'i';  
            vowels[3] = 'o';  
            vowels[4] = 'u';  
  
            printf("\nVowels = {%s}\n",  
                String.Join(",", vowels[0], vowels[1], vowels[2], vowels[3], vowels[4]));  
  
            def en : Alphabet = Alphabet("abcdefghijklmnopqrstuvwxyz");  
            printf("English Alphabet = {%s}\n", en.ToString());  
  
            printf("Alphabet Extract en[9..19] = {%s}\n",   
                          Alphabet(en.Slice(9, 10)).ToString());  
  
            def word1 : string = String.Join("", en[6], en[14], en[14], en[3]);  
            def word2 : string = String.Join("", en[1], en[24], en[4]);  
            def word3 : string = String.Join("", en[4], en[21], en[4], en[17],  
                                           en[24], en[14], en[13], en[4]);  
  
            printf("\n%s %s, %s!\n\n", word1, word2, word3);  
                                                  
            _ = ReadLine();
        }
        
        ReverseChar(arr : array[char]) : array[char]
        {
            def reversed : array[char] = array(arr.Length);
            mutable i : int = 0;
            for (mutable j : int = arr.Length - 1; j >= 0; j--)  
            {
                reversed[i] = arr[j];
                i++;
            }
            reversed;
        }
        
        BubbleSortInt(arr : array[int]) : array[int]
        {
            mutable swap : int = 0;
            for (mutable i : int = arr.Length - 1; i > 0; i--)
            {
                for (mutable j: int = 0; j < i; j++)
                {                    
                    if (arr[j] > arr[j + 1])  
                    { 
                        swap = arr[j];  
                        arr[j] = arr[j + 1];
                        arr[j + 1] = swap;
                    }
                    else{}
                }
            }
            arr;
        }

        BubbleSortString(arr : array[string]) : array[string]
        {
            mutable swap : string = "";
            for (mutable i : int = arr.Length - 1; i > 0; i--)
            {
                for (mutable j: int = 0; j < i; j++)
                {
                    if (arr[j][0] > arr[j + 1][0]) 
                    {
                        swap = arr[j];  
                        arr[j] = arr[j + 1];  
                        arr[j + 1] = swap;
                    }
                    else{}
                }
            }
            arr;
        }
        
        TransposeMatrix(m : array[2, int]) : array[2, int]
        {  
            /* Transposing a Matrix 2,3  
             *  
             * A =  [6  4 24]T [ 6  1]  
             *      [1 -9  8]  [ 4 -9] 
             *                 [24  8] 
            */  
            def transposed : array[2, int] = array(m.GetUpperBound(1) + 1,  
                                                   m.GetUpperBound(0) + 1);  
            for (mutable i : int = 0; i < m.GetUpperBound(0) + 1; i++)  
            {  
                for (mutable j = 0; j < m.GetUpperBound(1) + 1; j++)  
                {  
                    transposed[j, i] = m[i, j];  
                }  
            }  
            transposed;  
        }  
        
        UpperCaseRandomArray(arr : array[array[string]]) : void
        {  
            def r : Random = Random();  
            mutable i : int = r.Next(0, arr.Length - 1);  
            for (mutable j : int = 0; j <= arr[i].Length - 1; j++)  
                arr[i][j] = arr[i][j].ToUpper();  
        }  
        
        PrintArrayChar(arr : array[char]) : void  
        {
            printf("\nPrint Array Content %s\n", 
                arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));  
              
            for (mutable i : int = 0; i <= arr.Length - 1; i++)  
                WriteLine("  array [{0,2}] = {1,2} ", i, arr[i]);
        }  
        
        PrintArrayInt(arr : array[int]) : void  
        {
            printf("\nPrint Array Content %s\n", 
                arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));  
              
            for (mutable i : int = 0; i <= arr.Length - 1; i++)  
                WriteLine("  array [{0,2}] = {1,2} ", i, arr[i]);
        } 
        
        PrintArrayString(arr : array[string]) : void  
        {
            printf("\nPrint Array Content %s\n", 
                arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));  
              
            for (mutable i : int = 0; i <= arr.Length - 1; i++)  
                WriteLine("  array [{0,2}] = {1,2} ", i, arr[i]);
        } 
        
        PrintMatrix(m : array[2,int]) : void  
        {  
            printf("\nPrint Matrix Content %s[%s,%s]\n",  
                m.GetType().Name.Replace("[,]", ""),  
                (m.GetUpperBound(0) + 1).ToString(),  
                (m.GetUpperBound(1) + 1).ToString());  
  
            for (mutable i : int = 0; i <= m.GetUpperBound(0); i++)  
                for (mutable j : int = 0; j <= m.GetUpperBound(1); j++)  
                    WriteLine(" array [{0,2},{1,2}] = {2,2} ", i, j, m[i, j]);  
        }  
        
        GraphJaggedArray(arr : array[array[string]]) : void  
        {  
            /* When using Arrays, we can use foreach instead of for:  
             *  
             * for (mutable i : int = 0; i <= arr.Length - 1; i++) 
             *   for (mutable j : int = 0; j <= arr.Length - 1; j++)                 
             *  
            */  
            printf("\nPrint Text Content %s\n", arr.GetType().Name);  
            mutable lineCount : int = 1;  
            foreach (s : array[string] in arr)  
            {  
                Write("Line{0,2}|", lineCount);  
                foreach (_ : string in s)  
                {  
                    Write("{0,3}", '*');  
                }  
                printf(" (%s)\n", s.Length.ToString());  
                lineCount++;  
            }  
        }  
        
        PrintJaggedArray(arr : array[array[string]]) : void  
        {  
            mutable line : StringBuilder;  
            printf("\nPrint Jagged Array Content %s\n", arr.GetType().Name);  
            for (mutable i : int = 0; i <= arr.Length - 1; i++)  
            {  
                line = StringBuilder();  
                for (mutable j : int = 0; j <= arr[i].Length - 1; j++)  
                    _ = line.Append(" " + arr[i][j]);  
                if (line.ToString() == line.ToString().ToUpper()) 
                {
                    _ = line.Append(" <-- [UPPERCASED]");  
                }
                else {}
                printf("%s\n", line.ToString());  
            }  
        }  
        
        PrintCommonArrayExceptions(arr : array[array[string]]) : void
        {  
            try  
            {  
                arr[100][100] = "hola";  
            }  
            catch             
            {  
            | ex is Exception =>
                printf("\nException: \n%s\n%s\n", ex.GetType().Name, ex.Message);  
            }  
        }  
                
        PrintTitle(message : string) : void
        {
            print("\n");
            print("======================================================\n");
            printf("%s\n", message);  
            print("======================================================\n");  
        }
    }
    
    class Alphabet  
    {  
        // Array Field  
        private letters : array[char];  
  
        // Indexer Get/Set Property  
        public Item[index : int] : char
        {  
            get { letters[index] }  
            set { letters[index] = Char.ToUpper(value) }  
        }  

        // Read-Only Property  
        public Length : int
        {  
            get { this.letters.Length }  
        }  
  
        // Constructors  
        public this(size : int)  
        {  
            this.letters = array(size); 
        }  
  
        public this(lst : string)  
        {  
            this.letters = lst.ToUpper().ToCharArray();  
        }  
  
        public this(lst : array[char])  
        {  
            this.letters = lst;
        }  
  
        // Overridden Method  
        public override ToString() : string
        {  
            String.Join(",", this.letters); 
        }  
  
        // Method  
        public Slice(start : int, length : int) : array[char]
        {  
            def result : array[char] = array(length);  
            mutable j : int = start;
            for (mutable i : int = 0; i < length; i++)  
            {  
                result[i] = this[j];  
                j++;
            }  
            result;
        }  
  
    }  
}


The output:






















































































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

Saturday, September 14, 2013

Arrays and Indexers in Boo



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


namespace BooArrays
# python's import syntax supported only on latest Boo version (2.0.9.5 assemblies)
from System import Random
from System.Text import StringBuilder
from System.Console import WriteLine, Write, ReadKey
from System.Convert import ToChar 
from System.Char import ToUpper

# Console Program
public def Main(argv as (string)): 
 # Single-dimensional Array(s)
 printtitle('Reverse Array Elements');
 
 # Declare and initialize Array of Chars
 # Boo doesn't support yet (version 2.0.9.5 assemblies) Char literals.
 # 1 character literal such as 'A' or "A" are strings
 # so, I'm converting Convert.ToChar before assignment by element.
 # There are 2 ways to initialize inline. i.e.
 # option 1: a as (char) = (ToChar('A'), ToChar('B'), ToChar('C'))
 # option 2: a as (char) = "ABC".ToCharArray()
 letters as (char) = array(char, 5)
 letters[0] = ToChar('A')
 letters[1] = ToChar('E')
 letters[2] = ToChar('I')
 letters[3] = ToChar('O')
 letters[4] = ToChar('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)
 printtitle('Transpose Matrix')
 
 /* Matrix row=2,col=3  
 * A =  [6  4 24]  
 *   [1 -9  8]  
 */ 
 matrx as (int, 2) = matrix(int, 2, 3) 
 # or alternative syntax: = matrix of int(2, 3)
 matrx[0,0] = 6
 matrx[0,1] = 4
 matrx[0,2] = 24
 matrx[1,0] = 1
 matrx[1,1] = -9
 matrx[1,2] = 8
 
 printmatrix(matrx)
 transposed_matrix as (int, 2) = transposematrix(matrx)
 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 as ((string)) = (
    'Hoy es el día más hermoso de nuestra vida, querido Sancho;'.Split(ToChar(' ')), 
    'los obstáculos más grandes, nuestras propias indecisiones;'.Split(ToChar(' ')), 
    'nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;'.Split(ToChar(' ')), 
    'la cosa más fácil, equivocarnos;'.Split(ToChar(' ')), 
    'la más destructiva, la mentira y el egoísmo;'.Split(ToChar(' ')), 
    'la peor derrota, el desaliento;'.Split(ToChar(' ')), 
    'los defectos más peligrosos, la soberbia y el rencor;'.Split(ToChar(' ')), 
    'las sensaciones más gratas, la buena conciencia...'.Split(ToChar(' ')))
 
 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')

 vowels as Alphabet = Alphabet(5)
 vowels[0] = ToChar('a')
 vowels[1] = ToChar('e')
 vowels[2] = ToChar('i')
 vowels[3] = ToChar('o')
 vowels[4] = ToChar('u')
 
 print '\nVowels = {' + join((vowels[0], vowels[1], vowels[2], 
                        vowels[3], vowels[4]), ',') + '}'
 
 en as Alphabet = Alphabet('abcdefghijklmnopqrstuvwxyz')
 print "English Alphabet = {${en.ToString()}}"
 
 print "Alphabet Extract en[9..19] = {${Alphabet(en.slice(9, 10))}}"
 
 word1 as string = join((en[6], en[14], en[14], en[3]), '')
 word2 as string = join((en[1], en[24], en[4]), '')
 word3 as string = join((en[4], en[21], en[4], en[17], en[24], 
                            en[14], en[13], en[4]), '')
 print "\n$word1 $word2, $word3!\n"
 
 ReadKey()

def reversechar(arr as (char)) as (char): 
 reversed as (char) = array(char, arr.Length)
 i as int = 0
 for j in range(len(arr) - 1, -1, -1):
  reversed[i] = arr[j]
  i++
 return reversed

def bubblesortint(arr as (int)) as (int):
 swap as int = 0
 for i in range(len(arr) - 1, -1, -1):
  for j in range(0, len(arr) - 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 range(len(arr) - 1, -1, -1):
  for j in range(0, len(arr) - 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 (int, 2)) as (int, 2):
 /* Transposing a Matrix 2,3
 *
 * A =  [6  4 24]T [ 6  1]
 *    [1 -9  8]  [ 4 -9]
 *      [24  8]
 */
 transposed as (int, 2) = matrix(int, len(m, 1), len(m, 0))
 for i in range(len(m, 0)):
  for j in range(len(m, 1)):
   transposed[j, i] = m[i, j]
 return transposed

def uppercaserandomarray(arr as ((string))) as void:
 r as Random = Random()
 i as int = r.Next(len(arr))
 for j as int in range(len(arr[i])):    
  arr[i][j] = arr[i][j].ToUpper()
  
def printarraychar(arr as (char)) as void:
 print '\nPrint Array Content ' + arr.GetType().Name.Replace(']', len
(arr).ToString() + ']') 
 for i in range(len(arr)):
  WriteLine(' array [{0,2}] = {1,2} ', i, arr[i])
  
def printarrayint(arr as (int)):
 print '\nPrint Array Content ' + arr.GetType().Name.Replace(']', len
(arr).ToString() + ']') 
 for i in range(len(arr)):
  WriteLine(' array [{0,2}] = {1,2} ', i, arr[i])

def printarraystring(arr as (string)) as void:
 print '\nPrint Array Content ' + arr.GetType().Name.Replace(']', len

(arr).ToString() + ']') 
 for i in range(len(arr)):
  WriteLine(' array [{0,2}] = {1,2} ', i, arr[i])

def printmatrix(m as (int, 2)) as void:
 print '\nPrint Matrix Content ' + m.GetType().Name.Replace('[,]', '') + '[' + len

(m,0).ToString() + ',' + len(m,1).ToString() + ']' 
 for i in range(len(m, 0)):
  for j in range(len(m, 1)):
   WriteLine(' array [{0,2},{1,2}] = {2,2} ', i, j, m[i, j])

def graphjaggedarray(arr as ((string))) as void:
 /* 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 as int in range(len(arr)):
   Write('Line{0,2}|', i+1)
   for j as int in range(len(arr[i])):
    Write('{0,3}', '*')
   print " (${len(arr[i]).ToString()})"

def printjaggedarray(arr as ((string))) as void:
 line as StringBuilder    
 print "\nPrint Jagged Array Content ${arr.GetType().Name}"
 for i as int in range(len(arr)):  
  line = StringBuilder()
  for j in range(len(arr[i])):   
   line.Append(' ' + arr[i][j])   
  if line.ToString() == line.ToString().ToUpper():
   line.Append(' <-- [UPPERCASED]')
  print line

def printcommonarrayexceptions(arr as ((string))) as void:
 try: 
  arr[100][100] = 'hola'  
 except ex as System.Exception:    
  print "\nException: \n${ex.GetType().Name}\n${ex.Message}"

def printtitle(message as string) as void: 
 print ''
 print('=' * 54)
 print message
 print('=' * 54)

[System.Reflection.DefaultMember("item")]
class Alphabet: 
 # Array Field
 private letters as (char)
 
 # Indexer Get/Set Property
 public item[index as int]:
  get:
   rawArrayIndexing:
    return letters[index]
  set:
   rawArrayIndexing:
    letters[index] = ToUpper(value)
 # Read-Only Property
 public Length as int:    
  get:
   return len(self.letters) 

 # Constructors
 public def constructor(size as int):
  self.letters = array(char, size)
 
 public def constructor(list as string):
  self.letters = list.ToUpper().ToCharArray()

 public def constructor(list as (char)):
  self.letters = list

 # Overridden Method 
 public override def ToString():
  return join(self.letters, ',')

 # Method
 public def slice(start as int, length as int) as (char):
  # using Boo's slicing: 
  # container[<firstIndexWanted>:<firstIndexNotWanted>:<step>]
  return self.letters[start:start+length]


The output:






















































































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

Thursday, July 18, 2013

Arrays and Indexers in JScript.NET



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

IMPORTANT!
JScript provides two different types of arrays, JScript array objects and typed arrays. In JScript array objects, which are sparse, 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.

I chose to use the Typed Arrays (and all other variables as well) to keep it closer to the previous posts.


//C:\Windows\Microsoft.NET\Framework64\v4.0.30319>jsc.exe JsArrays.js
import System;
import Microsoft.JScript; // to get the JScriptException  

function reverseChar(arr: char[]): char[]
{              
    var reversed: char[] = new char[arr.length];  
    for (var i: int = 0, j: int = arr.length - 1; j >= 0; i++, j--)  
        reversed[i] = arr[j];  
    return reversed;  
}  

function bubbleSortInt(arr: int[]): int[]  
{  
    var swap: int = 0;  
    for (var i: int = arr.length - 1; i > 0; i--)  
    {  
        for (var j: int = 0; j < i; j++)  
        {  
            if (arr[j] > arr[j + 1])  
            {  
                swap = arr[j];  
                arr[j] = arr[j + 1];  
                arr[j + 1] = swap;  
            }  
        }  
    }  
    return arr;  
}  

function bubbleSortString(arr: String[]): String[]  
{  
    var swap: String = '';  
    for (var i: int = arr.length - 1; i > 0; i--)  
    {  
        for (var j: int = 0; j < i; j++)  
        {  
            if (arr[j][0] > arr[j + 1][0])  
            {  
                swap = arr[j];  
                arr[j] = arr[j + 1];  
                arr[j + 1] = swap;  
            }  
        }  
    }  
    return arr;  
}  

function transposeMatrix(m: int[,]): int[,]  
{  
    /* Transposing a Matrix 2,3  
     *  
     * A =  [6  4 24]T [ 6  1]  
     *      [1 -9  8]  [ 4 -9] 
     *                 [24  8] 
    */  
    var transposed: int[,] = new int[m.GetUpperBound(1) + 1,  
                             m.GetUpperBound(0) + 1];  
    for (var i: int = 0; i < m.GetUpperBound(0) + 1; i++)  
    {  
        for (var j: int = 0; j < m.GetUpperBound(1) + 1; j++)  
        {  
            transposed[j, i] = m[i, j];  
        }  
    }  
    return transposed;  
}  

function upperCaseRandomArray(arr: String[][])  
{  
    var r: Random = new Random();  
    var i: int = r.Next(0, arr.length - 1);  
    for (var j: int = 0; j <= arr[i].length - 1; j++)  
        arr[i][j] = arr[i][j].ToUpper();  
}  

function printArrayChar(arr: char[])  
{  
    print('\nPrint Array Content ',  
        arr.GetType().Name.Replace(']', arr.length.ToString() + ']'));  

    for (var i: int = 0; i <= arr.length - 1; i++)  
        Console.WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]);  
}  

function printArrayInt(arr: int[])  
{  
    print('\nPrint Array Content ',  
        arr.GetType().Name.Replace(']', arr.length.ToString() + ']'));  

    for (var i: int = 0; i <= arr.length - 1; i++)  
        Console.WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]);  
}  

function printArrayString(arr: String[])  
{  
    print('\nPrint Array Content ',  
        arr.GetType().Name.Replace(']', arr.length.ToString() + ']'));  

    for (var i: int = 0; i <= arr.length - 1; i++)  
        Console.WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]);  
}  

function printMatrix(m: int[,])  
{  
    print('\nPrint Matrix Content ', 
        m.GetType().Name.Replace('[,]', ''), '[',
        (m.GetUpperBound(0) + 1).ToString(),',',
        (m.GetUpperBound(1) + 1).ToString(),']');  

    for (var i: int = 0; i <= m.GetUpperBound(0); i++)  
        for (var j: int = 0; j <= m.GetUpperBound(1); j++)  
            Console.WriteLine(' array [{0,2},{1,2}] = {2,2} ', i, j, m[i, j]);  
}  

function graphJaggedArray(arr: String[][])  
{  
    /* When using Arrays, we can use for(each) instead of for:  
     * however, for some reason, JScript tries to convert the
     * elements of arr to System.Int32 instead of String[] 
     * so it fails.
     *  
     * for (var s: String[] in arr)  
     *   for (var w: String in s)                  
     *  
    */
    print('\nPrint Text Content ', arr.GetType().Name);      
    for (var i: int = 0; i <= arr.length - 1; i++)
    {  
        Console.Write('Line{0,2}|', i+1);  
        for (var j: int = 0; j <= arr[i].length - 1; j++)
        {  
            Console.Write('{0,3}', '*');  
        }              
        print(' (', arr[i].length, ')');          
    }  
}  
  
function printJaggedArray(arr: String[][])  
{  
    var line: System.Text.StringBuilder;  
    print('\nPrint Jagged Array Content ', arr.GetType().Name);  
    for (var i: int = 0; i <= arr.length - 1; i++)  
    {  
        line = new System.Text.StringBuilder();  
        for (var j: int = 0; j <= arr[i].length - 1; j++)  
            line.Append(' ' + arr[i][j]);  
        if (line.ToString() == line.ToString().ToUpper())  
            line.Append(' <-- [UPPERCASED]');  
        print(line);  
    }  
}  
  
function printCommonArrayExceptions(arr: String[][])  
{  
    try  
    {  
        arr[100][100] = 'hola';  
    }      
    catch (ex: JScriptException)  
    {  
        print('\nException: \n', 
                ex.GetType().Name,'\n', ex.Message);  
    }
    catch (ex: Exception)  
    {  
        print('\nException: \n', 
                ex.GetType().Name,'\n', ex.Message);  
    }  
}  
  
function printTitle(message: String)  
{  
    print();  
    print('======================================================');  
    Console.WriteLine('{0,10}', message);  
    print('======================================================');  
}  

package JsArrays 
{  
    class Alphabet  
    {  
        // Array Field  
        private var letters: char[];  

        // No indexer support. 
        // Getter/Setter Method instead. 
        public function getItem(index: int): char 
        {    
            return this.letters[index];   
        } 
        
        public function setItem(index: int, value: char) 
        {
            this.letters[index] = Char.ToUpper(value);
        }        
  
        // Read-Only Property 
        public function get Length(): int {    
            return this.letters.length;   
        }            
  
        // Constructors  
        public function Alphabet(size: int)  
        {              
            this.letters = new char[size];  
        }  
  
        public function Alphabet(list: String)  
        {              
            this.letters = list.ToUpper().ToCharArray();  
        }  
  
        public function Alphabet(list: char[])  
        {              
            this.letters = list;  
        }  
  
        // Overridden Method  
        public function toString(): String  
        {              
            return String.Join(',', this.letters, '');  
        }  
  
        // Method  
        public function slice(start: int, length: int): char[]
        {  
            var result: char[] = new char[length];  
            for (var i: int = 0, j: int = start; i < length; i++, j++)  
            {  
                result[i] = letters[j];  
            }  
            return result;  
        }   
    }  
};

import JsArrays;  
  
function Main() {  
    
    // Single-dimensional Array(s)  
    printTitle('Reverse Array Elements');  

    // Declare and Initialize Array of Chars  
    var letters: char[] = new char[5];  
    letters[0] = 'A';  
    letters[1] = 'E';  
    letters[2] = 'I';  
    letters[3] = 'O';  
    letters[4] = 'U';  

    printArrayChar(letters);  
    var inverse_letters: char[] = reverseChar(letters);  
    printArrayChar(inverse_letters);  

    printTitle('Sort Integer Array Elements');  

    // Declare and Initialize Array of Integers   
    var numbers: int[] = [ 10, 8, 3, 1, 5 ];  
    printArrayInt(numbers);  
    var ordered_numbers: int[] = bubbleSortInt(numbers);  
    printArrayInt(ordered_numbers);  

    printTitle('Sort String Array Elements');  

    // Declare and Initialize and Array of Strings  
    var names: String[] = [                       
            'Damian',   
            'Rogelio',  
            'Carlos',   
            'Luis',                       
            'Daniel'  
        ];  
    printArrayString(names);  
    var ordered_names: String[] = bubbleSortString(names);  
    printArrayString(ordered_names);  

    // Multi-dimensional Array (Matrix row,column)  

    printTitle('Transpose Matrix');  

    /* Matrix row=2,col=3 
     * A =  [6  4 24] 
     *      [1 -9  8] 
    */  
    var matrix: int[,] = new int[2,3];
    matrix[0,0] = 6; matrix[0,1] = 4; matrix[0,2] = 24;
    matrix[1,0] = 1; matrix[1,1] = -9; matrix[1,2] = 8;
    
    print(matrix.GetType().Name);
    printMatrix(matrix);  
    var transposed_matrix: 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: 
     * 
     * var array1: new String[] = [ 'word1', 'word2', 'wordN' ];
     * var array2: new string[] = [ 'word1', 'word2', 'wordM' ];
     * ...
     * var text: String[][] = [   
     *      array1,  
     *      array2,  
     *      ... 
     *      ]; 
     *  
     * Text extract from: 'El ingenioso hidalgo don Quijote de la Mancha' 
     *  
     */
    
    var text: String[][] = [   
    '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 Getter/Setter    
    printTitle('Alphabets');  

    var vowels: Alphabet = new Alphabet(5);  
    vowels.setItem(0, 'a');  
    vowels.setItem(1, 'e');  
    vowels.setItem(2, 'i');  
    vowels.setItem(3, 'o');  
    vowels.setItem(4, 'u');  

    print('\nVowels = {',   
        String.Join(',', vowels.getItem(0), vowels.getItem(1),
                    vowels.getItem(2), vowels.getItem(3), 
                    vowels.getItem(4)), '}');  

    var en: Alphabet = new Alphabet('abcdefghijklmnopqrstuvwxyz');  
    print('English Alphabet = {', en.toString(), '}');  

    print('Alphabet Extract en[9..19] = {',
            new Alphabet(en.slice(9, 10)).toString(), '}');  
  
    var word1: String = String.Join('', en.getItem(6), en.getItem(14), 
                                    en.getItem(14), en.getItem(3));
    var word2: String = String.Join('', en.getItem(1), en.getItem(24), 
                                    en.getItem(4), en.getItem(4));
    var word3: String = 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));  

    print('\n', word1, ', ', word2, ', ', word3, '!\n');  

    Console.Read();  
};  
  
Main();


The output:






















































































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

Tuesday, July 16, 2013

Arrays and Indexers in C++/CLI



Today's post is about Arrays and Indexers in C++/CLI. 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 C++/CLI, 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#, VB.NET and Oxygene 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.

Last thing. 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.

// CppArrays.cpp : main project file.

#include "stdafx.h"

using namespace System;

namespace CppArrays {

    static array<wchar_t>^ ReverseChar(array<wchar_t>^ arr) {
        array<wchar_t>^ reversed = gcnew array<wchar_t>(arr->Length);
        for (int i = 0, j = arr->Length - 1; j >= 0; i++, j--) {
            reversed[i] = arr[i];
        }
        return reversed;
    }

    static array<int>^ BubbleSortInt(array<int>^ arr)  {  
        int swap = 0;  
        for (int i = arr->Length - 1; i > 0; i--) {  
            for (int j = 0; j < i; j++) {  
                if (arr[j] > arr[j + 1]) {  
                    swap = arr[j];  
                    arr[j] = arr[j + 1];  
                    arr[j + 1] = swap;  
                }  
            }  
        }  
        return arr;  
    }  

    static array<String^>^ BubbleSortString(array<String^>^ arr) {  
        String^ swap = L"";  
        for (int i = arr->Length - 1; i > 0; i--) {  
            for (int j = 0; j < i; j++) {  
                if (arr[j][0] > arr[j + 1][0]) {  
                    swap = arr[j];  
                    arr[j] = arr[j + 1];  
                    arr[j + 1] = swap;  
                }  
            }  
        }  
        return arr;  
    }  

    static array<int, 2>^ TransposeMatrix(array<int, 2>^ m) {  
        /* Transposing a Matrix 2,3  
            *  
            * A =  [6  4 24]T [ 6  1]  
            *      [1 -9  8]  [ 4 -9] 
            *                 [24  8] 
        */  
        array<int, 2>^ transposed = gcnew array<int, 2>(m->GetUpperBound(1) + 1,  
                                                        m->GetUpperBound(0) + 1);  
        for (int i = 0; i < m->GetUpperBound(0) + 1; i++) {  
            for (int j = 0; j < m->GetUpperBound(1) + 1; j++) {  
                transposed[j, i] = m[i, j];  
            }  
        }  
        return transposed;  
    }  

    static void UpperCaseRandomArray(array<array<String^>^>^ arr) {  
        Random^ r = gcnew Random();
        int i = r->Next(0, arr->Length - 1);  
        for (int j = 0; j <= arr[i]->Length - 1; j++)  
            arr[i][j] = arr[i][j]->ToUpper();  
    }  

    static void PrintArrayChar(array<wchar_t>^ arr) {  
        Console::WriteLine(L"\nPrint Array Content {0}",  
            arr->GetType()->Name->Replace(L"]", arr->Length.ToString() + L"]"));  
  
        for (int i = 0; i <= arr->Length - 1; i++)  
            Console::WriteLine(L" array [{0,2}] = {1,2} ", i, arr[i]);  
    }  

    static void PrintArrayInt(array<int>^ arr) {  
        Console::WriteLine(L"\nPrint Array Content {0}",  
            arr->GetType()->Name->Replace(L"]", arr->Length.ToString() + L"]"));  
  
        for (int i = 0; i <= arr->Length - 1; i++)  
            Console::WriteLine(L" array [{0,2}] = {1,2} ", i, arr[i]);  
    }  

    static void PrintArrayString(array<String^>^ arr) {  
        Console::WriteLine(L"\nPrint Array Content {0}",  
            arr->GetType()->Name->Replace(L"]", arr->Length.ToString() + L"]"));  
  
        for (int i = 0; i <= arr->Length - 1; i++)  
            Console::WriteLine(L" array [{0,2}] = {1,2} ", i, arr[i]);  
    }  
  
    static void PrintMatrix(array<int, 2>^ m) {  
        Console::WriteLine(L"\nPrint Matrix Content {0}[{1},{2}]",  
            m->GetType()->Name->Replace(L"[,]", L""),  
            (m->GetUpperBound(0) + 1).ToString(),  
            (m->GetUpperBound(1) + 1).ToString());  
  
        for (int i = 0; i <= m->GetUpperBound(0); i++)  
            for (int j = 0; j <= m->GetUpperBound(1); j++)  
                Console::WriteLine(L" array [{0,2},{1,2}] = {2,2} ", i, j, m[i, j]);  
    }  

    static void GraphJaggedArray(array<array<String^>^>^ arr) {  
        /* When using Arrays, we can use foreach instead of for:  
            *  
            * for (int i = 0; i <= arr.Length - 1; i++) 
            *   for (int j = 0; j <= arr.Length - 1; j++)                 
            *  
        */  
        Console::WriteLine(L"\nPrint Text Content {0}", arr->GetType()->Name);  
        int lineCount = 1;  
        for each (array<String^>^ s in arr) {  
            Console::Write(L"Line{0,2}|", lineCount);  
            for each(String^ w in s) {  
                Console::Write(L"{0,3}", L'*');  
            }  
            Console::WriteLine(L" ({0})", s->Length);  
            lineCount++;  
        }  
    }  

    static void PrintJaggedArray(array<array<String^>^>^ arr) {  
        System::Text::StringBuilder^ line;  
        Console::WriteLine(L"\nPrint Jagged Array Content {0}", arr->GetType()->Name);  
        for (int i = 0; i <= arr->Length - 1; i++) {  
            line = gcnew System::Text::StringBuilder();  
            for (int j = 0; j <= arr[i]->Length - 1; j++)  
                line->Append(L" " + arr[i][j]);  
            if (line->ToString() == line->ToString()->ToUpper())  
                line->Append(L" <-- [UPPERCASED]");  
            Console::WriteLine(line);  
        }  
    }  

    static void PrintCommonArrayExceptions(array<array<String^>^>^ arr) {  
        try {  
            arr[100][100] = L"hola";  
        }  
        catch (Exception^ ex) {  
            Console::WriteLine(L"\nException: \n{0}\n{1}", 
                               ex->GetType()->Name, ex->Message);  
        }  
    }  

    static void PrintTitle(String ^message) {
        Console::WriteLine();
        Console::WriteLine(L"======================================================");  
        Console::WriteLine(L"{0,10}", message);  
        Console::WriteLine(L"======================================================");  
    }

    ref class Alphabet {        
    private:
        // Array Field  
        array<wchar_t>^ letters;  
    public:
        // Indexer Get/Set Property   
        property wchar_t default[int] {
            wchar_t get(int index) { return letters[index]; }
            void set(int index, wchar_t value) { letters[index] = Char::ToUpper(value);}
        }
        // Read-Only Property
        property int Length {
            int get() { return this->letters->Length; }
        }        
        // Constructors  
        Alphabet(int size) {  
            this->letters = gcnew array<wchar_t>(size);  
        }  
        Alphabet(String^ list) {  
            this->letters = list->ToUpper()->ToCharArray();  
        }    
        Alphabet(array<wchar_t>^ list) {  
            this->letters = list;  
        }  
        // Overridden Method
        virtual String^ ToString() override {
            return String::Join(L",", gcnew String(this->letters));
        }
        // Method  
        array<wchar_t>^ Slice(int start, int length) {  
            array<wchar_t>^ result = gcnew array<wchar_t>(length);  
            for (int i = 0, j = start; i < length; i++, j++) {  
                result[i] = this[j];  
            }  
            return result;  
        }  
    };
};

using namespace CppArrays;

int main(array<System::String ^> ^args)
{
    // Single-dimensional Array(s)  
    PrintTitle(L"Reverse Array Elements");  
  
    // Declare and Initialize Array of Chars  
    array<wchar_t>^ letters = gcnew array<wchar_t>(5);  
    letters[0] = L'A';  
    letters[1] = L'E';  
    letters[2] = L'I';  
    letters[3] = L'O';  
    letters[4] = L'U';  
  
    PrintArrayChar(letters);  
    array<wchar_t>^ inverse_letters = ReverseChar(letters);  
    PrintArrayChar(inverse_letters);  
  
    PrintTitle(L"Sort Integer Array Elements");  
  
    // Declare and Initialize Array of Integers   
    array<int>^ numbers = { 10, 8, 3, 1, 5 };  
    PrintArrayInt(numbers);  
    array<int>^ ordered_numbers = BubbleSortInt(numbers);  
    PrintArrayInt(ordered_numbers);  
  
    PrintTitle(L"Sort String Array Elements");  

    // Declare and Initialize and Array of Strings  
    array<String^>^ names = gcnew array<String^> {                       
            L"Damian",   
            L"Rogelio",  
            L"Carlos",   
            L"Luis",                       
            L"Daniel"  
        };  
    PrintArrayString(names);  
    array<String^>^ ordered_names = BubbleSortString(names);  
    PrintArrayString(ordered_names);  
  
    // Multi-dimensional Array (Matrix row,column)  
  
    PrintTitle(L"Transpose Matrix");  
  
    /* Matrix row=2,col=3 
        * A =  [6  4 24] 
        *      [1 -9  8] 
    */  
    array<int, 2>^ matrix = gcnew array<int, 2>(2, 3) {{ 6, 4, 24 },   
                                                       { 1, -9, 8 }};  
    PrintMatrix(matrix);  
    array<int, 2>^ transposed_matrix = TransposeMatrix(matrix);  
    PrintMatrix(transposed_matrix);  
  
    // Jagged Array (Array-of-Arrays)  
  
    PrintTitle(L"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: 
    *  
    * array<array<String^>^>^ text = gcnew array<array<String^>^> {  
    *      gcnew array<String^> { "word1", "word2", "wordN" },
    *      gcnew array<String^> { "word1", "word2", "wordM" },  
    *      ... 
    *      }; 
    *  
    * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
    *  
    */  
    array<array<String^>^>^ text = {   
    (gcnew String(L"Hoy es el día más hermoso de nuestra vida, querido Sancho;"))->Split(L' '),  
    (gcnew String(L"los obstáculos más grandes, nuestras propias indecisiones;"))->Split(L' '),  
    (gcnew String(L"nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;"))->Split(' '),  
    (gcnew String(L"la cosa más fácil, equivocarnos;"))->Split(' '),  
    (gcnew String(L"la más destructiva, la mentira y el egoísmo;"))->Split(' '),  
    (gcnew String(L"la peor derrota, el desaliento;"))->Split(' '),  
    (gcnew String(L"los defectos más peligrosos, la soberbia y el rencor;"))->Split(' '),  
    (gcnew String(L"las sensaciones más gratas, la buena conciencia..."))->Split(' ')   
    };  
    PrintJaggedArray(text);  
    UpperCaseRandomArray(text);  
    PrintJaggedArray(text);  
    GraphJaggedArray(text);  
  
    // Array Exceptions  
  
    PrintTitle(L"Common Array Exceptions");  
  
    PrintCommonArrayExceptions(nullptr);  
    PrintCommonArrayExceptions(text);  
  
    // Accessing Class Array Elements through Indexer  
  
    PrintTitle(L"Alphabets");  
  
    Alphabet^ vowels = gcnew Alphabet(5);
    vowels[0] = L'a';  
    vowels[1] = L'e';  
    vowels[2] = L'i';  
    vowels[3] = L'o';  
    vowels[4] = L'u';  
    
    Console::WriteLine(L"\nVowels = {{{0}}}",  
        String::Join(L",", vowels[0], vowels[1], vowels[2], vowels[3], vowels[4]));  
  
    Alphabet^ en = gcnew Alphabet(L"abcdefghijklmnopqrstuvwxyz");  
    Console::WriteLine(L"English Alphabet = {{{0}}}", en);  
  
    Console::WriteLine(L"Alphabet Extract en[9..19] = {{{0}}}",   
                    gcnew Alphabet(en->Slice(9, 10)));  
  
    String^ word1 = String::Join(L"", en[6], en[14], en[14], en[3]);  
    String^ word2 = String::Join(L"", en[1], en[24], en[4]);  
    String^ word3 = String::Join(L"", en[4], en[21], en[4], en[17],  
                                    en[24], en[14], en[13], en[4]);  
  
    Console::WriteLine(L"\n{0} {1}, {2}!\n", word1, word2, word3);  


    return 0;
}


The output:






















































































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

Friday, July 5, 2013

Arrays and Indexers in Oxygene



Today's post is about Arrays and Indexers in Oxygene. 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 Oxygene, 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 VB.NET 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. You can get a Oxygene Trial version with IDE support, or get the Free Command Line version and run it from the console.

Last thing. 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.

namespace OxygeneArrays;

interface

type
  Program = class
  public
    class method Main(args: array of String);
    class method ReverseChar(arr: array of Char): array of Char;  
    class method BubbleSortInt(arr: array of Integer): array of Integer;
    class method BubbleSortString(arr: array of String): array of String;
    class method TransposeMatrix(m: array[0..,0..] of Integer): array[0..,0..] of Integer;
    class method UpperCaseRandomArray(arr: array of array of String);
    class method PrintArrayChar(arr: array of Char);
    class method PrintArrayInt(arr: array of Integer);
    class method PrintArrayString(arr: array of String);  
    class method PrintMatrix(m: array[0..,0..] of Integer);
    class method GraphJaggedArray(arr: array of array of String);  
    class method PrintJaggedArray(arr: array of array of String);  
    class method PrintCommonArrayExceptions(arr: array of array of String);
    class method PrintTitle(message: String);   
  end;
  
type     
  Alphabet = public class  
  private  
    // Array Field  
    var letters: array of Char;  
  public      
    // Read-Only Property
    property Length: Integer read letters.Length;    
    // Indexer Get/Set Property
    property Item[idx: Integer]: Char read GetItem write SetItem; default;
    method GetItem(idx: Integer): Char;
    method SetItem(idx: Integer; value: Char);
    // Constructors
    constructor(size: Integer);
    constructor(list: String);
    constructor(list: array of Char);
    // Overriden Method
    method ToString: String; override;   
    // Method  
    method Slice(start: Integer; len: Integer): array of Char;
  end;  
*)
implementation

class method Program.Main(args: array of String);
var
  // Declare Array of Chars  
  letters, inverse_letters: array of Char;  
  // Declare Array of Integers 
  numbers, ordered_numbers: array of Integer;
  // Declare Array of String 
  names, ordered_names: array of String;
  // Declare Matrix
  transposed_matrix: array[0.., 0..] of Integer;
  // other vars
  word1,word2,word3: String;
begin  
  // Single-dimensional Array(s)  
  
  PrintTitle('Reverse Array Elements');

  // Initialize Array of Chars 
  letters := new Char[5];  
  letters[0] := 'A';  
  letters[1] := 'E';  
  letters[2] := 'I';  
  letters[3] := 'O';  
  letters[4] := 'U';  

  PrintArrayChar(letters); 
  inverse_letters := ReverseChar(letters);  
  PrintArrayChar(inverse_letters);  

  PrintTitle('Sort Integer Array Elements');  
  
  // Declare and Initialize Array of Integers   
  numbers := [ 10, 8, 3, 1, 5 ];  
  PrintArrayInt(numbers);  
  ordered_numbers := BubbleSortInt(numbers);  
  PrintArrayInt(ordered_numbers);  
  
  PrintTitle('Sort String Array Elements');  
  
  // Initialize and Array of Strings  
  names := [             
      'Damian',   
      'Rogelio',  
      'Carlos',   
      'Luis',             
      'Daniel'  
      ];  
  PrintArrayString(names);  
  ordered_names := BubbleSortString(names);  
  PrintArrayString(ordered_names);  
  
  // Multi-dimensional Array (Matrix row,column)  
  
  PrintTitle('Transpose Matrix');  
  
  (* Matrix row=2,col=3 
   * A =  [6  4 24] 
   *      [1 -9  8] 
  *)  
  // Array inline expression used to declare and initialize array
  var matrix: array[0..1, 0..2] of Integer := [ [ 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: 
  *  
  * var text: array of array of String := [    
  *    [ 'word1', 'word2', 'wordN' ], 
  *    [ 'word1', 'word2', 'wordM' ],   
  *    ... 
  *    ]; 
  *  
  * Text extract from: 'El ingenioso hidalgo don Quijote de la Mancha' 
  *  
  *)  
  var text: array of array of String := [   
  '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(Nil);  
  PrintCommonArrayExceptions(text);  
  
  // Accessing Class Array Elements through Indexer  
  
  PrintTitle('Alphabets');  

  var vowels: Alphabet := new Alphabet(5);  
  vowels[0] := 'a';  
  vowels[1] := 'e';  
  vowels[2] := 'i';  
  vowels[3] := 'o';  
  vowels[4] := 'u';

  Console.WriteLine(''#10'Vowels = {{{0}}}',  
    String.Join(',', vowels[0], vowels[1], vowels[2], vowels[3], vowels[4]));  
  
  var en: Alphabet := new Alphabet('abcdefghijklmnopqrstuvwxyz');  
  Console.WriteLine('English Alphabet = {{{0}}}', en.ToString);  
  
  Console.WriteLine('Alphabet Extract en[9..19] = {{{0}}}',   
          new Alphabet(en.Slice(9, 10)));  
  
  word1 := String.Join('', en[6], en[14], en[14], en[3]);  
  word2 := String.Join('', en[1], en[24], en[4]);  
  word3 := String.Join('', en[4], en[21], en[4], en[17],  
                           en[24], en[14], en[13], en[4]);  
  
  Console.WriteLine(''#10'{0} {1}, {2}!'#10'', word1, word2, word3);  

  Console.Read;
end;

class method Program.ReverseChar(arr: array of Char): array of Char; 
var 
  reversed: array of Char;
  i: Integer;
begin
  i := 0;
  reversed := new Char[arr.Length];
  for j: Integer := arr.Length - 1 downto 0 do
  begin
    reversed[i] := arr[j];
    i := i + 1;
  end;
  result := reversed;
end;

class method Program.BubbleSortInt(arr: array of Integer): array of Integer; 
var
  swap: Integer;
begin
  swap := 0;
  for i: Integer := arr.Length - 1 downto 1 do
  begin
    for j: Integer := 0 to i - 1 do
    begin
      if arr[j] > arr[j + 1] then
      begin
        swap := arr[j];  
        arr[j] := arr[j + 1];  
        arr[j + 1] := swap; 
      end;
    end;
  end;
  result := arr;
end;

class method Program.BubbleSortString(arr: array of String): array of String; 
var
  swap: String;
begin
  swap := '';
  for i: Integer := arr.Length - 1 downto 1 do
  begin
    for j: Integer := 0 to i - 1 do
    begin
      if arr[j][0] > arr[j + 1][0] then
      begin
        swap := arr[j];  
        arr[j] := arr[j + 1];  
        arr[j + 1] := swap; 
      end;
    end;
  end;
  result := arr;
end;

class method Program.TransposeMatrix(m: array[0..,0..] of Integer): array[0..,0..] of Integer;
var 
  transposed: array[0..,0..] of Integer;  
begin
  (* Transposing a Matrix 2,3  
   *  
   * A =  [6  4 24]T [ 6  1]  
   *      [1 -9  8]  [ 4 -9] 
   *                 [24  8] 
   *)  
  transposed := new Integer[m.GetUpperBound(1) + 1,  
                m.GetUpperBound(0) + 1];
  for i: Integer := 0 to m.GetUpperBound(0) do  
  begin
    for j: Integer := 0 to m.GetUpperBound(1) do
    begin
      transposed[j, i] := m[i, j];  
    end;
  end;
  result := transposed;
end;

class method Program.UpperCaseRandomArray(arr: array of array of String);
var
  r: Random;
  i: Integer;
begin
  r := new Random;
  i := r.Next(0, arr.Length - 1);
  for j: Integer := 0 to arr[i].Length - 1 do
  begin
    arr[i][j] := arr[i][j].ToUpper;
  end;
end;

class method Program.PrintArrayChar(arr: array of Char); 
begin
  Console.WriteLine(''#10'Print Array Content {0}',  
    arr.GetType.Name.Replace(']', arr.Length.ToString + ']'));  
  
  for i: Integer := 0 to arr.Length - 1 do
  begin
    Console.WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]);  
  end;
end;

class method Program.PrintArrayInt(arr: array of Integer); 
begin
  Console.WriteLine(''#10'Print Array Content {0}',  
    arr.GetType.Name.Replace(']', arr.Length.ToString + ']'));  
  
  for i: Integer := 0 to arr.Length - 1 do
  begin
    Console.WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]);  
  end;
end;

class method Program.PrintArrayString(arr: array of String); 
begin
  Console.WriteLine(''#10'Print Array Content {0}',  
    arr.GetType.Name.Replace(']', arr.Length.ToString + ']'));  
  
  for i: Integer := 0 to arr.Length - 1 do
  begin
    Console.WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]);  
  end;
end;

class method Program.PrintMatrix(m: array [0 .. ,0 .. ] of Integer); 
begin
  Console.WriteLine(''#10'Print Matrix Content {0}[{1},{2}]',  
    m.GetType.Name.Replace('[,]', ''),  
    (m.GetUpperBound(0) + 1).ToString,  
    (m.GetUpperBound(1) + 1).ToString);  

  for i: Integer := 0 to m.GetUpperBound(0) do
  begin
    for j: Integer := 0 to m.GetUpperBound(1) do
    begin
      Console.WriteLine(' array [{0,2},{1,2}] = {2,2} ', i, j, m[i, j]);
    end;
  end; 
end;

class method Program.GraphJaggedArray(arr: array of array of String);
var
  lineCount: Integer;
begin
  (* When using Arrays, we can use foreach instead of for:  
  *  
  * for i: Integer := 0 to arr.Length - 1 do
  *   for j: Integer := 0 to arr.Length - 1 do
  *  
  *)  
  Console.WriteLine(''#10'Print Text Content {0}', arr.GetType.Name); 
  lineCount := 1;    
  for each s: array of String in arr do
  begin
    Console.Write('Line{0,2}|', lineCount); 
    for each w: String in s do
    begin
      Console.Write('{0,3}', '*');
    end;
    Console.WriteLine(' ({0})', s.Length);
    lineCount := lineCount + 1;
  end;
end;

class method Program.PrintJaggedArray(arr: array of array of String); 
var
  line: System.Text.StringBuilder;
begin
  Console.WriteLine(''#10'Print Jagged Array Content {0}', arr.GetType.Name);
  for i: Integer := 0 to arr.Length - 1 do
  begin
    line := new System.Text.StringBuilder;  
    for j: Integer := 0 to arr[i].Length - 1 do
    begin
      line.Append(' ' + arr[i][j]);  
    end;
    if line.ToString() = line.ToString.ToUpper then
    begin
      line.Append(' <-- [UPPERCASED]');  
    end;    
    Console.WriteLine(line);  
  end;
end;

class method Program.PrintCommonArrayExceptions(arr: array of array of String); 
begin
  try
    arr[100][100] := 'hola';  
  except
    on ex: Exception do
      Console.WriteLine(''#10'Exception: '#10'{0}'#10'{1}', 
              ex.GetType().Name, ex.Message); 
  end;
end;

class method Program.PrintTitle(message: String); 
begin
  Console.WriteLine;  
  Console.WriteLine('======================================================');  
  Console.WriteLine('{0,10}', message);  
  Console.WriteLine('======================================================');  
end;

// Indexer Get/Set Property
method Alphabet.GetItem(idx: Integer): Char;
begin
  result := self.letters[idx];
end;

method Alphabet.SetItem(idx: Integer; value: Char); 
begin
  self.letters[idx] := Char.ToUpper(value);
end;

// Constructors
constructor Alphabet(size: Integer);
begin
  self.letters := new Char[size];
end;

constructor Alphabet(list: String);
begin
  self.letters := list.ToUpper.ToCharArray;
end;

constructor Alphabet(list: array of Char);
begin
  self.letters := list;
end;

// Overridden Method  
method Alphabet.ToString: String;
begin
  result := String.Join(',', self.letters); 
end;

// Method  
method Alphabet.Slice(start: Integer; len: Integer): array of Char;
var
  res: array of Char;
  i, j: Integer;
begin
  res := new Char[len];
  j := start;
  for i := 0 to len - 1 do
  begin
    res[i] := self[j];
    j := j + 1;
  end;
  result := res;
end;

end.


The output:






















































































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