tag:blogger.com,1999:blog-6946796115870405202024-03-05T21:29:47.719-08:00Carlos Quintanilla's blogOn (CLR, JVM) Programming LanguaguesCarlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.comBlogger118125tag:blogger.com,1999:blog-694679611587040520.post-9729450667947604352016-09-08T04:30:00.001-07:002017-04-21T03:21:34.148-07:00Arrays and Indexers in PowerShell<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
Today's post is about Arrays and Indexers in PowerShell. 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 PowerShell, in this case, compared to all other ~22 languages on future posts, which essentially, is the real aim behind this blog.<br />
<br />
By the way, if you missed my most recent post, "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
NOTE:<br />
PowerShell provides two different types of arrays, PowerShell [array] objects and typed arrays [type[]]. In PowerShell array objects, a script can dynamically add and remove elements, and elements can be of any data type. In typed arrays, which are dense, the size is fixed, and elements must be the same type as the base type of the array, the least are coming from .NET types, specially multi-dimensional arrays.<br />
<br />
I chose to use the Typed Arrays (and all other variables as well) to keep it closer to the previous posts. I used [array] for jagged arrays [array[]], and for function/method parameter even though [object[]] should also work also.<br />
<br />
<br />
<pre class="brush: powershell">
function ReverseChar($arr) {
[char[]] $reversed = @(1..$arr.length)
#[array]::Reverse($reversed) <-- better to use this but for demo purposes I did it with a for 2 indexes
for ($i, $j = 0, ($arr.length - 1); $j -ge 0; $i++, $j--) {
$reversed[$i] = $arr[$j]
}
return $reversed
}
function BubbleSort([array]$arr) {
$swap = 0
for ($i = ($arr.Length - 1); $i -gt 0; $i--) {
for ($j = 0; $j -lt $i; $j++) {
if ($arr[$j] -gt $arr[$j + 1]) {
$swap = $arr[$j]
$arr[$j] = $arr[$j + 1]
$arr[$j + 1] = $swap
}
}
}
return $arr
}
function TransposeMatrix([int[,]]$m) {
<# Transposing a Matrix 2,3
*
* A = [6 4 24]T [ 6 1]
* [1 -9 8] [ 4 -9]
* [24 8]
#>
[int[,]]$transposed = [int[,]]::new(
$m.GetUpperBound(1) + 1,
$m.GetUpperBound(0) + 1)
for ($i = 0; $i -le $m.GetUpperBound(0); $i++) {
for ($j = 0; $j -le $m.GetUpperBound(1); $j++) {
$transposed[$j,$i] = $m[$i,$j]
}
}
return ,$transposed # use comma operator to avoid unroll
}
function UpperCaseRandomArray([array[]]$arr)
{
#$r = new-object [System.Random]
#$i = $r.Next(0, ($arr.Length - 1))
$i = get-random -minimum -0 -maximum ($arr.Length - 1)
for ($j = 0; $j -lt $arr[$i].Count; $j++) {
$arr[$i][$j] = $arr[$i][$j].ToUpper()
}
return $arr
}
function PrintArray([array]$arr) {
if(!$arr) { $arr=@() }
Write-Host("`nPrint Array Content $($arr.GetType().Name) [$($arr.Length)]")
for ($i=0; $i -lt $arr.Length; $i++) {
Write-Host(" array [$($i.ToString().PadLeft(2))] = $($arr[$i].ToString().PadLeft(2))")
}
}
function PrintMatrix([int[,]]$m) {
Write-Host ("`nPrint Matrix Content {0}[{0},{0}]" -f
$m.GetType().Name.Replace("[,]", ""),
($m.GetUpperBound(0) + 1),
($m.GetUpperBound(1) + 1))
for ($i = 0; $i -le $m.GetUpperBound(0); $i++) {
for ($j = 0; $j -le $m.GetUpperBound(1); $j++) {
Write-Host (" array [{0,2},{1,2}] = {2,2} " -f $i, $j, $m[$i,$j])
}
}
}
function GraphJaggedArray([Array[]]$arr) {
<# When using Arrays, we can use foreach operator instead of for:
*
* for ($i = 0; $i -lt $arr.Length; $i++)
* for ($j = 0; $j -lt $arr.Length; $j++)
*
#>
Write-Host ("Print Text Content $($arr.GetType().Name)`n")
$lineCount = 1
foreach ($s in $arr) {
Write-Host -NoNewline ("Line{0,2}|" -f $lineCount)
foreach ($_ in $s) {
Write-Host -NoNewline ("{0,3}" -f '*')
}
Write-Host (" ($($s.Length))")
$lineCount++
}
}
function PrintJaggedArray([array[]]$arr) {
Write-Host ("`nPrint Jagged Array Content $($arr.GetType().Name)")
for ($i = 0; $i -lt $arr.Count; $i++) {
$line = [System.Text.StringBuilder]::new()
for ($j = 0; $j -lt $arr[$i].Count; $j++) {
[void]$line.Append(" ")
[void]$line.Append($arr[$i][$j].ToString())
}
if (($line.ToString()) -ceq ($line.ToString().ToUpper())) {
[void]$line.Append(" <-- [UPPERCASED]")
}
Write-Host $line
}
}
function PrintCommonArrayExceptions($arr) {
try {
if ($arr -eq $null) {
$arr[100] = "hola"
}
elseif ($arr[0] -eq $null) {
$arr[100] = "hola"
}
elseif ($arr[100] -eq $null) {
$arr[100][100] = "hola"
}
#throw [System.NullReferenceException]::new("")
#throw [System.Exception]::new("")
}
catch [System.Management.Automation.RuntimeException]{
Write-Host ("`nException: `n$($_.Exception.GetType().FullName)`n$($_.Exception.Message)")
}
catch [System.NullReferenceException],[System.IndexOutOfRangeException] {
Write-Host ("`nException: `n$($_.Exception.GetType().FullName)`n$($_.Exception.Message)")
}
catch [Exception] {
# pass
}
catch {
# pass
}
finally {
# pass
}
}
function PrintTitle([String]$message) {
Write-Host
Write-Host ("=" * 55)
Write-Host ($message)
Write-Host ("=" * 55)
}
class Alphabet {
# Array Field
hidden [char[]]$letters = @()
# No indexer support.
# Getter/Setter Method instead.
[char] GetItem([int]$index) {
return $this.letters[$index]
}
[void] SetItem([int]$index, [char]$value) {
$this.letters[$index] = [char]::ToUpper($value)
}
# "Read-Only Property"
[int] Length() {
return $this.letters.Length
}
# Constructors
Alphabet([int]$size) {
$this.letters = @(,' ' * $size)
}
Alphabet([string]$list) {
$this.letters = $list.ToUpper().ToCharArray()
}
Alphabet([char[]]$list) {
$this.letters = $list
}
# Overridden Method
[string] ToString() {
return [String]::Join(",", $this.letters)
}
# Method
[char[]] Slice([int]$start, [int]$length) {
[char[]]$result = @(,' ' * $length)
for ($i, $j = 0, $start
$i -lt $length
$i++, $j++) {
$result[$i] = $this.letters[$j]
}
return $result
}
}
# Single-dimensional Array(s)
printTitle("Reverse Array Elements")
# Declare and Initialize Array of Chars
[char[]] $letters = @(1..5)
$letters[0] = 'A'
$letters[1] = 'E'
$letters[2] = 'I'
$letters[3] = 'O'
$letters[4] = 'U'
# untyped arrays or an array of type [array] are all System.Object[]
# typed arrays need an explicit type [int[]], [string[]], or even [Object[]]
PrintArray($letters)
$inverse_letters = ReverseChar($letters)
PrintArray($inverse_letters)
PrintTitle("Sort Integer Array Elements")
# Declare and Initialize Array of Integers
[int[]]$numbers = @(10, 8, 3, 1, 5)
PrintArray($numbers)
[int[]]$ordered_numbers = [int[]](BubbleSort($numbers))
PrintArray($ordered_numbers)
PrintTitle("Sort String Array Elements")
# Declare and Initialize and Array of Strings
[string[]]$names = @(
"Damian",
"Rogelio",
"Carlos",
"Luis",
"Daniel"
)
PrintArray($names)
[string[]]$ordered_names = BubbleSort($names)
PrintArray($ordered_names)
# Multi-dimensional Array (Matrix row,column)
# To declare a multi-dimensional array in PowerShell
PrintTitle("Transpose Matrix");
<# Matrix row=2,col=3
* A = [6 4 24]
* [1 -9 8]
* #>
# $matrix = New-Object 'int[,]' 2,3
$matrix = [int[,]]::new(2,3)
$matrix[0,0], $matrix[0,1], $matrix[0,2] = 6, 4,24
$matrix[1,0], $matrix[1,1], $matrix[1,2] = 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:
*
* $text = @(
* ,( "word1", "word2", "wordN" )
* ,( "word1", "word2", "wordM" )
* ...
* )
*
* Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"
*
#>
[array[]]$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) > $null
PrintJaggedArray($text)
GraphJaggedArray($text)
# Array Exceptions
PrintTitle("Common Array Exceptions")
PrintCommonArrayExceptions($null)
PrintCommonArrayExceptions(@())
PrintCommonArrayExceptions($text)
# Accessing Class Array Elements through "Indexer" Getter/Setter
PrintTitle('Alphabets');
[Alphabet]$vowels = [Alphabet]::new(5)
$vowels.setitem(0, 'a')
$vowels.setitem(1, 'e')
$vowels.setitem(2, 'i')
$vowels.setitem(3, 'o')
$vowels.setitem(4, 'u')
Write-Host ("`nVowels = {" + [String]::Join(',',
$vowels.getitem(0), $vowels.getitem(1), $vowels.getitem(2),
$vowels.getitem(3), $vowels.getItem(4)) + "}")
[Alphabet]$en = [Alphabet]::new('abcdefghijklmnopqrstuvwxyz')
Write-Host ('English Alphabet = {' + $en.ToString() + "}")
Write-Host ('Alphabet Extract en[9..19] = {' +
([Alphabet]::new($en.slice(9, 10))).tostring() + '}')
$word1 = [String]::Join("", $en.getItem(6), $en.getitem(14),
$en.getitem(14), $en.getitem(3))
$word2 = [String]::Join("", $en.getitem(1), $en.getitem(24),
$en.getitem(4), $en.getitem(4))
$word3 = [String]::Join("", $en.getitem(4), $en.getitem(21),
$en.getitem(4), $en.getitem(17),
$en.getitem(24), $en.getitem(14),
$en.getitem(13), $en.getitem(4))
Write-Host ("`n$word1 $word2, $word3!")
Read-Host
</pre>
<br />
<br />
The output:
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjI1TkXmk-Rw5XKnRGELaeq82PD5CAhbsXdVsQ9i7a-nXJUOWAhje4OHfslhElO4-KKsIAGAIToz6HeujeN3JyAxgKDk_yyfmxONADVQZhkxaG7pr_MjHVmwCIjcEVADcNFoGf-sqxzhJA/s1600/PSArraysIndexers.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjI1TkXmk-Rw5XKnRGELaeq82PD5CAhbsXdVsQ9i7a-nXJUOWAhje4OHfslhElO4-KKsIAGAIToz6HeujeN3JyAxgKDk_yyfmxONADVQZhkxaG7pr_MjHVmwCIjcEVADcNFoGf-sqxzhJA/s1600/PSArraysIndexers.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com3tag:blogger.com,1999:blog-694679611587040520.post-37588612854702573192016-09-02T09:17:00.000-07:002017-04-21T03:21:02.148-07:00Factorial and Fibonacci in PowerShell<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a><script src="https://platform.twitter.com/widgets.js" type="text/javascript">
</script>
<script src="//platform.linkedin.com/in.js" type="text/javascript"></script>
<script data-counter="right" type="IN/Share"></script>
<br />
<br />
Here below a little program in PowerShell that implements 2 classes. There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the <i>Fibonacci</i> and the <i>Factorial</i> algorithms in two ways, one <i>Recursive</i> (using recursion) and the other <i>Imperative</i> (using loops and states). The second class is just an instance class that does the same thing, but its methods are not static. And finally the script part that instantiates and executes the script program.<br />
<br />
You can also find 3 more little examples at the bottom. One prints out the Factorial's Series and Fibonacci's Series, the second one just shows a class that mixes both: static and instance members, and finally the third one that uses different return types (including System.Numerics.BigInteger) for the Factorial method to compare the timing and result.<br />
<br />
As with the previous posts, you can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you some more basics of the Programming Language.<br />
<br />
There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: <a href="http://carlosqt.blogspot.com/2011/01/new-series-factorial-and-fibonacci.html">http://carlosqt.blogspot.com/2011/01/new-series-factorial-and-fibonacci.html</a> <a href="http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html"></a><br />
<br />
<br />
<b>The Fiborial Program</b><br />
<br />
<pre class="brush: powershell"># Factorial and Fibonacci in PowerShell
Add-Type -Path "C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Numerics.dll"
# Instance Class (No static modifier at class level)
class StaticFiborial {
# Static Field
hidden static [String] $className
# Static Constructor
static StaticFiborial() {
[StaticFiborial]::className = "Static Constructor"
Write-Host ([StaticFiborial]::className)
}
# Static Method - Factorial Recursive
static [System.Numerics.BigInteger] FactorialR([Int] $n) {
if ($n -eq 1) {
return 1 #[System.Numerics.BigInteger]::One
} else {
return $n * [StaticFiborial]::FactorialR($n - 1)
}
}
# Static Method - Factorial Imperative
static [System.Numerics.BigInteger] FactorialI([Int] $n) {
$res = [System.Numerics.BigInteger]::One
for($i = $n
$i -ge 1
$i--) {
#$res = [System.Numerics.BigInteger]::Multiply($res, [System.Numerics.BigInteger]::new($i))
$res *= $i
}
return $res
}
# Static Method - Fibonacci Recursive
static [System.Numerics.BigInteger] FibonacciR([Int] $n) {
if ($n -lt 2) {
return 1 #[System.Numerics.BigInteger]::One
} else {
return [StaticFiborial]::FibonacciR($n - 1) + [StaticFiborial]::FibonacciR($n - 2)
}
}
# Static Method - Fibonacci Imperative
static [System.Numerics.BigInteger] FibonacciI([Int] $n) {
[long] $pre = 1
[long] $cur = 1
[long] $tmp = 0
for ($i = 2; $i -le $n; $i++) {
$tmp = $cur + $pre
$pre = $cur
$cur = $tmp
}
return $cur
}
# Static Method - Benchmarking Algorithms
static [void] BenchmarkAlgorithm([Int] $algorithm, [int[]] $values) {
$timer = [System.Diagnostics.Stopwatch]::new()
$i = 0
$testValue = 0
$facTimeResult = [System.Numerics.BigInteger]::Zero
$fibTimeResult = 0
# "Switch" Flow Constrol Statement
switch ($algorithm) {
1 {
Write-Host "`nFactorial Imperative:"
# "For" Loop Statement
for($i = 0; $i -lt $values.Length; $i++) {
$testValue = $values[$i]
# Taking Time
$timer.Start()
$facTimeResult = [StaticFiborial]::FactorialI($testValue)
$timer.Stop()
# Getting Time
Write-Host (" ({0}) = {1}" -f $testValue, $timer.Elapsed)
}
}
2 {
Write-Host "`nFactorial Recursive:"
# "While" Loop Statement
while ($i -lt $values.Length) {
$testValue = $values[$i]
# Taking Time
$timer.Start()
$facTimeResult = [StaticFiborial]::FactorialR($testValue)
$timer.Stop()
# Getting Time
Write-Host (" ({0}) = {1}" -f $testValue, $timer.Elapsed)
$i++
}
}
3 {
Write-Host "`nFibonacci Imperative:"
# "Do-While" Loop Statement
do {
$testValue = $values[$i]
# Taking Time
$timer.Start()
$fibTimeResult = [StaticFiborial]::FibonacciI($testValue)
$timer.Stop()
# Getting Time
Write-Host (" ({0}) = {1}" -f $testValue, $timer.Elapsed)
$i++
} while ($i -lt $values.Length)
}
4 {
Write-Host "`nFibonacci Recursive:"
# "For" Loop Statement
foreach ($testValue in $values) {
# Taking Time
$timer.Start()
$fibTimeResult = [StaticFiborial]::FibonacciR($testValue)
$timer.Stop()
# Getting Time
Write-Host (" ({0}) = {1}" -f $testValue, $timer.Elapsed)
}
}
default {
echo "DONG!`n"
}
}
}
}
# Instance Class
class InstanceFiborial {
# Instance Field
hidden [string] $className
# Instance Constructor
InstanceFiborial() {
$this.className = "Instance Constructor"
Write-Host $this.className
}
# Instance Method - Factorial Recursive
[System.Numerics.BigInteger] FactorialR([int] $n) {
# Calling Static Method
return [StaticFiborial]::FactorialR($n)
}
# Instance Method - Factorial Imperative
[System.Numerics.BigInteger] FactorialI([int] $n) {
# Calling Static Method
return [StaticFiborial]::FactorialI($n)
}
# Instance Method - Fibonacci Recursive
[long] FibonacciR([int] $n) {
# Calling Static Method
return [StaticFiborial]::FibonacciR($n)
}
# Instance Method - Factorial Imperative
[long] FibonacciI([int] $n) {
# Calling Static Method
return [StaticFiborial]::FibonacciI($n)
}
}
Write-Host "`nInstance Class (with static methods)"
# Calling Static Methods
# Instantiation needed. Calling method directly from the class
Write-Host ("FacImp(5) = {0}" -f [StaticFiborial]::FactorialI(5))
Write-Host ("FacRec(5) = {0}" -f [StaticFiborial]::FactorialR(5))
Write-Host ("FibImp(11)= {0}" -f [StaticFiborial]::FibonacciI(11))
Write-Host ("FibRec(11)= {0}" -f [StaticFiborial]::FibonacciR(11))
Write-Host "`nInstance Class"
# Calling Instance Class and Methods
# Need to instantiate before using. Calling method from instantiated object
$ff = [InstanceFiborial]::new()
# or
# $ff = New-Object InstanceFiborial
Write-Host ("FacImp(5) = {0}" -f $ff.FactorialI(5))
Write-Host ("FacRec(5) = {0}" -f $ff.FactorialR(5))
Write-Host ("FibImp(11)= {0}" -f $ff.FibonacciI(11))
Write-Host ("FibRec(11)= {0}" -f $ff.FibonacciR(11))
# Create a (generic) list of integer values to test
# From 5 to 50 by 5
$values = @()
for($i = 5; $i -le 50; $i += 5) {
$values += $i
}
# Benchmarking Fibonacci
# 1 = Factorial Imperative
[StaticFiborial]::BenchmarkAlgorithm(1, $values)
# 2 = Factorial Recursive
[StaticFiborial]::BenchmarkAlgorithm(2, $values)
# Benchmarking Factorial
# 3 = Fibonacci Imperative
[StaticFiborial]::BenchmarkAlgorithm(3, $values)
# 4 = Fibonacci Recursive
[StaticFiborial]::BenchmarkAlgorithm(4, $values)
# Stop and Exit
Read-Host
</pre>
<br />
And the Output is: <br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEgt4064IllrIpklCWe7dTk6yBhFU7YRMPLEhQLGo9lfmW43NSozijkl_AoW8fCDUv16VUpbqpPCeKL9BsXYK_KE20zSu3BCK8lOF6eRSuCWOOIzFNhbGlrVVR4oYxvwV8oTY1K9ke7aY/s1600/PowerShellFiborialOutput.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEgt4064IllrIpklCWe7dTk6yBhFU7YRMPLEhQLGo9lfmW43NSozijkl_AoW8fCDUv16VUpbqpPCeKL9BsXYK_KE20zSu3BCK8lOF6eRSuCWOOIzFNhbGlrVVR4oYxvwV8oTY1K9ke7aY/s1600/PowerShellFiborialOutput.PNG" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<b>Printing the Factorial and Fibonacci Series</b><br />
<pre class="brush: powershell">Add-Type -Path "C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Numerics.dll"
class Fiborial {
# Using a StringBuilder as a list of string elements
static [String] GetFactorialSeries([int] $n) {
# Create the String that will hold the list
$series = [System.Text.StringBuilder]::new()
# We begin by concatenating the number you want to calculate
# in the following format: "!# ="
[void]$series.Append("!")
[void]$series.Append($n)
[void]$series.Append(" = ")
# We iterate backwards through the elements of the series
for($i = $n; $i -le $n -and $i -gt 0; $i--) {
# and append it to the list
[void]$series.Append($i)
if ($i -gt 1) {
[void]$series.Append(" * ")
}
else {
[void]$series.Append(" = ")
}
}
# Get the result from the Factorial Method
# and append it to the end of the list
[void]$series.Append([Fiborial]::Factorial($n))
# return the list as a string
return $series.ToString()
}
# Using a StringBuilder as a list of string elements
static [String] GetFibonnaciSeries([int] $n) {
# Create the String that will hold the list
$series = New-Object -TypeName "System.Text.StringBuilder"
# We begin by concatenating the first 3 values which
# are always constant
[void]$series.Append("0, 1, 1")
# Then we calculate the Fibonacci of each element
# and add append it to the list
for ($i = 2
$i -le $n
$i++) {
if ($i -lt $n) {
[void]$series.Append(", ")
}
else {
[void]$series.Append(" = ")
}
[void]$series.Append([Fiborial]::Fibonacci($i))
}
# return the list as a string
return $series.ToString()
}
static [System.Numerics.BigInteger] Factorial([Int] $n) {
if ($n -eq 1) {
return [System.Numerics.BigInteger]::One
} else {
return $n * [Fiborial]::Factorial($n - 1)
}
}
static [System.Numerics.BigInteger] Fibonacci([Int] $n) {
if ($n -lt 2) {
return [System.Numerics.BigInteger]::One
} else {
return [Fiborial]::Fibonacci($n - 1) + [Fiborial]::Fibonacci($n - 2)
}
}
}
echo ("Printing Factorial Series")
echo ([Fiborial]::GetFactorialSeries(5))
echo ([Fiborial]::GetFactorialSeries(7))
echo ([Fiborial]::GetFactorialSeries(9))
echo ([Fiborial]::GetFactorialSeries(11))
echo ([Fiborial]::GetFactorialSeries(40))
Write-Host ("Printing Fibonacci Series")
Write-Host ([Fiborial]::GetFibonnaciSeries(5))
Write-Host ([Fiborial]::GetFibonnaciSeries(7))
Write-Host ([Fiborial]::GetFibonnaciSeries(9))
Write-Host ([Fiborial]::GetFibonnaciSeries(11))
Write-Host ([Fiborial]::GetFibonnaciSeries(40))
</pre>
<br />
And the Output is:<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhyvV7SoyYCzDkxnNTqQCVJ4kJvf5dgMyqTAFy19cyuL7KEPXwQN6k5kHHy49YQFKGHsF5KMuTDl7jW5pedEpTP9mnHHG-zYIQUcmVUvJKm24KaTt1MJf9WQ5_gNROivkVnzhlTr7pQHX4/s1600/PowerShellFiborialSeries.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhyvV7SoyYCzDkxnNTqQCVJ4kJvf5dgMyqTAFy19cyuL7KEPXwQN6k5kHHy49YQFKGHsF5KMuTDl7jW5pedEpTP9mnHHG-zYIQUcmVUvJKm24KaTt1MJf9WQ5_gNROivkVnzhlTr7pQHX4/s1600/PowerShellFiborialSeries.PNG" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<b><br /></b>
<b><br /></b>
<b><br /></b>
<b><br /></b>
<b><br /></b>
<b>Mixing Instance and Static Members in the same Class</b><br />
<br />
Instance classes can contain both, instance and static members such as: fields, constructors, methods, etc. <br />
<br />
<pre class="brush: powershell">
Add-Type -Path "C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Numerics.dll"
# Instance Class
class Fiborial {
# Instance Field
hidden [int] $instanceCount
# Static Field
hidden static [int] $staticCount
# Instance Read-Only Property/Getter
# Within instance members, you can always use
# the "this" reference pointer to access your (instance) members.
[int] GetInstanceCount() {
return $this.instanceCount
}
# Static Read-Only Property/Getter
# As with Static Methods, you cannot reference your class members
# with the "this" reference pointer since static members are not
# instantiated.
static [int] GetStaticCount() {
return [Fiborial]::staticCount
}
# Instance Constructor
Fiborial() {
$this.instanceCount = 0
Write-Host ("Instance Constructor $($this.instanceCount)`n")
}
# Static Constructor
static Fiborial() {
[Fiborial]::staticCount = 0
Write-Host ("Static Constructor $([Fiborial]::staticCount)`n")
}
# Instance Method
[void] Factorial([int] $n)
{
$this.instanceCount++
Write-Host ("Factorial($n)`n")
}
# Static Method
static [void] Fibonacci([int] $n)
{
[Fiborial]::staticCount++
Write-Host ("Fibonacci($n)`n")
}
}
# Calling Static Constructor/Initializer and Methods
# No need to instantiate
[Fiborial]::Fibonacci(5)
# Calling Instance Constructor and Methods
# Instance required
$fib = [Fiborial]::new()
$fib.Factorial(5)
[Fiborial]::Fibonacci(15)
$fib.Factorial(5)
# Calling Instance Constructor and Methods
# for a second object
$fib2 = [Fiborial]::new()
$fib2.Factorial(5)
# Calling Static Method
Write-Host ("Static Count = $([Fiborial]::GetStaticCount())")
# Calling Instance Property of object 1 and 2
Write-Host ("Instance 1 Count = $($fib.GetInstanceCount())")
Write-Host ("Instance 2 Count = $($fib2.GetInstanceCount())")
Read-Host
</pre>
<br />
And the Output is:<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEis2LVGrMBpB5dEaY-yoZaElVcPOtx75vdUB6GrHoEVs1VabwJpRIBGmpNI9nfvtahYxElxwVHH1AAMisyjeFtkmbWkY5YGg0mHiz_-Glxpj5Fpwd40Vkc6JVKn7ut1RatZ2JGcJ3gmaVI/s1600/PSFiborialMix.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEis2LVGrMBpB5dEaY-yoZaElVcPOtx75vdUB6GrHoEVs1VabwJpRIBGmpNI9nfvtahYxElxwVHH1AAMisyjeFtkmbWkY5YGg0mHiz_-Glxpj5Fpwd40Vkc6JVKn7ut1RatZ2JGcJ3gmaVI/s1600/PSFiborialMix.PNG" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<b>Factorial using System.Int64, System.Double, System.Numerics.BigInteger</b><br />
<br />
The Factorial of numbers over 20 are massive!<br />
For instance: !40 = 815915283247897734345611269596115894272000000000!<br />
Because of this, the previous version of this program was giving the "wrong" result <br />
!40 = -70609262346240000 when using "long" (System.Int64) type, but it was not until I did the Fiborial version in VB.NET that I realized about this faulty code, because instead of giving me a wrong value, VB.NET, JScript.NET, Boo execution thrown an Overflow Exception when using the "Long/long" (System.Int64) type.<br />
<br />
My first idea was to use ulong and ULong, but both failed for "big" numbers. I then used Double (double floating point) type and got no more exception/wrong result. The result of the factorial was now correct !40 = 1.1962222086548E+56, but still I wanted to show the Integer value of it, so I did some research and found that there is a new System.Numerics.BigInteger class in the .NET Framework 4.0. Adding the reference to the project and using this new class as the return type of the Factorial methods, I was able to get the result I was expecting.<br />
!40 = 815915283247897734345611269596115894272000000000<br />
<br />
What I also found was that using different types change the time the algorithm takes to finish:<br />
System.Int64 < System.Double < System.Numerics.BigInteger <br />
Almost by double!<br />
<br />
To illustrate what I just said, lets have a look at the following code and the output we get. <br />
<br />
<pre class="php" name="code"></pre>
<br />
NOTE: you need to manually add a reference to the System.Numerics.dll assembly to your project so you can add it to your code.<br />
<br />
And the Output is:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnehOsMLbRhjbI3mJ4mkf9entrlPzYVG5ctQrsi3COZEQHfoMeFRGxMqqqBOpowy8SGrF51o4vB3o8yY7WGOwR7qVNyf_I2-1Ul8KIPvo9lZhakJ80wWm2Uh8tf_-ray0jmzx3fYGQnj0/s1600/PSFiborialMix.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnehOsMLbRhjbI3mJ4mkf9entrlPzYVG5ctQrsi3COZEQHfoMeFRGxMqqqBOpowy8SGrF51o4vB3o8yY7WGOwR7qVNyf_I2-1Ul8KIPvo9lZhakJ80wWm2Uh8tf_-ray0jmzx3fYGQnj0/s1600/PSFiborialMix.PNG" /></a><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnehOsMLbRhjbI3mJ4mkf9entrlPzYVG5ctQrsi3COZEQHfoMeFRGxMqqqBOpowy8SGrF51o4vB3o8yY7WGOwR7qVNyf_I2-1Ul8KIPvo9lZhakJ80wWm2Uh8tf_-ray0jmzx3fYGQnj0/s1600/PSFiborialMix.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><br /></a><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnehOsMLbRhjbI3mJ4mkf9entrlPzYVG5ctQrsi3COZEQHfoMeFRGxMqqqBOpowy8SGrF51o4vB3o8yY7WGOwR7qVNyf_I2-1Ul8KIPvo9lZhakJ80wWm2Uh8tf_-ray0jmzx3fYGQnj0/s1600/PSFiborialMix.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><br /></a><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnehOsMLbRhjbI3mJ4mkf9entrlPzYVG5ctQrsi3COZEQHfoMeFRGxMqqqBOpowy8SGrF51o4vB3o8yY7WGOwR7qVNyf_I2-1Ul8KIPvo9lZhakJ80wWm2Uh8tf_-ray0jmzx3fYGQnj0/s1600/PSFiborialMix.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><br /></a><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnehOsMLbRhjbI3mJ4mkf9entrlPzYVG5ctQrsi3COZEQHfoMeFRGxMqqqBOpowy8SGrF51o4vB3o8yY7WGOwR7qVNyf_I2-1Ul8KIPvo9lZhakJ80wWm2Uh8tf_-ray0jmzx3fYGQnj0/s1600/PSFiborialMix.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><br /></a><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnehOsMLbRhjbI3mJ4mkf9entrlPzYVG5ctQrsi3COZEQHfoMeFRGxMqqqBOpowy8SGrF51o4vB3o8yY7WGOwR7qVNyf_I2-1Ul8KIPvo9lZhakJ80wWm2Uh8tf_-ray0jmzx3fYGQnj0/s1600/PSFiborialMix.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><br /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-74357973711324411782015-11-17T09:26:00.000-08:002017-04-21T03:17:09.891-07:00PowerShell - Basics by Example<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a><script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>
<script src="//platform.linkedin.com/in.js" type="text/javascript"></script>
<script data-counter="right" type="IN/Share"></script>
<br />
<br />
To continue with the Basics by Example. today's version of the post written in <b>PowerShell</b> Enjoy!
<br />
<br />
You can copy and paste the code below in your favorite IDE/Editor, I use PowerShell ISE, and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.<br />
<br />
Beware that this is using the class keyword introduced on PowerShell version 5.0. If you're on Windows 10, you must have it already, otherwise you will need to download the <a href="https://www.microsoft.com/en-us/download/details.aspx?id=48729" target="_blank">Windows Management Framework 5.0 Production Preview</a> . You can check your current version using the following command:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgNEl1NBDC_hXZ3dD6vnZLgvIJuc80onbQarnSIRS-KN5bUlMDotkQ8wabVenLID8uWVpT4Zirx0PuSeUPZKkeLM8g8_jchFk1HY1isaIDJtEG3OtNEiBklvHbw_7FZhoEG9ZkJ-LvusU/s1600/ps+version.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="70" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgNEl1NBDC_hXZ3dD6vnZLgvIJuc80onbQarnSIRS-KN5bUlMDotkQ8wabVenLID8uWVpT4Zirx0PuSeUPZKkeLM8g8_jchFk1HY1isaIDJtEG3OtNEiBklvHbw_7FZhoEG9ZkJ-LvusU/s320/ps+version.PNG" width="320" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: <a href="http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html">http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html</a> <a href="http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html"></a><br />
<br />
<br />
<br />
<b>Greetings Program - Verbose</b><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<pre class="brush: powershell"># PowerShell Basics
# Greeting Class
class Greet {
# Fields and Auto-Properties (PowerShell doesn't differentiate between fields & properties)
[String] $message = ""
[String] $name = ""
[Int] $loopMessage = 0
# Set-Property method
[void] setMessage([String] $value) {
$this.message = $this.Capitalize($value)
}
[void] setName([String] $value) {
$this.name = $this.Capitalize($value)
}
# Constructor
Greet() {
$this.message = ""
$this.name = ""
$this.loopMessage = 1
}
# Overloaded Constructor
Greet([String] $message, [String] $name, [String] $loopMessage) {
$this.message = $message
$this.name = $name
$this.loopMessage = $loopMessage
}
# Method 1
[String] Capitalize([String] $val) {
if ($val.Length -eq 0) {
return ""
} else {
return (Get-Culture).TextInfo.ToTitleCase($val)
}
#Write-Host ("Hello {0}!`n" -f $this.name)
}
# Method 2
[void] Salute() {
# "for" statement (no need of ; if linebreak used)
for ($i = 0; $i -lt $this.loopMessage; $i++) {
Write-Host ("{0} {1}!" -f $this.message, $this.name)
}
}
# Overloaded Method 2.1
[void] Salute([String] $message, [String] $name, [String] $loopMessage) {
$i = 0
# "while" statement
while ($i -lt $loopMessage) {
Write-Host ("{0} {1}!" -f $this.Capitalize($message), $this.Capitalize($name))
$i++
}
}
# Overloaded Method 2.2
[void] Salute([String] $name) {
$dtNow = Get-Date
switch -regex ($dtNow.Hour) {
"^(10|11|[6-9])" {$this.message = "good morning,";break}
"^(1[2-7])" {$this.message = "good afternoon,";break}
"^(1[8-9]|2[0-2])" {$this.message = "good evening,";break}
"^(23|[0-5])" { $this.message = "good night,";break}
default {$this.message ="huh?"}
}
Write-Host ("{0} {1}!" -f $this.Capitalize($this.message), $this.Capitalize($name))
}
}
# Console Program
# Define object of type Greet and Instantiate. Call Constructor
$g = [Greet]::new()
# Call Set (Methods)Properties and Property (PS is case-insensitive)
$g.setMessage("hello")
$g.setName("world")
$g.LoopMessage = 5
# Call Method 2
$g.Salute()
# Call Overloaded Method 2.1 and Get Properties
$g.Salute($g.Message, "powershell", $g.LoopMessage)
# Call Overloaded Method 2.2
$g.Salute("carlos")
# Stop and Exit
Read-Host "Press any key to exit..."
</pre>
<br />
<b>Greetings Program - Minimal</b> <br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
And the Output is:<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgyGTmPsSPnKWPfuW4uemEfZQ63jCHCL33EijTH8zrGRiGKX-AHR0VPM1fBNW3K8rD2fScpGC8l7XZjpOPa8xNailTCV2KDfZMY6LgW7G1ihbmN0rkG8JKrXvIZluRjWH-4-aXlc1reFc/s1600/oobasics+ps1+output.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgyGTmPsSPnKWPfuW4uemEfZQ63jCHCL33EijTH8zrGRiGKX-AHR0VPM1fBNW3K8rD2fScpGC8l7XZjpOPa8xNailTCV2KDfZMY6LgW7G1ihbmN0rkG8JKrXvIZluRjWH-4-aXlc1reFc/s1600/oobasics+ps1+output.PNG" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIF_kbDI1-E3ygNvPTWp43TRRH3dNbRwZ4x-k2cG-Hhj5aokuc-C2yzz7ePKoXilDU-QVS9sdWuZs8LgQlG_CMyY_gUdKGvnrq2qlq_FUtvKWHShfEPbbjWydDEX2r1g9kZriDpaeyrk0/s1600/output_java.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"> </a><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIF_kbDI1-E3ygNvPTWp43TRRH3dNbRwZ4x-k2cG-Hhj5aokuc-C2yzz7ePKoXilDU-QVS9sdWuZs8LgQlG_CMyY_gUdKGvnrq2qlq_FUtvKWHShfEPbbjWydDEX2r1g9kZriDpaeyrk0/s1600/output_java.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"> </a><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIF_kbDI1-E3ygNvPTWp43TRRH3dNbRwZ4x-k2cG-Hhj5aokuc-C2yzz7ePKoXilDU-QVS9sdWuZs8LgQlG_CMyY_gUdKGvnrq2qlq_FUtvKWHShfEPbbjWydDEX2r1g9kZriDpaeyrk0/s1600/output_java.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"> </a></div>
<br />
<br />
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-72883551784738583152015-11-12T09:38:00.000-08:002017-04-21T03:20:08.943-07:00OO Hello World - PowerShell<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a><script src="http://platform.twitter.com/widgets.js" type="text/javascript">
</script>
<br />
<br />
The Hello World in PowerShell is finally here!<br />
<br />
"Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework." Its been around for ~8 years (2006), but it is until now, with the release of version 5.0, that they finally introduce classes as a built-in feature of the language.
<br />
<br />
Now that the language have classes, properties, methods, constructors, static members, inheritance and so, we can compare its syntax with all other languages on this blog.
<br />
<br />
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
By the way, you can see my previous post here: <a href="http://carlosqt.blogspot.com/2010/06/oo-hello-world.html" target="_blank">http://carlosqt.blogspot.com/2010/06/oo-hello-world.html</a> where I give some details on WHY these "OO Hello World series" samples.</div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<b><span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Version 1 (Minimal):</span></b><span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;"> </span></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">The minimum you need to type to get your program compiled and running.</span></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<b><span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;"><o:p></o:p></span></b></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
</div>
<pre class="brush: powershell">class Greet {
[String] $name;
Greet([String] $name) {
$this.name = ([String]$name[0]).ToUpper() + $name.Substring(1);
}
[void] Salute() {
Write-Host ("Hello {0}!`n" -f $this.name)
}
}
$g = [Greet]::new("World")
$g.Salute()
</pre>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<b><span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Version 2 (Verbose):</span></b></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Explicitly adding instructions and keywords that are optional to the compiler.</span></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
</div>
<pre class="brush: powershell">class Greet {
[String] $name;
Greet([String] $name) {
$this.name = ([String]$name[0]).ToUpper() + $name.Substring(1);
}
[void] Salute() {
Write-Host ("Hello {0}!`n" -f $this.name)
}
}
$g = [Greet]::new("World")
$g.Salute()
</pre>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<br />
<br />
Both version are completely similar.
<br />
<br />
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<b><span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">The Program Output:</span></b></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjIH5ljaabscAj9qaKHkeH9CQPLRERb0DqkuOXF60ZW5FUYqVrQSBPZ06K2G_R4cKwBeHmqHmTHqj4MloCRphvuZWFuA-XmYZ_URb39NJgZD5srXYe2KJszoCPiRW9RO3PRukiAwZihtM/s1600/oohellops1.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjIH5ljaabscAj9qaKHkeH9CQPLRERb0DqkuOXF60ZW5FUYqVrQSBPZ06K2G_R4cKwBeHmqHmTHqj4MloCRphvuZWFuA-XmYZ_URb39NJgZD5srXYe2KJszoCPiRW9RO3PRukiAwZihtM/s1600/oohellops1.PNG" /></a></div>
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNoSpacing">
<br />
<br />
<br />
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<b style="mso-bidi-font-weight: normal;"><u><span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">PowerShell Info:</span></u></b></div>
<div class="MsoNoSpacing">
“PowerShell is an automation platform and scripting language for Windows and Windows Server that allows you to simplify the management of your systems. Unlike other text-based shells, PowerShell harnesses the power of the .NET Framework, providing rich objects and a massive set of built-in functionality for taking control of your Windows environments. ” Taken from: <a href="https://msdn.microsoft.com/en-us/mt173057.aspx" target="_blank">https://msdn.microsoft.com/en-us/mt173057.aspx</a><br />
<br /></div>
<table border="1" cellpadding="0" cellspacing="0" class="MsoNormalTable" style="border-collapse: collapse; border: none; mso-border-alt: solid windowtext .5pt; mso-padding-alt: 0in 5.4pt 0in 5.4pt; mso-yfti-tbllook: 1184;"><tbody>
<tr style="mso-yfti-firstrow: yes; mso-yfti-irow: 0;"> <td style="border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Appeared:</span></div>
</td> <td style="border-left: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">2006</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 1;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Current Version:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">5.0</span><span style="font-family: "times new roman" , serif; font-size: 12pt;"> (<a href="http://carlosqt.blogspot.com/p/programming-languages.html">latest version in "Languages" page</a>) </span></div>
</td> </tr>
<tr style="mso-yfti-irow: 2;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Developed by:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Microsoft</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 3;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Creator:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Jeffrey Snover, Bruce Payette, James Truher</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 4;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Influenced by:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">C# and Perl, Tcl, Cmd</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 5;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Predecessor Language</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
~WSH (VBScript, JScript)</div>
</td> </tr>
<tr style="mso-yfti-irow: 6;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Predecessor Appeared</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
1998</div>
</td> </tr>
<tr style="mso-yfti-irow: 7;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Predecessor Creator</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: serif , serif; font-size: 16px;">Microsoft</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 8;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Runtime Target:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">CLR 4.x</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 9;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Latest Framework Target:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="font-family: "times new roman" , serif; font-size: 12pt;">CLR 4.x</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 10;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Mono Target:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="font-family: "times new roman" , serif; font-size: 12pt;">No</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 11;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Allows Unmanaged Code:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
</td> </tr>
<tr style="mso-yfti-irow: 12;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Source Code Extension:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">".ps1", "ps*"</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 13;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Keywords:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="font-family: "times new roman" , serif; font-size: 12pt;">35</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 14;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Case Sensitive:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">No</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 15;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Free Version Available:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Yes</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 16;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Open Source:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">No</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 17;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Standard:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">No</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 18;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Latest IDE Support:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNoSpacing">
PowerShell ISE</div>
<div class="MsoNoSpacing">
<a href="https://www.microsoft.com/en-us/download/details.aspx?id=48729" target="_blank">https://www.microsoft.com/en-us/download/details.aspx?id=48729</a></div>
<div class="MsoNoSpacing">
</div>
</td> </tr>
<tr style="mso-yfti-irow: 19;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Language Reference:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNoSpacing">
<a href="https://www.microsoft.com/en-us/download/details.aspx?id=36389" target="_blank">https://www.microsoft.com/en-us/download/details.aspx?id=36389</a></div>
</td> </tr>
<tr style="mso-yfti-irow: 20; mso-yfti-lastrow: yes;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">More Info:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNoSpacing">
<span style="font-family: "times new roman" , serif;"><a href="http://blogs.msdn.com/b/powershell/" target="_blank">http://blogs.msdn.com/b/powershell/</a></span><br />
<span style="font-family: "times new roman" , serif;"><a href="http://blogs.technet.com/b/heyscriptingguy/" target="_blank">http://blogs.technet.com/b/heyscriptingguy/</a></span><br />
<a href="https://github.com/PowerShell" target="_blank">https://github.com/PowerShell</a></div>
<div class="MsoNoSpacing">
</div>
</td> </tr>
</tbody></table>
<div class="MsoNormal" style="line-height: 19.2pt; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNormal">
<br /></div>
<div class="MsoNormal">
</div>
Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-64242934679445430322015-11-08T05:04:00.000-08:002015-11-08T05:04:26.300-08:00OO Hello World - Silver<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a><script src="http://platform.twitter.com/widgets.js" type="text/javascript">
</script>
<br />
<br />
Hi-yo Silver! Away!<br />
<br />
The Hello World in Silver is here! Silver is a free implementation of Apple's Swift programming language being actively developed by <a href="http://www.remobjects.com/about/" target="_blank">RemObjects</a>, the company behind the exceptional language Oxygene.<br />
<br />
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." <a href="http://www.elementscompiler.com/elements/silver" target="_blank">http://www.elementscompiler.com/elements/silver</a><br />
<br />
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
By the way, you can see my previous post here: <a href="http://carlosqt.blogspot.com/2010/06/oo-hello-world.html" target="_blank">http://carlosqt.blogspot.com/2010/06/oo-hello-world.html</a> where I give some details on WHY these "OO Hello World series" samples.</div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<b><span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Version 1 (Minimal):</span></b><span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;"> </span></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">The minimum you need to type to get your program compiled and running.</span></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<b><span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;"><o:p></o:p></span></b></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
</div>
<pre class="javascript" name="code">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()
</pre>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<b><span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Version 2 (Verbose):</span></b></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Explicitly adding instructions and keywords that are optional to the compiler.</span></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
</div>
<pre class="javascript" name="code">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()
</pre>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<b><span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">The Program Output:</span></b></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkFHQLMSd9czJmihROp20YNYpUI4hCUy2wo75-a_34TVjJ5scwW27iw4vYCXzexzpmFwclN_tr_-mqgGNAtAYhyphenhyphenDxlUM3ZwPRYm49jWyogF6sMfPjuo5ljhAyPZVwfi855eGalBpQi_QI/s1600/OOHelloWorldSilver.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkFHQLMSd9czJmihROp20YNYpUI4hCUy2wo75-a_34TVjJ5scwW27iw4vYCXzexzpmFwclN_tr_-mqgGNAtAYhyphenhyphenDxlUM3ZwPRYm49jWyogF6sMfPjuo5ljhAyPZVwfi855eGalBpQi_QI/s1600/OOHelloWorldSilver.PNG" /></a></div>
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNoSpacing">
<br />
<br />
<br />
<br /></div>
<div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<b style="mso-bidi-font-weight: normal;"><u><span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Swift (</span></u></b><b style="mso-bidi-font-weight: normal;"><u><span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Silver)</span></u></b><b style="mso-bidi-font-weight: normal;"><u><span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;"> Info:</span></u></b></div>
<div class="MsoNoSpacing">
“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: <a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11" target="_blank">https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11</a><br />
<br /></div>
<table border="1" cellpadding="0" cellspacing="0" class="MsoNormalTable" style="border-collapse: collapse; border: none; mso-border-alt: solid windowtext .5pt; mso-padding-alt: 0in 5.4pt 0in 5.4pt; mso-yfti-tbllook: 1184;"><tbody>
<tr style="mso-yfti-firstrow: yes; mso-yfti-irow: 0;"> <td style="border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Appeared:</span></div>
</td> <td style="border-left: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">2014</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 1;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Current Version:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Silver 8.2 beta, Swift 2.1</span><span style="font-family: "times new roman" , serif; font-size: 12pt;"> (<a href="http://carlosqt.blogspot.com/p/programming-languages.html">latest version in "Languages" page</a>) </span></div>
</td> </tr>
<tr style="mso-yfti-irow: 2;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Developed by:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Silver by RemObjects, Swift by Apple Inc.</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 3;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Creator:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Silver by RemObjects, Swift by Chris Lattner and Apple Inc.</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 4;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Influenced by:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, D </span></div>
</td> </tr>
<tr style="mso-yfti-irow: 5;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Predecessor Language</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
</td> </tr>
<tr style="mso-yfti-irow: 6;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Predecessor Appeared</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
</td> </tr>
<tr style="mso-yfti-irow: 7;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Predecessor Creator</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
</td> </tr>
<tr style="mso-yfti-irow: 8;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Runtime Target:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">CLR and JVM</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 9;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Latest Framework Target:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="font-family: "times new roman" , serif; font-size: 12pt;">CLR 4.x JDK 8</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 10;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Mono Target:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="font-family: "times new roman" , serif; font-size: 12pt;">No</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 11;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Allows Unmanaged Code:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Yes</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 12;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Source Code Extension:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">“.swift”</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 13;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Keywords:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="font-family: "times new roman" , serif; font-size: 12pt;">Silver 89, Swift 80</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 14;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Case Sensitive:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Yes</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 15;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Free Version Available:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Yes</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 16;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Open Source:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Swift Yes, Silver No.</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 17;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Standard:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">No</span></div>
</td> </tr>
<tr style="mso-yfti-irow: 18;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Latest IDE Support:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNoSpacing">
Visual Studio 2013</div>
<div class="MsoNoSpacing">
<a href="http://www.elementscompiler.com/elements/download.aspx" target="_blank">http://www.elementscompiler.com/elements/download.aspx</a></div>
<div class="MsoNoSpacing">
</div>
</td> </tr>
<tr style="mso-yfti-irow: 19;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">Language Reference:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNoSpacing">
<a href="http://docs.elementscompiler.com/Silver/" target="_blank">http://docs.elementscompiler.com/Silver/</a><br />
<span style="font-family: "times new roman" , serif;"><a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11" target="_blank">https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11</a></span></div>
</td> </tr>
<tr style="mso-yfti-irow: 20; mso-yfti-lastrow: yes;"> <td style="border-top: none; border: solid windowtext 1.0pt; mso-border-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 170.6pt;" valign="top" width="227"><div class="MsoNormal" style="line-height: normal; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<span style="color: #333333; font-family: "" , serif , "" , serif; font-size: 12pt;">More Info:</span></div>
</td> <td style="border-bottom: solid windowtext 1.0pt; border-left: none; border-right: solid windowtext 1.0pt; border-top: none; mso-border-alt: solid windowtext .5pt; mso-border-left-alt: solid windowtext .5pt; mso-border-top-alt: solid windowtext .5pt; padding: 0in 5.4pt 0in 5.4pt; width: 351.0pt;" valign="top" width="468"><div class="MsoNoSpacing">
<span style="font-family: "times new roman" , serif;"><a href="https://en.wikipedia.org/wiki/Swift_(programming_language)" target="_blank">https://en.wikipedia.org/wiki/Swift_(programming_language)</a></span></div>
<div class="MsoNoSpacing">
<span style="font-family: "times new roman" , serif;"><a href="http://www.elementscompiler.com/elements/silver/" target="_blank">http://www.elementscompiler.com/elements/silver/</a></span><br />
<a href="http://swiftlang.eu/" target="_blank">http://swiftlang.eu</a></div>
</td> </tr>
</tbody></table>
<div class="MsoNormal" style="line-height: 19.2pt; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto;">
<br /></div>
<div class="MsoNormal">
<br /></div>
<div class="MsoNormal">
</div>
Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-19025748767606699602015-11-05T02:17:00.000-08:002015-11-06T05:24:42.699-08:00Arrays and Indexers in Ceylon<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
Ceylon 1.2 was finally released, you can see the announcement and the new stuff included on the new release here: <a href="http://www.ceylon-lang.org/blog/2015/10/29/ceylon-1-2-0/" target="_blank">http://www.ceylon-lang.org/blog/2015/10/29/ceylon-1-2-0/</a>. 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.<br />
<br />
Ceylon does not have primitives, nor arrays, but you have sequences (read only arrays), generics Array<type> and Java's interop arrays. In this post i used Array<type> instead of CharArray, IntArray and ObjectType<string> interop arrays.</string></type></type><br />
<br />
For the Java interop arrays, you can get some documentation in these 2 pages:<br />
<a href="http://ceylon-lang.org/documentation/1.0/reference/interoperability/java-from-ceylon/#java_array_types_milestone_5" target="_blank">http://ceylon-lang.org/documentation/1.0/reference/interoperability/java-from-ceylon/#java_array_types_milestone_5</a><br />
<a href="http://ceylon-lang.org/documentation/1.0/reference/interoperability/type-mapping/" target="_blank">http://ceylon-lang.org/documentation/1.0/reference/interoperability/type-mapping/</a><br />
<br />
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:<br />
<a href="http://www.ceylon-lang.org/documentation/1.2/tour/sequences/" target="_blank">http://www.ceylon-lang.org/documentation/1.2/tour/sequences/</a><br />
<br />
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.<br />
<br />
By the way, if you missed my (not so) recent post (anymore), "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="scala" name="code">//module.ceylon
native("jvm") module com.carlosqt.hello "1.0.0" {
import java.base "8";
import ceylon.interop.java "1.2.0";
}
</pre>
<br />
<br />
<pre class="scala" name="code">//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];
}
</pre>
<br />
<br />
The output:
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_XmUu05xjf_jlxiCXf75phCJH5VHSJg4b3mZOJNlIVFqCYX0sUi9_t9Vn-NeWmxw5O6H_2qjtdiCQQRMnLrmOkDI_Z3IDjzDsaGEZaTpgNcpC5u9F2jorU9DWaRi1iJVT-Qs_7gYK9Wc/s1600/ceylon+arrays.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_XmUu05xjf_jlxiCXf75phCJH5VHSJg4b3mZOJNlIVFqCYX0sUi9_t9Vn-NeWmxw5O6H_2qjtdiCQQRMnLrmOkDI_Z3IDjzDsaGEZaTpgNcpC5u9F2jorU9DWaRi1iJVT-Qs_7gYK9Wc/s1600/ceylon+arrays.png" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days (or months haha).
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-2297731062131826392014-12-23T01:11:00.002-08:002014-12-23T01:11:37.225-08:00Arrays and Indexers in Kotlin<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
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.<br />
<br />
By the way, if you missed my (not so) recent post (anymore), "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="scala" name="code">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
}
}
</pre>
<br />
<br />
The output:
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicEmTmfVX1QrocR8yTgNFvN2ZV3ooBpnAO0WZ7WrrYbIw-L2Jt41E3jCYU6P97y16CNQ-UxjhyHPYzty1ZkS3OPTR-zA5o7E1pL5H_btzZ-RT8S7ZhLMkCP6Yp5Ueq-cXqBrV0PfLSvsE/s1600/KotlinArrays.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicEmTmfVX1QrocR8yTgNFvN2ZV3ooBpnAO0WZ7WrrYbIw-L2Jt41E3jCYU6P97y16CNQ-UxjhyHPYzty1ZkS3OPTR-zA5o7E1pL5H_btzZ-RT8S7ZhLMkCP6Yp5Ueq-cXqBrV0PfLSvsE/s1600/KotlinArrays.png" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-64494992552913225132014-12-22T03:20:00.000-08:002014-12-22T03:20:00.233-08:00Arrays and Indexers in Scala<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
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.<br />
<br />
By the way, if you missed my (not so) recent post (anymore), "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="scala" name="code">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)
}
</pre>
<br />
<br />
The output:
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi6GRvTvLivt8ncurODyU-5_cPUNa9r7-g9kWfe6z38i3l4Ri0Qw87iKv1ZBN_TZApIIpSFm4VV8r2lJTIy56L-oLUA7yzgwx_fy30R8a8eJhhpYIVzV1P5O_X1Ry5FuT1_VoZVn_-8mXw/s1600/ScalaArrays.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi6GRvTvLivt8ncurODyU-5_cPUNa9r7-g9kWfe6z38i3l4Ri0Qw87iKv1ZBN_TZApIIpSFm4VV8r2lJTIy56L-oLUA7yzgwx_fy30R8a8eJhhpYIVzV1P5O_X1Ry5FuT1_VoZVn_-8mXw/s1600/ScalaArrays.png" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-64961502923069022014-12-07T15:05:00.001-08:002014-12-22T03:26:25.872-08:00Arrays and Indexers in Xtend<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
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.<br />
<br />
By the way, if you missed my (not so) recent post (anymore), "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
"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
<br />
<pre class="java" name="code">// 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();
}
}
</pre>
<br />
"@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
<br />
<pre class="java" name="code">// 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
}
}
</pre>
<br />
<br />
The output:
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhciSmiXrKJIJX9Td4vHzvi6UIBZuuLnS68D4fWAEemRSSpPcMkvG4Qz1LUELfry0L5NbwCr9U-Bekm3_qAITILoRYEZO7ew2Rn7qEw7viV4WuwFEjUiOWpO8rjJwx0Z7szhzTxTT1PeJg/s1600/XtendArrays.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhciSmiXrKJIJX9Td4vHzvi6UIBZuuLnS68D4fWAEemRSSpPcMkvG4Qz1LUELfry0L5NbwCr9U-Bekm3_qAITILoRYEZO7ew2Rn7qEw7viV4WuwFEjUiOWpO8rjJwx0Z7szhzTxTT1PeJg/s1600/XtendArrays.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com3tag:blogger.com,1999:blog-694679611587040520.post-63393970290747635952014-12-05T08:58:00.000-08:002014-12-05T08:58:03.251-08:00Arrays and Indexers in Fantom<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
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.<br />
<br />
By the way, if you missed my (not so) recent post (anymore), "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="javascript" name="code">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)
}
}
</pre>
<br />
<br />
The output:
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8CWUblX8vglnvvhlftzfZVM7nLxWIci-KO8orYZ_CUUeSIzgTnBqSnzF1UH1mzwA9Z-i9J5ellTHAekHykwWNsNXmYGRHyL61XNaoUSY0jOuVnZVwhneD8QoKCJhK2751vYYtnFFRLx0/s1600/FantomArrays.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8CWUblX8vglnvvhlftzfZVM7nLxWIci-KO8orYZ_CUUeSIzgTnBqSnzF1UH1mzwA9Z-i9J5ellTHAekHykwWNsNXmYGRHyL61XNaoUSY0jOuVnZVwhneD8QoKCJhK2751vYYtnFFRLx0/s1600/FantomArrays.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-56030275414233403672014-12-04T00:42:00.002-08:002014-12-04T00:42:46.647-08:00Arrays and Indexers in Gosu<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
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.<br />
<br />
By the way, if you missed my (not so) recent post (anymore), "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="javascript" name="code">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()
}
}
</pre>
<br />
<br />
The output:
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvfbl8lAnPAhv6dTw5oOW-KOStdY_lMkOTXDxpMWE3Ple9Ap2RysBYUQnBs0eAOMwxUSVFaAOQc8-L4_scsovL_zBQ0HRzNf9BETmFHurZxGdniZciP4tLfJibzanNW8YKCxUSy7jYqSk/s1600/GosuArrays.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvfbl8lAnPAhv6dTw5oOW-KOStdY_lMkOTXDxpMWE3Ple9Ap2RysBYUQnBs0eAOMwxUSVFaAOQc8-L4_scsovL_zBQ0HRzNf9BETmFHurZxGdniZciP4tLfJibzanNW8YKCxUSy7jYqSk/s1600/GosuArrays.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-82957820850385934802014-12-02T04:59:00.001-08:002014-12-22T05:34:39.990-08:00Arrays and Indexers in Groovy<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
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.<br />
<br />
By the way, if you missed my (not so) recent post (anymore), "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="groovy" name="code">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[]
}
}
</pre>
<br />
<br />
The output:
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjAYw3uIXPVbDzSvdDKaTZjs_WLavI63O4Ju9j1rFUtGDDwqb5I8jHeEgQ04Tp2uGg5p3Ch58Y9SgTf67fQ6bxLsYwRPEFoHj4bFTBRs77BKPkD1S0Wmgii7CxcvM9Zg42v3qNOtf4b6zU/s1600/GroovyArrays.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjAYw3uIXPVbDzSvdDKaTZjs_WLavI63O4Ju9j1rFUtGDDwqb5I8jHeEgQ04Tp2uGg5p3Ch58Y9SgTf67fQ6bxLsYwRPEFoHj4bFTBRs77BKPkD1S0Wmgii7CxcvM9Zg42v3qNOtf4b6zU/s1600/GroovyArrays.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-76953825443787832652014-11-30T12:58:00.001-08:002014-11-30T12:58:06.717-08:00Arrays and Indexers in Java<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
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.<br />
<br />
By the way, if you missed my (not so) recent post (anymore), "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="java" name="code">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;
}
}
</pre>
<br />
<br />
The output:
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiH9eeCUtErUdLOAAswqNhGE5ejwB4zXO-D9YYbJvZZEvmNMguvJ9N_O6jl6RYySnI7I_Sqi1foFPCnrgfIUaovBjBtWH8vu36AE0VGRGf8iEHGodcDX0hV0Lt9xnxXIUZwX-jqcqgNTWU/s1600/JavaArrays.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiH9eeCUtErUdLOAAswqNhGE5ejwB4zXO-D9YYbJvZZEvmNMguvJ9N_O6jl6RYySnI7I_Sqi1foFPCnrgfIUaovBjBtWH8vu36AE0VGRGf8iEHGodcDX0hV0Lt9xnxXIUZwX-jqcqgNTWU/s1600/JavaArrays.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-51394097737305076232014-07-24T03:43:00.000-07:002017-04-21T06:40:00.006-07:00Arrays and Indexers in Jython<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
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.<br />
<br />
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.
<br />
By the way, if you missed my most recent post, "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="brush: python">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()
</pre>
<br />
The output:<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhrPdyB7U9TrGO6G4IHpqYfBKMFNnmy8LdHWtCy_vz5al8ewDK727_paCRJChcRpM9MfhNCk1sXBo73xmZXR9GfEOdfltXzRQ2j8kWQpsm7nRfkL9pkAW4bxp0TwcSHmwNeJ2G19mbM94/s1600/JyArraysOutput.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhrPdyB7U9TrGO6G4IHpqYfBKMFNnmy8LdHWtCy_vz5al8ewDK727_paCRJChcRpM9MfhNCk1sXBo73xmZXR9GfEOdfltXzRQ2j8kWQpsm7nRfkL9pkAW4bxp0TwcSHmwNeJ2G19mbM94/s1600/JyArraysOutput.png"></a></div>
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<!------><!------><br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-65788781339496952642014-05-06T14:58:00.000-07:002017-04-21T06:47:47.899-07:00Arrays and Indexers in JRuby<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
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.<br />
<br />
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 (<a href="http://plugins.netbeans.org/plugin/38549/?show=true">http://plugins.netbeans.org/plugin/38549/?show=true</a>) helped me decide what to publish next. <br />
<br />
By the way, if you missed my most recent post, "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="brush: ruby">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
</pre>
<br />
<br />
The output:
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi0rmAvCDg_flZDt_7J7baLYscL-voB9hf3cfms3U6xwVRyu17rq4CxnPjJ-FVosJRYJxudpg_vRXMpGhczfpNc2X2TuL5QAcNGSC4Sjl7Hreie-dloO0CiUKvkw2XiJFdT5sQhC2lh0yQ/s1600/JRbArraysOutput.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi0rmAvCDg_flZDt_7J7baLYscL-voB9hf3cfms3U6xwVRyu17rq4CxnPjJ-FVosJRYJxudpg_vRXMpGhczfpNc2X2TuL5QAcNGSC4Sjl7Hreie-dloO0CiUKvkw2XiJFdT5sQhC2lh0yQ/s1600/JRbArraysOutput.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-55941654163286366012014-03-06T09:37:00.005-08:002014-03-06T09:37:58.829-08:00Arrays and Indexers in F#<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
Today's post is about Arrays and Indexers in F#. 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 F#, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.<br />
<br />
By the way, if you missed my most recent post, "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
WARNING! I know that F# is intended to be use in a Functional way, however, my goal is to show its Imperative and OO language features, so it can be compared with other OO languages. Said that, if you know how to do something on the examples below on a Functional way, you are welcome to add them as a comment :)<br />
<br />
<br />
<pre class="csharp" name="code">open System
open System.Text
module FsArrays =
type Alphabet public (size: int) as this = class
// Array Field
[<DefaultValue>]
val mutable private letters: char array
do this.letters <- Array.create size ' '
// Indexer Get/Set Property
member public this.Item
with get(index) =
this.letters.[index]
and set index value =
this.letters.[index] <- value.ToString().ToUpper().[0]
// Read-only Property
member public this.Length
with get() = this.letters.Length
// Constructors
new() = new Alphabet(0)
new(l: string) as this = new Alphabet(l.Length) then
this.letters <- l.ToUpper().ToCharArray()
new(l: char[]) as this = new Alphabet(0) then
this.letters <- l
// Overridden Method
override this.ToString() =
String.Join(",", [|for c in this.letters -> c.ToString()|])
// Method
member public this.Slice(start: int, length: int): char[] =
this.letters.[start .. start + length - 1]
end
let ReverseChar (arr: char array) : char array =
Array.rev arr
let BubbleSortInt (arr: int array) =
let mutable swap = 0
for i in Array.rev(arr) do
for j in 0 .. arr.Length - 2 do
if arr.[j] > arr.[j + 1] then
swap <- arr.[j]
arr.[j] <- arr.[j + 1]
arr.[j + 1] <- swap
arr
let BubbleSortString (arr: string array) =
let mutable swap = ""
for i in Array.rev(arr) do
for j in 0 .. arr.Length - 2 do
if arr.[j].[0] > arr.[j + 1].[0] then
swap <- arr.[j]
arr.[j] <- arr.[j + 1]
arr.[j + 1] <- swap
arr
let TransposeMatrix(m: int[,]): int[,] =
(* Transposing a Matrix 2,3
*
* A = [6 4 24]T [ 6 1]
* [1 -9 8] [ 4 -9]
* [24 8]
*)
let transposed = Array2D.zeroCreate<int> (m.GetLength 1) (m.GetLength 0)
for i in 0 .. m.GetLength 0 - 1 do
for j in 0 .. m.GetLength 1 - 1 do
transposed.[j, i] <- m.[i, j]
transposed;
let UpperCaseRandomArray (arr: string[][]) =
let r = new System.Random()
let i = r.Next (arr.Length - 1)
for j in 0 .. arr.[i].Length - 1 do
arr.[i].[j] <- arr.[i].[j].ToUpper()
let PrintArrayChar (arr: char array) =
printfn "\nPrint Array Content %s"
(arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"))
for i in 0 .. arr.Length - 1 do
printfn " array [%2i] = %2c" i arr.[i]
let PrintArrayInt (arr: int array) =
printfn "\nPrint Array Content %s"
(arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"))
for i in 0 .. arr.Length - 1 do
printfn " array [%2i] = %2i" i arr.[i]
let PrintArrayString (arr: string array) =
printfn "\nPrint Array Content %s"
(arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"))
for i in 0 .. arr.Length - 1 do
printfn " array [%2i] = %2s" i arr.[i]
let PrintMatrix (m: int[,]) =
printfn "\nPrint Matrix Content %s[%i,%i]"
(m.GetType().Name.Replace("[,]", "")) (m.GetLength 0) (m.GetLength 1)
for i in 0 .. m.GetLength 0 - 1 do
for j in 0 .. m.GetLength 1 - 1 do
printfn " array [%2i,%2i] = %2i " i j m.[i, j]
let GraphJaggedArray (arr: string[][]) =
(* When using Arrays, we can use foreach instead of for + index:
*
* for i in 0 .. m.GetLength 0 - 1 do
* for j in 0 .. m.GetLength 1 - 1 do
*
*)
printfn "\nPrint Matrix Content %s" (arr.GetType().Name)
let mutable lineCount = 1
for s in arr do
printf "Line%2i|" lineCount
for w in s do
printf "%3c" '*'
printfn " (%i)" (s.Length)
lineCount <- lineCount + 1
let PrintJaggedArray (arr: string[][]) =
printfn "\nPrint Jagged Array Content %s" (arr.GetType().Name)
for i in 0 .. arr.Length - 1 do
let line = new StringBuilder()
for j in 0 .. arr.[i].Length - 1 do
line.Append (" " + arr.[i].[j]) |> ignore
if line.ToString() = line.ToString().ToUpper() then
line.Append " <-- [UPPERCASED]" |> ignore
printfn "%s" (line.ToString())
let PrintTitle (message: string) =
printfn "\n"
printfn "%s" ([|for i in 0..54 -> "*"|] |> String.concat "")
printfn "%s" message
printfn "%s" ([|for i in 0..54 -> "*"|] |> String.concat "")
let PrintCommonArrayExceptions (arr: string[][]) =
try
arr.[100].[100] <- "hola"
with
(*
| :? IndexOutOfRangeException as ex ->
| _ as ex ->
*)
| ex ->
printfn "\nException: \n%s\n%s" (ex.GetType().Name) (ex.Message)
[<EntryPoint>]
let main argv =
// Single-dimensional Array(s)
PrintTitle "Reverse Array Elements"
// Declare and Initialize Array of Chars
let letters: char array = Array.create 5 ' '
letters.[0] <- 'A'
letters.[1] <- 'E'
letters.[2] <- 'I'
letters.[3] <- 'O'
letters.[4] <- 'U'
PrintArrayChar letters
let inverse_letters = ReverseChar letters
PrintArrayChar inverse_letters
PrintTitle "Sort Integer Array Elements"
// Declare and Initialize Array of Integers
let numbers = [| 10; 8; 3; 1; 5 |]
PrintArrayInt numbers
let ordered_numbers = BubbleSortInt numbers
PrintArrayInt ordered_numbers
PrintTitle "Sort String Array Elements"
// Declare and Initialize and Array of Strings
let names : string array = [|"Damian";
"Rogelio";
"Carlos";
"Luis";
"Daniel"|]
PrintArrayString names
let ordered_names = BubbleSortString names
PrintArrayString ordered_names
// Multi-dimensional Array (Matrix row,column)
PrintTitle "Transpose Matrix"
// let matrix = Array2D.zeroCreate<int> 2 3
let matrix = array2D [|[|6; 4; 24|];
[|1; -9; 8|]|]
PrintMatrix matrix
let 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:
*
* let text: string[][] = [|
* [| "word1"; "word2"; "wordN" |];
* [| "word1"; "word2"; "wordM" |];
* ...
* |]
*
* Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"
*
*)
let mutable 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"
let vowels = new Alphabet(5)
vowels.[0] <- 'a'
vowels.[1] <- 'e'
vowels.[2] <- 'i'
vowels.[3] <- 'o'
vowels.[4] <- 'u'
printfn "\nVowels = {%s}" (String.Join(",", [|vowels.[0].ToString(); vowels.[1].ToString(); vowels.[2].ToString(); vowels.[3].ToString(); vowels.[4].ToString()|]))
let en = new Alphabet("abcdefghijklmnopqrstuvwxyz")
printfn "English Alphabet = {%s}" (en.ToString())
let x = new Alphabet(en.Slice(9, 10))
printfn "Alphabet Extract en[9..19] = {%s}" (x.ToString())
let word1 = String.Join("", [|en.[6].ToString(); en.[14].ToString(); en.[14].ToString(); en.[3].ToString()|])
let word2 = String.Join("", [|en.[1].ToString(); en.[24].ToString(); en.[4].ToString()|])
let word3 = String.Join("", [|en.[4].ToString(); en.[21].ToString(); en.[4].ToString(); en.[17].ToString(); en.[24].ToString(); en.[14].ToString(); en.[13].ToString(); en.[4].ToString()|])
printfn "\n%s %s, %s!\n" word1 word2 word3
Console.Read() |> ignore
0 // Return
</pre>
<br />
<br />
The output:
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9TGCpP8ybDpwnlDGFn37miiHkCFghx8DgthSqsZlfudtH6YE9b-EH6D5RrJLH2mZhytQtNxplN3dZBxXTR-ireBW3QSEOMjeTUNS2dLpLX1sI_6FVYU3CFCk55SP5kTGWB0RAQbhvC_k/s1600/FsArraysOutput.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9TGCpP8ybDpwnlDGFn37miiHkCFghx8DgthSqsZlfudtH6YE9b-EH6D5RrJLH2mZhytQtNxplN3dZBxXTR-ireBW3QSEOMjeTUNS2dLpLX1sI_6FVYU3CFCk55SP5kTGWB0RAQbhvC_k/s1600/FsArraysOutput.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-18346773213008488392014-02-27T14:17:00.001-08:002017-04-21T06:54:19.756-07:00Arrays and Indexers in IronRuby<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
Today's post is about Arrays and Indexers in IronRuby. 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 IronRuby, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.<br />
<br />
This is the last of the .NET dynamic languages. I'm considering to stop writing about it because the project seems to be dead with no updates since 13/03/11)... will see, probably this will be the last post about it if no news, fortunately, there is still JRuby. <br />
<br />
By the way, if you missed my most recent post, "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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 JRuby, later on, just to compare. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="brush: ruby">require "mscorlib"
include System
# 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 = System::Random.new
i = r.next(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.GetType().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.GetType().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.GetType().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.GetType().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.GetType().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
</pre>
<br />
<br />
The output:
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoO8U1KfZt37DLzhP5V_QG7UbX2zg82KBC4UnjDwQtBQYDf1kdDxQgrfZCiQ-e1q9jW0yjCSJNhngg1sdE6gtHug_ts-QpKW7_kMYYKuNktnptz17knhyphenhyphenc67hugheEhlub9Mqo8ZdVWtY/s1600/RbArraysOutput.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoO8U1KfZt37DLzhP5V_QG7UbX2zg82KBC4UnjDwQtBQYDf1kdDxQgrfZCiQ-e1q9jW0yjCSJNhngg1sdE6gtHug_ts-QpKW7_kMYYKuNktnptz17knhyphenhyphenc67hugheEhlub9Mqo8ZdVWtY/s1600/RbArraysOutput.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-78973775844781678232014-02-25T13:18:00.001-08:002017-04-21T06:40:19.667-07:00Arrays and Indexers in IronPython<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
Today's post is about Arrays and Indexers in IronPython. 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 IronPython, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.<br />
<br />
This is the second post of a dynamic language. As with Phalanger'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 .NET's System.Array, which can definitely be used in IronPython, specially when you need to inter operate with other CLS languages. You can even initialize a System.Array with a Python List like this: System.Array[int]([1, 2, 3]).<br />
<br />
By the way, if you missed my most recent post, "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="brush: python">import clr
clr.AddReference("System")
import System
from System 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)
# 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.Next(len(arr))
for j in range(len(arr[i])):
arr[i][j] = arr[i][j].upper()
def printarray(arr):
print '\nPrint Array Content ' + arr.GetType().Name.Replace(']', 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 ' + m.GetType().Name + '[' + 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 ' + arr.GetType().Name
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 ' + arr.GetType().Name
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:
arr[100][100] = 'hola'
except System.Exception as ex:
print '\nException: \n%s\n%s' % (ex.GetType().Name, ex.Message)
#except:
#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()
</pre>
<br />
<br />
The output:
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKIJ09Zh2ksMXfFzGIocsqOyHsl_tLx5U3dx1H91__mCINfoPahJdhsezkGgr5gjSBa5QpwFjQ8szzxo5ztiVaaF5yYrwPMvvjf2kJZj_13a3fg4K4ShOJ-cDoNXmve_hLpM9p4vYulFU/s1600/PyArraysOutput.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKIJ09Zh2ksMXfFzGIocsqOyHsl_tLx5U3dx1H91__mCINfoPahJdhsezkGgr5gjSBa5QpwFjQ8szzxo5ztiVaaF5yYrwPMvvjf2kJZj_13a3fg4K4ShOJ-cDoNXmve_hLpM9p4vYulFU/s1600/PyArraysOutput.png"></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-33293183105602969762014-02-22T16:52:00.001-08:002014-02-22T16:54:51.061-08:00Arrays and Indexers in Zonnon<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
Today's post is about Arrays and Indexers in Zonnon. 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 Zonnon, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.<br />
<br />
By the way, if you missed my most recent post, "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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 Oxygene just to compare. <br />
<br />
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 Zonnon Builder and run it. <br />
<br />
Last thing. 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.<br />
<br />
<pre class="delphi" name="code">
(*****************************************
String Utilities Module
*****************************************)
module Str;
type {private} MArrayOfChar = array {math} * of char;
type {private} ArrayOfChar = array * of char;
type {private} ArrayOfString = array * of string;
procedure {public} CountWords(s: array * of char; sep: char): integer;
var i,slen,wlen,c: integer;
begin
slen := len(s)-1;
c := 0;
for i := 0 to slen do
wlen := 0;
while (i < slen) & (s[i] # sep) do inc(wlen); inc(i); end;
if (i <= slen) & (wlen > 0) then inc(c) end;
end;
return c;
end CountWords;
procedure {public} Split(s: string; sep: char)
: array * of string;
var i,j,k,slen,wlen,pos: integer;
l: array * of char;
a: array * of string;
begin
l := new ArrayOfChar(len(s)+1);
copy(s, l);
slen := len(l)-1;
a := new ArrayOfString(CountWords(l,sep));
pos := 0; k := 0;
for i := 0 to slen do
wlen := 0;
while (i < slen) & (l[i] # sep) do inc(wlen); inc(i); end;
if (i <= slen) & (wlen > 0) then
if (i <= slen) then a[k] := s.Substring(pos,wlen); inc(k) end;
for j := 0 to wlen do inc(pos) end;
end;
end;
return a;
end Split;
procedure {public} Join(c: char; arr: array {math} * of char): string;
var i: integer;
s: string;
begin
s := "";
for i := 0 to len(arr) - 1 do
s := s + string(arr[i]) + string(c);
end;
if len(s) == 0 then return s end;
return s.Substring(0,s.LastIndexOf(c));
end Join;
end Str.
(*****************************************
Alphabet Object
*****************************************)
object {ref} Alphabet(asize: integer; astr: string; achar: array * of char)
implements [];
import Str;
type {private} ArrayOfChar = array * of char;
type {private} ArrayOfString = array * of string;
(* Array Field *)
var {private} letters: array {math} * of char;
(* Indexer Get/Set Property *)
procedure {public} Get(i: integer): char implements [].Get;
begin
return self.letters[i];
end Get;
procedure {public} Set(i: integer; c: char) implements [].Set;
var s: string;
begin
s := string(c);
if ~(s = s.ToUpper()) then s := s.ToUpper(); c := s[0] end;
self.letters[i] := c;
end Set;
(* No Property, Getter instead *)
procedure {public} GetLength: integer;
begin
return len(self.letters);
end GetLength;
(* Override Method *)
procedure {public} ToString: string implements System.Object.ToString;
begin
return Str.Join(char(','), self.letters);
end ToString;
(* Method *)
procedure {public} Slice(start: integer; length: integer)
: array * of char;
var l: integer;
a: array * of char;
begin
a := new ArrayOfChar(len(self.letters));
a := self.letters[start..length-1];
return a;
end Slice;
(* No Overloaded Constructors Support in v 1.3.0 *)
(* Contructor | Initializer *)
begin
if asize # 0 then
self.letters := new ArrayOfChar(asize);
elsif astr # nil then
self.letters := new ArrayOfChar(len(astr));
copy(astr.ToUpper(),self.letters);
elsif achar # nil then
self.letters := achar;
else
self.letters := new ArrayOfChar(0);
end;
end Alphabet.
(*****************************************
Program Module
*****************************************)
module Main;
import System.Random as Random,
Str, Alphabet;
type {private} ArrayOfChar = array * of char;
type {private} ArrayOfString = array * of string;
type {private} ArrayMatrix = array {math} *,* of integer;
type {private} JaggedArrayOfString = array * of array * of string;
procedure ReverseChar(var arr: array * of char)
: array * of char;
var
reversed: array * of char;
i,j: integer;
begin
i := 0;
reversed := new ArrayOfChar(len(arr));
for j := len(arr,0)-1 to 0 by -1 do
reversed[i] := arr[j];
inc(i);
end;
return reversed;
end ReverseChar;
procedure BubbleSortInt(var arr: array {math} * of integer)
: array {math} * of integer;
var i, j, swap: integer;
begin
swap := 0;
for i := len(arr) - 1 to 1 by -1 do
for j := 0 to i - 1 do
if arr[j] > arr[j + 1] then
swap := arr[j];
arr[j] := arr[j + 1];
arr[j + 1] := swap;
end;
end;
end;
return arr;
end BubbleSortInt;
procedure BubbleSortString(var arr: array * of string)
: array * of string;
var
i, j: integer;
swap: string;
begin
swap := "";
for i := len(arr) - 1 to 1 by -1 do
for j := 0 to i - 1 do
if arr[j,0] > arr[j + 1,0] then
swap := arr[j];
arr[j] := arr[j + 1];
arr[j + 1] := swap;
end;
end;
end;
return arr;
end BubbleSortString;
procedure TransposeMatrix(m: array {math} *,* of integer)
: array {math} *,* of integer;
var
i, j: integer;
transposed: array {math} *,* of integer;
begin
(* Transposing a Matrix 2,3
*
* A = [6 4 24]T [ 6 1]
* [1 -9 8] [ 4 -9]
* [24 8]
*)
transposed := new ArrayMatrix(len(m, 1), len(m, 0));
for i := 0 to len(m,0) - 1 do
for j := 0 to len(m,1) - 1 do
transposed[j, i] := m[i, j];
end;
end;
return transposed;
end TransposeMatrix;
procedure UpperCaseRandomArray(arr: array * of array * of string);
var r: Random;
i,j: integer;
s: string;
begin
r := new Random;
i := r.Next(0, len(arr) - 1);
for j := 0 to len(arr[i]) - 1 do
s := arr[i,j];
arr[i,j] := s.ToUpper();
end;
end UpperCaseRandomArray;
procedure PrintArrayChar(var arr: array * of char);
begin
writeln("Print Array Content Char[":0,string(len(arr)):0,"]":0);
for i := 0 to len(arr, 0) - 1 do
writeln(" array [",i:2,"] = ",arr[i]:2," ");
end;
writeln;
end PrintArrayChar;
procedure PrintArrayInt(var arr: array {math} * of integer);
begin
writeln("Print Array Content Int32[":0, string(len(arr)):0, "]":0);
for i := 0 to len(arr, 0) - 1 do
writeln(" array [",i:2,"] = ",arr[i]:2," ");
end;
writeln;
end PrintArrayInt;
procedure PrintArrayString(var arr: array * of string);
begin
writeln("Print Array Content String[":0, string(len(arr)):0, "]":0);
for i := 0 to len(arr, 0) - 1 do
writeln(" array [",i:2,"] = ",arr[i]:2," ");
end;
writeln;
end PrintArrayString;
procedure PrintMatrix(m: array {math} *,* of integer);
var i,j: integer;
begin
writeln("Print Matrix Content Int32[":0, string(len(m,0)):0, ",":0, string(len(m,1)):0, "]":0);
for i := 0 to len(m,0) - 1 do
for j := 0 to len(m,1) - 1 do
writeln(" array [":0,i:2,j:2,"] = ",m[i, j]:2," ":0);
end;
end;
writeln;
end PrintMatrix;
procedure GraphJaggedArray(arr: array * of array * of string);
var lineCount: integer;
i,j: integer;
begin
writeln;
writeln("Print Text Content String[][]":0);
lineCount := 1;
for i := 0 to len(arr) - 1 do
write("Line":0,lineCount:2,"|":0);
for j := 0 to len(arr[i]) - 1 do
write("*":3);
end;
writeln(" (":0,string(len(arr[i])):0,")":0);
inc(lineCount);
end;
writeln;
end GraphJaggedArray;
procedure PrintJaggedArray(arr: array * of array * of string);
var i,j: integer;
line: string;
linearr: array * of string;
begin
writeln;
writeln("Print Jagged Array Content String[][]":0);
for i := 0 to len(arr) - 1 do
line := "";
for j := 0 to len(arr[i]) - 1 do
line := line + " " + arr[i,j];
end;
if line = line.ToUpper() then
line := line + " <-- [UPPERCASED]";
end;
writeln(line:0);
end;
end PrintJaggedArray;
procedure PrintCommonArrayExceptions(arr: array * of array * of string);
(*
"Extra information about the exception can be accessed
by calling the predefined function 'reason'. This causes the
runtime system to return a string which explains the reason
for the exception." Not working in Zonnon version 1.3.0
var s: string;
do ... on exception do
s := reason; <- This gives a "reason not declared" error at compile time.
end;
*)
begin
do
arr[100,100] := 'hola';
on NilReference do
writeln;
writeln("Exception: NilReference":0);
on OutOfRange do
writeln;
writeln("Exception: OutOfRange":0);
on exception do
writeln;
writeln("Exception: Other":0);
on termination do
(* nothing *)
end;
writeln;
end PrintCommonArrayExceptions;
procedure PrintTitle(message: string);
begin
writeln('======================================================':0);
writeln(message:0);
writeln('======================================================':0);
writeln;
end PrintTitle;
var
(*writeln(pos,wlen,Substring(s,pos,wlen),s.Substring(pos,wlen));*)
i: integer;
(* Declare Array of Chars *)
letters: array 5 of char;
inverse_letters: array * of char;
(* Mathematical extensions
Mathematical extensions of Zonnon let use arrays in a more convenient way
for writing applications where multidimensional algebra is used.
Arrays to be used in mathematical extensions should be defined with special
{math} modifier. ArrayType = array "{" math "}" Length {"," Length} of Type.
This option allow you to initialize math array with array expressions,
but it only works for numerical arrays such as
array {math} of integer | real | boolean but not of string.
*)
(* Declare Array of Integers *)
numbers, ordered_numbers: array {math} * of integer;
(* Declare Array of Strings *)
names: array 5 of string;
ordered_names: array * of string;
(* Declare multi-dimensional Array *)
matrix: array {math} 2, 3 of integer;
transposed_matrix: array {math} *,* of integer;
(* Declare Jagged Array *)
text: array * of array * of string;
(* Indexer *)
vowels,en,na: Alphabet;
vs,w: array {math} * of char;
word1,word2,word3: string;
begin
(* Single-dimensional Array(s) *)
PrintTitle("Reverse Array Elements");
(* Initialize Array of Chars *)
letters[0] := 'A';
letters[1] := 'E';
letters[2] := 'I';
letters[3] := 'O';
letters[4] := 'U';
PrintArrayChar(letters);
inverse_letters := ReverseChar(letters);
PrintArrayChar(inverse_letters);
PrintTitle("Sort Integer Array Elements");
(* Initialize Math Array of Integers *)
numbers := [ 10, 8, 3, 1, 5];
PrintArrayInt(numbers);
ordered_numbers := BubbleSortInt(numbers);
PrintArrayInt(ordered_numbers);
PrintTitle("Sort String Array Elements");
(* Initialize Array of Strings *)
names[0] := "Damian";
names[1] := "Rogelio";
names[2] := "Carlos";
names[3] := "Luis";
names[4] := "Daniel";
PrintArrayString(names);
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]
*)
(* Array inline expression used to declare and initialize array *)
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 System.String arrays using the (System.)String.Split method
*
* Text extract from: 'El ingenioso hidalgo don Quijote de la Mancha'
*
*)
text := new JaggedArrayOfString(8,0);
text[0] := Str.Split("Hoy es el di­a mas hermoso de nuestra vida, querido Sancho;", ' ');
text[1] := Str.Split("los obstaculos mas grandes, nuestras propias indecisiones;", ' ');
text[2] := Str.Split("nuestro enemigo mas fuerte, miedo al poderoso y nosotros mismos;", ' ');
text[3] := Str.Split("la cosa mas facil, equivocarnos;", ' ');
text[4] := Str.Split("la mas destructiva, la mentira y el egoi­smo;", ' ');
text[5] := Str.Split("la peor derrota, el desaliento;", ' ');
text[6] := Str.Split("los defectos mas peligrosos, la soberbia y el rencor;", ' ');
text[7] := Str.Split("las sensaciones mas gratas, la buena conciencia...", ' ');
PrintJaggedArray(text);
UpperCaseRandomArray(text);
PrintJaggedArray(text);
GraphJaggedArray(text);
(* Array Exceptions *)
PrintTitle("Common Array Exceptions");
PrintCommonArrayExceptions(nil);
PrintCommonArrayExceptions(text);
(* Accessing Class Array Elements through Indexer *)
PrintTitle("Alphabets");
vowels := new Alphabet(5,nil,nil);
vowels[0] := char('a');
vowels[1] := char('e');
vowels[2] := char('i');
vowels[3] := char('o');
vowels[4] := char('u');
vs := new ArrayOfChar(5);
vs[0] := vowels[0]; vs[1] := vowels[1];
vs[2] := vowels[2]; vs[3] := vowels[3];
vs[4] := vowels[4];
writeln;
writeln("Vowels = {":0, Str.Join(',', vs):0, "}":0);
en := new Alphabet(0,'abcdefghijklmnopqrstuvwxyz',nil);
writeln("English Alphabet = {":0,en.ToString(),"}":0);
na := new Alphabet(0,nil,en.Slice(9, 19));
writeln("Alphabet Extract en[9..19] = {":0,na.ToString():0,"}":0);
w := new ArrayOfChar(5);
w[0] := en[6]; w[1] := en[14]; w[2] := en[14]; w[3] := en[3];
copy(w, word1);
w := new ArrayOfChar(4);
w[0] := en[1]; w[1] := en[24]; w[2] := en[4];
copy(w, word2);
w := new ArrayOfChar(9);
w[0] := en[4]; w[1] := en[21]; w[2] := en[4]; w[3] := en[17];
w[4] := en[24]; w[5] := en[14]; w[6] := en[13]; w[7] := en[4];
copy(w, word3);
writeln;
writeln(word1:0, " ":0, word2:0, ", ":0, word3:0, "!":0);
writeln;
readln;
end Main.
</pre>
<br />
<br />
The output:
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4PoCdlTmnVhyphenhyphen-QVyH-LVDteVE2Q_8Vz9HNrgePfUWiQETqIlyuf32XF6mpgXOzyHz02JgJ_-DCoCL2078w1B-qjluOmSJo_h8kKkiuvM7klI6PVtmhfhyLKKjAureBMpYFJcxPb0eUsw/s1600/ZnnArraysOutput.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4PoCdlTmnVhyphenhyphen-QVyH-LVDteVE2Q_8Vz9HNrgePfUWiQETqIlyuf32XF6mpgXOzyHz02JgJ_-DCoCL2078w1B-qjluOmSJo_h8kKkiuvM7klI6PVtmhfhyLKKjAureBMpYFJcxPb0eUsw/s1600/ZnnArraysOutput.png" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com1tag:blogger.com,1999:blog-694679611587040520.post-27388823242745853572013-11-19T09:25:00.000-08:002013-11-19T11:23:03.961-08:00Arrays and Indexers in Cobra<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
Today's post is about Arrays and Indexers in Cobra. 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 Cobra, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.<br />
<br />
By the way, if you missed my most recent post, "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="python" name="code">
use System.Text
namespace CobraArrays
class Program is public
shared
def main
# Single-dimensional Array(s)
.printTitle("Reverse Array Elements")
# Declare and initialize Array of Chars
letters as char[] = char[](5)
letters[0] = c'A'
letters[1] = c'E'
letters[2] = c'I'
letters[3] = c'O'
letters[4] = c'U'
.printArrayChar(letters)
inverse_letters as char[] = .reverseChar(letters)
.printArrayChar(inverse_letters)
.printTitle("Sort Integer Array Elements")
# Declare and Initialize Array of Integers
numbers as int[] = @[10, 8, 3, 1, 5]
.printArrayInt(numbers)
ordered_numbers as int[] = .bubblesortInt(numbers)
.printArrayInt(ordered_numbers)
.printTitle("Sort String Array Elements")
# Declare and Initialize and Array of Strings
names as String[] = @[
'Damian',
'Rogelio',
'Carlos',
'Luis',
'Daniel'
]
.printArrayString(names)
ordered_names as String[] = .bubblesortString(names)
.printArrayString(ordered_names)
# Multi-dimensional Array (Matrix row,column)
# Cobra does not support multi-dimensional arrays syntax
# using List<of List<of Type>> instead
.printTitle("Transpose Matrix")
/# Matrix row=2,col=3
# A = [6 4 24]
# [1 -9 8]
#/
matrix as List<of List<of int>> = [[6, 4, 24],
[1, -9, 8]]
.printMatrix(matrix)
transposed_matrix as List<of List<of int>> = .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 as String[] = @[
# @[ 'word1', 'word2', 'wordN' ],
# @[ 'word1', 'word2', 'wordM' ],
# ...
# ]
#
# Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"
#
#/
text = [ _
"Hoy es el día más hermoso de nuestra vida, querido Sancho;".split(c' '),
"los obstáculos más grandes, nuestras propias indecisiones;".split(c' '),
"nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;".split(c' '),
"la cosa más fácil, equivocarnos;".split(c' '),
"la más destructiva, la mentira y el egoísmo;".split(c' '),
"la peor derrota, el desaliento;".split(c' '),
"los defectos más peligrosos, la soberbia y el rencor;".split(c' '),
"las sensaciones más gratas, la buena conciencia...".split(c' ')
]
.printJaggedArray(text)
/#
.uppercaserandomArray(text)
#/
.printJaggedArray(text)
.graphJaggedArray(text)
# Array Exceptions
.printTitle("Common Array Exceptions")
.printCommonArrayExceptions(nil)
.printCommonArrayExceptions(text)
# Accessing Class Array Elements through Indexer
.printTitle("Alphabets")
vowels as Alphabet = Alphabet(5)
vowels[0] = c'a'
vowels[1] = c'e'
vowels[2] = c'i'
vowels[3] = c'o'
vowels[4] = c'u'
print "\nVowels = {" + [vowels[0], vowels[1], vowels[2],
vowels[3], vowels[4]].join(",") + "}"
en as Alphabet = Alphabet("abcdefghijklmnopqrstuvwxyz")
print "English Alphabet = {[en.toString]}"
print "Alphabet Extract en\[9..19\] = {[Alphabet(en.slice(9, 10))]}"
word1 as String = [en[6], en[14], en[14], en[3]].join('')
word2 as String = [en[1], en[24], en[4]].join('')
word3 as String = [en[4], en[21], en[4], en[17], en[24],
en[14], en[13], en[4]].join('')
print "\n[word1] [word2], [word3]!"
Console.read
def reverseChar(arr as char[]) as char[]
reversed as char[] = char[](arr.length)
i as int = 0
for j in arr.length-1:-1:-1
reversed[i] = arr[j]
i += 1
return reversed
def bubblesortInt(arr as int[]) as int[]
swap as int = 0
for i in arr.length-1:-1:-1
for j in arr.length-1
if arr[j] > arr[j + 1]
swap = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = swap
return arr
def bubblesortString(arr as String[]) as String[]
swap as String = ""
for i in arr.length-1:-1:-1
for j in arr.length-1
if arr[j][0] > arr[j + 1][0]
swap = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = swap
return arr
def transposeMatrix(m as List<of List<of int>>) as List<of List<of int>>
/# Transposing a Matrix 2,3
#
# A = [6 4 24]T [ 6 1]
# [1 -9 8] [ 4 -9]
# [24 8]
#/
transposed = [[0]] # to get [int] instead of [object]
transposed.clear
for i in 0:m[0].count
transposed.add([0]) # same here
transposed[i].clear
for j in 0:m.count
transposed[i].add(m[j][i])
return transposed
def printArrayChar(arr as char[])
print "\nPrint Array Content " + arr.getType.name.replace(']', _
arr.length.toString + ']')
for i in arr.length
print " array " + String.format("[[{0,2}]] = {1,2}", i, arr[i])
def printArrayInt(arr as int[])
print "\nPrint Array Content " + arr.getType.name.replace(']', _
arr.length.toString + ']')
for i in arr.length
print " array " + String.format("[[{0,2}]] = {1,2}", i, arr[i])
def printArrayString(arr as String[])
print "\nPrint Array Content " + arr.getType.name.replace(']', _
arr.length.toString + ']')
for i in arr.length
print " array " + String.format("[[{0,2}]] = {1,2}", i, arr[i])
def printMatrix(m as List<of List<of int>>)
print "\nPrint Matrix Content " + m.getType.name
for i in 0:m.count
for j in 0:m[0].count
print " array " + String.format("[[{0,2},{1,2}]] = {2,2} " _
, i, j, m[i][j])
def graphJaggedArray(arr as List<of String[]?>)
/# When using Arrays, we can use for(each) instead of for by index:
#
# for s in arr:
# for w as String in s
#
#/
print "\nPrint Text Content [arr.getType.name]"
for i in arr.count
Console.write("Line{0,2}|", i+1)
for j in arr[i].length
Console.write("{0,3}", "*")
print " ([arr[i].length.toString])"
def printJaggedArray(arr as List<of String[]?>)
line as StringBuilder?
print "\nPrint Jagged Array Content [arr.getType.name]"
for i in arr.count
line = StringBuilder()
for j in arr[i].length
line.append(" " + arr[i][j])
if line.toString == line.toString.toUpper
line.append(r" <-- [UPPERCASED]")
print line.toString
def printCommonArrayExceptions(arr as List<of String[]?>?)
try
arr[100][100] = "hola"
catch ex as Exception
print "\nException: \n[ex.getType.name]\n[ex.message]"
def printTitle(message as String)
print ""
print "======================================================"
print message
print "======================================================"
class Alphabet is public
# Array Field
var _letters as char[]? is private
# Indexer Get/Set Property
pro [index as int] as char is public
get
return _letters[index]
set
_letters[index] = value.toUpper
# Read-Only Property
get length as int is public
return _letters.length
# Constructors
cue init(size as int) is public
base.init
_letters = char[](size)
cue init(list as String) is public
base.init
_letters = list.toUpper.toCharArray
cue init(list as char[]) is public
base.init
_letters = list
# Overridden Method
def toString as String is override
return "" + _letters.join(',')
# Method
def slice(start as int, length as int) as char[]?
return _letters[start:start+length]
</pre>
<br />
<br />
The output:
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8MbWW2ZrV4M8dshGAiXd-p3e6pj76_YrmBNNBWCOOWKDjq-9mUMeuBx1CVVz9FoMpGXz1EuDP5nHs5dSHnysIXV01O0zyTwVINuBPhl3uP5Zpn_TOE56__tt1FZ9s0qFr285-kt7uxN0/s1600/cobraarraysoutput.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8MbWW2ZrV4M8dshGAiXd-p3e6pj76_YrmBNNBWCOOWKDjq-9mUMeuBx1CVVz9FoMpGXz1EuDP5nHs5dSHnysIXV01O0zyTwVINuBPhl3uP5Zpn_TOE56__tt1FZ9s0qFr285-kt7uxN0/s1600/cobraarraysoutput.png" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com1tag:blogger.com,1999:blog-694679611587040520.post-72456816998888086482013-10-27T08:02:00.000-07:002016-09-05T05:54:18.255-07:00Arrays and Indexers in Phalanger<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
Today's post is about Arrays and Indexers in Phalanger (PHP). 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 Phalanger (PHP), in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.<br />
<br />
This is the first post of a "dynamic" language implemented for the DLR. You will notice that the code structure its slightly different from previous posts. Besides that, because Phalanger is PHP, it is definitely better to use PHP's array type instead of System\Array, implemented in Phalanger as PhpArray which at the end, stores the data as a Dictionary<object,object>. <br />
<br />
By the way, if you missed my most recent post, "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="php" name="code"><?php
namespace PhpArrays
{
use System as S;
use System\Console;
use System\Random;
use System\Text as T;
class Program
{
static function Main()
{
/*
* An array in PHP is actually an ordered map.
* implements arrays as Phpp.Runtime.PhpArray class
* that internally implements a Dictionary<object,object>.
*/
// Single-dimensional Array(s)
self::printTitle("Reverse Array Elements");
// Declare and Initialize Array of Chars
$letters = array();
$letters[0] = "A";
$letters[1] = "E";
$letters[2] = "I";
$letters[3] = "O";
$letters[4] = "U";
//print_r($letters);
self::printArray($letters);
$inverse_letters = self::reverseChar($letters);
self::printArray($inverse_letters);
self::printTitle("Sort Integer Array Elements");
// Declare and Initialize Array of Integers
$numbers = array ( 10, 8, 3, 1, 5 );
self::printArray($numbers);
$ordered_numbers = self::bubbleSort($numbers);
self::printArray($ordered_numbers);
self::printTitle("Sort String Array Elements");
// Declare and Initialize and Array of Strings
$names = array (
"Damian",
"Rogelio",
"Carlos",
"Luis",
"Daniel"
);
self::printArray($names);
$ordered_names = self::bubbleSort($names);
self::printArray($ordered_names);
// Multi-dimensional Array (Matrix row,column)
// in PHP they are the same as Jagged Arrays or "array of arrays"
self::printTitle("Transpose Matrix");
/* Matrix row=2,col=3
* A = [6 4 24]
* [1 -9 8]
*/
$matrix = array ( array ( 6, 4, 24 ),
array ( 1, -9, 8 ));
self::printMatrix($matrix);
$transposed_matrix = self::transposeMatrix($matrix);
self::printMatrix($transposed_matrix);
// Jagged Array (Array-of-Arrays)
self::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 = array (
* array ( "word1", "word2", "wordN" ),
* array ( "word1", "word2", "wordM" ),
* ...
* );
*
* Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"
*
*/
// using php function explode (split also works)
$text = array (
\explode(" ", "Hoy es el día más hermoso de nuestra vida, querido Sancho;"),
\explode(" ", "los obstáculos más grandes, nuestras propias indecisiones;"),
\explode(" ", "nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;"),
\explode(" ", "la cosa más fácil, equivocarnos;"),
\explode(" ", "la más destructiva, la mentira y el egoísmo;"),
\explode(" ", "la peor derrota, el desaliento;"),
\explode(" ", "los defectos más peligrosos, la soberbia y el rencor;"),
\explode(" ", "las sensaciones más gratas, la buena conciencia...")
);
//print_r ($text);
self::printJaggedArray($text);
$text = self::upperCaseRandomArray($text); // param not by reference
self::printJaggedArray($text);
self::graphJaggedArray($text);
// Array Exceptions
self::printTitle("Common Array Exceptions");
self::printCommonArrayExceptions(NULL);
self::printCommonArrayExceptions($text);
// Accessing Class Array Elements through Indexer
self::printTitle("Alphabets");
$vowels = new Alphabet(5);
$vowels[0] = 'a';
$vowels[1] = 'e';
$vowels[2] = 'i';
$vowels[3] = 'o';
$vowels[4] = 'u';
//print_r ($vowels);
echo "\nVowels = {"
. \implode(",", array($vowels[0], $vowels[1], $vowels[2], $vowels[3], $vowels[4]))
. "}\n";
$en = new Alphabet("abcdefghijklmnopqrstuvwxyz");
echo "English Alphabet = {{$en}}\n";
echo "Alphabet Extract en[9..19] = {"
. new Alphabet($en->slice(9, 10))
. "}\n";
$word1 = \implode("", array ($en[6], $en[14], $en[14], $en[3]));
$word2 = \implode("", array ($en[1], $en[24], $en[4]));
$word3 = \implode("", array ($en[4], $en[21], $en[4], $en[17],
$en[24], $en[14], $en[13], $en[4]));
echo "\n$word1 $word2, $word3!\n";
\fgets(STDIN);
return 0;
}
static function reverseChar($arr)
{
$reversed = array();
for ($i = 0, $j = \count($arr) - 1; $j >= 0; $i++, $j--)
{
$reversed[$i] = $arr[$j];
}
return $reversed;
// or: return \array_reverse($arr);
}
static function bubbleSort($arr)
{
$swap = 0;
for ($i = \count($arr) - 1; $i > 0; $i--)
{
for ($j = 0; $j < $i; $j++)
{
// if ($arr[$j][0] > $arr[$j + 1][0])
if (\is_numeric($arr[$j]) ?
$arr[$j] > $arr[$j + 1] :
$arr[$j][0] > $arr[$j + 1][0])
{
$swap = $arr[$j];
$arr[$j] = $arr[$j + 1];
$arr[$j + 1] = $swap;
}
}
}
return $arr;
}
static function transposeMatrix($m)
{
/* Transposing a Matrix 2,3
*
* A = [6 4 24]T [ 6 1]
* [1 -9 8] [ 4 -9]
* [24 8]
*/
$transposed = array();
for ($i = 0; $i < \count($m); $i++)
{
for ($j = 0; $j < \count($m[0]); $j++)
{
$transposed[$j][$i] = $m[$i][$j];
}
}
return $transposed;
}
static function upperCaseRandomArray($arr)
{
$r = new Random();
$i = $r->Next(0, \count($arr) - 1);
for ($j = 0; $j < \count($arr[$i]); $j++)
{
$arr[$i][$j] = \strtoupper($arr[$i][$j]);
}
return $arr;
}
static function printArray($arr)
{
echo "\nPrint Array Content " . $arr->GetType()->Name . "\n";
for ($i = 0; $i < \count($arr); $i++)
{
Console::WriteLine(" array [{0,2}] = {1,2} ", $i, $arr[$i]);
}
}
static function printMatrix($m)
{
echo "\nPrint Matrix Content " . $m->GetType()->Name
. "[" . \count($m) . "," . \count($m[0]) . "]\n";
for ($i = 0; $i < \count($m); $i++)
{
for ($j = 0; $j < \count($m[0]); $j++)
{
Console::WriteLine(" array [{0,2},{1,2}] = {2,2} ", $i, $j, $m[$i][$j]);
}
}
}
static function graphJaggedArray($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++)
*
*/
echo "\nPrint Text Content " . $arr->GetType()->Name . "\n";
$lineCount = 1;
foreach ($arr as $s)
{
Console::Write("Line{0,2}|", $lineCount);
foreach ($s as $w)
{
Console::Write("{0,3}", '*');
}
echo " (" . \count($s) . ")\n";
$lineCount++;
}
}
static function printJaggedArray($arr)
{
echo "\nPrint Jagged Array Content " . $arr->GetType()->Name . "\n";
for ($i = 0; $i < \count($arr); $i++)
{
$line = new T\StringBuilder();
for ($j = 0; $j < \count($arr[$i]); $j++)
{
$line->Append(" " . $arr[$i][$j]);
}
if ($line->ToString() == \strtoupper($line->ToString()))
{
$line->Append(" <-- [UPPERCASED]");
}
echo $line . "\n";
}
}
static function printCommonArrayExceptions($arr)
{
// there is a bug throwing System\Exception(s) in Phalanger.
// but apparently it has been quickly fixed after reported.
try
{
/* Throwing System\Exception(s) do not get caught in
* the catch, instead they give an error message and
* continue executing. i.e.
* throw new S\NullReferenceException("");
* throw new S\Exception("");
*/
if (\is_null($arr))
{
throw new \ErrorException(
"Object reference not set to an instance of an object.",
0, \E_ERROR);
}
if (!isset($arr[100][100]))
{
throw new \OutOfRangeException(
"Index was outside the bounds of the array.", 0);
}
}
catch (\OutOfRangeException $ex)
{
echo "\nException: OutOfRangeException\n" .
$ex->getMessage() . "\n";
}
catch (\ErrorException $ex)
{
echo "\nException: ErrorException " .
$ex->getSeverity() . "\n" . $ex->getMessage() . "\n";
}
/*catch (S\Exception $ex)
{
echo "\nException: ", "Exception",
$ex->getMessage(), "\n";
}*/
}
static function printTitle(string $message)
{
echo "\n";
echo \str_repeat("=", 54) . "\n";
echo $message . "\n";
echo \str_repeat("=", 54) . "\n";
}
}
[\Export]
class Alphabet implements \ArrayAccess
{
// Array Field
private $letters = array();
// Indexer Get/Set methods
// Implementing ArrayAccess methods
public function offsetSet($offset, $value) {
if (\is_null($offset))
{
$this->letters[] = $value;
} else
{
$this->letters[$offset] = \strtoupper($value);
}
}
public function offsetExists($offset) {
return isset($this->letters[$offset]);
}
public function offsetUnset($offset) {
unset($this->letters[$offset]);
}
public function offsetGet($offset) {
return isset($this->letters[$offset]) ? $this->letters[$offset] : NULL;
}
// Read-Only Property
public function getLength()
{
return \count($this->letters);
}
// Constructor
// No Overloaded Constructors support in (PHP) Phalanger
public function __construct($param = NULL)
{
// int $size
if(\is_numeric($param))
{
$this->letters = \array_pad($this->letters, $size, ' ');
}
// string $list
else if(\is_string($param))
{
$this->letters = \str_split(\strtoupper($param));
}
// array $list
else if(\is_array($param))
{
$this->letters = $param;
}
else
{
$this->letters = NULL;
}
}
// Overridden Method
public function __toString()
{
return \join(",", $this->letters);
}
// Method
public function slice($start, $length)
{
return \array_slice($this->letters, $start, $length);
}
}
}
?>
</pre>
<br />
<br />
The output:
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZmbM61teWAtkGH0ygijWY3umb5iiuzr8-dt9TURmHYykdh-nWD0TGHRd1WMeNAq4uW7wWC-uwK96GfZPgTOWOaq3hRMRwsYOwCxTBKGg1llYBy2DExSDCZt2QZJjfsD5vTmkEPpdhxtw/s1600/PhpArraysOutput.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZmbM61teWAtkGH0ygijWY3umb5iiuzr8-dt9TURmHYykdh-nWD0TGHRd1WMeNAq4uW7wWC-uwK96GfZPgTOWOaq3hRMRwsYOwCxTBKGg1llYBy2DExSDCZt2QZJjfsD5vTmkEPpdhxtw/s1600/PhpArraysOutput.png" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-35204992269277770532013-10-22T12:03:00.000-07:002017-05-12T01:49:01.760-07:00Arrays and Indexers in Nemerle<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
Today's post is about Arrays and Indexers in Nemerle. 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 Nemerle, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.<br />
<br />
By the way, if you missed my most recent post, "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="brush: csharp">
using Nemerle.IO;
using System;
using System.Console;
using System.Text;
namespace NsArrays
{
module Program
{
Main() : void
{
// Single-dimensional Array(s)
PrintTitle("Reverse Array Elements");
// Declare and Initialize Array of Chars
def letters : array[char] = array(5);
letters[0] = 'A';
letters[1] = 'E';
letters[2] = 'I';
letters[3] = 'O';
letters[4] = 'U';
PrintArrayChar(letters);
def inverse_letters : array[char] = ReverseChar(letters);
PrintArrayChar(inverse_letters);
PrintTitle("Sort Integer Array Elements");
// Declare and Initialize Array of Integers
def numbers : array[int] = array [10, 8, 3, 1, 5];
PrintArrayInt(numbers);
def ordered_numbers : array[int] = BubbleSortInt(numbers);
PrintArrayInt(ordered_numbers);
PrintTitle("Sort String Array Elements");
// Declare and Initialize and Array of Strings
def names : array[string] = array[
"Damian",
"Rogelio",
"Carlos",
"Luis",
"Daniel"
];
PrintArrayString(names);
def 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]
*/
def matrix : array[2,int] = array.[2][[ 6, 4, 24 ],
[ 1, -9, 8 ]];
PrintMatrix(matrix);
def transposed_matrix : array[2,int] = 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 text : array[array[string]] = array[
* array[ "word1", "word2", "wordN" ],
* array[ "word1", "word2", "wordM" ],
* ...
* ];
*
* Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"
*
*/
def 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");
def vowels : Alphabet = Alphabet(5);
vowels[0] = 'a';
vowels[1] = 'e';
vowels[2] = 'i';
vowels[3] = 'o';
vowels[4] = 'u';
printf("\nVowels = {%s}\n",
String.Join(",", vowels[0], vowels[1], vowels[2], vowels[3], vowels[4]));
def en : Alphabet = Alphabet("abcdefghijklmnopqrstuvwxyz");
printf("English Alphabet = {%s}\n", en.ToString());
printf("Alphabet Extract en[9..19] = {%s}\n",
Alphabet(en.Slice(9, 10)).ToString());
def word1 : string = String.Join("", en[6], en[14], en[14], en[3]);
def word2 : string = String.Join("", en[1], en[24], en[4]);
def word3 : string = String.Join("", en[4], en[21], en[4], en[17],
en[24], en[14], en[13], en[4]);
printf("\n%s %s, %s!\n\n", word1, word2, word3);
_ = ReadLine();
}
ReverseChar(arr : array[char]) : array[char]
{
def reversed : array[char] = array(arr.Length);
mutable i : int = 0;
for (mutable j : int = arr.Length - 1; j >= 0; j--)
{
reversed[i] = arr[j];
i++;
}
reversed;
}
BubbleSortInt(arr : array[int]) : array[int]
{
mutable swap : int = 0;
for (mutable i : int = arr.Length - 1; i > 0; i--)
{
for (mutable j: int = 0; j < i; j++)
{
if (arr[j] > arr[j + 1])
{
swap = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = swap;
}
else{}
}
}
arr;
}
BubbleSortString(arr : array[string]) : array[string]
{
mutable swap : string = "";
for (mutable i : int = arr.Length - 1; i > 0; i--)
{
for (mutable j: int = 0; j < i; j++)
{
if (arr[j][0] > arr[j + 1][0])
{
swap = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = swap;
}
else{}
}
}
arr;
}
TransposeMatrix(m : array[2, int]) : array[2, int]
{
/* Transposing a Matrix 2,3
*
* A = [6 4 24]T [ 6 1]
* [1 -9 8] [ 4 -9]
* [24 8]
*/
def transposed : array[2, int] = array(m.GetUpperBound(1) + 1,
m.GetUpperBound(0) + 1);
for (mutable i : int = 0; i < m.GetUpperBound(0) + 1; i++)
{
for (mutable j = 0; j < m.GetUpperBound(1) + 1; j++)
{
transposed[j, i] = m[i, j];
}
}
transposed;
}
UpperCaseRandomArray(arr : array[array[string]]) : void
{
def r : Random = Random();
mutable i : int = r.Next(0, arr.Length - 1);
for (mutable j : int = 0; j <= arr[i].Length - 1; j++)
arr[i][j] = arr[i][j].ToUpper();
}
PrintArrayChar(arr : array[char]) : void
{
printf("\nPrint Array Content %s\n",
arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));
for (mutable i : int = 0; i <= arr.Length - 1; i++)
WriteLine(" array [{0,2}] = {1,2} ", i, arr[i]);
}
PrintArrayInt(arr : array[int]) : void
{
printf("\nPrint Array Content %s\n",
arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));
for (mutable i : int = 0; i <= arr.Length - 1; i++)
WriteLine(" array [{0,2}] = {1,2} ", i, arr[i]);
}
PrintArrayString(arr : array[string]) : void
{
printf("\nPrint Array Content %s\n",
arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));
for (mutable i : int = 0; i <= arr.Length - 1; i++)
WriteLine(" array [{0,2}] = {1,2} ", i, arr[i]);
}
PrintMatrix(m : array[2,int]) : void
{
printf("\nPrint Matrix Content %s[%s,%s]\n",
m.GetType().Name.Replace("[,]", ""),
(m.GetUpperBound(0) + 1).ToString(),
(m.GetUpperBound(1) + 1).ToString());
for (mutable i : int = 0; i <= m.GetUpperBound(0); i++)
for (mutable j : int = 0; j <= m.GetUpperBound(1); j++)
WriteLine(" array [{0,2},{1,2}] = {2,2} ", i, j, m[i, j]);
}
GraphJaggedArray(arr : array[array[string]]) : void
{
/* When using Arrays, we can use foreach instead of for:
*
* for (mutable i : int = 0; i <= arr.Length - 1; i++)
* for (mutable j : int = 0; j <= arr.Length - 1; j++)
*
*/
printf("\nPrint Text Content %s\n", arr.GetType().Name);
mutable lineCount : int = 1;
foreach (s : array[string] in arr)
{
Write("Line{0,2}|", lineCount);
foreach (_ : string in s)
{
Write("{0,3}", '*');
}
printf(" (%s)\n", s.Length.ToString());
lineCount++;
}
}
PrintJaggedArray(arr : array[array[string]]) : void
{
mutable line : StringBuilder;
printf("\nPrint Jagged Array Content %s\n", arr.GetType().Name);
for (mutable i : int = 0; i <= arr.Length - 1; i++)
{
line = StringBuilder();
for (mutable j : int = 0; j <= arr[i].Length - 1; j++)
_ = line.Append(" " + arr[i][j]);
if (line.ToString() == line.ToString().ToUpper())
{
_ = line.Append(" <-- [UPPERCASED]");
}
else {}
printf("%s\n", line.ToString());
}
}
PrintCommonArrayExceptions(arr : array[array[string]]) : void
{
try
{
arr[100][100] = "hola";
}
catch
{
| ex is Exception =>
printf("\nException: \n%s\n%s\n", ex.GetType().Name, ex.Message);
}
}
PrintTitle(message : string) : void
{
print("\n");
print("======================================================\n");
printf("%s\n", message);
print("======================================================\n");
}
}
class Alphabet
{
// Array Field
private letters : array[char];
// Indexer Get/Set Property
public Item[index : int] : char
{
get { letters[index] }
set { letters[index] = Char.ToUpper(value) }
}
// Read-Only Property
public Length : int
{
get { this.letters.Length }
}
// Constructors
public this(size : int)
{
this.letters = array(size);
}
public this(lst : string)
{
this.letters = lst.ToUpper().ToCharArray();
}
public this(lst : array[char])
{
this.letters = lst;
}
// Overridden Method
public override ToString() : string
{
String.Join(",", this.letters);
}
// Method
public Slice(start : int, length : int) : array[char]
{
def result : array[char] = array(length);
mutable j : int = start;
for (mutable i : int = 0; i < length; i++)
{
result[i] = this[j];
j++;
}
result;
}
}
}
</pre>
<br />
<br />
The output:
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhq59V-FOLgu0dsWuWBGojUPj2bUeaAliWXfzw3t1KlMf27Ups3sQImtaA7jS9IBntUK-eBhyQDDLMZyEttNPiHdSH1iDQli2mFttHjeOQMZ7W9uMFs44pOVen1DyJ1swQVuBpZUTv4A_M/s1599/arrays_indexers_cs+-+Copie.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhq59V-FOLgu0dsWuWBGojUPj2bUeaAliWXfzw3t1KlMf27Ups3sQImtaA7jS9IBntUK-eBhyQDDLMZyEttNPiHdSH1iDQli2mFttHjeOQMZ7W9uMFs44pOVen1DyJ1swQVuBpZUTv4A_M/s1600/arrays_indexers_cs+-+Copie.png"></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-42608234985623357652013-09-14T14:16:00.001-07:002013-10-23T00:43:24.325-07:00Arrays and Indexers in Boo<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
Today's post is about Arrays and Indexers in Boo. 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 Boo, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.<br />
<br />
By the way, if you missed my most recent post, "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
<br />
<pre class="csharp" name="code">namespace BooArrays
# python's import syntax supported only on latest Boo version (2.0.9.5 assemblies)
from System import Random
from System.Text import StringBuilder
from System.Console import WriteLine, Write, ReadKey
from System.Convert import ToChar
from System.Char import ToUpper
# Console Program
public def Main(argv as (string)):
# Single-dimensional Array(s)
printtitle('Reverse Array Elements');
# Declare and initialize Array of Chars
# Boo doesn't support yet (version 2.0.9.5 assemblies) Char literals.
# 1 character literal such as 'A' or "A" are strings
# so, I'm converting Convert.ToChar before assignment by element.
# There are 2 ways to initialize inline. i.e.
# option 1: a as (char) = (ToChar('A'), ToChar('B'), ToChar('C'))
# option 2: a as (char) = "ABC".ToCharArray()
letters as (char) = array(char, 5)
letters[0] = ToChar('A')
letters[1] = ToChar('E')
letters[2] = ToChar('I')
letters[3] = ToChar('O')
letters[4] = ToChar('U')
printarraychar(letters)
inverse_letters as (char) = reversechar(letters)
printarraychar(inverse_letters)
printtitle('Sort Integer Array Elements')
# Declare and Initialize Array of Integers
numbers as (int) = (10, 8, 3, 1, 5)
printarrayint(numbers)
ordered_numbers as (int) = bubblesortint(numbers)
printarrayint(ordered_numbers)
printtitle('Sort String Array Elements')
# Declare and Initialize and Array of Strings
names as (string) = (
'Damian',
'Rogelio',
'Carlos',
'Luis',
'Daniel'
)
printarraystring(names)
ordered_names as (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]
*/
matrx as (int, 2) = matrix(int, 2, 3)
# or alternative syntax: = matrix of int(2, 3)
matrx[0,0] = 6
matrx[0,1] = 4
matrx[0,2] = 24
matrx[1,0] = 1
matrx[1,1] = -9
matrx[1,2] = 8
printmatrix(matrx)
transposed_matrix as (int, 2) = transposematrix(matrx)
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 as ((string)) = (
* ( 'word1', 'word2', 'wordN' ),
* ( 'word1', 'word2', 'wordM' ),
* ...
* }
*
* Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"
*
*/
text as ((string)) = (
'Hoy es el día más hermoso de nuestra vida, querido Sancho;'.Split(ToChar(' ')),
'los obstáculos más grandes, nuestras propias indecisiones;'.Split(ToChar(' ')),
'nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;'.Split(ToChar(' ')),
'la cosa más fácil, equivocarnos;'.Split(ToChar(' ')),
'la más destructiva, la mentira y el egoísmo;'.Split(ToChar(' ')),
'la peor derrota, el desaliento;'.Split(ToChar(' ')),
'los defectos más peligrosos, la soberbia y el rencor;'.Split(ToChar(' ')),
'las sensaciones más gratas, la buena conciencia...'.Split(ToChar(' ')))
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 as Alphabet = Alphabet(5)
vowels[0] = ToChar('a')
vowels[1] = ToChar('e')
vowels[2] = ToChar('i')
vowels[3] = ToChar('o')
vowels[4] = ToChar('u')
print '\nVowels = {' + join((vowels[0], vowels[1], vowels[2],
vowels[3], vowels[4]), ',') + '}'
en as Alphabet = Alphabet('abcdefghijklmnopqrstuvwxyz')
print "English Alphabet = {${en.ToString()}}"
print "Alphabet Extract en[9..19] = {${Alphabet(en.slice(9, 10))}}"
word1 as string = join((en[6], en[14], en[14], en[3]), '')
word2 as string = join((en[1], en[24], en[4]), '')
word3 as string = join((en[4], en[21], en[4], en[17], en[24],
en[14], en[13], en[4]), '')
print "\n$word1 $word2, $word3!\n"
ReadKey()
def reversechar(arr as (char)) as (char):
reversed as (char) = array(char, arr.Length)
i as int = 0
for j in range(len(arr) - 1, -1, -1):
reversed[i] = arr[j]
i++
return reversed
def bubblesortint(arr as (int)) as (int):
swap as int = 0
for i in range(len(arr) - 1, -1, -1):
for j in range(0, len(arr) - 1):
if arr[j] > arr[j + 1]:
swap = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = swap
return arr
def bubblesortstring(arr as (string)) as (string):
swap as string = ''
for i in range(len(arr) - 1, -1, -1):
for j in range(0, len(arr) - 1):
if arr[j][0] > arr[j + 1][0]:
swap = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = swap
return arr
def transposematrix(m as (int, 2)) as (int, 2):
/* Transposing a Matrix 2,3
*
* A = [6 4 24]T [ 6 1]
* [1 -9 8] [ 4 -9]
* [24 8]
*/
transposed as (int, 2) = matrix(int, len(m, 1), len(m, 0))
for i in range(len(m, 0)):
for j in range(len(m, 1)):
transposed[j, i] = m[i, j]
return transposed
def uppercaserandomarray(arr as ((string))) as void:
r as Random = Random()
i as int = r.Next(len(arr))
for j as int in range(len(arr[i])):
arr[i][j] = arr[i][j].ToUpper()
def printarraychar(arr as (char)) as void:
print '\nPrint Array Content ' + arr.GetType().Name.Replace(']', len
(arr).ToString() + ']')
for i in range(len(arr)):
WriteLine(' array [{0,2}] = {1,2} ', i, arr[i])
def printarrayint(arr as (int)):
print '\nPrint Array Content ' + arr.GetType().Name.Replace(']', len
(arr).ToString() + ']')
for i in range(len(arr)):
WriteLine(' array [{0,2}] = {1,2} ', i, arr[i])
def printarraystring(arr as (string)) as void:
print '\nPrint Array Content ' + arr.GetType().Name.Replace(']', len
(arr).ToString() + ']')
for i in range(len(arr)):
WriteLine(' array [{0,2}] = {1,2} ', i, arr[i])
def printmatrix(m as (int, 2)) as void:
print '\nPrint Matrix Content ' + m.GetType().Name.Replace('[,]', '') + '[' + len
(m,0).ToString() + ',' + len(m,1).ToString() + ']'
for i in range(len(m, 0)):
for j in range(len(m, 1)):
WriteLine(' array [{0,2},{1,2}] = {2,2} ', i, j, m[i, j])
def graphjaggedarray(arr as ((string))) as void:
/* 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 ${arr.GetType().Name}"
for i as int in range(len(arr)):
Write('Line{0,2}|', i+1)
for j as int in range(len(arr[i])):
Write('{0,3}', '*')
print " (${len(arr[i]).ToString()})"
def printjaggedarray(arr as ((string))) as void:
line as StringBuilder
print "\nPrint Jagged Array Content ${arr.GetType().Name}"
for i as int in range(len(arr)):
line = StringBuilder()
for j in range(len(arr[i])):
line.Append(' ' + arr[i][j])
if line.ToString() == line.ToString().ToUpper():
line.Append(' <-- [UPPERCASED]')
print line
def printcommonarrayexceptions(arr as ((string))) as void:
try:
arr[100][100] = 'hola'
except ex as System.Exception:
print "\nException: \n${ex.GetType().Name}\n${ex.Message}"
def printtitle(message as string) as void:
print ''
print('=' * 54)
print message
print('=' * 54)
[System.Reflection.DefaultMember("item")]
class Alphabet:
# Array Field
private letters as (char)
# Indexer Get/Set Property
public item[index as int]:
get:
rawArrayIndexing:
return letters[index]
set:
rawArrayIndexing:
letters[index] = ToUpper(value)
# Read-Only Property
public Length as int:
get:
return len(self.letters)
# Constructors
public def constructor(size as int):
self.letters = array(char, size)
public def constructor(list as string):
self.letters = list.ToUpper().ToCharArray()
public def constructor(list as (char)):
self.letters = list
# Overridden Method
public override def ToString():
return join(self.letters, ',')
# Method
public def slice(start as int, length as int) as (char):
# using Boo's slicing:
# container[<firstIndexWanted>:<firstIndexNotWanted>:<step>]
return self.letters[start:start+length]
</pre>
<br />
<br />
The output:
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhq59V-FOLgu0dsWuWBGojUPj2bUeaAliWXfzw3t1KlMf27Ups3sQImtaA7jS9IBntUK-eBhyQDDLMZyEttNPiHdSH1iDQli2mFttHjeOQMZ7W9uMFs44pOVen1DyJ1swQVuBpZUTv4A_M/s1599/arrays_indexers_cs+-+Copie.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhq59V-FOLgu0dsWuWBGojUPj2bUeaAliWXfzw3t1KlMf27Ups3sQImtaA7jS9IBntUK-eBhyQDDLMZyEttNPiHdSH1iDQli2mFttHjeOQMZ7W9uMFs44pOVen1DyJ1swQVuBpZUTv4A_M/s1600/arrays_indexers_cs+-+Copie.png" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-2358081361875766092013-07-18T08:56:00.000-07:002017-04-21T06:58:13.911-07:00Arrays and Indexers in JScript.NET<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
Today's post is about Arrays and Indexers in JScript.NET. 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 JScript.NET, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.<br />
<br />
By the way, if you missed my most recent post, "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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. <br />
<br />
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.<br />
<br />
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.<br />
<br />
IMPORTANT!<br />
JScript provides two different types of arrays, JScript array objects and typed arrays. In JScript array objects, which are sparse, a script can dynamically add and remove elements, and elements can be of any data type. In typed arrays, which are dense, the size is fixed, and elements must be the same type as the base type of the array.<br />
<br />
I chose to use the Typed Arrays (and all other variables as well) to keep it closer to the previous posts.<br />
<br />
<br />
<pre class="brush: jscript">//C:\Windows\Microsoft.NET\Framework64\v4.0.30319>jsc.exe JsArrays.js
import System;
import Microsoft.JScript; // to get the JScriptException
function reverseChar(arr: char[]): char[]
{
var reversed: char[] = new char[arr.length];
for (var i: int = 0, j: int = arr.length - 1; j >= 0; i++, j--)
reversed[i] = arr[j];
return reversed;
}
function bubbleSortInt(arr: int[]): int[]
{
var swap: int = 0;
for (var i: int = arr.length - 1; i > 0; i--)
{
for (var j: int = 0; j < i; j++)
{
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: String = '';
for (var i: int = arr.length - 1; i > 0; i--)
{
for (var j: int = 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;
}
function transposeMatrix(m: int[,]): int[,]
{
/* Transposing a Matrix 2,3
*
* A = [6 4 24]T [ 6 1]
* [1 -9 8] [ 4 -9]
* [24 8]
*/
var transposed: int[,] = new int[m.GetUpperBound(1) + 1,
m.GetUpperBound(0) + 1];
for (var i: int = 0; i < m.GetUpperBound(0) + 1; i++)
{
for (var j: int = 0; j < m.GetUpperBound(1) + 1; j++)
{
transposed[j, i] = m[i, j];
}
}
return transposed;
}
function upperCaseRandomArray(arr: String[][])
{
var r: Random = new Random();
var i: int = r.Next(0, arr.length - 1);
for (var j: int = 0; j <= arr[i].length - 1; j++)
arr[i][j] = arr[i][j].ToUpper();
}
function printArrayChar(arr: char[])
{
print('\nPrint Array Content ',
arr.GetType().Name.Replace(']', arr.length.ToString() + ']'));
for (var i: int = 0; i <= arr.length - 1; i++)
Console.WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]);
}
function printArrayInt(arr: int[])
{
print('\nPrint Array Content ',
arr.GetType().Name.Replace(']', arr.length.ToString() + ']'));
for (var i: int = 0; i <= arr.length - 1; i++)
Console.WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]);
}
function printArrayString(arr: String[])
{
print('\nPrint Array Content ',
arr.GetType().Name.Replace(']', arr.length.ToString() + ']'));
for (var i: int = 0; i <= arr.length - 1; i++)
Console.WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]);
}
function printMatrix(m: int[,])
{
print('\nPrint Matrix Content ',
m.GetType().Name.Replace('[,]', ''), '[',
(m.GetUpperBound(0) + 1).ToString(),',',
(m.GetUpperBound(1) + 1).ToString(),']');
for (var i: int = 0; i <= m.GetUpperBound(0); i++)
for (var j: int = 0; j <= m.GetUpperBound(1); j++)
Console.WriteLine(' array [{0,2},{1,2}] = {2,2} ', i, j, m[i, j]);
}
function graphJaggedArray(arr: String[][])
{
/* When using Arrays, we can use for(each) instead of for:
* however, for some reason, JScript tries to convert the
* elements of arr to System.Int32 instead of String[]
* so it fails.
*
* for (var s: String[] in arr)
* for (var w: String in s)
*
*/
print('\nPrint Text Content ', arr.GetType().Name);
for (var i: int = 0; i <= arr.length - 1; i++)
{
Console.Write('Line{0,2}|', i+1);
for (var j: int = 0; j <= arr[i].length - 1; j++)
{
Console.Write('{0,3}', '*');
}
print(' (', arr[i].length, ')');
}
}
function printJaggedArray(arr: String[][])
{
var line: System.Text.StringBuilder;
print('\nPrint Jagged Array Content ', arr.GetType().Name);
for (var i: int = 0; i <= arr.length - 1; i++)
{
line = new System.Text.StringBuilder();
for (var j: int = 0; j <= arr[i].length - 1; j++)
line.Append(' ' + arr[i][j]);
if (line.ToString() == line.ToString().ToUpper())
line.Append(' <-- [UPPERCASED]');
print(line);
}
}
function printCommonArrayExceptions(arr: String[][])
{
try
{
arr[100][100] = 'hola';
}
catch (ex: JScriptException)
{
print('\nException: \n',
ex.GetType().Name,'\n', ex.Message);
}
catch (ex: Exception)
{
print('\nException: \n',
ex.GetType().Name,'\n', ex.Message);
}
}
function printTitle(message: String)
{
print();
print('======================================================');
Console.WriteLine('{0,10}', message);
print('======================================================');
}
package JsArrays
{
class Alphabet
{
// Array Field
private var letters: char[];
// No indexer support.
// Getter/Setter Method instead.
public function getItem(index: int): char
{
return this.letters[index];
}
public function setItem(index: int, value: char)
{
this.letters[index] = Char.ToUpper(value);
}
// Read-Only Property
public function get Length(): int {
return this.letters.length;
}
// Constructors
public function Alphabet(size: int)
{
this.letters = new char[size];
}
public function Alphabet(list: String)
{
this.letters = list.ToUpper().ToCharArray();
}
public function Alphabet(list: char[])
{
this.letters = list;
}
// Overridden Method
public function toString(): String
{
return String.Join(',', this.letters, '');
}
// Method
public function slice(start: int, length: int): char[]
{
var result: char[] = new char[length];
for (var i: int = 0, j: int = start; i < length; i++, j++)
{
result[i] = letters[j];
}
return result;
}
}
};
import JsArrays;
function Main() {
// Single-dimensional Array(s)
printTitle('Reverse Array Elements');
// Declare and Initialize Array of Chars
var letters: char[] = new char[5];
letters[0] = 'A';
letters[1] = 'E';
letters[2] = 'I';
letters[3] = 'O';
letters[4] = 'U';
printArrayChar(letters);
var inverse_letters: char[] = reverseChar(letters);
printArrayChar(inverse_letters);
printTitle('Sort Integer Array Elements');
// Declare and Initialize Array of Integers
var numbers: int[] = [ 10, 8, 3, 1, 5 ];
printArrayInt(numbers);
var ordered_numbers: int[] = bubbleSortInt(numbers);
printArrayInt(ordered_numbers);
printTitle('Sort String Array Elements');
// Declare and Initialize and Array of Strings
var names: String[] = [
'Damian',
'Rogelio',
'Carlos',
'Luis',
'Daniel'
];
printArrayString(names);
var ordered_names: 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]
*/
var matrix: int[,] = new int[2,3];
matrix[0,0] = 6; matrix[0,1] = 4; matrix[0,2] = 24;
matrix[1,0] = 1; matrix[1,1] = -9; matrix[1,2] = 8;
print(matrix.GetType().Name);
printMatrix(matrix);
var transposed_matrix: int[,] = 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 array1: new String[] = [ 'word1', 'word2', 'wordN' ];
* var array2: new string[] = [ 'word1', 'word2', 'wordM' ];
* ...
* var text: String[][] = [
* array1,
* array2,
* ...
* ];
*
* 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 Getter/Setter
printTitle('Alphabets');
var vowels: Alphabet = new Alphabet(5);
vowels.setItem(0, 'a');
vowels.setItem(1, 'e');
vowels.setItem(2, 'i');
vowels.setItem(3, 'o');
vowels.setItem(4, 'u');
print('\nVowels = {',
String.Join(',', vowels.getItem(0), vowels.getItem(1),
vowels.getItem(2), vowels.getItem(3),
vowels.getItem(4)), '}');
var en: Alphabet = new Alphabet('abcdefghijklmnopqrstuvwxyz');
print('English Alphabet = {', en.toString(), '}');
print('Alphabet Extract en[9..19] = {',
new Alphabet(en.slice(9, 10)).toString(), '}');
var word1: String = String.Join('', en.getItem(6), en.getItem(14),
en.getItem(14), en.getItem(3));
var word2: String = String.Join('', en.getItem(1), en.getItem(24),
en.getItem(4), en.getItem(4));
var word3: String = String.Join('', en.getItem(4), en.getItem(21),
en.getItem(4), en.getItem(17),
en.getItem(24), en.getItem(14),
en.getItem(13), en.getItem(4));
print('\n', word1, ', ', word2, ', ', word3, '!\n');
Console.Read();
};
Main();
</pre>
<br />
<br />
The output:
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhq59V-FOLgu0dsWuWBGojUPj2bUeaAliWXfzw3t1KlMf27Ups3sQImtaA7jS9IBntUK-eBhyQDDLMZyEttNPiHdSH1iDQli2mFttHjeOQMZ7W9uMFs44pOVen1DyJ1swQVuBpZUTv4A_M/s1599/arrays_indexers_cs+-+Copie.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhq59V-FOLgu0dsWuWBGojUPj2bUeaAliWXfzw3t1KlMf27Ups3sQImtaA7jS9IBntUK-eBhyQDDLMZyEttNPiHdSH1iDQli2mFttHjeOQMZ7W9uMFs44pOVen1DyJ1swQVuBpZUTv4A_M/s1600/arrays_indexers_cs+-+Copie.png" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com0tag:blogger.com,1999:blog-694679611587040520.post-69132533484692559282013-07-16T09:29:00.000-07:002017-04-21T03:29:31.665-07:00Arrays and Indexers in C++/CLI<a class="twitter-share-button" data-count="horizontal" data-via="carlosqt" href="http://twitter.com/share">Tweet</a>
<br />
<br />
Today's post is about Arrays and Indexers in C++/CLI. 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 C++/CLI, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.<br />
<br />
By the way, if you missed my most recent post, "<a href="http://carlosqt.blogspot.be/2013/06/new-series-arrays-and-indexers.html" target="_blank">New Series - Arrays and Indexers</a>", 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#, VB.NET and Oxygene just to compare. <br />
<br />
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.<br />
<br />
Last thing. 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.<br />
<br />
<pre class="brush: cpp">// CppArrays.cpp : main project file.
#include "stdafx.h"
using namespace System;
namespace CppArrays {
static array<wchar_t>^ ReverseChar(array<wchar_t>^ arr) {
array<wchar_t>^ reversed = gcnew array<wchar_t>(arr->Length);
for (int i = 0, j = arr->Length - 1; j >= 0; i++, j--) {
reversed[i] = arr[i];
}
return reversed;
}
static array<int>^ BubbleSortInt(array<int>^ arr) {
int 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;
}
}
}
return arr;
}
static array<String^>^ BubbleSortString(array<String^>^ arr) {
String^ swap = L"";
for (int i = arr->Length - 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 array<int, 2>^ TransposeMatrix(array<int, 2>^ m) {
/* Transposing a Matrix 2,3
*
* A = [6 4 24]T [ 6 1]
* [1 -9 8] [ 4 -9]
* [24 8]
*/
array<int, 2>^ transposed = gcnew array<int, 2>(m->GetUpperBound(1) + 1,
m->GetUpperBound(0) + 1);
for (int i = 0; i < m->GetUpperBound(0) + 1; i++) {
for (int j = 0; j < m->GetUpperBound(1) + 1; j++) {
transposed[j, i] = m[i, j];
}
}
return transposed;
}
static void UpperCaseRandomArray(array<array<String^>^>^ arr) {
Random^ r = gcnew Random();
int i = r->Next(0, arr->Length - 1);
for (int j = 0; j <= arr[i]->Length - 1; j++)
arr[i][j] = arr[i][j]->ToUpper();
}
static void PrintArrayChar(array<wchar_t>^ arr) {
Console::WriteLine(L"\nPrint Array Content {0}",
arr->GetType()->Name->Replace(L"]", arr->Length.ToString() + L"]"));
for (int i = 0; i <= arr->Length - 1; i++)
Console::WriteLine(L" array [{0,2}] = {1,2} ", i, arr[i]);
}
static void PrintArrayInt(array<int>^ arr) {
Console::WriteLine(L"\nPrint Array Content {0}",
arr->GetType()->Name->Replace(L"]", arr->Length.ToString() + L"]"));
for (int i = 0; i <= arr->Length - 1; i++)
Console::WriteLine(L" array [{0,2}] = {1,2} ", i, arr[i]);
}
static void PrintArrayString(array<String^>^ arr) {
Console::WriteLine(L"\nPrint Array Content {0}",
arr->GetType()->Name->Replace(L"]", arr->Length.ToString() + L"]"));
for (int i = 0; i <= arr->Length - 1; i++)
Console::WriteLine(L" array [{0,2}] = {1,2} ", i, arr[i]);
}
static void PrintMatrix(array<int, 2>^ m) {
Console::WriteLine(L"\nPrint Matrix Content {0}[{1},{2}]",
m->GetType()->Name->Replace(L"[,]", L""),
(m->GetUpperBound(0) + 1).ToString(),
(m->GetUpperBound(1) + 1).ToString());
for (int i = 0; i <= m->GetUpperBound(0); i++)
for (int j = 0; j <= m->GetUpperBound(1); j++)
Console::WriteLine(L" array [{0,2},{1,2}] = {2,2} ", i, j, m[i, j]);
}
static void GraphJaggedArray(array<array<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++)
*
*/
Console::WriteLine(L"\nPrint Text Content {0}", arr->GetType()->Name);
int lineCount = 1;
for each (array<String^>^ s in arr) {
Console::Write(L"Line{0,2}|", lineCount);
for each(String^ w in s) {
Console::Write(L"{0,3}", L'*');
}
Console::WriteLine(L" ({0})", s->Length);
lineCount++;
}
}
static void PrintJaggedArray(array<array<String^>^>^ arr) {
System::Text::StringBuilder^ line;
Console::WriteLine(L"\nPrint Jagged Array Content {0}", arr->GetType()->Name);
for (int i = 0; i <= arr->Length - 1; i++) {
line = gcnew System::Text::StringBuilder();
for (int j = 0; j <= arr[i]->Length - 1; j++)
line->Append(L" " + arr[i][j]);
if (line->ToString() == line->ToString()->ToUpper())
line->Append(L" <-- [UPPERCASED]");
Console::WriteLine(line);
}
}
static void PrintCommonArrayExceptions(array<array<String^>^>^ arr) {
try {
arr[100][100] = L"hola";
}
catch (Exception^ ex) {
Console::WriteLine(L"\nException: \n{0}\n{1}",
ex->GetType()->Name, ex->Message);
}
}
static void PrintTitle(String ^message) {
Console::WriteLine();
Console::WriteLine(L"======================================================");
Console::WriteLine(L"{0,10}", message);
Console::WriteLine(L"======================================================");
}
ref class Alphabet {
private:
// Array Field
array<wchar_t>^ letters;
public:
// Indexer Get/Set Property
property wchar_t default[int] {
wchar_t get(int index) { return letters[index]; }
void set(int index, wchar_t value) { letters[index] = Char::ToUpper(value);}
}
// Read-Only Property
property int Length {
int get() { return this->letters->Length; }
}
// Constructors
Alphabet(int size) {
this->letters = gcnew array<wchar_t>(size);
}
Alphabet(String^ list) {
this->letters = list->ToUpper()->ToCharArray();
}
Alphabet(array<wchar_t>^ list) {
this->letters = list;
}
// Overridden Method
virtual String^ ToString() override {
return String::Join(L",", gcnew String(this->letters));
}
// Method
array<wchar_t>^ Slice(int start, int length) {
array<wchar_t>^ result = gcnew array<wchar_t>(length);
for (int i = 0, j = start; i < length; i++, j++) {
result[i] = this[j];
}
return result;
}
};
};
using namespace CppArrays;
int main(array<System::String ^> ^args)
{
// Single-dimensional Array(s)
PrintTitle(L"Reverse Array Elements");
// Declare and Initialize Array of Chars
array<wchar_t>^ letters = gcnew array<wchar_t>(5);
letters[0] = L'A';
letters[1] = L'E';
letters[2] = L'I';
letters[3] = L'O';
letters[4] = L'U';
PrintArrayChar(letters);
array<wchar_t>^ inverse_letters = ReverseChar(letters);
PrintArrayChar(inverse_letters);
PrintTitle(L"Sort Integer Array Elements");
// Declare and Initialize Array of Integers
array<int>^ numbers = { 10, 8, 3, 1, 5 };
PrintArrayInt(numbers);
array<int>^ ordered_numbers = BubbleSortInt(numbers);
PrintArrayInt(ordered_numbers);
PrintTitle(L"Sort String Array Elements");
// Declare and Initialize and Array of Strings
array<String^>^ names = gcnew array<String^> {
L"Damian",
L"Rogelio",
L"Carlos",
L"Luis",
L"Daniel"
};
PrintArrayString(names);
array<String^>^ ordered_names = BubbleSortString(names);
PrintArrayString(ordered_names);
// Multi-dimensional Array (Matrix row,column)
PrintTitle(L"Transpose Matrix");
/* Matrix row=2,col=3
* A = [6 4 24]
* [1 -9 8]
*/
array<int, 2>^ matrix = gcnew array<int, 2>(2, 3) {{ 6, 4, 24 },
{ 1, -9, 8 }};
PrintMatrix(matrix);
array<int, 2>^ transposed_matrix = TransposeMatrix(matrix);
PrintMatrix(transposed_matrix);
// Jagged Array (Array-of-Arrays)
PrintTitle(L"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:
*
* array<array<String^>^>^ text = gcnew array<array<String^>^> {
* gcnew array<String^> { "word1", "word2", "wordN" },
* gcnew array<String^> { "word1", "word2", "wordM" },
* ...
* };
*
* Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"
*
*/
array<array<String^>^>^ text = {
(gcnew String(L"Hoy es el día más hermoso de nuestra vida, querido Sancho;"))->Split(L' '),
(gcnew String(L"los obstáculos más grandes, nuestras propias indecisiones;"))->Split(L' '),
(gcnew String(L"nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;"))->Split(' '),
(gcnew String(L"la cosa más fácil, equivocarnos;"))->Split(' '),
(gcnew String(L"la más destructiva, la mentira y el egoísmo;"))->Split(' '),
(gcnew String(L"la peor derrota, el desaliento;"))->Split(' '),
(gcnew String(L"los defectos más peligrosos, la soberbia y el rencor;"))->Split(' '),
(gcnew String(L"las sensaciones más gratas, la buena conciencia..."))->Split(' ')
};
PrintJaggedArray(text);
UpperCaseRandomArray(text);
PrintJaggedArray(text);
GraphJaggedArray(text);
// Array Exceptions
PrintTitle(L"Common Array Exceptions");
PrintCommonArrayExceptions(nullptr);
PrintCommonArrayExceptions(text);
// Accessing Class Array Elements through Indexer
PrintTitle(L"Alphabets");
Alphabet^ vowels = gcnew Alphabet(5);
vowels[0] = L'a';
vowels[1] = L'e';
vowels[2] = L'i';
vowels[3] = L'o';
vowels[4] = L'u';
Console::WriteLine(L"\nVowels = {{{0}}}",
String::Join(L",", vowels[0], vowels[1], vowels[2], vowels[3], vowels[4]));
Alphabet^ en = gcnew Alphabet(L"abcdefghijklmnopqrstuvwxyz");
Console::WriteLine(L"English Alphabet = {{{0}}}", en);
Console::WriteLine(L"Alphabet Extract en[9..19] = {{{0}}}",
gcnew Alphabet(en->Slice(9, 10)));
String^ word1 = String::Join(L"", en[6], en[14], en[14], en[3]);
String^ word2 = String::Join(L"", en[1], en[24], en[4]);
String^ word3 = String::Join(L"", en[4], en[21], en[4], en[17],
en[24], en[14], en[13], en[4]);
Console::WriteLine(L"\n{0} {1}, {2}!\n", word1, word2, word3);
return 0;
}
</pre>
<br />
<br />
The output:
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhq59V-FOLgu0dsWuWBGojUPj2bUeaAliWXfzw3t1KlMf27Ups3sQImtaA7jS9IBntUK-eBhyQDDLMZyEttNPiHdSH1iDQli2mFttHjeOQMZ7W9uMFs44pOVen1DyJ1swQVuBpZUTv4A_M/s1599/arrays_indexers_cs+-+Copie.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhq59V-FOLgu0dsWuWBGojUPj2bUeaAliWXfzw3t1KlMf27Ups3sQImtaA7jS9IBntUK-eBhyQDDLMZyEttNPiHdSH1iDQli2mFttHjeOQMZ7W9uMFs44pOVen1DyJ1swQVuBpZUTv4A_M/s1600/arrays_indexers_cs+-+Copie.png" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Voilà, that's it. Next post in the following days.
<br />
<br />Carlos Quintanillahttp://www.blogger.com/profile/15415604076909500411noreply@blogger.com1