Friday, July 5, 2013

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.

No comments:

Post a Comment