Today's post is about Arrays and Indexers in Boo. Here below you will find a very easy to follow program, that demonstrate arrays and indexer, by implementing some simple tasks that will make you grasp the idea of those 2 features real quick. The main goal of this post, is not really teaching arrays because, come on, you probably already know "all" about them, in fact, it is more to show you how you do that in Boo, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.
By the way, if you missed my most recent post, "New Series - Arrays and Indexers", check it out. It has more details about the following program, and a bunch of definitions for the concepts used on this, and the following, posts. Or you can check my previous posts about arrays in C# and C++ just to compare.
I encourage you to copy the code below and try it yourself, normally, all programs you find in this blog are source code complete, just paste it on your IDE and run it.
There is room for improvement of the code, using generics is one example, but Generics, Collections, lambdas, etc. will have their own "series" of posts.
namespace BooArrays # python's import syntax supported only on latest Boo version (2.0.9.5 assemblies) from System import Random from System.Text import StringBuilder from System.Console import WriteLine, Write, ReadKey from System.Convert import ToChar from System.Char import ToUpper # Console Program public def Main(argv as (string)): # Single-dimensional Array(s) printtitle('Reverse Array Elements'); # Declare and initialize Array of Chars # Boo doesn't support yet (version 2.0.9.5 assemblies) Char literals. # 1 character literal such as 'A' or "A" are strings # so, I'm converting Convert.ToChar before assignment by element. # There are 2 ways to initialize inline. i.e. # option 1: a as (char) = (ToChar('A'), ToChar('B'), ToChar('C')) # option 2: a as (char) = "ABC".ToCharArray() letters as (char) = array(char, 5) letters[0] = ToChar('A') letters[1] = ToChar('E') letters[2] = ToChar('I') letters[3] = ToChar('O') letters[4] = ToChar('U') printarraychar(letters) inverse_letters as (char) = reversechar(letters) printarraychar(inverse_letters) printtitle('Sort Integer Array Elements') # Declare and Initialize Array of Integers numbers as (int) = (10, 8, 3, 1, 5) printarrayint(numbers) ordered_numbers as (int) = bubblesortint(numbers) printarrayint(ordered_numbers) printtitle('Sort String Array Elements') # Declare and Initialize and Array of Strings names as (string) = ( 'Damian', 'Rogelio', 'Carlos', 'Luis', 'Daniel' ) printarraystring(names) ordered_names as (string) = bubblesortstring(names) printarraystring(ordered_names) # Multi-dimensional Array (Matrix row,column) printtitle('Transpose Matrix') /* Matrix row=2,col=3 * A = [6 4 24] * [1 -9 8] */ matrx as (int, 2) = matrix(int, 2, 3) # or alternative syntax: = matrix of int(2, 3) matrx[0,0] = 6 matrx[0,1] = 4 matrx[0,2] = 24 matrx[1,0] = 1 matrx[1,1] = -9 matrx[1,2] = 8 printmatrix(matrx) transposed_matrix as (int, 2) = transposematrix(matrx) printmatrix(transposed_matrix) # Jagged Array (Array-of-Arrays) printtitle('Upper Case Random Array & Graph Number of Elements') /* * Creating an array of string arrays using the String.Split method * instead of initializing it manually as follows: * * text as ((string)) = ( * ( 'word1', 'word2', 'wordN' ), * ( 'word1', 'word2', 'wordM' ), * ... * } * * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" * */ text as ((string)) = ( 'Hoy es el día más hermoso de nuestra vida, querido Sancho;'.Split(ToChar(' ')), 'los obstáculos más grandes, nuestras propias indecisiones;'.Split(ToChar(' ')), 'nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;'.Split(ToChar(' ')), 'la cosa más fácil, equivocarnos;'.Split(ToChar(' ')), 'la más destructiva, la mentira y el egoísmo;'.Split(ToChar(' ')), 'la peor derrota, el desaliento;'.Split(ToChar(' ')), 'los defectos más peligrosos, la soberbia y el rencor;'.Split(ToChar(' ')), 'las sensaciones más gratas, la buena conciencia...'.Split(ToChar(' '))) printjaggedarray(text) uppercaserandomarray(text) printjaggedarray(text) graphjaggedarray(text) # Array Exceptions printtitle('Common Array Exceptions') printcommonarrayexceptions(null) printcommonarrayexceptions(text) # Accessing Class Array Elements through Indexer printtitle('Alphabets') vowels as Alphabet = Alphabet(5) vowels[0] = ToChar('a') vowels[1] = ToChar('e') vowels[2] = ToChar('i') vowels[3] = ToChar('o') vowels[4] = ToChar('u') print '\nVowels = {' + join((vowels[0], vowels[1], vowels[2], vowels[3], vowels[4]), ',') + '}' en as Alphabet = Alphabet('abcdefghijklmnopqrstuvwxyz') print "English Alphabet = {${en.ToString()}}" print "Alphabet Extract en[9..19] = {${Alphabet(en.slice(9, 10))}}" word1 as string = join((en[6], en[14], en[14], en[3]), '') word2 as string = join((en[1], en[24], en[4]), '') word3 as string = join((en[4], en[21], en[4], en[17], en[24], en[14], en[13], en[4]), '') print "\n$word1 $word2, $word3!\n" ReadKey() def reversechar(arr as (char)) as (char): reversed as (char) = array(char, arr.Length) i as int = 0 for j in range(len(arr) - 1, -1, -1): reversed[i] = arr[j] i++ return reversed def bubblesortint(arr as (int)) as (int): swap as int = 0 for i in range(len(arr) - 1, -1, -1): for j in range(0, len(arr) - 1): if arr[j] > arr[j + 1]: swap = arr[j] arr[j] = arr[j + 1] arr[j + 1] = swap return arr def bubblesortstring(arr as (string)) as (string): swap as string = '' for i in range(len(arr) - 1, -1, -1): for j in range(0, len(arr) - 1): if arr[j][0] > arr[j + 1][0]: swap = arr[j] arr[j] = arr[j + 1] arr[j + 1] = swap return arr def transposematrix(m as (int, 2)) as (int, 2): /* Transposing a Matrix 2,3 * * A = [6 4 24]T [ 6 1] * [1 -9 8] [ 4 -9] * [24 8] */ transposed as (int, 2) = matrix(int, len(m, 1), len(m, 0)) for i in range(len(m, 0)): for j in range(len(m, 1)): transposed[j, i] = m[i, j] return transposed def uppercaserandomarray(arr as ((string))) as void: r as Random = Random() i as int = r.Next(len(arr)) for j as int in range(len(arr[i])): arr[i][j] = arr[i][j].ToUpper() def printarraychar(arr as (char)) as void: print '\nPrint Array Content ' + arr.GetType().Name.Replace(']', len (arr).ToString() + ']') for i in range(len(arr)): WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]) def printarrayint(arr as (int)): print '\nPrint Array Content ' + arr.GetType().Name.Replace(']', len (arr).ToString() + ']') for i in range(len(arr)): WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]) def printarraystring(arr as (string)) as void: print '\nPrint Array Content ' + arr.GetType().Name.Replace(']', len (arr).ToString() + ']') for i in range(len(arr)): WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]) def printmatrix(m as (int, 2)) as void: print '\nPrint Matrix Content ' + m.GetType().Name.Replace('[,]', '') + '[' + len (m,0).ToString() + ',' + len(m,1).ToString() + ']' for i in range(len(m, 0)): for j in range(len(m, 1)): WriteLine(' array [{0,2},{1,2}] = {2,2} ', i, j, m[i, j]) def graphjaggedarray(arr as ((string))) as void: /* When using Arrays, we can use for(each) instead of for by index: * * for s as (string) in arr: * for w as string in s: * */ print "\nPrint Text Content ${arr.GetType().Name}" for i as int in range(len(arr)): Write('Line{0,2}|', i+1) for j as int in range(len(arr[i])): Write('{0,3}', '*') print " (${len(arr[i]).ToString()})" def printjaggedarray(arr as ((string))) as void: line as StringBuilder print "\nPrint Jagged Array Content ${arr.GetType().Name}" for i as int in range(len(arr)): line = StringBuilder() for j in range(len(arr[i])): line.Append(' ' + arr[i][j]) if line.ToString() == line.ToString().ToUpper(): line.Append(' <-- [UPPERCASED]') print line def printcommonarrayexceptions(arr as ((string))) as void: try: arr[100][100] = 'hola' except ex as System.Exception: print "\nException: \n${ex.GetType().Name}\n${ex.Message}" def printtitle(message as string) as void: print '' print('=' * 54) print message print('=' * 54) [System.Reflection.DefaultMember("item")] class Alphabet: # Array Field private letters as (char) # Indexer Get/Set Property public item[index as int]: get: rawArrayIndexing: return letters[index] set: rawArrayIndexing: letters[index] = ToUpper(value) # Read-Only Property public Length as int: get: return len(self.letters) # Constructors public def constructor(size as int): self.letters = array(char, size) public def constructor(list as string): self.letters = list.ToUpper().ToCharArray() public def constructor(list as (char)): self.letters = list # Overridden Method public override def ToString(): return join(self.letters, ',') # Method public def slice(start as int, length as int) as (char): # using Boo's slicing: # container[<firstIndexWanted>:<firstIndexNotWanted>:<step>] return self.letters[start:start+length]
The output:
Voilà, that's it. Next post in the following days.