generate specific numbers for row and column in java - java

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.

Related

Storing all diagonals from top right to bottom left in array

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.

How to sum rows and columns of a 2D array individually with Java?

Here is the problem I'm working on:
Write a program that reads an 3 by 4 matrix and displays the sum of each
column and each row separately.
Here is the sample run:
Enter a 3-by-4 matrix row by row:
1.5 2 3 4
5.5 6 7 8
9.5 1 3 1
Sum of the elements at column 0 is 16.5
Sum of the elements at column 1 is 9.0
Sum of the elements at column 2 is 13.0
Sum of the elements at column 3 is 13.0
Sum of the elements at Row 0 is: 10.5
Sum of the elements at Row 0 is: 26.5
Sum of the elements at Row 0 is: 14.5
and here is the code that I have come up with:
package multidimensionalarrays;
public class MultidimensionalArrays {
public static void main(String[] args) {
double sumOfRow = 0;
double[][] matrix = new double[3][4];
java.util.Scanner input = new java.util.Scanner(System.in); //Scanner
System.out.println("Enter a 3 by 4 matrix row by row: ");
//Prompt user to enter matrix numbers
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
matrix[row][col] = input.nextDouble();
}
}
double[] sumOfCol =new double[matrix[0].length];
for (int i = 0; i < matrix.length; i++) { //row
for (int j = 0; j < matrix[i].length; j++) { //column
sumOfRow += matrix[i][j];
sumOfCol[j] += matrix[i][j];
}
System.out.println("Sum of the elements at row " + row + " is: " + sumOfRow);
}
System.out.println("Sum of the elements at column " + col + " is: " + sumOfCol);
}
}
My problem is that when it gets to the end to print the sums for columns and rows, it is not recognizing the row or col variables. I've been playing with it and switching things around for probably hours now and I just can't seem to get this right, can someone help me with what I'm doing wrong? Also I don't know if I'm doing the column summing correctly?
In your matrix, it is a 3-by-4 matrix from the code segment double[][] matrix = new double[3][4];. The first index is the row index, and the second index is the column index.
Please note that your double[][] matrix is an array of arrays. Namely, matrix is an array of three arrays of length 4, and by convention, each sub-array can be seen as an array of objects arranged in one row. This is called row major order.
For example, in the array
0 1 2 4
0 1 3 9
0 1 5 15
it is really stored as
matrix[0]: [matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3] and so [0 1 2 4]
matrix[1]: [matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3] and so [0 1 3 9]
matrix[2]: [matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3] and so [0 1 5 25]
Here is a simpler algorithm that uses loops to find the sum of values for each row and column value, but requires two passes:
/* After the prompt code segment and sumOfCol in the main method */
// Row (major index)
for (int row = 0; row < matrix.length; row++) {
int rowSum = 0;
for (int col = 0; col < matrix[row].length; col++) {
rowSum += matrix[row][col];
}
System.out.println("Sum of the elements at row " + row + " is: " + rowSum);
}
// Column (minor index)
// Assuming the length of each row is the same
for (int col = 0; col < matrix[0].length; col++) {
int colSum = 0;
for (int row = 0; row < matrix.length; row++) {
colSum += matrix[row][col];
}
System.out.println("Sum of the elements at col " + col + " is: " + colSum);
}
The output is
Enter a 3 by 4 matrix row by row:
0 1 2 4
0 1 3 9
0 1 5 15
Sum of the elements at row 0 is: 7
Sum of the elements at row 1 is: 13
Sum of the elements at row 2 is: 21
Sum of the elements at col 0 is: 0
Sum of the elements at col 1 is: 3
Sum of the elements at col 2 is: 10
Sum of the elements at col 3 is: 28
The variable counting the rows is called i at the point where you print the row sum.
For the column sums you need another loop to print them one by one.

Creating N by N diagonal matrix using basic logic

