2d Arrays

classic Classic list List threaded Threaded
5 messages Options
Reply | Threaded
Open this post in threaded view
|

2d Arrays

ngdrummer
Is it possible to do 2d arrays? I'm trying to set up functions that will draw based on position, but I was hoping to draw from a single array to do this. Are 2d arrays possible?
Reply | Threaded
Open this post in threaded view
|

Re: 2d Arrays

cadet1620
Administrator
There is no built-in support for 2-d arrays.  You could write a Matrix class.

The simplest interface would probably be:
    constructor Matrix new(int width, int height);
    method void dispose();
    method void set(int x, int y, int value);
    method int get(int x, int y);
Implementation would use an Array of Arrays to hold the values.

--Mark
Reply | Threaded
Open this post in threaded view
|

Re: 2d Arrays

asaph
Hi,

I'm trying to implement the matrix class suggested above. I created a new class called board, that holds an array of arrays. The problem is I don't know how to access an element within the board (a[i][j] doesn't seems to work), and I wonder if it is at all possible considering that Jack supposedly only knows how to handle 1D arrays. Does anyone figured the correct syntax to do that?

Here's the code, I highlighted the specific line the error occurs at:
   
 constructor Board new(int width, int height){
        var int i,j;
        let a = Array.new(width);
        let i = 0;
        let j = 0;
        while (i < width){
            let a[i] = Array.new(height);
            while (j < height){
                let a[i][j] = 0;
                }
            }
        return this;
        }
Reply | Threaded
Open this post in threaded view
|

Re: 2d Arrays

cadet1620
Administrator
asaph wrote
 constructor Board new(int width, int height){
        var int i,j;
        let a = Array.new(width);
        let i = 0;
        let j = 0;
        while (i < width){
            let a[i] = Array.new(height);
            while (j < height){
                let a[i][j] = 0;
                }
            }
        return this;
        }
You need to use an intermediary Array variable:
    var Array col;
    ...
            let col= a[i];    // a[i,j] = 0
            let col[j] = 0;
In this init code you can do it more efficiently if you move the first let out of the inner loop.

--Mark
Reply | Threaded
Open this post in threaded view
|

Re: 2d Arrays

asaph
Thanks a lot, that solved it!