Sunday, November 8, 2015

OO Hello World - Silver



Hi-yo Silver! Away!

The Hello World in Silver is here! Silver is a free implementation of Apple's Swift programming language being actively developed by RemObjects, the company behind the exceptional language Oxygene.

As mentioned on their website: "Silver is a truly native Swift compiler for the .NET CLR, the Java/Android JVM and the Cocoa runtime. Built on over ten years of solid compiler knowledge and technology, Silver is a truly native Swift compiler for the .NET CLR, the Java/Android JVM and the Cocoa runtime." http://www.elementscompiler.com/elements/silver

By the way, you can see my previous post here: http://carlosqt.blogspot.com/2010/06/oo-hello-world.html where I give some details on WHY these "OO Hello World series" samples.

Version 1 (Minimal):
The minimum you need to type to get your program compiled and running.
class Greet {
 var name: String

 init(name: String) {
        self.name = Char.ToUpper(name.0) + name.Substring(1)
    }

 func salute() {
  println("Hello \(name)!")
 }
}

let g = Greet(name: "world")
g.salute()

Version 2 (Verbose):
Explicitly adding instructions and keywords that are optional to the compiler.
import System
class Greet {
 private var name: String

 public init(name: String) {
        self.name = Char.ToUpper(name.0) + name.Substring(1)
    }

 public func salute() {
  println("Hello \(name)!")
 }
}

let g = Greet(name: "world")
g.salute()

The Program Output:









Swift (Silver) Info:
“Swift is a new programming language for iOS and OS X apps that builds on the best of C and Objective-C, without the constraints of C compatibility. Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible, and more fun..” Taken from: https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11

Appeared:
2014
Current Version:
Silver 8.2 beta, Swift 2.1 (latest version in "Languages" page) 
Developed by:
Silver by RemObjects, Swift by Apple Inc.
Creator:
Silver by RemObjects, Swift by Chris Lattner and Apple Inc.
Influenced by:
Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, D 
Predecessor Language

Predecessor Appeared

Predecessor Creator

Runtime Target:
CLR and JVM
Latest Framework Target:
CLR 4.x JDK 8
Mono Target:
No
Allows Unmanaged Code:
Yes
Source Code Extension:
“.swift”
Keywords:
Silver 89, Swift 80
Case Sensitive:
Yes
Free Version Available:
Yes
Open Source:
Swift Yes, Silver No.
Standard:
No
Latest IDE Support:
Visual Studio 2013
Language Reference:
More Info:


Thursday, November 5, 2015

Arrays and Indexers in Ceylon



Ceylon 1.2 was finally released, you can see the announcement and the new stuff included on the new release here: http://www.ceylon-lang.org/blog/2015/10/29/ceylon-1-2-0/.  This version looks really impressive doesn't it?. Anyway, I took advantage of this 1 year long await to finally come up, me too, with a new post, et voilà! today's post is about Arrays and Indexers in Ceylon.

Ceylon does not have primitives, nor arrays, but you have sequences (read only arrays), generics Array and Java's interop arrays. In this post i used Array instead of CharArray, IntArray and ObjectType interop arrays.

For the Java interop arrays, you can get some documentation in these 2 pages:
http://ceylon-lang.org/documentation/1.0/reference/interoperability/java-from-ceylon/#java_array_types_milestone_5
http://ceylon-lang.org/documentation/1.0/reference/interoperability/type-mapping/

There isn't either Indexers in Ceylon, as a built in feature of the language, however, you can implement some interfaces have a syntax sugar array[index], which behind the scenes is the usual array.get(index) method call. More info here:
http://www.ceylon-lang.org/documentation/1.2/tour/sequences/

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 Ceylon, 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.


//module.ceylon
native("jvm") module com.carlosqt.hello "1.0.0" {
 import java.base "8";
 import ceylon.interop.java "1.2.0";
}


//run.ceylon
import java.lang {  
 Str=String { 
  format 
 }
 ,Int=Integer
 ,Chr=Character
 /*,CharArray
  ,IntArray */
}
/*import ceylon.interop.java {
 createJavaIntArray
}*/
import java.util {
 Random
}

