There is a really easy way to access the rows of a 2D array in java
for (int i = 0 ; i < integer2D.length ; i++)
getMyArray(integer2D[i]);
But, I searched in the web to find such easy way to iterate on columns of the 2D-array, like
for (int j = 0 ; j < integer2D[0].length ; j++)
getMyArray(integer2D[][i]);
or
for (int j = 0 ; j < integer2D[0].length ; j++)
getMyArray(integer2D[...][i]);
which works in some programming languages. I just found the class RealMatrix and MatrixUtils that I can convert my array2D to a real matrix and then transpose it and again convert it to an array and iterate on it. But I suppose that there exist a simpler way?
Edit: iterating on rows as I noted in the first piece of code is easy but the main question is how to iterate on columns like the second and third codes work in some other programming languages.
Edit2: As I mentioned in the last paragraph of the main question, the easiest way that I know is transposing the matrix and the iterating on its rows.
If I understand your question, you could use a for-each as an easy way to get each row like
for (int[] row : integer2D) { // <-- for each int[] in the int[][]
for (int val : row) { // <-- for each int in the int[] row
// ...
}
}
For this, you can use the BigMatrixImpl Class of the commons math library. It has a getColumnAsDoubleArray() method which will return the specified column as an array.
Delivering only one index will give you the whole row, so:
integer2D[5] // returns an int[]
will give you an integer array, which is the 6th row in your matrix.
If you supply both indexes directly you get the value of the "cell"
integer2D[5][1] // returns an int
will give you the value of the second column of the 6th row.
This is direct access to your matrix, if you want to iterate through the rows the answer from Elliott is what you are looking for.
Edit: Transposing:
int width = array.length;
int height = array[0].length;
int[][] array_new = new int[height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
array_new[y][x] = array[x][y];
}
}
Related
I came across this problem in class and I'm stuck on it. I did plenty of research but I'm not being able to fix my code.
I need to create a matrix and find the smallest value in the row of the largest value (I believe this element is called minimax). I'm trying to do with a simple 3 x 3 matrix. What I have so far:
Scanner val = new Scanner(System.in);
int matrizVal[][] = new int[3][3];
for (int a = 0; a < matrizVal.length; a++) {
for (int b = 0; b < matrizVal.length; b++) {
System.out.print("(" + a + ", " + b + "): ");
matrizVal[a][b] = val.nextInt();
}
}
int largest = matrizVal[0][0];
int largestrow = 0;
int arr[] = new int[2];
for (int row = 0; row < matrizVal.length; row++){
for (int col = 0; col < matrizVal.length; col++){
if (largest < matrizVal[row][col]){
largest = matrizVal[row][col];
largestrow = row;
}
}
}
To find the so called minimax element I decided to create a for each loop and get all the values of largestrow except the largest one.
for (int i : matrizVal[largestrow]){
if (i != largest){
System.out.print(i);
}
}
Here's where I'm stuck! I'd simply like to 'sort' this integer and take the first value and that'd be the minimax. I'm thinking about creating an array of size [matrizVal.length - 1], but not sure if it's gonna work.
I did a lot of research on the subject but nothing seems to help. Any tips are welcome.
(I don't think it is but I apologize if it's a duplicate)
Given the code you have provided, matrizVal[largestrow] should be the row of the matrix that contains the highest valued element.
Given that your task is to extract the smallest value in this array, there are a number of options.
If you want to simply extract the minimum value, a naive approach would go similarly to how you determined the maximum value, just with one less dimension.
For example:
int min = matrizVal[largestrow][0];
for (int i = 0; i < matrizVal.length; i++) {
if (matrizVal[largestrow][i] < min) {
min = matrizVal[largestrow][i];
}
}
// min will be the target value
Alternatively, if you want to sort the array such that the first element of the array is always the smallest, first ensure that you're making a copy of the array so as to avoid mutating the original matrix. Then feel free to use any sorting algorithm of your choice. Arrays.sort() should probably suffice.
You can simplify your approach by scanning each row for the maximum and minimum values in that row and then deciding what to do with those values based on the maximum value found in previous rows. Something like this (untested) should work:
int largestValue = Integer.MIN_VALUE;
int smallestValue = 0; // anything, really
for (int[] row : matrizVal) {
// First find the largest and smallest value for this row
int largestRowValue = Integer.MIN_VALUE;
int smallestRowValue = Integer.MAX_VALUE;
for (int val : row) {
smallestRowValue = Math.min(smallestRowValue, val);
largestRowValue = Math.max(largestRowValue, val);
}
// now check whether we found a new highest value
if (largestRowValue > largestValue) {
largestValue = largestRowValue;
smallestValue = smallestRowValue;
}
}
This doesn't record the row index, since it didn't sound like you needed to find that. If you do, then replace the outer enhanced for loop with a loops that uses an explicit index (as with your current code) and record the index as well.
I wouldn't bother with any sorting, since that (1) destroys the order of the original data (or introduces the expense of making a copy) and (2) has higher complexity than a one-time scan through the data.
You may want to consider a different alternative using Java 8 Stream :
int[] maxRow = Arrays.stream(matrizVal).max(getCompertator()).get();
int minValue = Arrays.stream(maxRow).min().getAsInt();
where getCompertator() is defined by:
private static Comparator<? super int[]> getCompertator() {
return (a1, a2)->
Integer.compare(Arrays.stream(a1).max().getAsInt(),
Arrays.stream(a2).max().getAsInt()) ;
}
Note that it may not give you the (undefined) desired output if two rows include the same highest value .
I am trying to populate a 2d array with String values.
int m; n; are used in my loops to assign to rows and columns.
In an inner loop I am pulling out strings from a separate string array and assigning each value to a string variable. Then I am trying to assign that string variable to the 2d array of strings.
String variable = value of string in string array at a specific index;
String[m][n] example = variable;
It seems to working fine except it doesn't seem to be loading the string in the string variable into the 2d array.
Can anyone help me to understand why this is happening and how I might successfully assign the data to the 2d array?
for(m = 0; m < people.size(); m++){
for(n = 0; n < people.get(m).getNames().length; n++){
for(int i = 0; i < people.size(); i ++){
for(j = 0; j < people.get(i).getNames().length; j++){
String name = people.get(i).getNames()[j];
}
NamesGrid [m][n] = name;
}
It's hard to tell just what you want to accomplish. The fact that you've posted non-matching curly braces doesn't help.
But basically, a double to populate all the array elements would look like:
for(m = 0; m < people.size(); m++){
for(n = 0; n < people.get(m).getNames().length; n++){
namesGrid[m][n] = ?????????;
}
}
where you have to fill in the expression. (And maybe add some code above the assignment to help with the computation.)
So what info do we have at the point where the array element is being assigned? We know what m and n are--the row and column of the namesGrid array. It also looks like they are also the "row" and "column" of objects in some people object. (It looks like people has several lists of names, and people.get(i) gives you one list of names? I'm not sure.)
But since we already know the row and column numbers for people, i.e. m and n, we can use those to access the data in people. We don't need extra for loops to do that. Or, to look at it another way: you need to iterate through all the elements of namesGrid, and you need to iterate through all the people, but you are iterating over them at the same time since the two structures are roughly the same shape, so to speak. When you use m and n to iterate through namesGrid, they are also iterating through people. So you don't need extra loops to iterate through people.
So get rid of those two extra i and j loops, and just use m and n to get the name:
String name = people.get(m).getNames()[n];
If this isn't what you really wanted, please edit your question and provide more details. Also, variable names by convention begin with a lower-case letter in Java, so I've changed namesGrid in my answer.
Try going through the 2d array using two for loops. Here is some sample code that goes through a for loop and assigns every element with a string.
String[][] names = new String[14][10];
for(int rows = 0; rows < names.length; rows++) {
for(int cols = 0; cols < names[0].length; cols++) {
names[rows][cols] = "Strings!";
}
}
for(int rows = 0; rows < names.length; rows++) {
for(int cols = 0; cols < names[0].length; cols++) {
System.out.print(names[rows][cols]);
}
System.out.println();
}
Okay probably it's a very easy solution, but I can't seem to find it. I've got two ArrayLists:
ArrayList<Candidate>partyList and ArrayList<Party>electoralList
Now I want to make a 2d int array that represents the parties and candidates like this:
p c
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
etc.
I think I already have the right for-loop to fill the array but I only miss the correct formula to do it.
int[][]ArrList;
for (int i=0; i<parties.size(); i++){
for(int j=0; j<parties.get(i).getPartyList().size(); j++){
ArrList[i][j]=
Is the for-loop indeed correct? And what is the formula to fill the array then?
I will try and answer the question from how I understood what you are looking for here.
You should understand this first:
A 2D array consists of a nestled array i.e. ArrList[2][3] = [ [1,2,3], [1,2,3] ] -> The first digit declares How many arrays as elements, the second digit declares Size or if you like: length, of the array elements
If you are looking for to represent the candidates and parties as numbers. Here is my solution:
int[][]ArrList = new int[parties.size()][electoral.size()]
for (int depth=0; depth < parties.size(); depth++){
for(int itemIndex=0; itemIndex<parties.get(depth).getPartyList().size(); itemIndex++){
ArrList[depth][itemIndex]= itemIndex;
I hope this is what you were looking for.
First of all, ArrList should not have a starting capital letter (it is not a class but an object).
Second point (I think what troubles you) is that you are not initializing the matrix and the parties.size() are always 0. I am not sure since there is not enough code though.
You could do something like this
int ROWS = 10;
int COLS = 2;
int [][] matrix = new int[ROWS][];
for(int i=0; i< matrix.length; i++){
matrix[i] = new int[COLS];
}
or, with lists
int ROWS = 10;
int COLS = 2;
List<List<Object>> matrix = new ArrayList<>(ROWS);
for (int i = 0; i < ROWS; i++) {
ArrayList<Object> row = new ArrayList<>(COLS);
for (int j = 0; j < COLS; j++) {
row.add(new Object());
}
matrix.add(row);
}
int[][] arrList=new int[parties.size()][2];
int i=0,j=0,k=0;
for(;i<parties.size();i++,j++){
if(j==1){
arrList[k][j]=electoralList .get(--i);
j=-1;
k++;
}
else{
arrList[k][j]=parties.get(i);
}
}
arrList[k][j]=aarM.get(electoralList .size()-1);
System.out.println(Arrays.deepToString(arrList));
I currently have a 2D array which looks the equivalent of:
int[] my2Darray = {{1, 2}, {3, 4, 5}, {1}};
//the second dimensions can and do vary
I was wondering how I can print all elements of this array automatically.
My code to print currently looks like:
for(int t = 0; t < movieactorsbulk.size(); t++) {
temparray = movieactorsbulk.get(t).split("\\s");
movieactorsindiv[t] = new String[temparray.length];
for(int v = 0; v < temparray.length; v++) {
movieactorsindiv[t][v] = temparray[v];
}
}
movieactorsbulk contains: [a00011974 a00011975, a00011975 a00011974, a77777777]
So I am trying to separate the indexes of the ArrayList movieactorsbulk) and put it into a 2D array (movieactorsindiv) then print everything no matter the size.
Right now I know my problem is that on the last go around the code splits "a77777777" and puts it into movieactorsindiv[2][0] but when I try to print based on temparray.length it only prints the first indexes as temparray[] only contains "a77777777" at that point. How can I print all indexes of movieactorsindiv ([0][0] through to [x][y]; where x and y can be any number)?
Any help would be appreciated. Sorry if the question isn't easy to understand. :S
Try using this skeleton of a traversal:
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
// print matrix[i][j]
}
}
It takes into consideration the case where each row's columns can be of different length. It works for 2-D matrices of any height and width (even of varying widths), and it'll be easy to adapt for your problem in particular.
Good evening all,
I'm trying to write a method that creates and returns a 2D array whose elements in each location are the same as the elements in the mirror image location of the parameter array. Unfortunately, no matter what pair of numbers I enter into the method call I get an "out of bounds" error in my compiler. Below is my program. Tell me where I've gone wrong! Thanks!
public static int[][] transpose(int [][] a) {
int r = a.length;
int c = a[r].length;
int [][] t = new int[c][r];
for(int i = 0; i < r; ++i) {
for(int j = 0; j < c; ++j) {
t[j][i] = a[i][j];
}
}
return t;
}
}
Arrays in java are 0 based, change your assignment to c to :
int c = a[r - 1].length;
#Suraj is correct, however you must assume the 2D array is rectangular, in which case it is sightly more efficient to change line 3 to:
int c = a[0].length;
#Kris answer text is correct however code sample is wrong line.
Note this error is a reproduction of a broken "answer" posted in "Yahoo Answers": http://answers.yahoo.com/question/index?qid=20080121204551AAn62RO
Your problem lies in line two: a[r].length returns the number of columns, but arrays are indexed from 0. You should adjust accordingly:
int r = a.length - 1;