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.

No comments:

Post a Comment