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.

Arrays and Indexers in VB.NET



Today's post is about Arrays and Indexers in VB.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 VB.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 post about arrays in C# (or the next one in 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.

Namespace VbArrays

    Module Program

        Sub Main()

            ' Single-dimensional Array(s)  
            PrintTitle("Reverse Array Elements")

            ' Declare and Initialize Array of Chars  
            ' You must specify the maximum index instead of the Length.
            Dim letters(4) As Char
            letters(0) = "A"
            letters(1) = "E"
            letters(2) = "I"
            letters(3) = "O"
            letters(4) = "U"

            PrintArrayChar(letters)
            Dim inverse_letters() As Char = ReverseChar(letters)
            PrintArrayChar(inverse_letters)

            PrintTitle("Sort Integer Array Elements")

            Dim numbers() As Integer = {10, 8, 3, 1, 5}
            PrintArrayInt(numbers)
            Dim ordered_numbers() As Integer = BubbleSortInt(numbers)
            PrintArrayInt(ordered_numbers)

            PrintTitle("Sort String Array Elements")

            ' Declare and Initialize and Array of Strings  
            Dim names() As String = New String() {
                    "Damian",
                    "Rogelio",
                    "Carlos",
                    "Luis",
                    "Daniel"
                }
            PrintArrayString(names)
            Dim 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] 
            '
            Dim matrix(,) As Integer = New Integer(1, 2) {{6, 4, 24},
                                                          {1, -9, 8}}
            PrintMatrix(matrix)
            Dim transposed_matrix(,) As Integer = 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: 
            '  
            ' Dim text As String()() = New String()() {  
            '      New String() { "word1", "word2", "wordN" },  
            '      New String() { "word1", "word2", "wordM" },  
            '      ... 
            '      } 
            '  
            ' Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
            '  
            '  
            Dim text As 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(Nothing)
            PrintCommonArrayExceptions(text)

            ' Accessing Class Array Elements through Indexer  

            PrintTitle("Alphabets")

            Dim vowels As Alphabet = New Alphabet(4)
            vowels(0) = "a"
            vowels(1) = "e"
            vowels(2) = "i"
            vowels(3) = "o"
            vowels(4) = "u"

            Console.WriteLine(ControlChars.CrLf & "Vowels = {{{0}}}",
                String.Join(",", vowels(0), vowels(1), vowels(2), vowels(3), vowels(4)))

            Dim en As New Alphabet("abcdefghijklmnopqrstuvwxyz")
            Console.WriteLine("English Alphabet = {{{0}}}", en.ToString())

            Console.WriteLine("Alphabet Extract en[9..19] = {{{0}}}",
                          New Alphabet(en.Slice(9, 10)))

            Dim word1 As String = String.Join("", en(6), en(14), en(14), en(3))
            Dim word2 As String = String.Join("", en(1), en(24), en(4))
            Dim word3 As String = String.Join("", en(4), en(21), en(4), en(17),
                                           en(24), en(14), en(13), en(4))

            Console.WriteLine(ControlChars.CrLf & "{0} {1}, {2}!" &
                               ControlChars.CrLf, word1, word2, word3)

        End Sub

        Function ReverseChar(ByVal arr() As Char) As Char()
            Dim reversed(arr.Length - 1) As Char
            Dim i As Integer = 0
            For j As Integer = arr.Length - 1 To 0 Step -1
                reversed(i) = arr(j)
                i += 1
            Next
            Return reversed
        End Function

        Function BubbleSortInt(ByVal arr() As Integer) As Integer()
            Dim swap As Integer = 0
            For i As Integer = arr.Length - 1 To 0 Step -1
                For j As Integer = 0 To i - 1
                    If arr(j) > arr(j + 1) Then
                        swap = arr(j)
                        arr(j) = arr(j + 1)
                        arr(j + 1) = swap
                    End If
                Next j
            Next i
            Return arr
        End Function

        Function BubbleSortString(ByVal arr() As String) As String()
            Dim swap As String = ""
            For i As Integer = arr.Length - 1 To 0 Step -1
                For j As Integer = 0 To i - 1
                    If arr(j)(0) > arr(j + 1)(0) Then
                        swap = arr(j)
                        arr(j) = arr(j + 1)
                        arr(j + 1) = swap
                    End If
                Next j
            Next i
            Return arr
        End Function

        Function TransposeMatrix(ByVal m(,) As Integer) As Integer(,)
            ' Transposing a Matrix 2,3  
            '  
            ' A =  [6  4 24]T [ 6  1]  
            '      [1 -9  8]  [ 4 -9] 
            '                 [24  8] 
            '
            Dim transposed(m.GetUpperBound(1), m.GetUpperBound(0)) As Integer
            For i As Integer = 0 To m.GetUpperBound(0)
                For j As Integer = 0 To m.GetUpperBound(1)
                    transposed(j, i) = m(i, j)
                Next
            Next
            Return transposed
        End Function

        Sub UpperCaseRandomArray(ByRef arr As String()())
            Dim r As Random = New Random
            Dim i As Integer = r.Next(0, arr.Length - 1)
            For j As Integer = 0 To arr(i).Length - 1
                arr(i)(j) = arr(i)(j).ToUpper
            Next
        End Sub

        Sub PrintArrayChar(ByVal arr() As Char)
            Console.WriteLine(ControlChars.CrLf & "Print Array Content {0}",
               arr.GetType().Name.Replace("]", arr.Length.ToString + "]"))

            For i As Integer = 0 To arr.Length - 1
                Console.WriteLine(" array [{0,2}] = {1,2} ", i, arr(i))
            Next
        End Sub

        Sub PrintArrayInt(ByVal arr() As Integer)
            Console.WriteLine(ControlChars.CrLf & "Print Array Content {0}",
               arr.GetType.Name.Replace("]", arr.Length.ToString + "]"))

            For i As Integer = 0 To arr.Length - 1
                Console.WriteLine(" array [{0,2}] = {1,2} ", i, arr(i))
            Next
        End Sub

        Sub PrintArrayString(ByVal arr() As String)
            Console.WriteLine(ControlChars.CrLf & "Print Array Content {0}",
               arr.GetType.Name.Replace("]", arr.Length.ToString + "]"))

            For i As Integer = 0 To arr.Length - 1
                Console.WriteLine(" array [{0,2}] = {1,2} ", i, arr(i))
            Next
        End Sub

        Sub PrintMatrix(ByVal m As Integer(,))
            Console.WriteLine(ControlChars.CrLf & "Print Matrix Content {0}[{1},{2}]",
                m.GetType.Name.Replace("[,]", ""),
                (m.GetUpperBound(0) + 1).ToString,
                (m.GetUpperBound(1) + 1).ToString)

            For i As Integer = 0 To m.GetUpperBound(0)
                For j As Integer = 0 To m.GetUpperBound(1)
                    Console.WriteLine(" array [{0,2},{1,2}] = {2,2} ", i, j, m(i, j))
                Next
            Next
        End Sub

        Sub GraphJaggedArray(ByVal arr()() As String)
            ' When using Arrays, we can use foreach instead of for:  
            '  
            ' For i As Integer = 0 To arr.Length
            '   For j As Integer = 0 To arr.Length
            '  
            '
            Console.WriteLine(ControlChars.CrLf & "Print Text Content {0}",
                              arr.GetType.Name)
            Dim lineCount As Integer = 1
            For Each s In arr
                Console.Write("Line{0,2}|", lineCount)
                For Each w In s
                    Console.Write("{0,3}", "*")
                Next
                Console.WriteLine(" ({0})", s.Length)
                lineCount += 1
            Next
        End Sub

        Sub PrintJaggedArray(ByVal arr()() As String)
            Dim line As System.Text.StringBuilder
            Console.WriteLine(ControlChars.CrLf & "Print Jagged Array Content {0}",
                              arr.GetType.Name)
            For i As Integer = 0 To arr.Length - 1
                line = New System.Text.StringBuilder
                For j As Integer = 0 To arr(i).Length - 1
                    line.Append(" " + arr(i)(j))
                Next
                If line.ToString = line.ToString.ToUpper Then
                    line.Append(" <-- [UPPERCASED]")
                End If
                Console.WriteLine(line)
            Next
        End Sub

        Sub PrintCommonArrayExceptions(ByVal arr()() As String)
            Try
                arr(100)(100) = "hola"
            Catch ex As Exception
                Console.WriteLine(ControlChars.CrLf & "Exception: " &
                                  ControlChars.CrLf & "{0}" &
                                  ControlChars.CrLf & "{1}", ex.GetType.Name, ex.Message)
            End Try
        End Sub

        Sub PrintTitle(ByVal message As String)
            Console.WriteLine()
            Console.WriteLine("======================================================")
            Console.WriteLine("{0,10}", message)
            Console.WriteLine("======================================================")
        End Sub

    End Module

    Class Alphabet
        ' Array Field
        Private letters() As Char

        ' Indexer Get/Set Property 
        Default Public Property Item(ByVal index As Integer) As Char
            Get
                Return letters(index)
            End Get
            Set(value As Char)
                letters(index) = Char.ToUpper(value)
            End Set
        End Property

        ' Read-Only Property 
        Public ReadOnly Property Length() As Integer
            Get
                Return Me.letters.Length
            End Get
        End Property

        ' Constructors
        Public Sub New(ByVal size As Integer)
            Me.letters = New Char(size) {}
        End Sub

        Public Sub New(ByVal list As String)
            Me.letters = list.ToUpper.ToCharArray
        End Sub

        Public Sub New(ByVal list() As Char)
            Me.letters = list
        End Sub

        ' Overridden Method 
        Public Overrides Function ToString() As String
            Return String.Join(",", letters)
        End Function

        ' Method
        Public Function Slice(ByVal start As Integer, ByVal length As Integer) As Char()
            Dim result(length) As Char
            Dim j As Integer = start
            For i As Integer = 0 To length
                result(i) = Me(j)
                j += 1
            Next
            Return result
        End Function

    End Class