I want to create a matrix of size N by N where N is a constant value defined globally, for now I just want to create a matrix where N=6. Where I fall short is I want to make it diagonally, like so:
0 1 2 3 4 5
1 0 1 2 3 4
2 1 0 1 2 3
3 2 1 0 1 2
4 3 2 1 0 1
5 4 3 2 1 0
Currently I have this method:
public static void drawMatrix(){
for (int line = 0; line < N; line++){
for (int j = 0; j < N; j++){
System.out.print(j + " ");
}
System.out.println();
}
}
Unfortunately it's only able to print 0 1 2 3 4 5 in every line, so I suppose I need another nested for-loop, however I'm not sure how to set it up.
j is the column number, so it will be the same for all rows. What you need to do is to add or subtract j from the line number, depending on the line number, in order to make a "shift". Since the result could become negative, you will need to add N and mod by N:
if (j > line) {
System.out.print((N-line+j)%N + " ");
} else {
System.out.print((line-j+N)%N + " ");
}
Demo.
You can also rewrite it without an if using a conditional expression:
int sign = j > line ? -1 : 1;
System.out.print((N+sign*(line-j))%N + " ");
Demo.
A little change in your code works
public static void drawMatrix() {
for(int line = 0; line < N; line++) {
for(int j = 0; j < N; j++) {
System.out.print(Math.abs(line - j) + " ");
}
System.out.println();
}
}
I would do something like :
int n=6;
for(int row=0;row<n;row++)
{
for(int col = 0;col<n;col++)
{
System.out.print(abs(col-row) +" ");
}
System.out.println();
}
assuming you can use abs().
I hoped that help your purpose.
This also works :
public static void main(String[] args) {
int N = 6;
int column = 0;
for (int row = 0; row < N; row++) {
for (column = row; column >= 0; column--) //prints till row number reaches 0
System.out.print(column + " ");
for (column = 1; column < N - row; column++)//from 1 to N-row
System.out.print(column + " ");
System.out.println();
}
}

How to draw a set of horizontal lines?

I am new to OpenGL as learning exercise I decided to draw a set of horizontal lines from a grid of m x n matrix containing the vertices locations
This is what I have
and If I use LINE_STRIP
A code snippet using vertex arrays and indices will be great, I cant seem to be able to get the concept just from a text book I need to see and play with a code example
Any help will be much appreciated!
#Thomas
Got it working with the following code
totalPoints = GRID_ROWS * 2 * (GRID_COLUMNS - 1);
indices = new int[totalPoints];
points = new GLModel(this, totalPoints, LINES, GLModel.DYNAMIC);
int n = 0;
points.beginUpdateVertices();
for ( int row = 0; row < GRID_ROWS; row++ ) {
for ( int col = 0; col < GRID_COLUMNS - 1; col++ ) {
int rowoffset = row * GRID_COLUMNS;
int n0 = rowoffset + col;
int n1 = rowoffset + col + 1;
points.updateVertex( n, pointsPos[n0].x, pointsPos[n0].y, pointsPos[n0].z );
indices[n] = n0;
n++;
points.updateVertex( n, pointsPos[n1].x, pointsPos[n1].y, pointsPos[n1].z );
indices[n] = n1;
n++;
}
}
points.endUpdateVertices();
Then I update and draw by doing
points.beginUpdateVertices();
for ( int n = 0; n < totalPoints; n++ ) {
points.updateVertex( n, pointsPos[indices[n]].x, pointsPos[indices[n]].y, pointsPos[indices[n]].z );
}
points.endUpdateVertices();
This is the result
Fix it by changing the nested for loop
for ( int col = 0; col < GRID_COLUMNS; col++ ) {
for ( int row = 0; row < GRID_ROWS - 1; row++ ) {
int offset = col * GRID_ROWS;
int n0 = offset + row;
int n1 = offset + row + 1;
indices[n++] = n0;
indices[n++] = n1;
}
}
Now I can have any number of rows and columns
Thanks agin!
You need to draw a line for each segment and resuse an index, i.e. for the first part you'd draw a line for (0,1), (1,2), (2,3) and so on.
Edit:
Suppose you have a 4x5 array (4 lines, 5 vertices per line). You could then calculate the indices like this (pseudo code):
Vertex[] v = new Vertex[20]; // 20 vertices in the grid
for(int row = 0; row < numrows; row++) // numrows = 4
{
int rowoffset = row * numcols ; //0, 4, 8, 12
for(int col = 0; col < (numcols - 1); col++) //numcols = 5
{
addLineIndices(rowoffset + col, rowoffset + col +1); //adds (0,1), (1,2), (2,3) and (3, 4) for the first row
}
}
Then issue the draw call for numrows * (numcols - 1) linesegments (GL_LINES), i.e. 16 in the example. Note that addLineIndices would be a function that adds the index pair for one line segment to an index array which is then supplied to the draw call.

