Rectangular Arrays
Orgoton
orgoton at mindless.com
Sun Feb 25 11:09:19 PST 2007
Another Roadside Attraction Wrote:
> I'm learning D by writing a logic game with a grid-shaped board. If possible, I'd like to use a rectangular array for the board, but I'd like to define the width of the board at runtime when I instantiate the class. Ideally, I'd like to do something like this:
>
> public class Board {
>
> private Piece[,] grid;
>
> public this(uint width) {
> grid = new Piece[width,width];
> }
>
> }
>
> But that doesn't compile. It looks like the dimensions of rectangular arrays has to be known at compile-time. Is that right, or am I missing something?
>
> I've also tried declaring the array as an ordinary multi-dimensional array, but this doesn't compile either:
>
> public class Board {
>
> private Piece[][] grid;
>
> public this(uint width) {
> grid = new Piece[width][width];
> }
>
> }
>
> What's the best way to write this code? As I expand on this project, I plan on incorporating some time-consuming algorithms (think, n-Queens problem), so I'd prefer to use the most efficent data structure possible for the board.
>
> Thanks!!
>
> --ARA
You can declare a variable length array by doing something like
int numbers[];
//in runtime on the program:::
numbers.length=size;
//for bidimensionality:
int table[][]; //or matrix
table.length=HowManyCollumns;
foreache (int[] row, table[]) row.length=HowManyRows; //or the size of the collumn
See also:
http://www.digitalmars.com/d/arrays.html
Specially the dynamic array thingy. This is the best solution I have for you and I belive this one to be the simplest you got so far.
More information about the Digitalmars-d-learn
mailing list