A simple 2D array exercise. I ran into (I think) a Scala compiler
bug, but worked around it by declaring arDbl, my own
Array[Double] class. (Here are THECLAPP's Java and Lisp solutions.)
And here's my Scala solution:
class arDbl {
var ar : Array[Double] = _;
def length = ar.length;
def apply( i: Int ) = ar(i);
def update( i:Int, nv: Double) = ar.update(i, nv );
def this( sz: Int ) = {
this();
ar= new Array[Double]( sz );
}
};
class ar2D {
var ard : Array[ arDbl ] = _;
def length = ard.length;
def apply( i: Int ) = ard(i);
def update( i:Int, j:Int, nv:Double ) = {
ard(i).update(j, nv );
}
def this( rows:Int, cols: Int ) = {
this();
ard= new Array[ arDbl ]( rows );
for( val j <- Iterator.range(0, rows) ) {
ard(j) = new arDbl(cols);
}
}
};
object c4x19 {
def create ( rows:Int, cols:Int, start:Double, end:Double )
: ar2D = {
var ar = new ar2D( rows, cols );
var current = start;
var step = (end - start) / (rows * cols -1);
for( val j <- Iterator.range( 0, rows ) ) {
var curr_row = ar(j);
for( val i <- Iterator.range( 0, cols ) ) {
curr_row.update( i, current);
current = current + step;
}
}
ar
}
def print ( ar : ar2D ) = {
var rows = ar.length;
var cols = ar(0).length; // assumes a non-empty rectangular array
for( val i <- Iterator.range( 0, rows ) ) {
for( val j <- Iterator.range( 0, cols ) ) {
Console.print( ar(i)(j) + " " );
}
Console.println("");
}
}
def main (args: Array[String] ) = {
Console.println("--> create( 3, 3, 1.0, 10.0 )" );
print( create( 3, 3, 1.0, 10.0 ) );
Console.println("");
Console.println("--> create( 3, 4, 1.0, 20.0 )" );
print( create( 3, 4, 1.0, 20.0 ) );
Console.println("");
Console.println("--> create( 5, 5, -10.0, 10.0 )" );
print( create( 5, 5, -10.0, 10.0 ) );
}
}