Tuesday, December 23, 2014

Arrays and Indexers in Kotlin



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

import java.util.Random

fun main(args: Array<String>) {
    // Single-dimensional Array(s)
    printTitle("Reverse Array Elements")

    // Declare and Initialize Array of Chars
    //val letters = Array<Char>(5, {c -> ' '})
    val letters = CharArray(5)
    letters[0] = 'A'
    letters[1] = 'E'
    letters[2] = 'I'
    letters[3] = 'O'
    letters[4] = 'U'

    printArrayChar(letters)
    val inverse_letters = reverseChar(letters)
    printArrayChar(inverse_letters)

    printTitle("Sort Integer Array Elements")

    // Declare and Initialize Array of Integers
    val numbers: IntArray = intArray(10, 8, 3, 1, 5)
    printArrayInt(numbers)
    val ordered_numbers = bubbleSortInt(numbers)
    printArrayInt(ordered_numbers)

    printTitle("Sort String Array Elements")

    // Declare and Initialize and Array of Strings
    val names: Array<String> = array(
        "Damian",
        "Rogelio",
        "Carlos",
        "Luis",
        "Daniel"
    )
    printArrayString(names)
    val ordered_names: Array<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]
    */
    val matrix = array(array(6, 4, 24),
                       array(1, -9, 8))
    printMatrix(matrix)
    val 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:
     *
     * val text:Array<Array<String>> = array(
     *      array( "word1", "word2", "wordN" ),
     *      array( "word1", "word2", "wordM" ),
     *      ...
     *      )
     *
     * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"
     *
     */
    val text: Array<Array<String>> = array(
    "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) // Null-Safety
    printCommonArrayExceptions(text)

    // Accessing Class Array Elements through Indexer

    printTitle("Alphabets")

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

    println("\nVowels = {${charArray(vowels[0], vowels[1], vowels[2], vowels[3], vowels[4]).joinToString(",")}}")

    val en = Alphabet(0)
    en.init("abcdefghijklmnopqrstuvwxyz")
    println("English Alphabet = {${en.toString()}}")

    val en2 = Alphabet(0)
    en2.init(en.slice(9, 10))
    println("Alphabet Extract en[9..19] = {${en2}}")

    val word1 = charArray(en[6], en[14], en[14], en[3]).joinToString("")
    val word2 = charArray(en[1], en[24], en[4]).joinToString("")
    val word3 = charArray(en[4], en[21], en[4], en[17],
            en[24], en[14], en[13], en[4]).joinToString("")

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

fun reverseChar(arr: CharArray): CharArray {
    val reversed = CharArray(arr.size())
    var i: Int = arr.size()-1
    for (j in 0..i) {
        reversed[i] = arr[j]
        i--
    }
    return reversed
}

fun bubbleSortInt(arr: IntArray): IntArray {
    var swap: Int
    for(i in arr.indices) {
        for(j in 0..arr.size() - 2) {
            if (arr[j] > arr[j + 1]) {
                swap = arr[j]
                arr[j] = arr[j + 1]
                arr[j + 1] = swap
            }
        }
    }
    return arr
}

fun bubbleSortString(arr: Array<String>): Array<String> {
    var swap: String
    for(i in arr.indices) {
        for(j in 0..arr.size() - 2) {
            if (arr[j][0] > arr[j + 1][0]) {
                swap = arr[j]
                arr[j] = arr[j + 1]
                arr[j + 1] = swap
            }
        }
    }
    return arr
}

fun transposeMatrix(m: Array<Array<Int>>): Array<Array<Int>> {
    /* Transposing a Matrix 2,3
     *
     * A =  [6  4 24]T [ 6  1]
     *      [1 -9  8]  [ 4 -9]
     *                 [24  8]
    */
    val transposed = Array(m[0].size(), {c -> Array(m.size(), {v -> 0})})
    for (i in m.indices) {
        for (j in m[0].indices) {
            transposed[j][i] = m[i][j]
        }
    }
    return transposed
}

fun upperCaseRandomArray(arr: Array<Array<String>>) {
    val r = Random()
    val i = r.nextInt(arr.size())
    for (j in arr[i].indices) {
        arr[i][j] = arr[i][j].toUpperCase()
    }
}

fun printArrayChar(arr: CharArray) {
    println("\nPrint Array Content ${arr.javaClass.getName()}[${arr.size()}]")

    for (i in arr.indices) {
        println(java.lang.String.format(" array [%2d] = %2s", i, arr[i]))
    }
}

fun printArrayInt(arr: IntArray) {
    println("\nPrint Array Content ${arr.javaClass.getName()}[${arr.size()}]")

    for (i in arr.indices) {
        println(java.lang.String.format(" array [%2d] = %2d", i, arr[i]))
    }
}

fun printArrayString(arr: Array<String>) {
    println("\nPrint Array Content ${arr.javaClass.getName()}[${arr.size()}]")

    for (i in arr.indices) {
        println(java.lang.String.format(" array [%2d] = %2s", i, arr[i]))
    }
}

fun printMatrix(m: Array<Array<Int>>) {
    println("\nPrint Matrix Content ${m.javaClass.getName()}[${m.size()},${m[0].size()}]")

    for(i in m.indices) {
        for(j in m[0].indices) {
            println(java.lang.String.format(" array [%2d,%2d] = %2d", i, j, m[i][j]))
        }
    }
}

fun graphJaggedArray(arr:Array<Array<String>>) {
    /* When using Arrays, we can use foreach instead of for:
     *
     * for (i in arr.indices)
     *   for (j in arr.indices)
     *
    */
    println("\nPrint Text Content ${arr.javaClass.getName()}")
    var lineCount = 1
    for(s in arr) {
        print(java.lang.String.format("Line%2s|", lineCount))
        for(w in s) {
            print(java.lang.String.format("%3s", '*'))
        }
        println(" (${s.size()})")
        lineCount += 1
    }
}

fun printJaggedArray(arr: Array<Array<String>>) {
    println("\nPrint Jagged Array Content ${arr.javaClass.getName()}")
    var line: StringBuilder
    for(i in arr.indices) {
        line = StringBuilder {}
        for(j in arr[i].indices) {
            line.append(' ').append(arr[i][j])
        }
        if (line.toString() == line.toString().toUpperCase())
            line.append(" <-- [UPPERCASED]")
        println(line)
    }
}

fun printCommonArrayExceptions(arr: Array<Array<String>>) {
    try {
        arr[100][100] = "hola"
    } catch(ex: ArrayIndexOutOfBoundsException) {
        println("\nException: \n${ex.javaClass.getName()}\n${ex.getMessage()}\n")
    } catch(ex: Exception) {
        println("\nException: \n${ex.javaClass.getName()}\n${ex.getMessage()}\n")
    }
}

fun printTitle(message: String) {
    println()
    println("=".repeat(54))
    println(message)
    println("=".repeat(54))
}


// Main Constructor and Array Field
class Alphabet (private val size: Int) {
    private var letters = CharArray(size)

    // Indexer Getter/Setter
    fun get(index: Int): Char = letters[index]
    fun set(index: Int, value: Char) {
        letters[index] = value.toString().toUpperCase().charAt(0)
    }

    //
    fun size() = letters.size()

    // Constructors
    // Classes in Kotlin can only have a single constructor.
    // Using methods instead.
    fun init(list: String) {
        letters = list.toUpperCase().toCharArray()
    }

    fun init(arr: CharArray) {
        letters = arr
    }

    // Overridden Method
    override fun toString(): String = letters.joinToString(".")

    // Method
    fun slice(start: Int, length: Int): CharArray {
        val result = CharArray(length)
        var i: Int = 0
        for(c in letters.slice(start..start+length-1)) {
            result[i++] = c
        }
        return result
    }
}


The output:




























































































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

Monday, December 22, 2014

Arrays and Indexers in Scala



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

import scala.util.Random

object ScalaArrays {

  /* Took this brilliant idea ??? 
   * from odersky http://www.scala-lang.org/old/node/11113.html */
  def ??? : Nothing =
    throw new UnsupportedOperationException("not implemented")

  def main(args:Array[String]) {
    // Single-dimensional Array(s)
    printTitle("Reverse Array Elements");

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

    printArrayChar(letters)
    val inverse_letters = reverseChar(letters)
    printArrayChar(inverse_letters)

    printTitle("Sort Integer Array Elements")

    // Declare and Initialize Array of Integers
    val numbers:Array[Int] = Array(10, 8, 3, 1, 5)
    printArrayInt(numbers)
    val ordered_numbers = bubbleSortInt(numbers)
    printArrayInt(ordered_numbers)

    printTitle("Sort String Array Elements")

    // Declare and Initialize and Array of Strings
    val names = Array(
      "Damian",
      "Rogelio",
      "Carlos",
      "Luis",
      "Daniel"
    )
    printArrayString(names)
    val 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]
    */
    //val matrix2 = Array.ofDim[Int](2,3)
    val matrix = Array(Array(6, 4, 24),
      Array(1, -9, 8))

    printMatrix(matrix)
    val 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:
     *
     * val text:Array[Array[String]] = Array(
     *      Array( "word1", "word2", "wordN" ),
     *      Array( "word1", "word2", "wordM" ),
     *      ...
     *      )
     *
     * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"
     *
     */
    val text: Array[Array[String]] = Array(
      "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")

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

    println(s"\nVowels = {${Array(vowels(0), vowels(1), vowels(2), vowels(3), vowels(4)).mkString(",")}}")

    val en = new Alphabet("abcdefghijklmnopqrstuvwxyz")
    println(s"English Alphabet = {${en.toString()}}")

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

    val word1 = Array(en(6), en(14), en(14), en(3)).mkString
    val word2 = Array(en(1), en(24), en(4)).mkString
    val word3 = Array(en(4), en(21), en(4), en(17),
      en(24), en(14), en(13), en(4)).mkString

    println(s"\n$word1 $word2, $word3!")
  }

  def reverseChar(arr:Array[Char]): Array[Char] = arr.reverse

  def bubbleSortInt(arr:Array[Int]): Array[Int] = {
    var swap = 0
    for(i <- arr.length - 1 to 0 by -1) {
      for (j <- 0 to arr.length - 2) {
        if(arr(j) > arr(j + 1)) {
          swap = arr(j)
          arr(j) = arr(j + 1)
          arr(j + 1) = swap
        }
      }
    }
    arr
  }

  def bubbleSortString(arr:Array[String]): Array[String] = {
    var swap = ""
    for(i <- arr.length-1 to 0 by -1) {
      for (j <- 0 to arr.length - 2) {
        if(arr(j)(0) > arr(j + 1)(0)) {
          swap = arr(j)
          arr(j) = arr(j + 1)
          arr(j + 1) = swap
        }
      }
    }
    arr
  }

  def transposeMatrix(m:Array[Array[Int]]) = {
    /* Transposing a Matrix 2,3
     *
     * A =  [6  4 24]T [ 6  1]
     *      [1 -9  8]  [ 4 -9]
     *                 [24  8]
    */
    val transposed = Array.ofDim[Int](m(0).length, m.length)
    for (i <- 0 to m.length - 1)
      for (j <- 0 to m(0).length - 1)
        transposed(j)(i) = m(i)(j)
    transposed
  }

  def upperCaseRandomArray(arr:Array[Array[String]]) {
    val r = scala.util.Random
    val i = r.nextInt(arr.length)
    for (j <- 0 to arr(i).length - 1)
      arr(i)(j) = arr(i)(j).toUpperCase
  }

  def printArrayChar(arr:Array[Char]) {
    println(s"\nPrint Array Content ${arr.getClass.getName}[${arr.length}]")

    for (i <- 0 to arr.length-1) {
      printf(" array [%2d] = %2s\n", i, arr(i))
    }
  }

  def printArrayInt(arr:Array[Int]) {
    println(s"\nPrint Array Content ${arr.getClass.getName}[${arr.length}]")

    for (i <- 0 to arr.length-1) {
      printf(" array [%2d] = %2d\n", i, arr(i))
    }
  }

  def printArrayString(arr:Array[String]) {
    println(s"\nPrint Array Content ${arr.getClass.getName}[${arr.length}]")

    for (i <- 0 to arr.length-1) {
      printf(" array [%2d] = %2s\n", i, arr(i))
    }
  }

  def printMatrix(m:Array[Array[Int]]) {
    println(s"\nPrint Matrix Content ${m.getClass.getName}[${m.length},${m(0).length}]")

    for(i <- 0 to m.length - 1)
      for(j <- 0 to m(0).length - 1)
        printf(" array [%2d,%2d] = %2d\n", i, j, m(i)(j))
  }

  def graphJaggedArray(arr:Array[Array[String]]) {
    /* When using Arrays, we can use foreach instead of for:
     *
     * for (i <- 0 to arr.length - 1)
     *   for (j <- 0 to arr.length - 1)
     *
    */
    println(s"\nPrint Text Content ${arr.getClass.getName}")
    var lineCount = 1
    for(s <- arr) {
      printf("Line%2s|", lineCount)
      for(w <- s) {
        printf("%3s", '*')
      }
      printf(" (%d)\n", s.length)
      lineCount += 1
    }
  }

  def printJaggedArray(arr:Array[Array[String]]) {
    println(s"\nPrint Jagged Array Content ${arr.getClass.getName}")
    var line = new StringBuilder
    for(i <- 0 to arr.length - 1) {
      line = new StringBuilder
      for(j <- 0 to arr(i).length - 1)
        line += ' ' ++= arr(i)(j)
      if (line.toString == line.toString.toUpperCase)
        line ++= " <-- [UPPERCASED]"
      println(line)
    }
  }

  def printCommonArrayExceptions(arr:Array[Array[String]]) {
    try {
      arr(100)(100) = "hola"
    } catch {
      case ex: ArrayIndexOutOfBoundsException =>
        println(s"\nException: \n${ex.getClass.getName}\n${ex.getMessage}\n")
      case ex: Exception =>
        println(s"\nException: \n${ex.getClass.getName}\n${ex.getMessage}\n")
    }
  }

  def printTitle(message:String) {
    println
    println("=" * 54)
    println(message)
    println("=" * 54)
  }

}

