I was wondering while using java.
There are two-dimensional arrays as shown below.
int[][] test = {{3, 9, 3, 5}, {4, 19, 4, 9}, {2, 10, 5, 6}};
I want to find the max value in each row in a two-dimensional array, and I wonder how to code it.
I want to result is
int[] answer = {4, 19, 5, 9}
Simply add a comment, I want to extract the largest value.
[0][0] = 3;
[1][0] = 4;
[2][0] = 2;
[0][1] = 9;
[1][1] = 19;
[2][1] = 10;
[0][2] = 3;
[1][2] = 4;
[2][2] = 5;
[0][3] = 5;
[1][3] = 9;
[2][3] = 6;
So max value is 4, 19, 5, 9
I tried this method but this method is arr[i][j] compares all elements in a two-dimensional array and finds only max in the comparison.
for (int i = 0; i < test.length; i++) {
int max = test[i][0];
for (int j = 0; j < test[i].length; j++)
if (test[i][j] > max)
max = test[i][j]
}
You can init the result with the first row, then iterate on this matrix, if the current element test[row][column] is greater than result[column], reassign result[column]:
public static void main(String[] args) {
int[][] test = {{3, 9, 3, 5}, {4, 19, 4, 9}, {2, 10, 5, 6}};
int[] result = test[0];
for (int row = 1; row < test.length; row++) {
for (int column = 0; column < test[0].length; column++) {
if (test[row][column] > result[column]) {
result[column] = test[row][column];
}
}
}
for (int number : result) {
System.out.print(number + " "); // 4 19 5 9
}
}
According to your exemple, the "big" loop is going through the columns and the "small" loop through the lines. Sou you'll have something like that :
for(int j=0; j<test[0].length; j++) { //loop through columns
for(int i=0; i<test.length; i++) { //loop through lines
}
}
Then you need a result variable that will be an array : int[] result = new int[test[0].length];
Then you need to have a variable to store the max number of a column. This variable will be re-initialise at every "big" loop since you want to re-determine the max.
int[] result = new int[test[0].length]; //Array to store the result
for(int j=0; j<test[0].length; j++) { //loop through columns
int max = 0; //int to store the max of the i column
for(int i=0; i<test.length; i++) { //loop through lines
}
}
Then for every line check if the number is bigger than max. If it is replace max by the new value.
if(test[i][j] > max) { //if the number at the column i and line j is bigger than max
max = test[i][j]; then max becomes this number
}
Finally when you've run through every line of the column, add the found max to the result
result[i] = max; //Add the found max to the result array
This should give you this :
int[] result = new int[test[0].length]; //Array to store the result
for(int j=0; j<test[0].length; j++) { //loop through columns
int max = 0; //int to store the max of the i column
for(int i=0; i<test.length; i++) { //loop through lines
if(test[i][j] > max) { //if the number at the column i and line j is bigger than max
max = test[i][j]; then max becomes this number
}
}
result[i] = max; //Add the found max to the result array
}
System.out.println(Arrays.toString(result)); //print the result
Related
Can you please help me understand what the following code means and what the value of number[2][2] is?
public static void main(String[] args) {
int[][] numbers = new int [3][3];
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[0].length; j++) {
numbers[i][j] = i*j;
}
In Java, a multiple dimension array is constructed with multiple one dimensional arrays. In your example numbers[3][3] will look like the below array:
numbers = [
[0, 0, 0],
[0, 1, 2],
[0, 2, 4]
]
Now when you ask what will be the length of numbers[0]? Then it is easy to say 3. numbers[0] holds [0, 0, 0]. And if you ask what is the value of numbers[2][2] then it is 4 ( since array index starts with 0 ).
Now here I put another example.
public class Array {
public static void main(String[] args) {
int[][] numbers = new int[3][];
numbers[0] = new int[2];
numbers[1] = new int[3];
numbers[2] = new int[4];
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
numbers[i][j] = j;
}
}
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
System.out.print(numbers[i][j] + " ");
}
System.out.println();
}
}
}
Here I take an array and make the internal array size differently. This array will look like this:
numbers = [
[0, 1],
[0, 1, 2],
[0, 1, 2, 3]
]
Here I create the first array with size 2, second array with size 3 and third array with size 4, put some data into it and simply print it.
I think you may now visualize what numbers[0].length actually means.
I have 2d array java, I need to look at it and check on the max value, then print it with the count of how many it is in the array
I was trying to do like this but it doesn't work
int[][] rand = new int[][]{
{1, 80, 3, 4, 5},
{13, 199, 80, 8},
{12, 22, 80, 190}
};
int max = rand[0][0];
int count = 0;
for (int i = 0; i < rand.length; i++){
for (int ii = 0; ii < rand[i].length; ii++) {
if (rand[i][ii] > max) {
max = rand[i][ii];
count++;
}
}
}
System.out.println(max + " " + count);
You are not handling count correctly:
int max = rand[0][0];
int count = 0
for (int i = 0; i < rand.length; i++){
for (int ii = 0; ii < rand[i].length; ii++) {
if (rand[i][ii] > max) {
max = rand[i][ii];
count = 1; // a new maximum's first occurrence
} else if (rand[i][ii] == max) {
count++; // another occurrence of the current maximum
}
}
}
System.out.println(max + " " + count);
When you find a new maximum, you should reset count to 1.
You should check if the current element is equal to the current maximum, and increment count if that's the case.
Output:
199 1
EDIT:
Fixed the case where the first element is the maximum. It turns out count should be initialized to 0 after all, since the loops re-visit the first element, so we don't want to count it twice if it's the maximum.
You can use streams:
int max = Arrays.stream(rand)
.mapToInt(row -> Arrays.stream(row).max().getAsInt())
.max().getAsInt();
int count = Arrays.stream(rand)
.mapToInt(row -> (int) Arrays.stream(row).filter(i-> i==max).count())
.reduce(Integer::sum).getAsInt();
I have written the following code that takes two arrays and searches the index of the first occurrence of each value from the first array in the second one. For example if first = {15, 10, 18, 17, 15} and second = {10, 15, 10, 17} then the output would be an array with an equal length to first which contains the indices output = {1, 0, -1, 3, 1}, as e.g. 15 occurs in index 1 of the second array, 10 occurs at the 0th index, etc. The index will be -1 if the value in first doesn't occur in second. The code I've written to loop through the arrays is as follows:
public static int[] searchIndexes(int[] first, int[] second) {
int[] indices = new int[first.length];
int index = -1;
for (int i = 0; i < first.length; i ++) {
for (int j = 0; j < second.length; j ++) {
if (first[i] == second[j])
index = j;
}
indices[i] = index;
}
return indices;
}
However, for the given example the output is instead {1, 2, 2, 3, 1}. I think I do understand the issue; since 10 occurs twice in second then the index of the second occurrence is recorded, but I don't know how to get around this. Putting a break; statement after the if clause doesn't seem to fix it.
This would be straightforward by using the ArrayUtils.indexOf() utility method. Moving through the second array, call ArrayUtils.indexOf() for each of its elements in reference to the first array, storing the results in the indices array. This will also mean that there would be a single loop, not a nested loop.
The ArrayUtils class is a part of the org.apache.commons.lang3 library.
A different option, not requiring an external library, would be to convert your arrays to Lists and then take advantage of the List.indexOf() method.
I hope that helps!
Two issues in your code:
Once index is set to any value at all, it can never again become -1
Once you find the first occurrence in the second array, you keep going - need a break.
Updated code:
public static int[] searchIndexes(int[] first, int[] second) {
int[] indices = new int[first.length];
int index;
for (int i = 0; i < first.length; i ++) {
// reset index on each iteration
index = -1;
for (int j = 0; j < second.length; j ++) {
if (first[i] == second[j]) {
// once the first match is found, break out of the inner loop
index = j;
break;
}
}
indices[i] = index;
}
return indices;
}
try this
public static int[] searchIndexes(int[] first, int[] second) {
int[] indices = new int[first.length];
//fill all values with -1
Arrays.fill(indices,0,first.length - 1, -1);
for (int i = 0; i < first.length; i++) {
for (int j = 0; j < second.length; j++) {
// when you met with same value fill your indices array with second array's value's index and break the loop
if (first[i] == second[j]) {
indices[i] = j;
break;
}
}
}
return indices;
}
Just add break after found the element and reset the index
public static int[] searchIndexes(int[] first, int[] second) {
int[] indices = new int[first.length];
int index = -1;
for (int i = 0; i < first.length; i++) {
index = -1;
for (int j = 0; j < second.length; j++) {
if (first[i] == second[j]) {
index = j;
break;
}
}
indices[i] = index;
}
return indices;
}
, main
public static void main(String args[]) {
int[] indices = searchIndexes(new int[] { 15, 10, 18, 17, 15 }, new int[] { 10, 15, 10, 17 });
for (int i = 0; i < indices.length; i++)
System.out.print(indices[i] + " ");
System.out.println();
}
, output
1 0 -1 3 1
Im Swedish so maybe I did give the wrong title.
I have two arrays of different size:
{2, 5, 10, 13}
{5, 7, 5, 22, 44, 75}
I want to add each element and put it in a third array.
So the result should be {7, 12, 15, 25, 44, 75}
I have manage to done some code.
I get an exeption of out of bounds.
I think the problem is that I canĀ“t add a non existing element.
But how can I solve it?
public static void main(String[] args) {
int[] samling = {1, 2, 4, 3, 8};
int[] samling2 = {1, 2, 4, 3, 8, 8, 3};
int[] svar = concateArrays(samling, samling2);
for(int i=0; i < svar.length; i++)
System.out.println("Ny Array " + svar[i]);
}
public static int[] concateArrays(int[] samling, int[] samling2)
{
int sum = samling.length + samling2.length;
int[] total = new int[sum];
for(int i=0; i < total.length; i++){
//if (samling2.length != 0) // || samling.length != 0)
total[i] = samling[i] + samling2[i];
}
return total;
}
The length of the output array shouldn't be the sum of lengths of the input arrays, it should be the length of the longer input array. And before accessing an element of either input array, you must check the current index i is a valid index of that array.
public static int[] concateArrays(int[] samling, int[] samling2)
{
int[] total = new int[Math.max(samling.length,samling2.length)];
for(int i=0; i < total.length; i++) {
total[i] = (i < samling.length ? samling[i] : 0) +
(i < samling2.length ? samling2[i] : 0);
}
return total;
}
You can use one loop to loop over both arrays simultaneously.
You first need to check which array is the longest, and make a new array:
int[] arr = new int[longest];
Then you need to walk over the array. In this example, I assume the latter array is always the longest.
for (int i = 0; i < samling2.length; i++) {
int totalValue = samling[i];
if (i < samling.length) {
totalValue += samling2[i];
}
arr[i] = totalValue;
}
You can make an array of length equal to max of the two arrays you have. Then you can add the elements from both arrays if the specific index exist in both arrays else simply copy the index from the array which contain that index.
See the following code to get a better picture
import java.io.*;
class GFG {
public static void main(String[] args) {
int[] samling = {1, 2, 4, 3, 8};
int[] samling2 = {1, 2, 4, 3, 8, 8, 3};
int[] svar = concateArrays(samling, samling2);
System.out.println("Ny Array :");
for(int i=0; i < svar.length; i++)
System.out.print(svar[i] + " ");
}
public static int[] concateArrays(int[] samling, int[] samling2)
{
int len = 0;
if (samling.length > samling2.length)
len = samling.length;
else
len = samling2.length;
int[] total = new int[len];
for(int i=0; i < len; i++){
if (i >= samling2.length) {
total[i] = samling[i];
}else if( i >= samling.length) {
total[i] = samling2[i];
}else{
total[i] = samling2[i] + samling[i];
}
}
return total;
}
}
Another variant, with no need for a conditional operation in each iteration of the copying loop:
public static int[] concateArrays(int[] samling, int[] samling2)
{
// max length of the two arrays
int maxLen = Math.max(samling.length,samling2.length);
// decide which of the inputs is shorter and which is longer
int[] shorter = maxLen == samling.length ? samling2 : samling;
int[] longer = maxLen == samling.length ? samling : samling2;
int[] total = new int[maxLen];
// add both as long as there are elements in the shorter
for(int i=0; i < shorter.length; i++) {
total[i] = shorter[i] + longer[i];
}
// copy the remainder of the longer
for(int i=shorter.length; i < longer.length; i++) {
total[i] = longer[i];
}
return total;
}
You can try this :
public static int[] concateArrays(int[] samling, int[] samling2)
{
int minLength = samling.length;
int[] array = null;
if (samling2.length > samling.length) {
array = samling2;
} else {
minLength = samling2.length;
array = samling;
}
for (int i = 0; i < minLength; i++) {
array[i] = samling[i] + samling2[i];
}
return array;
}
Suppose I have an array of numbers
1, 2, 3, 4, 5, 6, 7, 8, 9
How do I construct a 3x3 matrix where the first row contains 1,2,3; the second row contains 4,5,6; the third row contains 7, 8, 9?
Essentially, I want to fill the numbers into the 3x3 matrix row by row.
In R, I can construct this matrix using this command:
matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, ncol=3, byrow = TRUE)
How do I accomplish this in Java?
int arr[][] = { {1,2,3}, {4,5,6}, {7,8,9} };
Initial the array :
int [][] numbers = new int [nrow][ncol]; // suppose 3X3
Assign each index to some integer number:
Scanner s = new Scanner(System.in);
for(int i = 0 ; i < nrow ; i++)
for(int j = 0 ; j < ncol; j++)
numbers[i][j] = s.nextInt();
And print the matrix :
for(int []n : numbers){
for(int i : n){
System.out.println(i);
}
System.out.println();
}