How to switch two columns in a 2 dimensional array? - java

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

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 set value of cell in List<int[][]>?

I have a list List<int[][]> orgnisms = new ArrayList<>();, which I have populated a few empty (only 0 values) tables and I want to set the value of certain cells now. For example, I want the first table from list and cell [1][1] to have a value of 1. How do I accomplish that?
EDIT:
I have a problem because orgnisms.get(0)[1][1] = 1; adds the value 1 to each table in list, not only table which has index 0...
Here is my code to generate a new empty multi-dimensional array which then gets added to the orgnisms list:
private void newEmptyArrays(){
int[][] emptyTable = new int[n][n];
for( int[] ii : emptyTable)
for (int i : ii)
i = 0;
for(int i=0;i<mi;i++)
orgnisms.add(emptyTable);
}
The same 'table' is being added multiple times to the list, but it is just the only one 'table' that was created in following code part (original problem, not the solution):
int[][] emptyTable = new int[n][n];
for(int i=0;i<mi;i++)
orgnisms.add(emptyTable);
since there is only one instance multiple times, there is no difference by which index of the list the table is being changed. orgnism.get(0) is the same (instance) as orgnism.get(1) and so on...
Solution: create a new 'table' for each entry in the list:
for(int i=0;i<mi;i++) {
int[][] emptyTable = new int[n][n];
orgnisms.add(emptyTable);
}
and just a note, the assignment in following code part is not changing the value inside the array - it wouldn't work to clear an array:
for (int i : ii)
i = 0; // this only changes the value of the variable,
// not of the array entry (not written back)
List<int[][]> orgnisms = new ArrayList<>();
each element within the list is a multi-dimensional array, hence if you want to access any of them you'll first need to retrieve it through the List#get method then perform some operations on it i.e
orgnisms.get(0)[1][1] = 1;
orgnisms.get(0) will retrieve the reference to the multi-dimensional array, then [1][1] will index into row 1 and column 1 of the retrieved multi-dimensional array and assign a value 1 to it.
Update
I have a problem because orgnisms.get(0)[1][1] = 1; adds the value 1
to each table in list, not only table which has index 0...
Look carefully at your last loop, you're storing multiple references to the same multi-dimensional array within the orgnisms list thus it makes sense for such behavior to happen.
Also, as per your update, the code is not doing what you think it's. In fact, the nested for loops are not doing anything to the emptyTable multi-dimensional array. However, by default, all the arrays inside emptyTable have a value of 0 set to each element anyway, meaning attempting to set them to 0 again is redundant.
That said, you can change your method accordingly:
private void newEmptyArrays(){
for(int i = 0; i < mi ; i++){
int[][] emptyTable = new int[n][n];
orgnisms.add(emptyTable);
}
}

how to use convert model of Jtable

I have a jTable and I want to delete selected rows:
for( int i=0; i<selectedRows.length ; i++){
defaultablemodel.removeRow( selectedRows[i] - i);
int viewRowIndex = jTableMyTable.convertRowIndexToView(i); <<--- convert it here?
}
I searched around and most suggestions whenever delete rows, we should convert row index to view. Is the above correctly implemented?
I hit this problem because after i sorted my rows, i am unable to delete the row sometimes. but after sorting again i am able to delete a row. So i believe I need to use this convertRowIndexToView method.
You should actually be using
convertRowIndexToModel - Maps the index of the row in terms of the view to the underlying TableModel. If the contents of the model are not sorted the model and view indices are the same.
You have your selected rows, which are the selected indices in the view. So you need to convert those indices to the model indices before deleting.
When you use convertRowIndexToView, you're actually doing the opposite, trying to convert the model index to the table index.
" Is the above correctly implemented?"
First thing, when you want to remove rows this way, you should be traversing the indices backwards, from the last row up. The reason is that when you remove a row, the indices change. So you loop should go backwards like
int [] selectedRows = table.getSelectedRows();
for (int i = selectedRows.length - 1; i >= 0; i--) {
int viewIndex = selctedRows[i];
int modelIndex = table.convertRowIndexToModel(viewIndex);
model.removeRow(modelIndex);
}
The point is you want to remove the highest index first and work your way down to the lower indices.

Initialize 2D arrayList with specified number of columns but not rows?

I want to make a 2D ArrayList, with the number of columns already specified but not the rows.
For example, I want to create a table with 26 columns and 0 or 1 columns at first, then after each loop of doing something else, the number of rows will increase along with that loop.
When I increase the number of rows (length of an ArrayList of ArrayLists), I also want all 26 arrays to increase as well. What is the syntax for it?
And how would I index into, or add a new item into a specific location - say array[2][3] = item?
BTW this is a DFSA table converted from a NFSA table
You could have a list of lists, essentially something like so:
List<List<String>> table = new ArrayList<List<String>>();
Then add the 26 columns:
for(int i = 0; i < 26; i++)
{
table.add(new ArrayList<String>());
}
You can then have a method, called, say, addToColumn(int column, String value, List<List<String>> table) in which you do something like so:
for(int i = 0; i < table.size(); i++)
{
if(i == column)
{
table.get(i).add(value);
}
else
{
table.get(i).add("");
}
}
This should allow you to have lists which grow together. Of course, my assumption in the above is that you will be entering one element at a time.
Alternatively, you can do something like so:
public void addToColumns(Map<int, String> data, List<List<String>> table)
{
for(int key : data.keyset())
{
table.get(key).add(data.get(key));
}
for(int i = 0; i < table.size(); i++)
{
if(!data.containsKey(i))
{
table.get(i).add("");
}
}
}
The above algorithm should allow you to add items to multiple columns, while filling the rest up with empty strings. This should allow you to end up with rows of equal length. Also, the map will be used to store a key-value pair where the key is the column number, and the value will be whatever string you would like to throw in there. This will allow you to populate your table one row at a time.
You can simply create an array by giving only the number of rows:
int[][] array = new int[4][];
Now you may treat your array as the transpose of what you have defined so if you want to enter an element at 3rd column of 2nd row you can enter as transpose i.e.
array[3][2]=5;

Java 2D Array Issue

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.

Categories