Trouble filling 2D array with values obtained from method - java

I'm having trouble filling a matrix with values I get by iterating through a method. I want to use a 3x3 matrix and then fill it with the values I obtain by iterating my method from 0 to 8. My idea was a for-loop but it does not work unfortunately. I would be glad if someone could help or has a link where I can look that up.
int[][] matrix = new int[3][3];
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++){
for(int a = 0; a < 9; a++) {
matrix[i][j] = fields.get(a).getSign().getFieldValue();
}
}
}

Correct me if I'm wrong.
The way I understood your question was you want to fill the matrix like this:
012
345
678
In that case you can do the first 2 forloops and add some maths, to get the correct numbers on every position:
int[][] matrix = new int[3][3];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = i * matrix[i].length + j;
}
}
The way this works is for every row (i) you multiply the rownumber by the rows length (the number of columns) and add the current column to it

To iterate through a two dimensional field (e.g. a matrix), you can use two for loops:
int dimension = 3;
int [][] matrix = new int [dimension][dimension];
for (int i = 0; i < dimension; i++){
for ( int j = 0; j < dimension; j++){
matrix[i][j] = fields.get(i).get(j);
}
}
I don't exactly know how you want to retrieve the values, but your current call looks suspicious to say the least :-)
It will simply assign the same value to all ints in column j.

If you simulate your loop, this is what it looks like
i -> 0
j -> 0
matrix[0][0] -> loop over all values from field
this way you would be putting the fields.get(8) into each index in your matrix.
#Alan's answers show how to properly loop and fill a 2d matrix from a 1d matrix

Related

Inplace transpose of a matrix in Java

I'm trying a simple intuition to transpose a matrix in place.
I'm trying to swap elements of matrix[i][j] and matrix[j][i] but it is not working, I'm wondering what is happening behind the scene.
class Solution {
public int[][] transpose(int[][] matrix) {
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
return matrix;
}
}
Output
For matrix -> [[1,2,3],[4,5,6],[7,8,9]]
It is giving output -> [[1,2,3],[4,5,6],[7,8,9]]
but the expected output should be -> [[1,4,7],[2,5,8],[3,6,9]]
You are transposing each pair of elements twice, which puts them back how they were.
One solution would be to change for(int j = 0; in the inner loop to for(int j = i + 1;. This would make sure that each pair of elements is only transposed once.
Also be aware that this general solution only works for square matrices.
how about this way?
public int[][] transpose(int[][] matrix) {
int[][] result = new int[matrix.length][matrix[0].length];
for(int i = 0; i < matrix[0].length; i++){
for(int j = 0; j < matrix.length; j++){
result[j][i] = matrix[i][j];
System.out.println(Arrays.deepToString(result));
}
}
return result;
}

how to convert nested loop to 2D array

i would ask if there is some way to print some thing called (Star pattern)!
for(int x=1; x<=5; x++)
{
for(int y=1; y<=x; y++)
{
System.out.print("*");
}
System.out.println();
}
the output (i guess...)
*****
****
***
**
*
so...
could you tell me please, it is possible to print same with array 2d?
thank you for help!
Yes: it's possible. You have to crate an array of 5x5 and fill previously with stars and spaces. Then you have to create a function to print that array.
Did you mean creating and handling arrays that consist of arrays of different sizes? Then it might look, for example, like the following:
public class TestArray {
public static void main(String... args) {
// Create and fill the array we need
char[][] array = new char[5][]; // Create an array of 5 arrays
for (int i = 0; i < array.length; i++) {
array[i] = new char[i+1]; // Each item of the array is a new array of a new size
for (int j = 0; j < array[i].length; j++)
array[i][j] = '*'; // fill the new array with stars
}
// Print the contents of the array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) // Each item is an array
System.out.print(array[i][j]); // print its contents
System.out.println(); // new line
}
}

Matrix -> blocks division

I want to load some matrix into my program and then I want to divide it into smaller blocks.
What I want exactly can be seen on an image below:
http://postimg.org/image/aki19hjx9/ba463111/
In red squares are 3 examples of my "blocks" in which I would like to divide whole matrix. In this case each block should be (smaller) 3x3 matrix. I know how to load it into 2d array, but what should I do then?
int[][] bigMatrix = new int[9][9];
// initialize bigMatrix
int[][][] smallMatrices = new int[3][3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
smallMatrices[i][j][k] = bigMatrix[3*i+j][3*i+k];
}
}
}
// The submatrices are now in smallMatrices[i], 0 <= i < 3

