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.

No comments:

Post a Comment