End Namespace


The output:






















































































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

Monday, July 1, 2013

Arrays and Indexers in C#



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

Ok, enough talk, let's see C# version of the code.
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.

using System;

namespace CsArrays
{
    class Program
    {
        static void Main(string[] args)
        {
            // Single-dimensional Array(s)
            PrintTitle("Reverse Array Elements");

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

            PrintArrayChar(letters);
            char[] inverse_letters = ReverseChar(letters);
            PrintArrayChar(inverse_letters);

            PrintTitle("Sort Integer Array Elements");

            // Declare and Initialize Array of Integers 
            int[] numbers = { 10, 8, 3, 1, 5 };
            PrintArrayInt(numbers);
            int[] ordered_numbers = BubbleSortInt(numbers);
            PrintArrayInt(ordered_numbers);

            PrintTitle("Sort String Array Elements");

            // Declare and Initialize and Array of Strings
            string[] names = new string[] {                     
                    "Damian", 
                    "Rogelio",
                    "Carlos", 
                    "Luis",                     
                    "Daniel"
                };
            PrintArrayString(names);
            string[] 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]
            */
            int[,] matrix = new int[2, 3] { { 6, 4, 24 }, 
                                            { 1, -9, 8 } };
            PrintMatrix(matrix);
            int[,] transposed_matrix = TransposeMatrix(matrix);
            PrintMatrix(transposed_matrix);

