Yesterday I asked a very similar question and I kind of messed up with asking it.
I need to pass an array to a method and inside of that method I need to swap the rows around so if it's
1 2 3
3 2 1
2 1 3
it needs to be
3 2 1
1 2 3
3 1 2
With the code I have right now it swaps the last column to the first column spot correctly then it puts the column that's supposed to be last.
3 1 2
1 3 2
3 2 1
Also, it needs to stay a void because I need to be modifying the original array so I can't set it as a temp array but I can use a temp integer to store.
Here is the code I have right now that's sort of working
public static void reverseRows(int[][] inTwoDArray)
{
for (int row = 0; row < inTwoDArray.length; row++)
{
for (int col = 0; col < inTwoDArray[row].length; col++)
{
int tempHolder = inTwoDArray[row][col];
inTwoDArray[row][col] = inTwoDArray[row][inTwoDArray[0].length - 1];
inTwoDArray[row][inTwoDArray[0].length - 1] = tempHolder;
}
}
}
any help would be great, I'm running out of hair to pull out! Thanks!
First, how to reverse a single 1-D array:
for(int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
Note that you must stop in half of your array or you would swap it twice (it would be the same one you started with).
Then put it in another for loop:
for(int j = 0; j < array.length; j++){
for(int i = 0; i < array[j].length / 2; i++) {
int temp = array[j][i];
array[j][i] = array[j][array[j].length - i - 1];
array[j][array[j].length - i - 1] = temp;
}
}
Another approach would be to use some library method such as from ArrayUtils#reverse():
ArrayUtils.reverse(array);
And then again put into a cycle:
for(int i = 0; i < array.length; i++){
ArrayUtils.reverse(array[i]);
}
I guess this the easiest approach, tried and tested
For instance, you have
1 2
3 4
and you want
2 1
4 3
You can reverse the loop, without any extra space or inbuilt function.
Solution:
for(int i =0;i<arr.length;i++) //arr.length=no of rows
{
for(int j = arr[i].length-1;j>=0;j--)//arr[i].length=no of col in a ith row
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Not sure if I didn't confuse what array stores the rows and which one the columns.... but this should work (long time since I've done Java last, so be nice to me when spotting any errors please ^^):
public static void reverseRows(int[][] array)
{
for (int i = 0 ; i < array.length ; i++) { // for each row...
int[] reversed = new int[array[i].length]; // ... create a temporary array that will hold the reversed inner one ...
for(int j = 0 ; j < array[i].length ; j++) { // ... and for each column ...
reversed[reversed.length - 1 - j] = array[i][j]; // ... insert the current element at the mirrored position of our temporary array
}
array[i] = reversed; // finally use the reversed array as new row.
}
}
Java Code :-
import java.util.Scanner;
public class Rev_Two_D {
static int col;
static int row;
static int[][] trans_arr = new int[col][row];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
row = m;
int n = sc.nextInt();
col = n;
int[][] arr = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
arr[i][j] = sc.nextInt();
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
for (int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr[j].length / 2; i++) {
int temp = arr[j][i];
arr[j][i] = arr[j][arr[j].length - i - 1];
arr[j][arr[j].length - i - 1] = temp;
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Reverse of two D array - Print your two D array in reverse order
public void reverse(){
int row = 3;
int col = 3;
int[][] arr = new int[row][col];
int k=0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++,k++) {
arr[i][j] = k;
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
for (int i = arr.length -1; i >=0 ; i--) {
for (int j = arr.length -1; j >=0 ; j--) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int [][] a={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a.length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
System.out.println("***************************");
for(int i=0 ; i<a.length;i++)
{
for(int j=a.length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
}
Reverse 2 D Array
public static void main(String[] args) {
int a[][] = {{1,2,3},
{4,5,6},
{8,9,10,12,15}
};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a[i].length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
for(int i=0 ; i<a.length;i++)
{
for(int j=a[i].length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
Related
hello guys I am struggling to find the right way to print only the even numbers of the array.
I made a 1 dimensionnal array to save the element of the columns and then make sure if the index of the col%2==0 put that number in the output.
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//array with 3 row in 5 col
int[][] matrix = new int[3][5];
//int []y = new int[5];
// to impalement th array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.print("Enter matrix[" + i + "][" + j + "]: ");
matrix[i][j] = input.nextInt();
}
System.out.print("\n");
}
System.out.print("matrix values \n");
// to show up the originally array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.print("\n");
}
//////the new array to display only the even numbers in the col
System.out.print("\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
int[] y = matrix[j];
for (int k = 0; i < y.length; i++) {
if (y[k] % 2 == 0)
System.out.println(y[k]);
}
}
}
}
}
the output doesn't print the new array
matrix values
1 2 3 4 5
6 7 8 9 10
3 2 4 5 9
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Matrix.main(Matrix.java:43)
Replace i by k here :
for (int j = 0; j < 5; j++) {
int[] y = matrix[j];
for (int k = 0; i < y.length; i++) {
if (y[k] % 2 == 0)
System.out.println(y[k]);
}
}
I'm trying to figure out what's wrong with my code for printing the two dimensional array
int[][] container = new int [3][6];
for (int i = 0; i <= 3; i++) {
for (int j = 0; j <== 6; j++) {
System.out.print(contianer[i][j] + " ");
}
}
System.out.println();
<==is not an operator.
Array start from 0 to length - 1
you have a typo in your variable inside the for
System.out.println();must be executed inside the first for not outside.
int[][] container = new int [3][6];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
System.out.print(container[i][j] + " ");
}
System.out.println();
}
I want to traverse a 3*3 submatrix within a large 7*7 matrix starting position from (1,1) that is middle element (2nd row , 2nd column).
The corresponding submatrix of position (1,1) will be
[(0,1),(0,2),(0,3)]
[(1,1),(1,2),(1,3)]
[(2,1),(2,2),(2,3)]
Like this traversing will go on.. and next submatrix starting posiion will be (1,2)
[(0,2),(0,3),(0,4)]
[(1,2),(1,3),(1,4)]
[(2,2),(2,3),(2,4)]
My Code
static int i;
static int j;
static int g;
static int h;
static void submatrix(int p,int q,int[][] mat) {
System.out.print("Submatrix for : ");
System.out.println(p+","+q);
shiftmatrix(p,q,mat);
}
static void shiftmatrix(int p,int q,int[][] mat) {
int m,n;
int[][] d = new int[3][3];
for( m=0;m<3;m++) {
for( n=0;n<3;n++) {
p=m+(p-1);
q=n+q;
d[m][n]=mat[p][q];
}
}
System.out.println("Your 3*3 SubMatrix is : ");
for ( m = 0; m < 3; m++){
for ( n = 0; n < 3; n++){
System.out.print(d[m][n]+"\t");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] a = new int[7][7];
int[][] mat = new int[7][7];
for ( i = 0; i < 7; i++)
{
for ( j = 0; j < 7; j++){
Random rand = new Random();
a[i][j] = rand.nextInt(10);
}
}
//copying large matrix to another for passing by argument
System.out.println("Copied matrix is : ");
for (i = 0; i < 7; i++){
for (j = 0; j < 7; j++){
mat[g][h]=a[i][j];
System.out.print(mat[g][h]+"\t");
}
System.out.println();
}
//Here is the 3*3 submatrix traversing starts...
for (i=1;i<6;i++) {
for (j=1;j<5;j++) {
int p=i;
int q=j;
submatrix(p,q,mat);
}
}
}
}
while running this code getting error as
ArrayIndexOutOfBoundsException: -1
Please help
The IndexOutOfBoundsException in your code was from you calling p = m + (p - 1). You don't need to change the p and q variables within every iteration of the loop.
In addition, you had several unnecessary variables, and had some of them static, something you should avoid when you're only using them in a loop like this. After cleaning up the code's formatting and deleting all unnecessary variables I believe the code functions as you want it to.
The code ignores the first row and column of your random matrix. Is this desired behavior?
import java.util.Random;
public class MatrixTest {
public static void subMatrix(int startRow, int startCol, int[][] mat) {
System.out.print("Submatrix for : ");
System.out.println(startRow + ", " + startCol);
shiftMatrix(startRow, startCol, mat);
}
public static void shiftMatrix(int startRow, int startCol, int[][] mat) {
int[][] d = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//to properly move within the 3x3 you only need to add a
//constant buffer to the indices of mat[][]
d[i][j] = mat[i + startRow][j + startCol];
}
}
System.out.println("Your 3*3 SubMatrix is : ");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(d[i][j] + "\t");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] mat = new int[7][7];
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++){
Random rand = new Random();
mat[i][j] = rand.nextInt(10);
}
}
//copying large matrix to another for passing by argument
System.out.println("Copied matrix is : ");
for (int i = 0; i < 7; i++){
for (int j = 0; j < 7; j++) {
System.out.print(mat[i][j] + "\t");
}
System.out.println();
}
//Here is the 3*3 submatrix traversing starts...
for (int i = 1; i < 5; i++) { //changed from i < 6 to i < 5 to stay inside 7x7
for (int j = 1; j < 5; j++) {
subMatrix(i, j, mat);
}
}
}
}
I have already done with normal jagged array, but I don't understand how to reverse it upside down. Also I have a question, how to shift the side of triangle from left side to right? Can I do this with loops or I need to write different quantity of whitespaces for every line of my array?
static int[][] triangle(int lines){
int[][] arr = new int[lines][];
for(int i = 0; i < arr.length; i++){
arr[i] = new int[i + 1];
}
int count = 0;
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < arr[i].length; j++){
arr[i][j] = count++;
}
}
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < arr[i].length; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
return arr;
}
Some kind of result:
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
You can quickly create a reversed triangle by changing the way you initialize your arr array.
static int[][] revTriangle(int lines) {
int[][] arr = new int[lines][];
for (int i = 0; i < arr.length; i++) {
arr[i] = new int[lines - i]; // this line
}
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = count++;
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
return arr;
}
I get the following output:
0 1 2 3 4
5 6 7 8
9 10 11
12 13
14
Hope this helps!
If you need a more compact solution you can group some loops (basing on anacron answer):
static int[][] triangle( int lines, boolean straight)
{
int[][] arr = new int[lines][];
int count = 0;
for ( int i = 0; i < arr.length; i++ )
{
int start = (straight? i : lines);
int step = (straight? 1 : -i);
arr[i] = new int[start + step ];
for ( int j = 0; j < arr[i].length; j++ )
{
arr[i][j] = count++;
System.out.print( arr[i][j] + " " );
}
System.out.println();
}
return arr;
}
Where is the logic error?.. Sometimes the solution is correct and sometimes it is not. The program is suppose to calculate the row with the greatest sum and column with the greatest sum. For example:
1 1 1 1
0 0 1 0
0 0 1 0
0 0 1 0
Then the output would be:
largest row = 0
largest column = 2 //since count starts at 0
This is what I have:
import java.util.Random;
public class LargestRowAndColumn {
public static void main(String[] args) {
Random f = new Random();
int[][] m = new int[4][4];
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
System.out.println("The largest row is index: " + computeRow(m));
System.out.println("The largest column is index: " + computeColumn(m));
}
public static int computeRow(int[][] m) {
int[] count = new int[m.length];
int sum;
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[i][j];
}
count[i] = sum;
}
int maxIndex = 0;
for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
public static int computeColumn(int[][] m) {
int[] count = new int[m.length];
int sum = 0;
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[j][i];
}
count[i] = sum;
}
int maxIndex = 0;
for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
}
Your maxIndex nested loop is too complex. It should be a single loop, checking the current max value seen so far with the current item in the loop. Something like this:
int maxIndex = 0;
for (int i = 1; i < count.length; i++) {
if (count[i] > count[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
Your code is correct , but
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
Because of the two loops:
You are creating two random 2-dimensional array instead of one.
There is one which is being printed and the other one which is not being printed but being used for index values you require so do :
System.out.print("Index" + "\t0"+"\t1"+"\t2"+"\t3" +"\n");
System.out.print("--------------------------------------------\n");
for (int i = 0; i < m.length; i++) {
System.out.print(i+ "|\t");
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(101);
System.out.print(m[i][j] + " \t");
}
System.out.println();
}
This will also print the index, which may assist you
Why you made your job difficult. Make 2 loops, 1 for calculating the row with biggest sum, 1 for calculating the line with the bigger sum.
You don't need an int array count[i]. In your example you calculate the row with the greatest sum, you don't need to know the sum of every row after the for loop finished, so you can use a simple int bigRow.
int bigRow = 1, sumRow = 0;
// We assume that 1st row is the biggest
// Calculate the sumRow
for (int j=0;j<n;j++)
sumRow = sumRow + m[i][j] ;
// At this moment our maximum is row 1 with its sum.
// Now we compare it with the rest of the rows
// If another row is bigger, we set him as the biggest row
for ( int i=1;i<n;i++) // We start with row 2 as we calculated the 1st row
{ int auxRow = 0;
for (int j=0;j<m;j++)
{ auxRow = auxRow + m[i][j] ; }
if (auxRow > sumRow ) { auxRow=sumRow ; bigRow = i;}
}
Do the same with lines.
int bigLine = 1, sumLine = 0 ;
Let me know if you have another problem.