Thursday, December 4, 2014

Arrays and Indexers in Gosu



Today's post is about Arrays and Indexers in Gosu. 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 Gosu, 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 (not so) recent post (anymore), "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 Java 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.


package gosuarrays
uses java.lang.Character
uses java.lang.Integer
uses java.util.Random
uses java.lang.System
uses java.lang.StringBuffer
uses java.lang.Exception
uses java.util.Arrays

// Single-dimensional Array(s)
printTitle("Reverse Array Elements")

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

printArrayChar(letters)
var inverse_letters = reverseChar(letters)
printArrayChar(inverse_letters)

printTitle("Sort Integer Array Elements")

// Declare and Initialize Array of Integers
var numbers: Integer[] = {10, 8, 3, 1, 5}
printArrayInt(numbers)

var ordered_numbers = bubbleSortInt(numbers)
printArrayInt(ordered_numbers)

printTitle("Sort String Array Elements");

// Declare and Initialize and Array of Strings
var names = new String[] {
    "Damian",
    "Rogelio",
    "Carlos",
    "Luis",
    "Daniel"
}
printArrayString(names)
var 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]
        */
var matrix: Integer[][] = {{ 6, 4, 24 },
                           { 1, -9, 8 }}
printMatrix(matrix)
var 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: String[][] = {
 *      { "word1", "word2", "wordN" },
 *      { "word1", "word2", "wordM" },
 *      ...
 *      }
 *
 * 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 Indexer

printTitle("Alphabets")

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

print("\nVowels = {${{vowels.getAt(0), vowels.getAt(1), vowels.getAt(2), vowels.getAt(3), vowels.getAt(4)}.join(",")}}")

var en = new Alphabet("abcdefghijklmnopqrstuvwxyz")
print("English Alphabet = {${en.toString()}}")

print("Alphabet Extract en[9..19] = {${new Alphabet(en.slice(9, 10))}}")

var word1 = {en.getAt(6), en.getAt(14), en.getAt(14), en.getAt(3)}.toTypedArray().join("")
var word2 = {en.getAt(1), en.getAt(24), en.getAt(4)}.toTypedArray().join("")
var word3 = {en.getAt(4), en.getAt(21), en.getAt(4), en.getAt(17),
             en.getAt(24), en.getAt(14), en.getAt(13), en.getAt(4)}.toTypedArray().join("")

print("\n${word1} ${word2}, ${word3}!")


function reverseChar(arr: Character[]): Character[] {
  var reversed = new Character[arr.length]
  for (c in arr index i) {
    reversed[i] = c
  }
  return reversed
}

function bubbleSortInt(arr: Integer[]): Integer[] {
  var swap: int = 0
  for (i in arr.length|..0) {
    for (j in 0..|i) {
      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 = ""
  for (i in arr.length|..0) {
    for (j in 0..|i) {
      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: Integer[][]): Integer[][] {
  /* Transposing a Matrix 2,3
   *
   * A =  [6  4 24]T [ 6  1]
   *      [1 -9  8]  [ 4 -9]
   *                 [24  8]
  */
  var transposed = new Integer[m[0].length][m.length]
  for (i in 0..|m.length) {
    for (j in 0..|m[0].length) {
      transposed[j][i] = m[i][j]
    }
  }
  return transposed
}

function upperCaseRandomArray(arr: String[][]) {
  var r = new Random()
  var i = r.nextInt(arr.length)
  for (j in 0..|arr[i].length) {
    arr[i][j] = arr[i][j].toUpperCase()
  }
}

function printArrayChar(arr: Character[]) {
  print("\nPrint Array Content ${arr.Class.Name} [${arr.length}]")

  for (i in 0..|arr.length) {
    print(" array [${String.valueOf(i).leftPad(2)}] = ${String.valueOf(arr[i]).leftPad(2)}")
  }
}

function printArrayInt(arr: Integer[]) {
  print("\nPrint Array Content ${arr.Class.Name} [${arr.length}]")

  for (i in 0..|arr.length) {
    print(" array [${String.valueOf(i).leftPad(2)}] = ${String.valueOf(arr[i]).leftPad(2)}")
  }
}

function printArrayString(arr: String[]) {
  print("\nPrint Array Content ${arr.Class.Name} [${arr.length}]")

  for (i in 0..|arr.length) {
    print(" array [${String.valueOf(i).leftPad(2)}] = ${arr[i].leftPad(2)}")
  }
}

function printMatrix(m: Integer[][]) {
  print("\nPrint Matrix Content ${m.Class.Name}[${m.length},${m[0].length}]")

  for (i in 0..|m.length) {
    for (j in 0..|m[0].length) {
      print(" array [${String.valueOf(i).leftPad(2)},${String.valueOf(i).leftPad(2)}] = ${m[i][j].toString().leftPad(2)}")
    }
  }
}

function graphJaggedArray(arr: String[][]) {
  /* When using Arrays, we can use foreach instead of for:
   *
   * for (i in 0..|arr.length)
   *   for (j in 0..|arr.length)
   *
  */
  print("\nPrint Text Content " + arr.Class.Name)
  var lineCount = 1
  for(s in arr) {
    System.out.print("Line${String.valueOf(lineCount).leftPad(2)}|")
    for(w in s) {
      System.out.print("*".leftPad(3))
    }
    print(" (${s.length})")
    lineCount++
  }
}

function printJaggedArray(arr: String[][]) {
  var line: StringBuffer
  print("\nPrint Jagged Array Content " + arr.Class.Name)
  for (i in 0..|arr.length) {
    line = new StringBuffer()
    for (j in 0..|arr[i].length) {
      line.append(" ").append(arr[i][j])
    }
    if (line.toString() == line.toString().toUpperCase()) {
      line.append(" <-- [UPPERCASED]")
    }
    print(line)
  }
}

function printCommonArrayExceptions(arr: String[][]) {
  try {
    arr[100][100] = "hola"
  }
  catch (ex: Exception) {
    print("\nException: \n${ex.Class.Name}\n${ex.Message}")
  }
}

function printTitle(message: String) {
  print("")
  print("=".repeat(54))
  print(message)
  print("=".repeat(54))
}

class Alphabet {
  // Array Field
  var _letters: Character[]

  // Indexer Getter/Setter
  // cannot use property get because no parameter allowed for index
  // cannot use property set because only 1 parameter allowed (can use Map<int,char>)
  // property get getAt(index:int): Character { return letters[index] }
  // property set setAt(value: Map<int, Character>) { letters[value[0]] = value[1]
  function getAt(index: int): Character {
    return _letters[index]
  }
  function setAt(index: int, value: Character) {
    _letters[index] = String.valueOf(value).toUpperCase().charAt(0)
  }

  // Getter
  function getLength(): int {
    return _letters.length
  }

  // Constructors
  construct(size: int) {
    _letters = new Character[size]
  }

  construct(list: String) {
    _letters = list.toUpperCase().toCharArray().toList().toTypedArray()
  }

  construct(list: Character[]) {
    _letters = list
  }

  // Overridden Method
  override function toString(): String {
    return _letters.join(",")
  }

  // Method
  function slice(start: int, length: int): Character[] {
    return _letters.toList().subList(start, start+length).toTypedArray()
  }
}


The output:








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

No comments:

Post a Comment