Java 2D Array Issue - java

Hi i'm writing a program thats using 2 dimensional int arrays in java. whenever i try to create the array with two different numbers it throws an ArrayIndex out of bounds.
An Example of this would be...
private int[][] tileMap;
public EditWindow(int rows, int columns, int tileSize){
this.columns = columns;
this.rows = rows;
this.tileSize = tileSize;
addMouseListener(this);
tileMap = new int[rows][columns];
}
If i set rows and columns to be the 10, for example, the code runs flawlessly but as soon as i set it to two different values(10 and 20 for example) it throws An error.
If theres something i didn't explain well or you need more code to understand the question let me know

The code you've posted here is fine. ArrayIndexOutOfBoundsException is normally thrown when you're accessing your array, not creating it. I'd guess that you've got a nested for loop somewhere in your code. Something like:
for (int currRow=0; currRow<this.rows; currRow++)
{
for (int currCol=0; currCol<this.columns; currCol++)
{
do something(tileMap[currRow][currCol]);
}
}
That's the code you need to look at. Make sure that you have your 'currRow' and 'currCol' around the right way, and that you're using the right ones in each place.
If you get your array indices around the wrong way (tileMap[currCol][currRow] instead of tileMap[currRow][currCol]) then you will get just such an exception in every case except where rows == columns (because if they're the same, you'll never try to find a column or row which doesn't exit)

My guess is that you're declaring the array as int[rows][columns], but iterating over it with the row/column values transposed, eg:
for (int row = 0; row < rows; row++)
for (int col = 0; col < columns; col++)
int tile = tileMap[col][row]; // oops - row/col transposed
This situation (or similar) would explain why having the same values doesn't explode, but different values do explode.

Related

Is there ANY way to access the reference of a column in the form of an array from a matrix?

I have been thinking of this for a while, but I couldn't come up with a solution. In java, we can access the reference of a row in a matrix like this:
int [][] matrix = new int[3][4];
int [] toChangeTo = new int[4];
matrix[0] = toChangeTo;
Here, if I will make any changes in matrix[0], it will reflect in the actual matrix. However, there is no such way I could find to access a column. When I looked for some answers online, they were:
int [][] matrix = new int[3][4];
int column = new int[3];
for(int r = 0 ; r < matrix.length ; r++) {
column[r] = matrix[r][0];
}
In this code, column does have the values of the first column of matrix, but it is not its reference. I want a way to access the reference of any column of a matrix and without for loop iterations. Thanks a lot in advance.
int[3][4] means, I'll have a cupboard with three big boxes, then in each box, I'll put four smaller boxes. You can take a whole big box from the cupboard and have it still contain its four sub-boxes; but there's nothing that already contains the first sub-box of each big box, unless you manually rearrange it.
Same thing with Java.
As for any way, we could create a class.
class Column{
private final int[][] data;
private final int column;
public Column( int[][] data, int c ){
this.data = data;
column = c;
}
int get(int i){
return data[i][column];
}
int set(int index, int value){
data[index][column] = value;
}
}
We could add more methods like length etc.
Hey as other mention there is no way you can do that. You can read about how matrix is create in memory. Each row is sequence of memory location horizontally.
If you want to set reference of column to two variable, just store column values in row and row values in column OR take transpose of matrix.

How to switch two columns in a 2 dimensional array?

I am writing a Sudoku code in Java.
I already wrote a code, but instead of columns, rows are switched!
int[] tempField = array2D[myFirstCol_toSwitch];
array2D[myFirstCol_toSwitch] = array2D[mySecondCol_toSwitch];
array2D[mySecondCol_toSwitch] = tempField;
In order to generate a Sudoku board I need to swap columns randomly.
The "rows" and "columns" of a 2D Java array depend on your perspective; i.e. how you are mentally mapping the array into vertical and horizontal.
However, if what you are currently doing in your example is switching the "rows" (per your mental model) then the way to switch "columns" is to iterate over the individual elements; e.g. something like this:
for (int i = 0; i < array2D; i++) {
int tempField = array2D[i][myFirstCol_toSwitch];
array2D[i][myFirstCol_toSwitch] = array2D[i][mySecondCol_toSwitch];
array2D[i][mySecondCol_toSwitch] = tempField;
}
This can be written in other ways that are (arguably) neater. I have chosen this way to make it clear what actually needs to happen to transpose the two columns.
The entries of a column are distributed across all the rows, one item per row. So in order to swap two columns, you have to loop through all the rows and swap the appropriate items in each row, like this:
// ints c1 and c2 are the indices of the columns to be swapped
for (int[] row : array2d){
{
int t = row[c1];
row[c1] = row[c2];
row[c2] = t;
}

How to draw a triangle in a 2D array (Java)

For a class project we need to be able to draw a triangle in a 2D array of chars. Algorithmically I can't work out how to do it.
My current code is this (but it does not work):
public void fill() {
for (int i = 0; i < h; i++) {
double x=h;
while(x<=0){
drawing.setPoint(i, x, myChar);
x=Math.ceil(x/2);
}
}
}
I want the output to look something like this:
....*....
...***...
..*****..
.*******.
*********
We can't use any pre-existing methods or classes that relate to drawing.
Thanks for your help
Based on your drawing, you need 9 columns for 5 rows. So,
int height = 5;
int width = 2*height - 1;
Even though I'm not sure what drawing.setPoint(i, x, myChar); does, I think this example will get you going. I will build a String based on chars.
char fill = '*';
char blank = '.';
I'll start the rows at 0 but the columns at 1 to make the math a little clearer.
For row = 0, ....*.... you need one star in column = 5.
For row = 1, ...***... you need three stars in column = 4,5,6.
For row = 3, .*******. you need seven stars in column = 2,3,4,5,6,7,8.
Notice that for row i you need a star in column j if the distance between the height = 5 and the column j is less than or equal to i. That is, when | height - column | <= row
for (int row = 0; row < height; row ++) {
StringBuilder line = new StringBuilder(width);
for (int column = 1; column <= width; column ++) {
char out = Math.abs(column - height) <= row ? fill : blank;
line.append(out);
}
System.out.println(line);
}
This yields
....*....
...***...
..*****..
.*******.
*********
I assume you can use Math.abs since your example has Math.ceil. If not, you can convert Math.abs to an if statement.
There are lots of ways to tackle this, and you've already seen one answer which draws the picture row-by-row.
I'm going to assume that you've already got routines to create char[][] and to print the characters in that array of arrays to the screen. It looks as if you already have a setPoint() method too, to poke a point into the structure.
As a beginner, I don't think it helps you to be given a solution. You need to be pointed in the right direction to solve it yourself.
Lots of experienced coders now use Test Driven Design, and you could learn from this: start with a simple case, create a test for that, make that test pass, repeat with more tests until there are no more tests to write.
Eventually you should learn a test framework like jUnit, but for now you can "test" by just running your program. So the first test is, does it work for height == 1?
You can pass this test (for now that means, run the program and see that the output looks right) with:
public void drawTriangle(int height) {
drawing.setPoint(0,5,'*')
}
Job done.
Now to make it work for height==2:
public void drawTriangle(int height) {
drawing.setPoint(0,5,'*');
if(height == 2) {
drawing.setPoint(1,4,'*');
drawing.setPoint(1,5,'*');
drawing.setPoint(1,6,'*');
}
}
This still works for height == 1, but also works for height == 2.
But you can immediately see an opportunity for a loop to replace those three commands for the second row. So:
public void drawTriangle(int height) {
drawing.setPoint(0,5,'*');
if(height == 2) {
for(int 4; i<7; i++) {
drawing.setPoint(1,i,'*');
}
}
}
... and you can pull that out into a method:
public void drawTriangle(int height) {
drawing.setPoint(0,5,'*');
if(height == 2) {
drawRow2();
}
}
private void drawRow2() {
for(int 4; i<7; i++) {
drawing.setPoint(1,i,'*');
}
}
This is called refactoring -- writing something that works, but isn't written the best way, testing it to ensure it works, then changing the way it's written one step at a time, so it still works, but in a tidier way.
Hopefully you can see where this is going. You can modify drawRow2() to be more general -- drawRow(int rowNumber), and gradually replace the literal numbers in there with variables derived from rowNumber. Then you can use drawRow(0) to draw the first row, and drawRow(1) to draw the second. Then you can draw a three row triangle by adding drawRow(2), and then you can improve that by using a loop instead.

2 dimensional array & method calls - beginner

I'm currently working on a homework assignment for a beginner-level class and I need help building a program that tests if a sodoku solution presented as an int[][] is valid. I do this by creating helper methods that check both rows, columns and grids.
To check the column I call a method called getColumn that returns a column[]. When I test it out it works fine. I then pass it out on a method called uniqueEntries that makes sure that there are no duplicates.
Problem is, when I call my getColumn method, it returns an array consisting of only one number (for example 11111111, 22222222, 33333333). I have no idea why it does that. Here is my code:
int[][] sodokuColumns = new int[length][length];
for(int k = 0 ; k < sodokuPuzzle.length ; k++) {
sodokuColumns[k] = getColumn(sodokuPuzzle, k);
}
for (int l = 0; l < sodokuPuzzle.length; l++) {
if(uniqueEntries(sodokuColumns[l]) == false) {
columnStatus = false;
}
}
my helper is as follows
public static int[] getColumn(int[][] intArray, int index) {
int[] column = new int[intArray.length];
for(int i = 0 ; i < intArray.length ; i++) {
column[i] = intArray[i][index];
}
return column;
}
Thanks !
You said:
when I call my getColumn method, it returns an array consisting of only one number (for example 11111111, 22222222, 33333333).
I don't see any issue with your getColumn method other than the fact it's not even needed because getColumn(sodokuPuzzle, k) is the same as sodokuPuzzle[k]. If you're going to conceptualize your 2D array in such a way that your first index is the column then for your purpose of checking uniqueness you only need to write a method to get rows.
The issue you're having would seem to be with another part of your code that you did not share. I suspect there's a bug in the logic that accepts user input and that it's populating the puzzle incorrectly.
Lastly a tip for checking uniqueness (if you're allowed to use it) would be to create a Set of some kind (e.g. HashSet) and add all of your items (in your case integers) to that set. If the set has the same size as your original array of items then the items are all unique, if the size differs there are duplicates.

How to check a matrix postion value in java?

Given a matrix filled in with all its values, there's the need of pulling out data randomly in order to create a random matrix (intialized with null values each position). The issue lies while checking if a position (within the randomMatrix) is different from null, as shown below:
public void randomLogic(String[][] givenMatrix){
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
int positioni = this.randInt(0, 1);
int positionj = this.randInt(0, 1);
int x = this.randInt(0, 3);
int y = this.randInt(0, 2);
/*In here lies the reported issue while checking if empty. */
while (!this.randomMatrix[x][y].isEmpty()) {
x = this.randInt(0, 3);
y = this.randInt(0, 2);
this.randomMatrix[x][y] = givenMatrix[positioni][positionj];
}
}
}
}
I've also tried with the following: while(this.randomMatrix[x][y] != null) and the code breaks down right away. All the solving-logic work out as expected (because if I ommit that part it works with flaws but works) the only problem is that validation. Regardless of what position is being evaluated it always stops working.
Is there any other way of checking a matrix position value?
are you trying to pull random values (and consequently, some will be repeated) from a givenMatrix OR do you want to specifically randomize the givenMatrix?
If it's the latter, I would approach it differently.
First of all, gather all values of the givenMatrix in one linear-array or list.
Then, you can randomize this array, and you'll be left with a big array of rows*columns items, with all the values from the original matrix already randomized.
Then, you can systematically fill the new randomized matrix, taking each element of the array in order, till you complete each row and column of the new matrix.
I would choose this approach, because it's easier, and it will finish in a fixed number of steps; rather than filling random positions, because maybe you land 2 times in the same place to fill, and you'll have to randomize until you hit all the spots.
(Also, if you don't care of repeating the values for the new matrix, then instead of taking each element of the randomized array, you can simply pick a random position of this array each time)
Have you declared String[][] randomMatrix as a class level member variable? If you have declared the randomMatrix correctly then the isEmpty() and != null checks should work.

Categories