// Main Constructor and Array Field
class Alphabet (private val letters:Array[Char]) {

  // Indexer Getter/Setter
  def apply(index:Int) = letters(index)
  def update(index:Int, value:Char) = letters(index) = value.toUpper

  // Getter
  def length() = letters.length

  // Constructors
  //def this(size:Int) = this(new Array[Char](size))
  def this(size:Int) = this(Array.ofDim[Char](size))
  def this(lst:String) = this(lst.toUpperCase.toCharArray)

  // Overridden Method
  override def toString:String = letters.mkString(",")

  // Method
  def slice(start:Int, len:Int) = letters.slice(start, start+len)
}


The output:




























































































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

Sunday, December 7, 2014

Arrays and Indexers in Xtend



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


"Xtend does not support Multidimensional Arrays out-of-the box. You can add support by declaring a Java class like this : " by Sven Efftinge - Google Groups: Xtend Programming Language
// ArrayLiterals2.java
package xtendarrays;

import org.eclipse.xtext.xbase.lib.Inline;

public class ArrayLiterals2 {
 @Inline("new int[$1][$2]")
 public static int[][] new2DIntArrayOfSize(int outerSize, int innerSize) {
  throw new UnsupportedOperationException();
 }
}

"@Inline tells the compiler to replace any calls to the annotated method with the to-be-inlined Java expression (the 'value' template). Note that the @Inlined is not stable API (flagged as @Beta) and will likely be removed once Xtend has support for more powerful method-macros." by Sven Efftinge - Google Groups: Xtend Programming Language
// XtendArrays.xtend
package xtendarrays