"Run the module `com.carlosqt.hello`."
shared void run() {
 // Single-dimensional Array(s)  
 printTitle("Reverse Array Elements");  
 
 // Declare and Initialize Array of Chars
 //value letters = CharArray(5); // Java interop
 value letters = Array<Character>.ofSize(5, ' ');
 letters.set(0, 'A');  
 letters.set(1, 'E'); 
 letters.set(2, 'I'); 
 letters.set(3, 'O'); 
 letters.set(4, 'U'); 
  
 printArray(letters);
 Array<Character> inverse_letters = reverseChar(letters);  
 printArray(inverse_letters);
 
 printTitle("Sort Integer Array Elements");
 
 // Declare and Initialize Array of Integers
 //IntArray numbers = IntArray(10, 8, 3, 1, 5) 
 //value x = createJavaIntArray({10, 8, 3, 1, 5});
 
 value numbers = Array<Integer|String>({10, 8, 3, 1, 5});
 printArray(numbers);
 value ordered_numbers = bubbleSort(numbers);   
 printArray(ordered_numbers);  
 
 printTitle("Sort String Array Elements");
 
 // Declare and Initialize and Array of Strings
 value names = Array<String|Integer>({
  "Damian",  
  "Rogelio",  
  "Carlos",  
  "Luis",  
  "Daniel"}
 ); 
 
 printArray(names);  
 value 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] 
  */
 value matrix = Array<Array<Integer>>({
  Array<Integer>({6, 4, 24}),
  Array<Integer>({1, -9, 8})
 });
  
 printMatrix(matrix);
 value 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: 
    * 
    * value text = Array<Array<String>>({ 
    *      Array<Integer>({"word1", "word2", "wordN"}), 
    *      Array<Integer>({"word1", "word2", "wordM"}),
    *      ... 
    *      ) 
    * 
    * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
    * 
    */  
 value text = Array<Array<String>>({  
  Array<String>("Hoy es el día más hermoso de nuestra vida, querido Sancho;".split()),
  Array<String>("los obstáculos más grandes, nuestras propias indecisiones;".split()),
  Array<String>("nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;".split()),
  Array<String>("la cosa más fácil, equivocarnos;".split()),
  Array<String>("la más destructiva, la mentira y el egoísmo;".split()),
  Array<String>("la peor derrota, el desaliento;".split()),
  Array<String>("los defectos más peligrosos, la soberbia y el rencor;".split()),
  Array<String>("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");  
 
 
 value vowels = Alphabet(5);  
 vowels.set(0, 'a');  
 vowels.set(1, 'e');  
 vowels.set(2, 'i');  
 vowels.set(3, 'o');  
 vowels.set(4, 'u');  
 
 print("\nVowels = {``",".join({vowels.get(0), vowels.get(1)
  , vowels.get(2), vowels.get(3), vowels.get(4)})``}");
   
 value en = Alphabet.initstr("abcdefghijklmnopqrstuvwxyz");  
 print("English Alphabet = {``en.string``}");  
 
 print("Alphabet Extract en[9..19] = {``Alphabet.initarr(en.slice(9, 10))``}");  
 
 value word1 = "".join({en.get(6), en.get(14), en.get(14), en.get(3)});  
 value word2 = "".join({en.get(1), en.get(24), en.get(4)});
 value word3 = "".join({en.get(4), en.get(21), en.get(4), en.get(17),  
  en.get(24), en.get(14), en.get(13), en.get(4)});
 
 print("\n``word1`` ``word2``, ``word3``!");  
}

Array<Character> reverseChar(Array<Character> arr) {
 variable Integer i = !arr.empty then arr.size-1 else 0;  
 value reversed = Array<Character>.ofSize(arr.size, ' ');
 for (j in 0..i) {  
  if(exists c = arr.get(j)) {
   reversed.set(i, c);
  }
  i--;
 }  
 return reversed;  
}  

Array<Integer|String> bubbleSort(Array<Integer|String> arr) {
 if(!arr.empty) {   
  variable Integer|String swap;
  for(i in arr.indexes()) {  
   for(j in 0..arr.size - 2) {
    if(exists l = arr.get(j), exists r = arr.get(j+1)) {
     if (is Integer l, is Integer r,  l > r) {
      swap = l;
      arr.set(j, r);
      arr.set(j+1, swap);
     } else if (is String l, is String r, l > r) {
      swap = l;
      arr.set(j, r);
      arr.set(j+1, swap);
     }
    }
   }
  }
 }
 return arr;
}

Array<Array<Integer>> transposeMatrix(Array<Array<Integer>> m) {  
 /* Transposing a Matrix 2,3 
  * 
  * A =  [6  4 24]T [ 6  1] 
  *      [1 -9  8]  [ 4 -9] 
  *                 [24  8] 
  */
 if(!m.empty, exists r = m.get(0), exists c = r.get(0)) { 
  value transposed = Array<Array<Integer>>.ofSize(r.size, Array<Integer>.ofSize(m.size, 0));
  for(i in r.indexes()) {
   transposed.set(i, Array<Integer>.ofSize(m.size, 0));
  }
  for(i in m.indexes()) {     
     for(j in r.indexes()) {     
      //transposed[j][i] = m[i][j];      
      if (exists a = m.get(i), exists v = a.get(j), 
       exists tr = transposed.get(j)) {
        tr.set(i, v);
    }
   }
  }
  return transposed;
 }
 else {
  return m;
 }
}  

