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.

Sunday, November 30, 2014

Arrays and Indexers in Java



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


package javaarrays;
import java.util.Random;

public class JavaArrays {
    
    public static void main(String[] args) {
        
        // Single-dimensional Array(s)  
        printTitle("Reverse Array Elements");  
  
        // Declare and Initialize Array of Chars  
        char[] letters = new char[5];  
        letters[0] = 'A';  
        letters[1] = 'E';  
        letters[2] = 'I';  
        letters[3] = 'O';  
        letters[4] = 'U';  
        
        printArrayChar(letters);  
        char[] inverse_letters = reverseChar(letters);  
        printArrayChar(inverse_letters);  

        printTitle("Sort Integer Array Elements");  

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

        printTitle("Sort String Array Elements");  

        // Declare and Initialize and Array of Strings  
        String[] names = new String[] {                       
                "Damian",   
                "Rogelio",  
                "Carlos",   
                "Luis",                       
                "Daniel"  
            };  
        printArrayString(names);
        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] 
        */  
        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: 
         *  
         * String[][] text = new String[][] {  
         *      new String[] { "word1", "word2", "wordN" },  
         *      new String[] { "word1", "word2", "wordM" },  
         *      ... 
         *      }; 
         *  
         * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
         *  
         */  
        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");  

        Alphabet vowels = new Alphabet(5);  
        vowels.set(0, 'a');  
        vowels.set(1, 'e');  
        vowels.set(2, 'i');  
        vowels.set(3, 'o');  
        vowels.set(4, 'u');  
        
        System.out.format("\nVowels = {%s}\n",  
                String.join(",", String.valueOf(vowels.get(0)), 
                    String.valueOf(vowels.get(1)), String.valueOf(vowels.get(2)), 
                    String.valueOf(vowels.get(3)), String.valueOf(vowels.get(4))));
        
        Alphabet en = new Alphabet("abcdefghijklmnopqrstuvwxyz");  
        System.out.format("English Alphabet = {%s}\n", en.toString()); 
        
        System.out.format("Alphabet Extract en[9..19] = {%s}\n",   
                          new Alphabet(en.slice(9, 10))); 
        
        String word1 = String.join("", String.valueOf(en.get(6)), 
                String.valueOf(en.get(14)), String.valueOf(en.get(14)), 
                String.valueOf(en.get(3)));  
        String word2 = String.join("", String.valueOf(en.get(1)), 
                String.valueOf(en.get(24)), String.valueOf(en.get(4)));  
        String word3 = String.join("", String.valueOf(en.get(4)), 
                String.valueOf(en.get(21)), String.valueOf(en.get(4)), 
                String.valueOf(en.get(17)), String.valueOf(en.get(24)), 
                String.valueOf(en.get(14)), String.valueOf(en.get(13)), 
                String.valueOf(en.get(4)));  
  