import java.util.Random
import java.lang.StringBuffer
import static extension xtendarrays.ArrayLiterals2.*

class XtendArrays {
 def static void main(String[] args) {
  // Single-dimensional Array(s)  
        printTitle("Reverse Array Elements")
        
        // Declare and Initialize Array of Chars  
        val char[] letters = newCharArrayOfSize(5)
        letters.set(0, 'A')
        letters.set(1, 'E')
        letters.set(2, 'I')
        letters.set(3, 'O')
        letters.set(4, 'U')
        
        printArrayChar(letters)  
        val char[] inverse_letters = reverseChar(letters)  
        printArrayChar(inverse_letters)
        
        printTitle("Sort Integer Array Elements")  

        // Declare and Initialize Array of Integers   
        val int[] numbers = #[10, 8, 3, 1, 5]
        printArrayInt(numbers)
        val int[] ordered_numbers = bubbleSortInt(numbers)
        printArrayInt(ordered_numbers)

        printTitle("Sort String Array Elements")  

        // Declare and Initialize and Array of Strings  
        val String[] names = #[                       
                "Damian",   
                "Rogelio",  
                "Carlos",   
                "Luis",                       
                "Daniel"  
            ]
        printArrayString(names)
        val 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] 
        */  
        val int[][] matrix = #[#[6, 4, 24],   
                               #[1, -9, 8]]  
        printMatrix(matrix)
        val 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: 
         *  
         * val text = #[  
         *      #[ "word1", "word2", "wordN" ],  
         *      #[ "word1", "word2", "wordM" ],  
         *      ... 
         *      ] 
         *  
         * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
         *  
         */  
        val 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")
        
        val vowels = new Alphabet(5)
        vowels.set(0, 'a')  
        vowels.set(1, 'e')  
        vowels.set(2, 'i')  
        vowels.set(3, 'o')  
        vowels.set(4, 'u')
        
        println(String.format("\nVowels = {%s}",  #[vowels.get(0), 
         vowels.get(1), vowels.get(2), vowels.get(3), vowels.get(4)].join(',')))
         
        var en = new Alphabet("abcdefghijklmnopqrstuvwxyz")
        println('''English Alphabet = «en.toString»''') 
        
        println('''Alphabet Extract en[9..19] = «new Alphabet(en.slice(9, 10))»''')   
     
      var word1 = #[en.get(6), en.get(14), en.get(14), en.get(3)].join('')
      var word2 = #[en.get(1), en.get(24), en.get(4)].join('')
      var word3 = #[en.get(4), en.get(21), en.get(4), en.get(17), 
           en.get(24), en.get(14), en.get(13), en.get(4)].join('')
  
      println
      println('''«word1» «word2», «word3»!''')                      
 }
 
 def static char[] reverseChar(char[] arr) {  
        val char[] reversed = newCharArrayOfSize(arr.length)  
        for (var i = 0, var j = arr.length - 1; j >= 0; i++, j--) {
            reversed.set(i, arr.get(j))  
        }
        return reversed
    }  
    
    def static int[] bubbleSortInt(int[] arr) {  
        var int swap = 0  
        for (var i = arr.length - 1; i > 0; i--) {  
            for (var j = 0; j < i; j++) {  
                if (arr.get(j) > arr.get(j + 1)) {  
                    swap = arr.get(j)  
                    arr.set(j, arr.get(j + 1))
                    arr.set(j + 1, swap)
                }  
            }  
        }  
  return arr;  
    }  
    
    def static String[] bubbleSortString(String[] arr) {  
        var String swap = ""
        for (var i = arr.length - 1; i > 0; i--) {  
            for (var j = 0; j < i; j++) {                  
                if (arr.get(j).charAt(0) > arr.get(j + 1).charAt(0)) {  
                    swap = arr.get(j)  
                    arr.set(j, arr.get(j + 1))  
                    arr.set(j + 1, swap)
                }  
            }  
        }  
        return arr;  
    }
    
    def static int[][] transposeMatrix(int[][] m) {  
        /* Transposing a Matrix 2,3  
         *  
         * A =  [6  4 24]T [ 6  1]  
         *      [1 -9  8]  [ 4 -9] 
         *                 [24  8] 
        */  
        val int[][] transposed = new2DIntArrayOfSize(m.get(0).length, m.length)   
        for (var i = 0; i < m.length; i++) {  
            for (var j = 0; j < m.get(0).length; j++) {  
                transposed.get(j).set(i, m.get(i).get(j))  
            }  
        }  
        return transposed
    }    
    
    def static void upperCaseRandomArray(String[][] arr) {  
        val r = new Random
        var int i = r.nextInt(arr.length)
        for (var j = 0; j < arr.get(i).length; j++) {
            arr.get(i).set(j, arr.get(i).get(j).toUpperCase)
        }
    }
 
 def static printArrayChar(char[] arr) {
  println
  println('''Print Array Content «arr.class.name» «arr.class.name.class.name»[«arr.length»]''')
  
     for(var i = 0; i < arr.length; i++) {
      println(String::format(" array [%2d] = %2s", i, arr.get(i)))
     }
 }
 
 def static printArrayInt(int[] arr) {
  println
  println('''Print Array Content «arr.class.name» «arr.class.name.class.name»[«arr.length»]''')
  
     for(var i = 0; i < arr.length; i++) {
      println(String::format(" array [%2d] = %2s", i, arr.get(i)))
     }
 }
 
 def static printArrayString(String[] arr) {
  println
  println('''Print Array Content «arr.class.name» «arr.class.name.class.name»[«arr.length»]''')
  
     for(var i = 0; i < arr.length; i++) {
      println(String::format(" array [%2d] = %2s", i, arr.get(i)))
     }
 }
 
 def static void printMatrix(int[][] m) {  
        println(String.format("\nPrint Matrix Content %s[%d,%d]\n",  
            m.class.name.class.name,
            m.length,  
            m.get(0).length))

        for (var i = 0; i < m.length; i++) { 
            for (var j = 0; j < m.get(0).length; j++) {
                println(String.format(" array [%2d,%2d] = %2d", i, j, m.get(i).get(j)))
            }
        }    
 }
 
 def static void graphJaggedArray(String[][] arr) {  
        /* When using Arrays, we can use foreach instead of for:  
         *  
         * for (var i = 0; i < arr.length; i++) 
         *   for (var j = 0; j < arr.length; j++)                 
         *  
        */  
        println("\nPrint Text Content " + arr.class.name.class.name)
        var lineCount = 1
        for(s : arr) {  
            print(String.format("Line%2s|", lineCount))
            for(w : s) {  
                print(String.format("%3s", '*'))
            }  
            print(String.format(" (%d)\n", s.length))  
            lineCount++
        }  
    }  
    
    def static void printJaggedArray(String[][] arr) {  
        var StringBuffer line
        println("\nPrint Jagged Array Content " + arr.class.name + 
         " " + arr.class.name.class.name + "[]") 
        for (var i = 0; i < arr.length; i++)  {  
            line = new StringBuffer 
            for (var j = 0; j < arr.get(i).length; j++) {  
                line.append(" ").append(arr.get(i).get(j)) 
            }
            if (line.toString.equals(line.toString.toUpperCase)) {
                line.append(" <-- [UPPERCASED]")
            }
            println(line)
        }  
    }  
    
    def static void printCommonArrayExceptions(String[][] arr) {  
        try {  
            arr.get(100).set(100, "hola") 
        }  
        catch (NullPointerException ex) { 
         println(String.format("\nException: \n%s\n%s\n", 
                    ex.class.name, ex.message))
        }
        catch (ArrayIndexOutOfBoundsException ex) {  
            println(String.format("\nException: \n%s\n%s\n", 
                    ex.class.name, ex.message))  
        }  
    }  
 
    def static printTitle(String message) {
        println
        println("======================================================")
        println(message)
        println("======================================================")
    }
}