            // Jagged Array (Array-of-Arrays)

            PrintTitle("Upper Case Random Array & Graph Number of Elements");

            /*             
             * Creating an array of string arrays using the String.Split method
             * instead of initializing it manually as follows:
             * 
             * string[][] text = new string[][] { 
             *      new string[] { "word1", "word2", "wordN" }, 
             *      new string[] { "word1", "word2", "wordM" }, 
             *      ...
             *      };
             * 
             * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"
             * 
             */
            string[][] text = { 
            "Hoy es el día más hermoso de nuestra vida, querido Sancho;".Split(' '),
            "los obstáculos más grandes, nuestras propias indecisiones;".Split(' '),
            "nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;".Split(' '),
            "la cosa más fácil, equivocarnos;".Split(' '),
            "la más destructiva, la mentira y el egoísmo;".Split(' '),
            "la peor derrota, el desaliento;".Split(' '),
            "los defectos más peligrosos, la soberbia y el rencor;".Split(' '),
            "las sensaciones más gratas, la buena conciencia...".Split(' ') 
            };
            PrintJaggedArray(text);
            UpperCaseRandomArray(text);
            PrintJaggedArray(text);
            GraphJaggedArray(text);

            // Array Exceptions

            PrintTitle("Common Array Exceptions");

            PrintCommonArrayExceptions(null);
            PrintCommonArrayExceptions(text);