Generating random non-repeating numbers 2d array - all numbers same

This question is for Java. I keep on trying to create a Block[][] of size N, where the numbers 0 - 9 are placed randomly. I've created an array and then shuffled it to prevent numbers from being repeated. When I iterate over the array and assign the numbers to the two dimensional array, I keep on finding that all of the numbers in the two dimensional array are the same. The block keeps on coming out as:
222
222
222
I'd greatly appreciate your help!
public class Board {
int N = 3;
static int [][] copy;
//construct a board from an N-by-N array of blocks
//(where blocks[i][j] = block in row i, column j)
public Board(int[][] blocks){
blocks = new int[N][N]; //creates array of size N
//generates random numbers 0 inclusive to # exclusive
List<Integer> randomList = new ArrayList<>();
for (int i = 0; i < blocks.length; i++){
randomList.add(i);
}
int randomNum = 0;
for (int i = 0; i < blocks.length; i++){
randomNum = randomList.get(i);
}
Collections.shuffle(randomList);
for (int i = 0; i < blocks.length; i++){
for (int j = 0; j < blocks[i].length; j++){
blocks[i][j] = randomNum;
}
}
copy = blocks.clone();
}
int counter = 0;
Collections.shuffle(randomList);
for (int i = 0; i < blocks.length; i++){
for (int j = 0; j < blocks[i].length; j++){
blocks[i][j] = randomList.get(counter);
counter++;
}
}
You should create a counter that will loop through each element of your original arraylist and assign to the multi-dimensional arraylist
Also change:
for (int i = 0; i < 10; i++){
randomList.add(i);
}
You say you want 0-9 the above loop will give you 0-9. The loop you have will only give you 0-2.
The problem is you're assigning the value from randomNum to all of your cells. This variable is defined before your second for-loop and is left at the highest value at which that loop terminated (in your example the value 2).
You probably want to add a value from your randomList and then reshuffle it when the i index changes.
Your code for selecting a random number has no randomness in it at all:
int randomNum = 0;
for (int i = 0; i < blocks.length; i++){
randomNum = randomList.get(i);
}
You do shuffle randomList afterwards, but then make no use of the shuffled list.
You need to use the value in your random list of the position you are setting. In addition to this, if you want 0-9 values to be inserted, you need to modify the random list creation:
public Board(int[][] blocks){
blocks = new int[N][N]; //creates array of size N
//generates random numbers 0 inclusive to # exclusive
List<Integer> randomList = new ArrayList<>();
for (int i = 0; i < 10; i++){
randomList.add(i);
}
Collections.shuffle(randomList);
for (int i = 0; i < blocks.length; i++){
for (int j = 0; j < blocks[i].length; j++){
blocks[i][j] = randomList.get(j);
}
// Shuffle the list again to get different values for the next line
Collections.shuffle(randomList);
}
copy = blocks.clone();
}

Java loop over half of array

I would like to loop over half of an array in Java; this is because the matrix will be completely symmetric. If I loop throw i columns and j rows, every time I do an operation of matrix[i][j] I will do the exact same operation to matrix[j][i]. I should be able to save time by not looping over half of the matrix. Any ideas on the easiest way to do this?
If you're trying to get a triangle:
for(int i=0; i<array.length; i++){
for(int j=0; j<=i; j++){
..do stuff...
}
}
for (i = 0;i < size; ++i) {
for (j = 0; j < i; ++j) {
result = do_operation(i,j);
matrix[i][j] = result;
matrix[j][i] = result ;
}
}
So you invoke the operation method do_operation only once for each pair.
for(int i = 0; i<array.length; i++){
for(int j = 0; j < array[i].length - i; j++){
// operation here
}
}
Maybe I'm missing something here, but let's say you have two arrays representing your rows and columns respectively, and assuming that it's symmetric (as you say):
int dimension = rows.Length;
for(int i=0; i<dimension; i++)
{
int j = (dimension-1) - i; //need dimension-1 to avoid an off-by-one error
DoSomething(matrix[i][j]);
DoSomehting(matrix[j][i]);
}
This solution has the runtime complexity benefit of only iterating over one loop as opposed to two.

Categories