        System.out.format("\n%s %s, %s!\n", word1, word2, word3);
    }
    
    private static char[] reverseChar(char[] arr) {  
        char[] reversed = new char[arr.length];  
        for (int i = 0, j = arr.length - 1; j >= 0; i++, j--) {
            reversed[i] = arr[j];  
        }
        return reversed;  
    }  
    
    static int[] bubbleSortInt(int[] arr) {  
        int swap;  
        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;  
                }  
            }  
        }  
        return arr;  
    }  

    static String[] bubbleSortString(String[] arr) {  
        String swap;  
        for (int i = arr.length - 1; i > 0; i--) {  
            for (int j = 0; j < i; j++) {                  
                if (arr[j].charAt(0) > arr[j + 1].charAt(0)) {  
                    swap = arr[j];  
                    arr[j] = arr[j + 1];  
                    arr[j + 1] = swap;  
                }  
            }  
        }  
        return arr;  
    }  
    
    private 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 = new int[m[0].length][m.length];  
        for (int i = 0; i < m.length; i++) {  
            for (int j = 0; j < m[0].length; j++) {  
                transposed[j][i] = m[i][j];  
            }  
        }  
        return transposed;  
    }  

    private static void upperCaseRandomArray(String[][] arr) {  
        Random r = new Random();  
        int i = r.nextInt(arr.length);  
        for (int j = 0; j <= arr[i].length - 1; j++) {
            arr[i][j] = arr[i][j].toUpperCase();  
        }
    }
    
    private static void printArrayChar(char[] arr) {  
        System.out.println("\nPrint Array Content " 
                + arr.getClass().getName() + "[" + arr.length + "]");

        for (int i = 0; i <= arr.length - 1; i++) {
            System.out.format(" array [%2d] = %2s\n", i, arr[i]);   
        }
    }  
    
    private static void printArrayInt(int[] arr) {  
        System.out.println("\nPrint Array Content " 
                + arr.getClass().getName() + "[" + arr.length + "]");

        for (int i = 0; i <= arr.length - 1; i++) {
            System.out.format(" array [%2d] = %2s\n", i, arr[i]);   
        }
    }
    
    private static void printArrayString(String[] arr) {  
        System.out.println("\nPrint Array Content " 
                + arr.getClass().getName() + "[" + arr.length + "]");

        for (int i = 0; i <= arr.length - 1; i++) {
            System.out.format(" array [%2d] = %2s\n", i, arr[i]);   
        }
    }
    
    private static void printMatrix(int[][] m) {  
        System.out.format("\nPrint Matrix Content %s[%d,%d]\n",  
            m.getClass().getName(),
            m.length,  
            m[0].length);

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

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

    // Indexer Getter/Setter 
    public char get(int index) {
        return letters[index];
    }
    
    public void set(int index, char value) {
       letters[index] = String.valueOf(value).toUpperCase().charAt(0);
    }

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

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

    public Alphabet(char[] list) {  
        this.letters = list;  
    }  
    
    // Overridden Method  
    @Override public String toString() {  
        return String.join(",", (new String(this.letters)).split(""));  
    }  
    
    // Method  
    public char[] slice(int start, int length) {  
        char[] result = new char[length];  
        for (int i = 0, j = start; i < length; i++, j++) {  
            result[i] = this.letters[j];  
        }  
        return result;
    }  
}


The output:








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

Thursday, July 24, 2014

Arrays and Indexers in Jython



Today's post is about Arrays and Indexers in Jython. 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 Jython, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

This is the second post of a dynamic language. As with IronPython's version of the program, code structure changed slightly from previous posts. Besides that, because you normally don't use Arrays per se in Python (except for numerical arrays when better performance is required), it is more practical to use Python's List object instead of Java's java.lang.ArrayList, which can definitely be used in Jython, specially when you need to inter operate with other JVM languages.
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 Boo (or Cobra or Jython later on) 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.


import java  
from java.util import Random

