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.

No comments:
Post a Comment