browncatmegazord
browncatmegazord

Reputation: 1

Reading input into an int 2D array with varying number of columns per row

So we just had a small practical exam which required us to read in inputs in the following format as rules of a nonogram question. The actual algorithm wasn't difficult to do at all, but none of me and my mates could figure out how to even scan these inputs at all to begin with.

4 4

1 1
1 2 3
1
1

0
2
1 1
2 2

*actual 4x4 grid here*

The first two integers indicate the number of rows (4) and number of columns. (4) So the next four lines indicate the rules for each row (1 2 3 for row 2) and the next four indicate the rules for each column (2 2 for column 4) and so on.

After a semester doing C, we've only dealt with arrays where each row had the same number of columns, and four weeks into this Java module has not taught us to deal with this kind of problem at all.

It would have been easy enough to scan an array as such using nextInt() and a double for loop, but without the zeroes we were all out of luck with this one.

1 1 0
1 2 3
1 0 0 
1 0 0

The exam's over and all but I'm really annoyed at not knowing how to solve this problem. Would appreciate some insight from you guys.

Upvotes: 0

Views: 1022

Answers (1)

Tobias G
Tobias G

Reputation: 583

In Java you can have multidimensional arrays with different lengths.

Try this:

int rows = 4; // read
int cols = 4; // read

int[][] arr = new int[rows][]; // notice how we do not tell the cols here
for(int i=0,i<arr.length;i++){
    // read line or somehow get the numbers of the line into an array
    String line = ...
    String[] splitLine = line.split(" ");
    int[] rowArr = new int[splitLine.length];
    for(int x=0;x<splitLine.length;x++){
        // assume no NumberFormatException
        rowArr[x] = Integer.parseInt(splitLine[x]);
    }
    arr[i] = rowArr;
}

then you have your array with 4 rows, but only as much columns as you need per row:

{{1, 1}, {1, 2, 3}, {1}, {1}}

This works, because in Java, multidimensional arrays are just an array of references to arrays.

Upvotes: 1

Related Questions