public static void main(String[] args)
{
int[][] data = {{1, 2, 3}, {2, 3, 9}, {3, 4, 5}};
int row = 0;
int maxRow = data[row][0];
int minRow = data[row][0];
int rowCounter = 0;
int rowRange = 0;
for (row = 0; row < data.length; row++)
{
for (int col = 0; col < data[row].length; col++)
{
if (data[row][col] > maxRow)
{
maxRow = data[row][col];
}
else if (data[row][col] < minRow)
{
minRow = data[row][col];
}
}
rowCounter++;
rowRange = maxRow - minRow;
}
System.out.printf("The row with the greatest range is row #%d the range is %d%n", rowCounter, rowRange);
}
I'm looking to find the row with the greatest range and what row number its in, but I'm having some trouble.
The answer should be a "range of 7 row number 1"
With the code above I'm only getting the overall max range and row of everything. Any ideas?
Note: This is a small scale example I want to carry over to a huge array file.
By doing:
rowRange = maxRow - minRow;
you're overriding the range again and again.
Do instead:
int tmpRowRange = maxRow - minRow;
if (tmpRowRange > rowRange)
rowRange = tmpRowRange;
This way, you'll override rowRange only with values that are greater than the previous ones, which will leave you at the end of the iteration with the maximum range.
Related
I want to write a function that takes an 2d array and fills it with 1...n but counting the columns first instead of the rows:
input = {{0, 0, 0, 0}, {0}, {0}, {0, 0}};
the output should be: {{1, 5, 7, 8}, {2}, {3}, {4, 6}};
if i were to loop through rows and then colums i get:
private static void fill1(int[][] input) {
int count = 1;
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input[i].length; j++) {
input[i][j] = count;
count++;
}
}
}
How do I loop through colums first?
You can do this by first transposing your input, executing your fill1 code and then transposing the output again.
See this question for how to transpose a 2 dimensional array in Java: java multi-dimensional array transposing
If you were dealing with a regular 2d matrix, where all the rows had the same number of columns, the code would be a simple modification of the code for filling the matrix row-by-row:
private static void fill1(int[][] input) {
int count = 1;
for (int j = 0; j < input[0].length; j++) {
for (int i = 0; i < input.length; i++) {
input[i][j]= count;
count++;
}
}
}
The process is basically the same for a ragged 2d array, but with a couple added twists:
You need to do some extra work to figure out how many columns there could be (i.e., the maximum row length)
You need to be prepared for the case when there's no cell at a given row/column position.
The following modification of the previous code addresses these issues:
private static void fill1(int[][] input) {
int maxCols = input[0].length;
for (int i = 1; i < input.length; ++i) {
if (input[i].length > maxCols) {
maxCols = input[i].length;
}
}
int count = 1;
for (int j = 0; j < maxCols; j++) {
for (int i = 0; i < input.length; i++) {
if (j < input[i].length) {
input[i][j]= count;
count++;
}
}
}
}
To iterate first over the columns of a jagged 2d array to fill it, you have to know the maximum number of columns beforehand, but if you don't know that, you can iterate to the Integer.MAX_VALUE and check at each step if the columns are still present or not:
int[][] arr = {{0, 0, 0, 0}, {0}, {0}, {0, 0}};
int count = 1;
for (int col = 0; col < Integer.MAX_VALUE; col++) {
boolean max = true;
for (int row = 0; row < arr.length; row++) {
if (col < arr[row].length) {
arr[row][col] = count;
count++;
max = false;
}
}
if (max) break;
}
for (int[] row : arr) {
System.out.println(Arrays.toString(row));
}
Output:
[1, 5, 7, 8]
[2]
[3]
[4, 6]
See also: How do you rotate an array 90 degrees without using a storage array?
To populate a 2d array first by columns, you can use two nested streams. In case of a jagged 2d array, when you don't know beforehand the number of the columns in each row, in an outer stream you can traverse while the columns are still present.
/**
* #param arr array that should be populated.
* #return maximum row length, i.e. columns count.
*/
private static long populate(int[][] arr) {
AtomicInteger counter = new AtomicInteger(1);
return IntStream
// traverse through the array columns
.iterate(0, i -> i + 1)
// process the array rows where
// this column is present
.mapToLong(i -> Arrays.stream(arr)
// filter those rows where
// this column is present
.filter(row -> row.length > i)
// assign a value to the element and increase the counter
.peek(row -> row[i] = counter.getAndIncrement())
// count of rows where this column is present
.count())
// while the columns are still present
.takeWhile(i -> i > 0)
// max columns count
.count();
}
public static void main(String[] args) {
int[][] arr = {{0, 0, 0, 0, 0, 0}, {0, 0}, {0}, {0, 0, 0}};
System.out.println("Max columns count: " + populate(arr));
System.out.println(Arrays.deepToString(arr));
}
Output:
Max columns count: 6
[[1, 5, 8, 10, 11, 12], [2, 6], [3], [4, 7, 9]]
See also: How to create a new List from merging 3 ArrayLists in round robin style?
I need to write a java code that get a 2D array as a matrix and check every rows and columns and find the number that its the max at the rows but the min at the cols.
For example, the 13 is the min at col and max at the row:
I wrote the code but I get lost:
import java.util.Scanner;
public class maxmin {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("enter matrix size ");
int num = input.nextInt();
int num1 = input.nextInt();
maxMin(num, num1);
}
private static void maxMin(int num, int num1) {
int max = 0;
int min = 0;
int[][] matrix = new int[num][num1];
System.out.println("ENTER ARRAY NUMBERS");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = input.nextInt();
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] >= max) {
max = matrix[i][j];
for (int a = 0; a < matrix.length; a++) {
if (matrix[i][a] <= min) {
min = matrix[i][a];
}
if (max == min) {
System.out.println(max);
}
}
}
}
}
}
}
You can use IntStream for this purpose:
int[][] arr = {
{1, 2, 3, 6, 5},
{3, 2, 5, 6, 7},
{5, 6, 7, 8, 9},
{1, 3, 0, 2, 4}};
int num = Arrays
// iterate over the nested arrays,
// i.e. rows of the 2d array
.stream(arr)
// find maximum value of the row
// return IntStream of maximums
.mapToInt(row -> Arrays.stream(row)
// maximum value of the row
.max().orElse(Integer.MIN_VALUE))
// find minimum value of row maximums
.min().orElse(Integer.MIN_VALUE);
// output
System.out.println(num); // 4
So first thing. Since you are trying to find a number that is MAX at row and MIN at column, it means you are trying to find multiple numbers. As such, there should be some resetting code for resetting the max and min in order to find new max and min.
Then, what you need to think about is HOW you are gonna find it. Since it must be max in the column first, you have to iterate all positions in each row first while recording the max position. Then you iterate that particular column associated with the max position in that row. You get it? You ONLY iterate the column again (beside the first time) when you finish an entire row first and know the position.
#Alex Rudenko notes that since there are negative numbers in the matrix, an initial value of max and min should default to
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
which is essential for the below code to work.
So the code for the last block should look something like this:
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix[0].length; j++){
if (matrix[i][j] > max){
max = matrix[i][j];
maxPos = j; //declare this beforehand
}
}
for (int a = 0; a < matrix.length; a++ ){
if( matrix[a][maxPos] < min){
min = matrix[a][maxPos];
}
}
if(max == min) {
System.out.println(matrix[i][maxPos]);
max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;
}
}
That’s it! There could be something down to avoid repetition on already checked position, but this is the central logic of this operation.
Also, I assume you are only printing the max&min number. You can also save those numbers in an array or something if you need to use it later.
Since you are trying to learn, I would suggest refrain from using advanced methods. This is a helpful basic to solidify you coding muscle.
I have been recently working with 2D and Jagged Arrays and am trying to add each element in a row and each element inside a column. I got the code to print out the sum of each row, but am having difficulty with adding each column in the array.
Note: I tried doing sum += numbers[c][r]; but it is not working
import java.util.Arrays;
import java.io.*;
public class Homework{
public static void main(String[] args) {
int[][] numbers = { {3, 2, 5,},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
//Adding each row in the array
int sum = 0;
for(int r = 0; r < numbers.length; r++) {
sum = 0;
for(int c = 0; c < numbers[r].length; c++) {
sum += numbers[r][c];
}
System.out.println("Sum of row: " + sum);
}
//Adding each column in the row
int sum2 = 0;
for(int r = 0; r < numbers.length; r++) {
sum2 = 0;
for(int c = 0; c < numbers[r].length; c++) {
sum2 += numbers[c][r];
}
System.out.println("Sum of column: " + sum2);
}
}
}
Okay so you were sort of on the right track. Let me explain a way of thinking before I get into the code.
You have a non-square 2d Array and you want the total of each row and column. Row is simple, you've accomplished that already. Column is a little more difficult because since its non-square, you will run into ArrayOutOfBoundsExceptions because it tries to access a art of the array that doesn't exist.
To combat this, you need to know the max number of columns there are and then iterate through the array. BUT, you also need to be careful about that ArrayOutOfBoundsException, making sure to account for when the current column iteration is greater than the row length.
I added an int max to your row sum section, this way I don't have to iterate over the same info more than once.
After that, I replace c < numbers[r].length with 'max', since we need to iterate over X columns.
Then I iterate over the rows, since they are uniform and easily found by numbers.length.
So, a simple change to your code yields the results you need. See below.
int[][] numbers = {
{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}
};
int max = 0;
//Adding each row in the array
int sum;
for(int r = 0; r < numbers.length; r++) {
sum = 0;
for(int c = 0; c < numbers[r].length; c++) {
sum += numbers[r][c];
if(numbers[r].length > max){
max = numbers[r].length;
}
}
System.out.println("Sum of row: " + sum);
}
System.out.println("Max " + max);
//Adding each column in the row
int sum2;
for(int c = 0; c < max; c++) {
sum2 = 0;
for(int y = 0; y < numbers.length; y++){
if(numbers[y].length > c){
sum2 += numbers[y][c];
System.out.println(numbers[y][c]);
}
}
System.out.println("Sum of column: " + sum2);
}
}
The problem I am having is that I must create program that uses an object to reverse the elements of each row in a 2D Array and prints out the resulting matrix. The code I have only prints out the first 3 numbers of each row in reverse. This is my code:
class Reverse {
void matrixReverse(int[][] data) {
int row_val = data.length;
int col_val = data[0].length;
int[][] data_reverse = new int[row_val][col_val];
for(int row = row_val - 1; row >= 0; row--){
for(int col = col_val - 1; col >= 0; col--){
data_reverse[row_val - 1 - row][col_val - 1 - col] = data[row][col];
}
}
for(int row = 0; row < row_val; row++){
for(int col = 0; col < col_val; col++){
System.out.println(data_reverse[row][col]);
}
System.out.println();
}
}
}
public class ArrayReverse {
public static void main(String[] args) {
int[][] data = {
{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}
}; // Creates the array
Reverse reverse = new Reverse();
reverse.matrixReverse(data);
}
}
The output is:
6
2
0
0
1
9
4
4
1
5
2
3
As you can see, it's only printing the first 3 numbers of the rows but I need it to print all of them.
Your columns are variable width yet you are getting the width from the first row (which may not even exist!). You need to check the size of the array before accessing an element of it. You also have the array size parameters switched, start with row first.
To fix your specific problem, you need to set the col_val for each row inside the row loop.
void matrixReverse(int[][] data) {
int rowWidth = data.length;
int[][] reversedData = new int[rowWidth][];
for (int row = rowWidth - 1; row >= 0; row--) {
int colWidth = data[row].length;
int reverseRow = rowWidth - 1 - row;
reversedData[reverseRow] = new int[colWidth];
for (int col = colWidth - 1; col >= 0; col--) {
int reverseCol = colWidth - 1 - col;
reversedData[reverseRow][reverseCol] = data[row][col];
}
}
for (int row = 0; row < rowWidth; row++) {
int colWidth = reversedData[row].length;
for (int col = 0; col < colWidth; col++) {
System.out.println(reversedData[row][col]);
}
System.out.println();
}
}
P.S. row_val and col_val are bad names. They are widths not values and the naming convention in Java is colWidth and rowWidth not col_width or row_width.
I'm trying to take the sum of each row in a 2d array and store the values in a new array. Right now sum[] is only returning the values stored in the first row. Please help me understand what I'm missing here.
public static int[] rowSum(int[][] matrix) //find sum of digits in given row
{
int[] sum = new int[6];
for (int col = 0; col < ARRAY_LENGTH; col++)
{
for (int row = 0; row < ARRAY_LENGTH; row++)
{
sum[row] += matrix[col][row];
}
}
return sum;
}
Since you use Java 8 you can use:
return Arrays.stream(matrix) // Stream<int[]>
.mapToInt(row -> Arrays.stream(row).sum()) // IntStream
.toArray(); // int[]
Following code works for 2D arrays of different size as well.
public static void main(String[] args) {
int[][] matrix = {
{2, 3, 4, 5, 6, 7, 8, 9}, // 8 elements
{2, 1, 4, 5, 7, 2, 86} // 7 elements
};
int[] sum = rowSum(matrix);
for (int i : sum) {
System.out.println(i);
}
}
public static int[] rowSum(int[][] matrix) //find sum of digits in given row
{
int[] sum = new int[matrix.length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
sum[i] = sum[i] + matrix[i][j];
}
}
return sum;
}
simple
public static int[] rowSum(int[][] matrix) //find sum of digits in given row
{
int[] sum = new int[6];
ARRAY_LENGTH = 6;
for (int col = 0; col < ARRAY_LENGTH; col++)
{
for (int row = 0; row < ARRAY_LENGTH; row++)
{
sum[col] += matrix[col][row];
}
}
}
careful with ARRAY_LENGTH