void upperCaseRandomArray(Array<Array<String>> arr) { 
 value r = Random();
 value i = Integer(r.nextInt(arr.size));
 if(exists s = arr.get(i)) {
  for (j in s.indexes()) {  
   //arr[i][j] = arr[i][j].toUpperCase()
   if(exists m = s.get(j)) {
    s.set(j, m.uppercased);
   }
  }
 }
}

/**/
//void printArrayChar(CharArray|IntArray|StringArray arr) {
// Using Union Types to print all types of Array content
void printArray(Array<Character>|Array<Integer>|Array<String>|Array<Integer|String> arr) {
 String arrtype; 
 if(!arr.empty, exists t = arr.get(0)) { 
  arrtype = className(t); 
 } else { 
  arrtype = "empty";
 } 
 print("\nPrint Array Content ``className(arr)``<``arrtype``>[``arr.size``]");
 
 for (i in 0..arr.size-1) {
  print(format(" array [%2d] = %2s", Int(i), Str(arr.get(i)?.string)));
 }
}

void printMatrix(Array<Array<Integer>> m) {   
 if(!m.empty, exists r = m.get(0), exists c = r.get(0)) { 
  print("\nPrint Matrix Content ``className(m)``<``className(r)``<``className(c)``>>[``m.size``,``r.size``]");
 
  for(i in m.indexes()) {
   if (exists e = m.get(i)) {  
    for(j in e.indexes()) {      
     if (exists f = e.get(j)) {
      print(format(" array [%2d,%2d] = %2d", Int(i), Int(j), Int(f)));
     }  
    }  
   }
  }  
 }   
}  

void graphJaggedArray(Array<Array<String>> arr) {  
    /* When using Arrays, we can use foreach-like instead of for-like loop: 
     * 
     * for (i in arr.indexes()) 
     *   for (j in arr.indexes()) 
     * 
    */  
    print("\nPrint Text Content ``className(arr)``");
    if(!arr.empty) {  
     variable Integer lineCount = 1;
     variable String line = "";  
     for(s in arr) {  
         //print(format("Line%2s|", Int(lineCount)));
         line = "Line ``lineCount``|";  
         for(w in s) {  
             //print(format("%3s", Chr('*')));
             line += " * ";
         }  
         //print(" (``s.size``)");
         line += " (``s.size``)";
         print(line);
         lineCount += 1;
  }  
 }
}  

void printJaggedArray(Array<Array<String>> arr) {  
    print("\nPrint Jagged Array Content ``className(arr)``");
    if(!arr.empty) { 
     //variable StringBuilder line;
     for(i in arr.indexes()) {  
         value line = StringBuilder();
         if(exists r = arr.get(i)) {  
          for(j in r.indexes()) {          
              if(exists s = r.get(j)) {      
               line.append(" ").append(s);
              }  
          }  
          if (line.string == line.string.uppercased) {  
              line.append(" <-- [UPPERCASED]");
          }          
          print(line);
         }
     }
 }  
}  

void printCommonArrayExceptions(Array<Array<String>> arr) {  
 try {
  if(exists i = arr.get(0)) {  
   i.set(100, "hola");
  }
 } catch(AssertionError e) {  
  print("\nException: \n``className(e)``\n``e.message``\n");  
 }  
}  

void printTitle(String message) {  
 print("");  
 print("=".repeat(54));  
 print(message);  
 print("=".repeat(54));  
}  

class Alphabet {
 // Array field
 shared Array<Character> letters; //= Array<Character>.ofSize(size, ' ');

 // Constructors  
 // Only one default constructor
 shared new(Integer size) {
  this.letters = Array<Character>.ofSize(size, ' ');  
 }   
 // and 2 more named constructors
 shared new initstr(String list) {
  this.letters = Array<Character>(list.uppercased); 
 }
 
 shared new initarr(Array<Character> arr) {
  this.letters = arr;
 }

 shared Integer size() 
  => this.letters.size;
 
 // Overridden Method
 
 // No indexers, using methods instead.
 "Gets the item at the specified index"
 shared Character get(Integer index) {
  if(exists l = letters.get(index)) {
   return l;
  } else {
   return ' ';
  }
 }
 
 "Sets the item at the specified index"
 shared void set(Integer index, Character element) {
  if(!letters.empty, exists l = letters.get(index)) {
   letters.set(index, element.uppercased);   
  }
 }
  
 // Overriden (refined)
 "Java's toString"
 shared actual String string 
  => ".".join(letters);
  
  // Method  
  "Returns a subset of this alphabet"
  shared Array<Character> slice(Integer start, Integer len) 
   //=> Array<Character>(letters.sublist(start, start+len-1));  
  => letters[start..start+len-1];  
  
}


The output:





























































































Voilà, that's it. Next post in the following days (or months haha).

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.