            // Accessing Class Array Elements through Indexer

            PrintTitle("Alphabets");

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

            Console.WriteLine("\nVowels = {{{0}}}",
                String.Join(",", vowels[0], vowels[1], vowels[2], vowels[3], vowels[4]));

            Alphabet en = new Alphabet("abcdefghijklmnopqrstuvwxyz");
            Console.WriteLine("English Alphabet = {{{0}}}", en.ToString());

            Console.WriteLine("Alphabet Extract en[9..19] = {{{0}}}", 
                          new Alphabet(en.Slice(9, 10)));

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

            Console.WriteLine("\n{0} {1}, {2}!\n", word1, word2, word3);

        }

        static char[] ReverseChar(char[] arr)
        {
            char[] reversed = new char[arr.Length];
            for (int i = 0, j = arr.Length - 1; j >= 0; i++, j--)
                reversed[i] = arr[j];
            return reversed;
        }

        static int[] BubbleSortInt(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 string[] BubbleSortString(string[] arr)
        {
            string swap = "";
            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 int[,] TransposeMatrix(int[,] m)
        {
            /* Transposing a Matrix 2,3 
             * 
             * A =  [6  4 24]T [ 6  1] 
             *      [1 -9  8]  [ 4 -9]
             *                 [24  8]
            */
            int[,] transposed = new int[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(string[][] arr)
        {
            Random r = new 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(char[] arr)
        {
            Console.WriteLine("\nPrint Array Content {0}",
                arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));

            for (int i = 0; i <= arr.Length - 1; i++)
                Console.WriteLine(" array [{0,2}] = {1,2} ", i, arr[i]);
        }

        static void PrintArrayInt(int[] arr)
        {
            Console.WriteLine("\nPrint Array Content {0}",
                arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));

            for (int i = 0; i <= arr.Length - 1; i++)
                Console.WriteLine(" array [{0,2}] = {1,2} ", i, arr[i]);
        }

        static void PrintArrayString(string[] arr)
        {
            Console.WriteLine("\nPrint Array Content {0}",
                arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));

            for (int i = 0; i <= arr.Length - 1; i++)
                Console.WriteLine(" array [{0,2}] = {1,2} ", i, arr[i]);
        }

        static void PrintMatrix(int[,] m)
        {
            Console.WriteLine("\nPrint Matrix Content {0}[{1},{2}]",
                m.GetType().Name.Replace("[,]", ""),
                (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(" array [{0,2},{1,2}] = {2,2} ", i, j, m[i, j]);
        }

        static void GraphJaggedArray(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("\nPrint Text Content {0}", arr.GetType().Name);
            int lineCount = 1;
            foreach (string[] s in arr)
            {
                Console.Write("Line{0,2}|", lineCount);
                foreach (string w in s)
                {
                    Console.Write("{0,3}", '*');
                }
                Console.WriteLine(" ({0})", s.Length);
                lineCount++;
            }
        }

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

        static void PrintCommonArrayExceptions(string[][] arr)
        {
            try
            {
                arr[100][100] = "hola";
            }
            catch (Exception ex)
            {
                Console.WriteLine("\nException: \n{0}\n{1}", ex.GetType().Name, ex.Message);
            }
        }

        static void PrintTitle(string message)
        {
            Console.WriteLine();
            Console.WriteLine("======================================================");
            Console.WriteLine("{0,10}", message);
            Console.WriteLine("======================================================");
        }

    }

    class Alphabet
    {
        // Array Field
        private char[] letters;

        // Indexer Get/Set Property 
        public char this[int index]
        {
            get { return letters[index]; }
            set { letters[index] = Char.ToUpper(value); }
        }

        // Read-Only Property
        public int Length
        {
            get { return this.letters.Length; }
        }

        // Constructors
        public Alphabet(int size)
        {
            this.letters = new char[size];
        }

        public Alphabet(string list)
        {
            this.letters = list.ToUpper().ToCharArray();
        }

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

        // Overridden Method
        public override string ToString()
        {
            return String.Join(",", this.letters);
        }

        // Method
        public char[] Slice(int start, int length)
        {
            char[] result = new char[length];
            for (int i = 0, j = start; i < length; i++, j++)
            {
                result[i] = this[j];
            }
            return result;
        }

    }
}


The output:






















































































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