class Alphabet {
 // Array Field
    var char[] letters
    
    // Indexer Getter/Setter 
    def char get(int index) {
     return letters.get(index)
    }
    def void set(int index, char value) {
     this.letters.set(index, value.toString.toUpperCase.charAt(0))
    }
    
    // Getter
    def int length() {  
        return this.letters.length  
    }  
    
    // Constructors  
    new(int size) {  
        this.letters = newCharArrayOfSize(size)  
    }  

    new(String list) {  
        this.letters = list.toUpperCase.toCharArray
    }  

    new(char[] list) {  
        this.letters = list  
    }  
    
    // Overridden Method  
    override String toString() {  
        return this.letters.join(",")
    } 
    
    // Method  
    def char[] slice(int start, int length) {  
        val char[] result = newCharArrayOfSize(length)  
        for (var i = 0, var j = start; i < length; i++, j++) {  
            result.set(i, this.letters.get(j))  
        }  
        return result
    }  
}


The output:








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

Friday, December 5, 2014

Arrays and Indexers in Fantom



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


using [java] fanx.interop::CharArray
using [java] fanx.interop::IntArray 

class FantomArrays
{
  static Void main()
  {
    // For char and int I'm using primitive arrays (CharArray and IntArray)
    // and for String arrays and Multi-dimensional arrays I'm using List (Type[])
    // reference: http://fantom.org/doc/docLang/JavaFFI
    // section Interop Summary and Arrays
    
    // Single-dimensional Array(s)
    printTitle("Reverse Array Elements")
    
    // Declare and Initialize Array of Chars
    letters := CharArray.make(5)
    letters[0] = 'A'
    letters[1] = 'E'
    letters[2] = 'I'
    letters[3] = 'O'
    letters[4] = 'U'

    printArrayChar(letters)
    CharArray inverse_letters := reverseChar(letters)
    printArrayChar(inverse_letters)
    
    printTitle("Sort Integer Array Elements")
    
    // Declare and Initialize Array of Integers
    numbers := IntArray(5)
    numbers[0] = 10
    numbers[1] = 8
    numbers[2] = 3
    numbers[3] = 1
    numbers[4] = 5
    
    printArrayInt(numbers)
    IntArray ordered_numbers := bubbleSortInt(numbers)
    printArrayInt(ordered_numbers)
    
    printTitle("Sort String Array Elements") 

    // Declare and Initialize and Array of Strings  
    Str[] names := Str[                      
            "Damian",   
            "Rogelio",  
            "Carlos",   
            "Luis",                       
            "Daniel"  
          ] 
    printArrayString(names)
    Str[] 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 := [[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: 
     *  
     * Str[][] text := [  
     *      [ "word1", "word2", "wordN" ],  
     *      [ "word1", "word2", "wordM" ],  
     *      ... 
     *      ]
     *  
     * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
     *  
     */  
    Str[][] text := [   
    "Hoy es el dia mas hermoso de nuestra vida, querido Sancho;".split,  
    "los obstaculos mas grandes, nuestras propias indecisiones;".split,  
    "nuestro enemigo mas fuerte, miedo al poderoso y nosotros mismos;".split,  
    "la cosa mas facil, equivocarnos;".split,  
    "la mas destructiva, la mentira y el egoismo;".split,  
    "la peor derrota, el desaliento;".split,  
    "los defectos mas peligrosos, la soberbia y el rencor;".split,  
    "las sensaciones mas 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")

    vowels := Alphabet(5)  
    vowels.set(0, 'a')  
    vowels.set(1, 'e')  
    vowels.set(2, 'i')  
    vowels.set(3, 'o')  
    vowels.set(4, 'u') 
    
    l := [vowels.get(0).toChar, vowels.get(1).toChar, vowels.get(2).toChar, vowels.get(3).toChar, vowels.get(4).toChar].join(",")
    echo("\nVowels = {$l}")
    
    //en := Alphabet.make(...) <-- this should work...
    en := Alphabet.makeFromStr("abcdefghijklmnopqrstuvwxyz")
    echo("English Alphabet = {${en.toStr}}") 
    
    //extract := Alphabet.make(...) <-- this should work...
    extract := Alphabet.makeFromList(en.slice(9, 10))
    echo("Alphabet Extract en[9..19] = {$extract}")
    
    word1 := [en.get(6).toChar, en.get(14).toChar, en.get(14).toChar, en.get(3).toChar].join
    word2 := [en.get(1).toChar, en.get(24).toChar, en.get(4).toChar].join
    word3 := [en.get(4).toChar, en.get(21).toChar, en.get(4).toChar, en.get(17).toChar, en.get(24).toChar, en.get(14).toChar, en.get(13).toChar, en.get(4).toChar].join
    
    echo("\n$word1 $word2, $word3!")
  }
  
  static CharArray reverseChar(CharArray arr) 
  {
    // for List Int[] you use arr.reverse() 
    reversed := CharArray.make(arr.size)
    Int j := arr.size - 1
    for (i := 0; i < arr.size; ++i) {
        reversed[i] = arr[j]
        j--
    }
    return reversed
  }
  
  static IntArray bubbleSortInt(IntArray arr) 
  {  
    Int swap := 0
    for (Int i := arr.size - 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 Str[] bubbleSortString(Str[] arr) 
  {  
    Str swap := ""  
    for (Int i := arr.size - 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 := [,]    

    for (Int i := 0; i < m[0].size; i++) 
    { 
      Int[] row := [,]
      for (Int j := 0; j < m.size; j++) 
      {        
        row.add(m[j][i])        
      }  
      transposed.add(row)
    }
    return transposed
  }  
  
  static Void upperCaseRandomArray(Str[][] arr) 
  {   
    Int i := Int.random(0..<arr.size)
    for (Int j := 0; j < arr[i].size; j++) 
    {
      arr[i][j] = arr[i][j].upper
    }
  }
  
  static Void printArrayChar(CharArray arr) 
  {
    echo("\nPrint Array Content ${arr.typeof.name} [${arr.size}]")
  
    for (i := 0; i < arr.size; i++)  
    {
      echo(" array [${i.toStr.padl(2)}] = ${arr[i].toChar.padl(2)}")
    }
  }
  
  static Void printArrayInt(IntArray arr) 
  {
    echo("\nPrint Array Content ${arr.typeof.name} [${arr.size}]")
  
    for (i := 0; i < arr.size; i++)  
    {
      echo(" array [${i.toStr.padl(2)}] = ${arr[i].toStr.padl(2)}")
    }
  }
  
  static Void printArrayString(Str[] arr) 
  {
    echo("\nPrint Array Content ${arr.typeof.name} ${arr[0].typeof.name}[${arr.size}]")
  
    for (i := 0; i < arr.size; i++)  
    {
      echo(" array [${i.toStr.padl(2)}] = ${arr[i].padl(2)}")
    }
  }
  
  static Void printMatrix(Int[][] m) 
  {  
    echo("\nPrint Matrix Content ${m.typeof.name} ${m[0][0].typeof.name}[${m.size},${m[0].size}]")
  
    for (Int i := 0; i < m.size; i++) 
    { 
      for (Int j := 0; j < m[0].size; j++) 
      {
        echo(" array [${i.toStr.padl(2, ' ')},${j.toStr.padl(2, ' ')}] = ${m[i][j].toStr.padl(2, ' ')}")
      }
    }
  }  
  
  static Void graphJaggedArray(Str[][] arr) 
  { 
    echo("\nPrint Text Content ${arr.typeof.name} ${arr[0][0].typeof.name}[${arr.size}]")
    Int lineCount := 1  
    arr.each |Str[] s| 
    {  
      Env.cur.out.print("Line${lineCount.toStr.padl(2)}|")  
      s.each |Str w| 
      {  
        Env.cur.out.print(" * ")  
      }  
      echo(" (${s.size})")
      lineCount++  
    }      
  }
  
  static Void printJaggedArray(Str[][] arr) 
  {  
    echo("\nPrint Jagged Array Content ${arr.typeof.name} ${arr[0][0].typeof.name}[${arr.size}]")
    for (Int i := 0; i < arr.size; i++)  
    {  
      line := StrBuf()
      for (Int j := 0; j < arr[i].size; j++) 
      {  
          line.add(" ").add(arr[i][j])  
      }
      if (line.toStr == line.toStr.upper) 
      {
        line.add(" <-- [UPPERCASED]")
      }
      echo(line)  
    }  
  }  
  
  static Void printCommonArrayExceptions(Str?[]?[]? arr) 
  {  
    try 
    {  
        arr[100][100] = "hola"        
    }  
    catch (NullErr ex) 
    {  
      echo("\nException: \n${ex.typeof.name}\n$ex") 
    } 
    catch (IndexErr ex) 
    {  
      echo("\nException: \n${ex.typeof.name}\n$ex") 
    } 
    catch (Err ex)
    {  
      echo("\nException: \n${ex.typeof.name}\n$ex") 
    } 
  }  
  
  static Void printTitle(Str message) 
  {
    echo()
    echo("".padr(54, '='))
    echo(message)
    echo("".padr(54, '='))
  }
}

class Alphabet
{
  // Array Field
  Int[] letters := [,]
  
  // Indexer Getter/Setter 
  Int get(Int index) 
  {
    return letters[index]
  }
  
  Void set(Int index, Int value) 
  {
    letters[index] = value.upper
  }
  
  // Constructors
  new make(Int size) 
  {  
    letters.fill(0, size)
  }  

  new makeFromStr(Str list) 
  {  
    letters = list.upper.chars
  }  

  new makeFromList(Int[] list) 
  {  
    letters = list
  }  
  
  // Overriden Method
  override Str toStr()
  {
    Str[] characters := [,]
    this.letters.each |Int c| { characters.add(c.toChar) }
    return characters.join(",")
  }
  
  // Method
  Int[] slice(Int start, Int length)
  {
    return letters.getRange(start..<start+length)
  }
  
}


The output:








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

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.

Tuesday, December 2, 2014

Arrays and Indexers in Groovy



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

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

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

printArray letters
def inverse_letters = reverseChar letters
printArray inverse_letters

printTitle "Sort Integer Array Elements"

// Declare and Initialize Array of Integers
def numbers = [ 10, 8, 3, 1, 5 ].toArray()
printArray numbers
def ordered_numbers = bubbleSort numbers
printArray ordered_numbers

printTitle "Sort String Array Elements"

// Declare and Initialize and Array of Strings
def names = [                       
    "Damian",   
    "Rogelio",  
    "Carlos",   
    "Luis",                       
    "Daniel"
    ].toArray()
printArray names
def ordered_names = bubbleSort names  
printArray ordered_names 

// Multi-dimensional Array (Matrix row,column)  

printTitle "Transpose Matrix"  

/* Matrix row=2,col=3 
 * A =  [6  4 24] 
 *      [1 -9  8] 
*/  
def matrix = [[6, 4, 24] as int[],
              [1, -9, 8] as int[]] as int[][]

printMatrix matrix
def 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: 
 *  
 * def text1 = [ 
 *      [ "word1", "word2", "wordN" ].toArray() as String[],   
 *      [ "word1", "word2", "wordM" ].toArray() as String[]  
 *      ... 
 *      ].toArray() as String[]
 *  
 * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
 *  
 */  
def 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(" ")   
].toArray()

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"

def vowels = new Alphabet(5)  
vowels[0] = 'a'  
vowels[1] = 'e'  
vowels[2] = 'i'  
vowels[3] = 'o'  
vowels[4] = 'u'  
        
println "\nVowels = {${[vowels[0], vowels[1], vowels[2], vowels[3], vowels[4]].join(",")}}"                   

def en = new Alphabet("abcdefghijklmnopqrstuvwxyz") 
println "English Alphabet = {${en.toString()}}" 

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

word1 = [en[6], en[14], en[14], en[3]].toArray().join('')
word2 = [en[1], en[24], en[4]].toArray().join('')
word3 = [en[4], en[21], en[4], en[17], 
         en[24], en[14], en[13], en[4]].toArray().join('')

println "\n$word1 $word2, $word3!"  


def reverseChar(arr) {
    arr.toList().reverse().toArray() as char[]
    /* // or...
    def reversed = new char[arr.length]
    j = arr.length-1
    for (i in 0..<arr.length) {
        reversed[i] = arr[j]
        j--
    }
    reversed
    */
}

def bubbleSort(arr) {
    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;
            }
    arr
}

def transposeMatrix(m) {
    /* Transposing a Matrix 2,3
     *
     * A =  [6  4 24]T [ 6  1]
     *      [1 -9  8]  [ 4 -9]
     *                 [24  8]
    */
    def transposed = new int[m[0].length][m.length]
    for (i in 0..<m.length)
        for (j in 0..<m[0].length)
            transposed[j][i] = m[i][j]   
    transposed
}

def upperCaseRandomArray(arr) {  
    def r = new Random() 
    int i = r.nextInt arr.length 
    for (j in 0..<arr[i].length) 
        arr[i][j] = arr[i][j].toUpperCase()
}

def printArray(arr) {
    println "\nPrint Array Content ${arr.getClass().getName()}[$arr.length]"
    for (i in 0..<arr.length)
        println sprintf(" array [% 2d] = %2s", i, arr[i])
}

def printMatrix(m) {
    println sprintf("\nPrint Matrix Content %s[%d,%d]",
        m.getClass().getName(), m.length, m[0].length)

    for (int i = 0; i < m.length; i++)
        for (int j = 0; j < m[0].length; j++)
            println sprintf(" array [%2d,%2d] = %2s", i, j, m[i][j].toString())
}

def graphJaggedArray(arr) {  
    /* When using Arrays, we can use foreach instead of for:  
     *  
     * for (i in 0..<arr.length) 
     *   for (j in 0..<arr.length)                 
     *  
    */  
    println "\nPrint Text Content ${arr.getClass().getName()}"  
    lineCount = 1  
    for(s in arr) {  
        print sprintf("Line%2s|", lineCount)
        for(w in s) 
            print sprintf("%3s", '*')
        println sprintf(" (%d)", s.length)  
        lineCount++
    }  
}  

def printJaggedArray(arr) {
    println "\nPrint Jagged Array Content ${arr.getClass().getName()}"
    for (i in 0..<arr.length) {
        def line = new StringBuffer()
        for (j in 0..<arr[i].length) 
            line.append(" ").append(arr[i][j])
        if (line.toString().equals(line.toString().toUpperCase())) 
            line.append(" <-- [UPPERCASED]")
        println line
    }
}

def printCommonArrayExceptions(arr) {  
    try {  
        arr[100][100] = "hola" 
    }  
    catch (ex) {  
        println "\nException: \n${ex.getClass().getName()}\n${ex.getMessage()}"                
    }  
}  

def printTitle(message) {
    println ""
    println "=" * 54
    println message
    println "=" * 54
}


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

    // Indexer Getter/Setter 
    def getAt(int index) {
        letters[index]
    }    
    def putAt(int index, def value) {
       letters[index] = value.toUpperCase()
    }

    // Getter
    def getLength() {  
        letters.length
    }  
  
    // Constructors  
    public Alphabet(int size) {  
        letters = new char[size]
    }  

    public Alphabet(String list) {  
        letters = list.toUpperCase().toCharArray()
    }  

    public Alphabet(char[] list) {  
        letters = list
    }  
    
    // Overridden Method  
    @Override
    String toString() {  
        letters.toString().split("").join(",")
    }  
    
    // Method  
    def slice(int start, int length) {  
        letters[start..<start+length].toArray() as char[]
    }  
}


The output:








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