# Console Program     
def main():     
    # Single-dimensional Array(s)     
    printtitle('Reverse Array Elements')   
  
    # Declare and Initialize Array (Python List) of Chars     
    # or letters = list('AEIOU')  
    # or letters = 5 * [' ']        
    letters = list(' ' * 5) # letters = []  
    letters[0] = 'A'        # letters.append('A')  
    letters[1] = 'E'        # letters.append('E')  
    letters[2] = 'I'        # letters.append('I')  
    letters[3] = 'O'        # letters.append('O')  
    letters[4] = 'U'        # letters.append('U')  
      
    printarray(letters)  
    inverse_letters = reversechar(letters)  
    printarray(inverse_letters)  
  
    printtitle('Sort Integer Array Elements')  
    # Declare and Initialize Array of Integers     
    numbers = [10, 8, 3, 1, 5]  
      
    printarray(numbers)     
    ordered_numbers = bubblesort(numbers)     
    printarray(ordered_numbers)  
  
    printtitle('Sort String Array Elements')    
  
    # Declare and Initialize and Array of Strings     
    names = ['Damian', 'Rogelio', 'Carlos', 'Luis', 'Daniel']  
  
    printarray(names)     
    ordered_names = bubblesort(names)     
    printarray(ordered_names)  
  
    # Multi-dimensional Array (Matrix row,column)     
    printtitle('Transpose Matrix')     
  
    matrix = [[6, 4, 24],        
              [1, -9, 8]]  
  
    printmatrix(matrix)  
    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:    
  
    $text = [     
        [ ["word1", "word2, "wordN"],     
        [ ["word1", "word2, "wordN"],     
        ... 
    ]    
      
    Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"         
    '''  
    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(None)     
    printcommonarrayexceptions(text)   
    a = java.util.ArrayList() 
    printcommonarrayexceptions(a)
    o = java.lang.Object
    printcommonarrayexceptions(o)
    # Accessing Class Array Elements through Indexer  
    printtitle('Alphabets')    
      
    vowels = Alphabet(5)  
    vowels[0] = 'a'  
    vowels[1] = 'e'  
    vowels[2] = 'i'  
    vowels[3] = 'o'  
    vowels[4] = 'u'  
  
    print '\nVowels = {%s}' % ','.join([vowels[0],vowels[1],vowels[2],vowels[3],vowels[4]])  
  
    en = Alphabet('abcdefghijklmnopqrstuvwxyz')     
    print 'English Alphabet = {%s}' % (str(en))  
  
    print 'Alphabet Extract en[9..19] = {%s}' % (str(Alphabet(en.slice(9, 10))))  
     
    word1 = ''.join([en[6], en[14], en[14], en[3]])  
    word2 = ''.join([en[1], en[24], en[4]])     
    word3 = ''.join([en[4], en[21], en[4], en[17], en[24], en[14], en[13], en[4]])     
    print "\n%s %s, %s!\n" % (word1, word2, word3)    
  
    raw_input()  
  
def reversechar(arr):  
    return list(reversed(arr))  
    # or   
    # return arr[::-1]  
    # or   
    # reversedarr = [], i = 0  
    # for j in range(len(arr) - 1,-1,-1):  
    #   reversedarr[i] = arr[j]  
    # return reversedarr  
    #  
  
def bubblesort(arr):  
    for i in reversed(arr):     
        for j in range(len(arr) - 1):     
            if arr[j] > arr[j + 1]:     
                swap = arr[j]     
                arr[j] = arr[j + 1]     
                arr[j + 1] = swap     
    return arr  
  
def transposematrix(m):     
    ''' Transposing a Matrix 2,3   
      
     A =  [6  4 24]T [ 6  1]   
          [1 -9  8]  [ 4 -9]   
                     [24  8]   
    '''  
    transposed = [len(m)*[0] for i in range(len(m[0]))]  
    for i in range(len(m)):     
        for j in range(len(m[0])):     
            transposed[j][i] = m[i][j]  
    return transposed    
  
def uppercaserandomarray(arr):     
    r = Random()     
    i = r.nextInt(len(arr))     
    for j in range(len(arr[i])):  
        arr[i][j] = arr[i][j].upper()  
  
def printarray(arr):  
    print '\nPrint Array Content ' + str(type(arr))[7:-2]  + '[' + str(len(arr)) + ']'  
    for i in range(len(arr)):     
        print ' array [{0:2}'.format(i) + '] = {0:2}'.format(arr[i])  
  
def printmatrix(m):     
    print '\nPrint Matrix Content ' + str(type(m))[7:-2]  + '[' + str(len(m)) + ',' + str(len(m[0])) + ']'  
    for i in range(len(m)):     
        for j in range(len(m[0])):     
            print ' array [{0:2},{1:2}] = {2:2} '.format(i, j, m[i][j])  
  
def graphjaggedarray(arr):     
    '''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 ' + str(type(arr))[7:-2]  
    for i in range(len(arr)):     
        line = ''  
        line += 'Line{0:2}|'.format(i+1)  
        for j in range(len(arr[i])):     
            line += '{0:3}'.format('*')     
        line += '(' + str(len(arr[i])) + ')'  
        print line  
          
  
def printjaggedarray(arr):  
    print '\nPrint Jagged Array Content ' + str(type(arr))[7:-2]  
    for i in range(len(arr)):  
        line = ''  
        for j in range(len(arr[i])):        
            line += ' ' + arr[i][j]  
        if line == line.upper():  
            line += ' <-- [UPPERCASED]'  
        print line  
  
def printcommonarrayexceptions(arr):  
    try:  
        print type(arr)
        arr[100][100] = 'hola'
    except TypeError, e:  
        print '\nType Exception: \n', e
    except IndexError, e:
        print '\nIndex Exception: \n', e
    except java.lang.Exception, e:
        print '\nJava Exception: ', e
    #except e:  
    #    print '\nException:' 
    #else:  
  
def printtitle(message):      
    print ''    
    print '=' * 54     
    print message     
    print '=' * 54

class Alphabet:  
    # Array Field     
    _letters = []  
      
    # Indexer Get/Set Property  
    def __getitem__(self, idx):  
        return self._letters[idx]  
    def __setitem__(self, idx, value):  
        self._letters[idx] = str(value).upper()  
      
    # Read-Only Property  
    def get_Length(self):  
        return len(self._letters)     
    Length = property(fget=get_Length)  
  
    # Constructor  
    def __init__(self, param=None):             
        if type(param) == type(1):  
            self._letters = list(' ' * param)  
        elif type(param) == type(''):  
            self._letters = list(str(param).upper())  
        elif type(param) == type([]):  
            self._letters = param  
        else:  
            self._letters = None  
  
    # Overridden Method      
    def __str__(self):  
        return ','.join(self._letters)  
  
    # Method     
    def slice(self, start, length):  
        return self._letters[start:start+length]  
  
if __name__ == '__main__':  
    main()


The output:








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

Tuesday, May 6, 2014

Arrays and Indexers in JRuby



Today's post is about Arrays and Indexers in JRuby. 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 JRuby, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

This is the first post on this series on a language targeting the JVM. Besides the fact that I had the code from a previous post written in (Iron)Ruby, the newly released version of the (J)Ruby plugin for NetBeans IDE (http://plugins.netbeans.org/plugin/38549/?show=true) helped me decide what to publish next.

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.

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.


require "java"

# Console Program  
def main()  
    # Single-dimensional Array(s)  
    print_title("Reverse Array Elements")  
   
    # Declare and Initialize Array of Chars        
    letters = Array.new(5," ")  
    letters[0] = "A"  
    letters[1] = "E"  
    letters[2] = "I"  
    letters[3] = "O"  
    letters[4] = "U"  
   
    print_array(letters)    
    inverse_letters = reverse_char(letters)  
    print_array(inverse_letters)  
  
    print_title("Sort Integer Array Elements")  
    # Declare and Initialize Array of Integers     
    numbers = [10, 8, 3, 1, 5]  
      
    print_array(numbers)         
    ordered_numbers = bubblesort(numbers)     
    print_array(ordered_numbers)  
  
    print_title("Sort String Array Elements")    
   
    # Declare and Initialize and Array of Strings   
    #names = Array.new(5, ["Damian","Rogelio","Carlos","Luis","Daniel"])  
    # or just   
    names = ["Damian",   
      "Rogelio",   
      "Carlos",   
      "Luis",   
      "Daniel"]  
  
    print_array(names)     
    ordered_names = bubblesort(names)     
    print_array(ordered_names)  
  
    # Multi-dimensional Array (Matrix row,column)     
    print_title("Transpose Matrix")     
  
    # for an empty table initialized to 0s  
    # matrix = Array.new(rows,0) { Array.new(cols,0) }  
    matrix = [[6, 4, 24],        
              [1, -9, 8]]  
  
    print_matrix(matrix)  
    transposed_matrix = transpose_matrix(matrix)     
    print_matrix(transposed_matrix)    
   
    # Jagged Array (Array-of-Arrays)     
    print_title("Upper Case Random Array & Graph Number of Elements")     
  
=begin  
# Creating an array of string arrays using the String.Split method     
# instead of initializing it manually as follows:     
#   
# text = [      
#  [ ["word1", "word2, "wordN"],      
#  [ ["word1", "word2, "wordN"],      
#  ...  
#  ]     
#       
# Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"          
=end  
    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(" ")  
    ]   
   
    print_jagged_array(text)     
    uppercase_random_array(text)        
    print_jagged_array(text)     
    graph_jagged_array(text)  
  
    # Array Exceptions  
    print_title('Common Array Exceptions')  
      
    print_common_array_exceptions(nil)  
    print_common_array_exceptions(text)    
  
    # Accessing Class Array Elements through Indexer  
    print_title('Alphabets')  
      
    vowels = Alphabet.new(5)  
    vowels[0] = "a"  
    vowels[1] = "e"  
    vowels[2] = "i"  
    vowels[3] = "o"  
    vowels[4] = "u"  
  
    puts "\nVowels={%s}" % [vowels[0],vowels[1],vowels[2],vowels[3],vowels[4]].join(",")  
  
    en = Alphabet.new("abcdefghijklmnopqrstuvwxyz")     
  
    puts "English Alphabet = {%s}" % [en]  
  
    puts "Alphabet Extract en[9..19] = {%s}" % [Alphabet.new(en.slice(9, 10))]  
  
    word1 = [en[6],en[14],en[14],en[3]].join("")  
    word2 = [en[1],en[24],en[4]].join("")     
    word3 = [en[4],en[21],en[4],en[17],en[24],en[14],en[13],en[4]].join("")     
    puts "\n%s %s, %s!\n" % [word1, word2, word3]  
   
    gets  
end  
  
def reverse_char(arr)  
    arr.reverse  
end   
  
def bubblesort(arr)    
    for i in arr.reverse  
        for j in (0..arr.count-2)  
            if arr[j] > arr[j + 1]      
                swap = arr[j]     
                arr[j] = arr[j + 1]     
                arr[j + 1] = swap     
            end      
        end   
    end     
    arr  
end  
  
def transpose_matrix(m)    
=begin  
# Transposing a Matrix 2,3    
#       
#   A =  [6  4 24]T [ 6  1]    
#        [1 -9  8]  [ 4 -9]    
#                [24  8]    
=end  
    transposed = Array.new(m[0].size) { Array.new(m.size) }   
    for i in 0..(m.size-1)     
        for j in 0..(m[0].size-1)     
            transposed[j][i] = m[i][j]  
        end  
    end  
    transposed    
end  
  
def uppercase_random_array(arr)        
    r = java.util.Random.new()
    i = r.nextInt(arr.size)
    for j in 0..(arr[i].size-1)     
        arr[i][j] = arr[i][j].upcase  
    end  
end  
  
def print_array(arr)  
    puts "\nPrint Array Content #{arr.class.name}[#{arr.size}]"  
    for i in 0..(arr.size-1)  
        puts " array [%2s] = %2s" % [i, arr[i]]  
    end  
end  
  
def print_matrix(m)  
    puts "\nPrint Array Content #{m.class.name}[#{m.size}][#{m[0].size}]"  
    for i in 0..(m.size-1)  
        for j in 0..(m[0].size-1)  
            puts " array [%2s,%2s] = %2s" % [i, j, m[i][j]]  
        end  
    end  
    m  
end  
  
def graph_jagged_array(arr)  
=begin  
# When using Arrays, we can use for(each) instead of for by index  
#    for s in arr    
#        for w in s   
#        end  
#    end  
=end   
    puts "\nPrint Text Content #{arr.class.name}"  
    for i in 0..(arr.size-1)    
        line = ""  
        line += "Line %2s|" % (i+1).to_s   
        for j in 0..(arr[i].size-1)     
            line += " * "  
        end              
        line += "(#{arr[i].size})"  
        puts line  
    end  
end  
  
def print_jagged_array(arr)  
    puts "\nPrint Jagged Array Content #{arr.class.name}"  
    for i in 0..(arr.size-1)  
        line = ""  
        for j in 0..(arr[i].size-1)       
            line += " " + arr[i][j]  
        end  
        if line == line.upcase  
            line += " <-- [UPPERCASED]"  
        end  
        puts line  
    end  
end  
  
def print_common_array_exceptions(arr)  
    begin    
        arr.fetch(100)  
    rescue Exception => ex  
      puts "\nException: \n%s\n%s" % [ex.class.name, ex.message]  
    #else  
    #   others  
    end  
end  
  
def print_title(message)     
    puts ""    
    puts ("=" * 54)     
    puts message     
    puts ("=" * 54)  
end       
  
  
class Alphabet  
    # Array Field     
    @letters = []  
  
    # Indexer Get/Set Property  
    def [](idx)  
        @letters[idx]  
    end  
    def []=(idx, value)  
        @letters[idx] = value.upcase  
    end  
      
    # Read-Only Getter  
    def length  
        @letters.size  
    end            
  
    # Constructor/Initializer  
    def initialize(param)    
        if param.class == 1.class  
            @letters = Array.new(param, " ")  
        elsif param.class == "".class  
            @letters = param.upcase.chars.to_a  
        elsif param.class == [].class  
            @letters = param  
        else  
            @letters = nil  
        end  
    end  
  
    # Overridden Method      
    def to_s  
        @letters.join(",")  
    end  
   
    # Method     
    def slice(start, length)  
        @letters[start..start+length-1]  
    end  
  
end  
  
main


The output:



































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