switching columns of a 2d array

so my problem is that i cannot get the elements of a 2d array to switch like i would be able to do in a single variable array. Instead of switching the elements they are just being continuously rewritten...
for (int column = 0; column < m[0].length; column++) {
shufcol = (int)(Math.random()*4);
temp = column;
System.out.println(shufcol);
for(int row = 0; row < m.length; row++) {
temp = row;
m[row][temp]=m[row][column];
m[row][column]= m[row][shufcol];
m[row][temp] = m[row][shufcol];
}
}
input array (3X4)
{{0 1 2 3}
{1 4 5 6}
{0 7 8 9}}
output array
{{2 2 3 2}
{5 5 6 5}
{8 8 9 8}}
If your curious about the math.random, that is just to generate a random column between 0 to 3 to switch with. Again the issue is why is it only rewriting elements and not switching them?
I don't fully understand what you want to achieve at the end (because you haven't told), but I think, if you reread this piece of code:
temp = row;
m[row][temp]=m[row][column];
m[row][column]= m[row][shufcol];
m[row][temp] = m[row][shufcol];
several times and try to execute it with piece of paper and pen you'll find the mistake.
If I understood, this will switch the values in column and shufcol for all rows (I didn't test it):
for (int column = 0; column < m[0].length; column++) {
shufcol = (int)(Math.random()*4);
System.out.println(shufcol);
for(int row = 0; row < m.length; row++) {
temp = m[row][shufcol];
m[row][shufcol] = m[row][column];
m[row][column] = temp;
}
}
This will switch elements inside their rows:
//input array (3X4) {{0 1 2 3} {1 4 5 6} {0 7 8 9}}
int[][] m = {{0, 1, 2, 3}, {1, 4, 5, 6}, {0, 7, 8, 9}};
for (int column = 0; column < m[0].length; column++) {
int shufcol = (int)(Math.random()*4);
int shufrow = (int)(Math.random()*3); //need row to switch with, too
for(int row = 0; row < m.length; row++) {
if(row == shufrow){
int tempField =m[row][column];
m[row][column]= m[row][shufcol];
m[row][shufcol] = tempField;
System.out.println("In row " + row + " : column " + column + " was switched with column " + shufcol + "!");
break; //just switch once per row, easier debugging ^^-d
}
}
}
//print output array
for(int row = 0; row < m.length; row++) {
String line = "\n";
for (int column = 0; column < m[0].length; column++) {
line += m[row][column] + " ";
}
System.out.print(line);
}
Output:
In row 2 : column 0 was switched with column 2!
In row 0 : column 1 was switched with column 2!
In row 1 : column 2 was switched with column 3!
In row 0 : column 3 was switched with column 2!
0 2 3 1
1 4 6 5
8 7 0 9
Since i am not totally sure what you want to do, here is switching elements in the whole array randomly:
//input array (3X4) {{0 1 2 3} {1 4 5 6} {0 7 8 9}}
int[][] m = {{0, 1, 2, 3}, {1, 4, 5, 6}, {0, 7, 8, 9}};
for (int column = 0; column < m[0].length; column++) {
int shufcol = (int)(Math.random()*4);
int shufrow = (int)(Math.random()*3); //need row to switch with, too
//there is no point in duplicating the count variable of a loop!
System.out.println(shufcol);
for(int row = 0; row < m.length; row++) {
//check that random field is not current field!
if(row != shufrow && column != shufcol){
//switch current with random
int temp = m[row][column]; // le backuppe
m[row][column] = m[shufrow][shufcol]; // write le new value of "random source field" to current field
m[shufrow][shufcol] = temp; // write value of current field to "random source field"
System.out.println("switched [" + row + "][" + column + "] with [" + shufrow + "]["+ shufcol + "]");
break; // use break to switch only once per row, easier debugging ^^-d
}
else {
System.out.println("will not switch with self!");
}
}
}
//print output array
for(int row = 0; row < m.length; row++) {
String line = "\n";
for (int column = 0; column < m[0].length; column++) {
line += m[row][column] + " ";
}
System.out.print(line);
}
Yielding the following output:
2
switched [0][0] with [2][2]
0
switched [0][1] with [1][0]
0
switched [0][2] with [2][0]
2
switched [0][3] with [1][2]
8 1 0 5
1 4 3 6
2 7 0 9
Hope this helps! ^^-d

Categories