GIGO: words unreadable aloud
Mishrogo Weedapeval
 

 

  Thursday 27 May 2004
Chapter 4, Exercise 19

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 ) );
    }
}

9:09:33 PM   comment/     


Click here to visit the Radio UserLand website. Click to see the XML version of this web page. © Copyright 2007 Doug Landauer .
Last update: 07/2/6; 12:40:02 .
Click here to send an email to the editor of this weblog.

May 2004
Sun Mon Tue Wed Thu Fri Sat
            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31          
Apr   Jun

Previous/Next