Today's post is about Arrays and Indexers in Oxygene. 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 Oxygene, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.
By the way, if you missed my most recent post, "New Series - Arrays and Indexers", check it out. It has more details about the following program, and a bunch of definitions for the concepts used on this, and the following, posts. Or you can check my previous posts about arrays in C# and VB.NET just to compare.
I encourage you to copy the code below and try it yourself, normally, all programs you find in this blog are source code complete, just paste it on your IDE and run it. You can get a Oxygene Trial version with IDE support, or get the Free Command Line version and run it from the console.
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.
namespace OxygeneArrays;
interface
type
Program = class
public
class method Main(args: array of String);
class method ReverseChar(arr: array of Char): array of Char;
class method BubbleSortInt(arr: array of Integer): array of Integer;
class method BubbleSortString(arr: array of String): array of String;
class method TransposeMatrix(m: array[0..,0..] of Integer): array[0..,0..] of Integer;
class method UpperCaseRandomArray(arr: array of array of String);
class method PrintArrayChar(arr: array of Char);
class method PrintArrayInt(arr: array of Integer);
class method PrintArrayString(arr: array of String);
class method PrintMatrix(m: array[0..,0..] of Integer);
class method GraphJaggedArray(arr: array of array of String);
class method PrintJaggedArray(arr: array of array of String);
class method PrintCommonArrayExceptions(arr: array of array of String);
class method PrintTitle(message: String);
end;
type
Alphabet = public class
private
// Array Field
var letters: array of Char;
public
// Read-Only Property
property Length: Integer read letters.Length;
// Indexer Get/Set Property
property Item[idx: Integer]: Char read GetItem write SetItem; default;
method GetItem(idx: Integer): Char;
method SetItem(idx: Integer; value: Char);
// Constructors
constructor(size: Integer);
constructor(list: String);
constructor(list: array of Char);
// Overriden Method
method ToString: String; override;
// Method
method Slice(start: Integer; len: Integer): array of Char;
end;
*)
implementation
class method Program.Main(args: array of String);
var
// Declare Array of Chars
letters, inverse_letters: array of Char;
// Declare Array of Integers
numbers, ordered_numbers: array of Integer;
// Declare Array of String
names, ordered_names: array of String;
// Declare Matrix
transposed_matrix: array[0.., 0..] of Integer;
// other vars
word1,word2,word3: String;
begin
// Single-dimensional Array(s)
PrintTitle('Reverse Array Elements');
// Initialize Array of Chars
letters := new Char[5];
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');
// Declare and Initialize Array of Integers
numbers := [ 10, 8, 3, 1, 5 ];
PrintArrayInt(numbers);
ordered_numbers := BubbleSortInt(numbers);
PrintArrayInt(ordered_numbers);
PrintTitle('Sort String Array Elements');
// Initialize and Array of Strings
names := [
'Damian',
'Rogelio',
'Carlos',
'Luis',
'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
var matrix: array[0..1, 0..2] of Integer := [ [ 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:
*
* var text: array of array of String := [
* [ 'word1', 'word2', 'wordN' ],
* [ 'word1', 'word2', 'wordM' ],
* ...
* ];
*
* Text extract from: 'El ingenioso hidalgo don Quijote de la Mancha'
*
*)
var text: array of array of 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(Nil);
PrintCommonArrayExceptions(text);
// Accessing Class Array Elements through Indexer
PrintTitle('Alphabets');
var vowels: Alphabet := new Alphabet(5);
vowels[0] := 'a';
vowels[1] := 'e';
vowels[2] := 'i';
vowels[3] := 'o';
vowels[4] := 'u';
Console.WriteLine(''#10'Vowels = {{{0}}}',
String.Join(',', vowels[0], vowels[1], vowels[2], vowels[3], vowels[4]));
var en: Alphabet := new Alphabet('abcdefghijklmnopqrstuvwxyz');
Console.WriteLine('English Alphabet = {{{0}}}', en.ToString);
Console.WriteLine('Alphabet Extract en[9..19] = {{{0}}}',
new Alphabet(en.Slice(9, 10)));
word1 := String.Join('', en[6], en[14], en[14], en[3]);
word2 := String.Join('', en[1], en[24], en[4]);
word3 := String.Join('', en[4], en[21], en[4], en[17],
en[24], en[14], en[13], en[4]);
Console.WriteLine(''#10'{0} {1}, {2}!'#10'', word1, word2, word3);
Console.Read;
end;
class method Program.ReverseChar(arr: array of Char): array of Char;
var
reversed: array of Char;
i: Integer;
begin
i := 0;
reversed := new Char[arr.Length];
for j: Integer := arr.Length - 1 downto 0 do
begin
reversed[i] := arr[j];
i := i + 1;
end;
result := reversed;
end;
class method Program.BubbleSortInt(arr: array of Integer): array of Integer;
var
swap: Integer;
begin
swap := 0;
for i: Integer := arr.Length - 1 downto 1 do
begin
for j: Integer := 0 to i - 1 do
begin
if arr[j] > arr[j + 1] then
begin
swap := arr[j];
arr[j] := arr[j + 1];
arr[j + 1] := swap;
end;
end;
end;
result := arr;
end;
class method Program.BubbleSortString(arr: array of String): array of String;
var
swap: String;
begin
swap := '';
for i: Integer := arr.Length - 1 downto 1 do
begin
for j: Integer := 0 to i - 1 do
begin
if arr[j][0] > arr[j + 1][0] then
begin
swap := arr[j];
arr[j] := arr[j + 1];
arr[j + 1] := swap;
end;
end;
end;
result := arr;
end;
class method Program.TransposeMatrix(m: array[0..,0..] of Integer): array[0..,0..] of Integer;
var
transposed: array[0..,0..] of Integer;
begin
(* Transposing a Matrix 2,3
*
* A = [6 4 24]T [ 6 1]
* [1 -9 8] [ 4 -9]
* [24 8]
*)
transposed := new Integer[m.GetUpperBound(1) + 1,
m.GetUpperBound(0) + 1];
for i: Integer := 0 to m.GetUpperBound(0) do
begin
for j: Integer := 0 to m.GetUpperBound(1) do
begin
transposed[j, i] := m[i, j];
end;
end;
result := transposed;
end;
class method Program.UpperCaseRandomArray(arr: array of array of String);
var
r: Random;
i: Integer;
begin
r := new Random;
i := r.Next(0, arr.Length - 1);
for j: Integer := 0 to arr[i].Length - 1 do
begin
arr[i][j] := arr[i][j].ToUpper;
end;
end;
class method Program.PrintArrayChar(arr: array of Char);
begin
Console.WriteLine(''#10'Print Array Content {0}',
arr.GetType.Name.Replace(']', arr.Length.ToString + ']'));
for i: Integer := 0 to arr.Length - 1 do
begin
Console.WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]);
end;
end;
class method Program.PrintArrayInt(arr: array of Integer);
begin
Console.WriteLine(''#10'Print Array Content {0}',
arr.GetType.Name.Replace(']', arr.Length.ToString + ']'));
for i: Integer := 0 to arr.Length - 1 do
begin
Console.WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]);
end;
end;
class method Program.PrintArrayString(arr: array of String);
begin
Console.WriteLine(''#10'Print Array Content {0}',
arr.GetType.Name.Replace(']', arr.Length.ToString + ']'));
for i: Integer := 0 to arr.Length - 1 do
begin
Console.WriteLine(' array [{0,2}] = {1,2} ', i, arr[i]);
end;
end;
class method Program.PrintMatrix(m: array [0 .. ,0 .. ] of Integer);
begin
Console.WriteLine(''#10'Print Matrix Content {0}[{1},{2}]',
m.GetType.Name.Replace('[,]', ''),
(m.GetUpperBound(0) + 1).ToString,
(m.GetUpperBound(1) + 1).ToString);
for i: Integer := 0 to m.GetUpperBound(0) do
begin
for j: Integer := 0 to m.GetUpperBound(1) do
begin
Console.WriteLine(' array [{0,2},{1,2}] = {2,2} ', i, j, m[i, j]);
end;
end;
end;
class method Program.GraphJaggedArray(arr: array of array of String);
var
lineCount: Integer;
begin
(* When using Arrays, we can use foreach instead of for:
*
* for i: Integer := 0 to arr.Length - 1 do
* for j: Integer := 0 to arr.Length - 1 do
*
*)
Console.WriteLine(''#10'Print Text Content {0}', arr.GetType.Name);
lineCount := 1;
for each s: array of String in arr do
begin
Console.Write('Line{0,2}|', lineCount);
for each w: String in s do
begin
Console.Write('{0,3}', '*');
end;
Console.WriteLine(' ({0})', s.Length);
lineCount := lineCount + 1;
end;
end;
class method Program.PrintJaggedArray(arr: array of array of String);
var
line: System.Text.StringBuilder;
begin
Console.WriteLine(''#10'Print Jagged Array Content {0}', arr.GetType.Name);
for i: Integer := 0 to arr.Length - 1 do
begin
line := new System.Text.StringBuilder;
for j: Integer := 0 to arr[i].Length - 1 do
begin
line.Append(' ' + arr[i][j]);
end;
if line.ToString() = line.ToString.ToUpper then
begin
line.Append(' <-- [UPPERCASED]');
end;
Console.WriteLine(line);
end;
end;
class method Program.PrintCommonArrayExceptions(arr: array of array of String);
begin
try
arr[100][100] := 'hola';
except
on ex: Exception do
Console.WriteLine(''#10'Exception: '#10'{0}'#10'{1}',
ex.GetType().Name, ex.Message);
end;
end;
class method Program.PrintTitle(message: String);
begin
Console.WriteLine;
Console.WriteLine('======================================================');
Console.WriteLine('{0,10}', message);
Console.WriteLine('======================================================');
end;
// Indexer Get/Set Property
method Alphabet.GetItem(idx: Integer): Char;
begin
result := self.letters[idx];
end;
method Alphabet.SetItem(idx: Integer; value: Char);
begin
self.letters[idx] := Char.ToUpper(value);
end;
// Constructors
constructor Alphabet(size: Integer);
begin
self.letters := new Char[size];
end;
constructor Alphabet(list: String);
begin
self.letters := list.ToUpper.ToCharArray;
end;
constructor Alphabet(list: array of Char);
begin
self.letters := list;
end;
// Overridden Method
method Alphabet.ToString: String;
begin
result := String.Join(',', self.letters);
end;
// Method
method Alphabet.Slice(start: Integer; len: Integer): array of Char;
var
res: array of Char;
i, j: Integer;
begin
res := new Char[len];
j := start;
for i := 0 to len - 1 do
begin
res[i] := self[j];
j := j + 1;
end;
result := res;
end;
end.
The output:
Voilà, that's it. Next post in the following days.

No comments:
Post a Comment