The following segment of code is from a system that generates a 5 by 5 grid of JButtons. I need to iterate over an ArrayList of JButtons and pass the row and column of the JButton into the ButtonListener's constructor. The way the code is currently shown below works, but I was wondering if I could clean up the code at all or re-factor in any way. I seem to have a lot of instructions for trying to construct a grid.
int row = 1, col = 1;
for (JButton curButton : view.getButtons()) {
curButton.addActionListener(new ButtonListener(row, col));
row++;
if (row > 5) {
row = 1;
col++;
}
}
Is there any way I can improve the quality or simplify the above code segment?
int iterator = 0;
for (JButton curButton : view.getButtons()) {
curButton.addActionListener(new ButtonListener(iterator%5 + 1, iterator/5 + 1));
iterator++;
}
Note here that I'm using integer division, which always rounds down. iterator/5 + 1 will map {0,1,2,3,4,5,6,...} to {1,1,1,1,1,2,2...}
Can't you have:
col = row = 5;
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
curButton.addActionListener(new ButtonListener(i, j));
}
}
Might have to make col and row 6 or make i and j start at a different number.
Related
I am trying to store all of the values in the matrix from the top right to the bottom left and store them in an array.
int matrixSample [][] = {
{6,4,1,4},
{7,5,4,4},
{4,4,8,3},
{4,4,8,3}
};
The output should be
[4,1,4,4,4,3,6,5,8,3,7,4,8,4,4,4]
I can get the bottom right diagonal
static int[] getAllDiagonalsInMatrix(int matrix[][]){
// Sum of arithmetic progression
int diagonal[] = new int[matrix.length * (matrix.length + 1)*2];
int index = 0;
for(int row = 0; row < matrix.length; row++) {
for(int col = 0; col < matrix[row].length - row; col++) {
diagonal[index++] = matrix[row + col][col];
}
}
return diagonal;
}
Is this even possible to do using the same two loops by adjustments made in the loops above?
Okay, here is my thought process on your problem. However, I'm going to print values instead of collecting them to make it a little easier on me and keep the solution easy to read.
First, how do you get a diagonal? We need to do this frequently so lets start by making a function for that. Maybe we could pass in the top left corner of the diagonal and go from there.
public void getDiagonal(int[][] array, int row, int col) {
// While row and col are within the bounds of the array
while (row < array.length && col < array[row].length) {
// Print element in diagonal
System.out.println(array[row][col]);
// Diagonal moves from top-left to bottom-right
row++;
col++;
}
}
Now that we have a function to get a diagonal, we just need a way to call it. Essentially, we just need to follow an L shape going from the top-right to the top-left to the bottom-left.
// Get diagonals starting in the first row with a column > 0
for (int col = array.length - 1; col > 0; col--) {
getDiagonal(array, 0, col);
}
// Get all diagonals starting from the left most column
for (int row = 0; row < array.length; row++) {
getDiagonal(array, row, 0);
}
Now that we have a working way to iterate through the values, we can rewrite it to save the values into an array instead. You could also choose to remove the function entirely now that you have a process.
Edit: I almost forgot, but the mathematical solution you were looking for is as follows.
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array.length; col++) {
// Index along diagonal
int diagonal = Math.min(row, col);
// Which part of L contains value
if (col >= row) {
int start = array.length - 1 - (col - row);
int passed = start * (start + 1) / 2;
solution[passed + diagonal] = array[row][col];
} else {
int start = array.length - 1 - (row - col);
int passed = array.length * array.length - 1 - start * (start + 1) / 2; solution[passed - array.length + 1 + row] = array[row][col];
}
}
}
One solution is to iterate through a matrix where you consider positions outside of the matrix, but exclude every index out of bounds.
static int[] getDiagonals(int[][] mat) {
int diagonal[] = new int[mat.length * (mat[0].length)];
int index = 0;
int yStart = -mat[0].length;
for (int y = yStart; y < mat.length; y++) {
for (int x = 0; x < mat[0].length; x++) {
if (y + x >= 0 && y + x < mat.length) {
diagonal[index++] = mat[y+x][x];
}
}
}
return diagonal;
}
Might not be optimal as you are effectively traversing a matrix nearly twice the size, but it is pretty intuitive.
i want to write a code that makes a specific numbers in the loop .
for example generate numbers like this :
column 1 - row 1
column 1 - row 2
column 1 - row 3
and then generate this ( for example):
column 2 - row 1
column 2 - row 2
column 2 - row 3
column 2 - row 4
is there any way to write this Algorithm ? thank you so much
code , i have a code like this but i want to manage it :
boolean[][] mapEq = new boolean[mapWidth][mapHeight];
int free = mapWidth * mapHeight;
int randomFree = ((int) (free * Math.random()));
int x = 0, y = 0;
for (int i = 0, k = 0; i < mapWidth; i++) {
for (int j = 0; j < mapHeight; j++) {
if (!mapEq[i][j]) {
if (k == randomFree) {
x = i;
y = j;
break SearchRandom;
} else {
k++;
}
}
}
}
it creat a random thing but i want to make a specific number for example
for column 1 - row 1 and row 2 and row 3
and for column 2 - row 1 and row 2 and row 3 and row 4
Maybe something like this?
int[] columnLengths = {3, 4}; // Lengths of the columns
for(int i = 0; i < columnLengths.length; i++) { // Loop the columns
for(int j = 0; j < columnLengths[j]; j++) { // Loop the rows
System.out.println("column " + i + " - row " + j);
}
}
I am really not sure what you are trying to make, but this is what I understood.
I have 2 images and each is partial of a complete image, and the 2 combined could create the complete image.
However there is overlap on the 2 images, and I am trying to create a program that will find where the top row of image2 meets whichever row of pixels in image 1.
I created a for loop to gather each row of pixels per image in an array.
this is my code:
int row = 0;
for (int i = 0; i < imageArray1.length; i++) {
for (int j = 0; j < imageArray1[i].length; j++) {
if (imageArray1[i][j] == (imageArray2[0][0])) {
row = imageArray1[i][j];
}
}
}
the problem is I am pretty sure I am only gathering a with the individual pixel that is top left of the second image, rather than the whole row.
Any ideas how to get around this?
new to java
You need to cross check each rows in image1 against each rows in image2. Therefore, 3 levels of looping: 1) loop through the rows in image1 2) loop through the rows in image2 3) loop through the columns in the current row in image1 and image2 to decide if they are overlapping
int overlappingRowInImage1 = 0;
int overlappingRowInImage2 = 0;
int[][] imageArray1 = null;
int[][] imageArray2 = null;
// loop through the rows in the first image
for (int row1 = 0; row1 < imageArray1.length; row1++) {
boolean foundIdenticalRow = false;
// loop through the rows in the second image
for (int row2 = 0; row2 < imageArray2.length; row2++) {
foundIdenticalRow = true;
// two rows are identical if each column in both rows are the same
for (int col = 0; col < imageArray1[row1].length; col++) {
if (imageArray1[row1][col] != (imageArray2[row2][col])) {
foundIdenticalRow = false;
break;
}
}
if (foundIdenticalRow) {
overlappingRowInImage1 = row1;
overlappingRowInImage2 = row2;
break;
}
}
if (foundIdenticalRow) {
System.out.println("Row " + overlappingRowInImage1 + " in image 1 is overlapping with Row " +
overlappingRowInImage2 + " in image 2");
break;
}
}
You need to fix the imageArray2[0][0] so it's always comparing with the first index of imageArray2 only. You need to iterate your imageArray2 along with imageArray1 for full comparison. For this I would suggest you to use a nested for loop for imageArray2.
Please give me a hand to tell me why second for loop 'row' could not be found in the printSeating Method.
public void printSeating()
{
for (int row = FIRST_ROW_NUMBER; row <= firstClass.length; row++)
{
if (row < 10)
System.out.print(" ");
System.out.print(row);
System.out.println(":" + firstClass[row - FIRST_ROW_NUMBER]);
}
int firstEconomyRowNumber = FIRST_ROW_NUMBER + firstClassRowCount;
int lastEconomyRowNumber = firstEconomyRowNumber + economyRowCount - 1;
for (int row = firstEconomyRowNumber;
row <= lastEconomyRowNumber; row++);
{
if (row < 10)
System.out.print(" ");
System.out.print(row);
System.out.println(":" + economy[row - firstEconomyRowNumber]);
}
}
When declaring the FOR loop, you put a semicolon after the loop, like this:
for (int row = firstEconomyRowNumber;
row <= lastEconomyRowNumber; row++);{
//..insert code here
}
This declares a FOR loop without a body, so when you access the variable row after this statement, it cannot find the variable because it can only be used in the non-existent body of the FOR loop. To fix this, you would need to delete the semicolon, like so:
for (int row = firstEconomyRowNumber;
row <= lastEconomyRowNumber; row++){
//...insert code here
}
This is your error.
for (int row = firstEconomyRowNumber;
row <= lastEconomyRowNumber; row++);
get rid of that ; after the for loop and it should work.
I am just curious as to how that is done. I am writing a small program to get a better understanding of two dimensional arrays. I want to know how I can go though each row and then each column separately using for loops.
Lets say I have a 2D array that is made out of different letters. I want to go through each row and each column and check if a certain letter is there. Then I want it to print how many occurrences of this letter happened in each row and then each column.
First index is row and second index is column.
Assuming that the something[][] is an something[] of something-rows (that is something[i] gives us a row, not a column - if it'S the way round, just change the examples):
public static void loopExample (String[][] someTwoDimArray) {
// Looping rows
for (var row = 0 ; row < someTwoDimArray.length ; row++) {
for (var col = 0 ; col < someTwoDimArray[0].length ; col++) {
System.out.println(someTwoDimArray[row][col]);
}
}
// looping columns
for (var col = 0 ; col < someTwoDimArray[0].length ; col++) {
for (var row = 0 ; row < someTwoDimArray.length ; row++) {
System.out.println(someTwoDimArray[row][col]);
}
}
}
I don't know if the first or second index is considered rows or columns, but this is a pretty standard nested loop for iterating over every element of a 2d array.
for(int column = 0; column < array.length(); ++column) {
for(int row = 0; row < array[column].length(); ++row) {
// do stuff to array[column][row]
}
}
Given your update, let's look for the letter 'N', in a 2d char array called myLetters.
int counter = 0;
for(int i = 0; i < myLetters.length(); ++i) {
for(int j = 0; j < myLetters[i].length(); ++j) {
if('N' == myLetters[i][j]) {
++counter;
}
}
}
System.out.println("N occurs " + counter + " times.");
if you have a 2D array if you want to access each cell you will have to use a nested for loop.
eg:
for(int i = 0; i < length1; i++)
for(int j = 0; j<length2; j++){
// do something
to format column first do array[i][j] = //do something
to format row first do array[j][i] = // do something
}
"I tried using a for loop however i dont have a good understanding of for loops and i was wondering how not just go through array in its entirety but small bits like rows and columns"
A for loop is a java control flow statement. It lets you initialize a variable (i and j) it gives you a condition (i
int i = 0
while (i < length1){
//do something
i++
}
if working with arrays for loops are almost always required.