how to sort 2d array diagonal elements - java

public class DiagonalSort {
static int sortDiagonal(int m[][]) {
int[] intArray = new int[4];
int k=0;
//to insert 2d array diagonal elements into 1d array
for(int i = 0; i<m.length; i++){
for(int j= 0; j<m[i].length; j++) {
if(i == j) {
int n = m[i][j];
intArray[k]=n;
k++;
}
}
}
// sorting 1d array elements
Arrays.sort(intArray);
// inserting sorted elements to its appropriate positions
for(int i = 0; i<m.length; i++){
for(int j= 0; j<m[i].length; j++) {
if(i == j) {
m[i][j]= intArray[i];
}
}
}
//printing the diagonal elements
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
return 0;
}
public static void main(String args[])
{
int m[][] = { { 36, 10, 24, 8 },
{ 12, 23, 0, 2 },
{ 9, 5, 10, 2 },
{ 6, 3, 1, 2 } };
sortDiagonal(m);
} }
I have used very simple logic:
first insert the diagonal elements to 1d array
sort the 1d array
insert the elements of sorted 1d array into 2d array diagonal positions
Always welcome for more efficient answer.

1.Your logic is good enough but you can optimize your code by removing some extra loops.
2.If you want to access only diagonal elements then you don't need to run 2 loops.
3.You can do like this
package test.code;
import java.util.Arrays;
public class DiagonalSort {
static int sortDiagonal(int m[][]) {
int[] intArray = new int[4];
//to insert 2d array diagonal elements into 1d array
for(int i = 0; i<m.length; i++){
intArray[i] = m[i][i];
}
// sorting 1d array elements
Arrays.sort(intArray);
// inserting sorted elements to its appropriate positions
for(int i = 0; i<m.length; i++){
m[i][i]= intArray[i];
}
//printing the diagonal elements
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
return 0;
}
public static void main(String args[])
{
int m[][] = { { 36, 10, 24, 8 },
{ 12, 23, 0, 2 },
{ 9, 5, 10, 2 },
{ 6, 3, 1, 2 } };
sortDiagonal(m);
} }

**Java class to sort diagonal element**
class Solution {
public int[][] diagonalSort(int[][] mat) {
int row=mat.length;
int col=mat[0].length;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
for(int r=i+1,c=j+1;r<row && c<col;r++,c++){
if(mat[i][j]>mat[r][c]){
// Swap the value
int temp=mat[i][j];
mat[i][j]=mat[r][c];
mat[r][c]=temp;
}
}
}
}
return mat;
}
}

Related

How to reverse the rows of the matrix, if the sum row is less than the sum last column?

How can I reverse rows in a matrix, which sums less than the sum last column?
For example:
1,2,3 -> sumRow1 = 6;
4,5,6 -> sumRow2 = 15;
7,8,9 -> sumRow3 = 24;
sumLastCol = 18;
row1 & row2 - reverse, row3 - unchange
Can I do it at once in the matrix or do I need to create a new array?
This is my code, but it doesn't work correctly:
public static void reverseMatrix(int n, int[][]randMatrix, int sumRow, int sumCol){
for(int i=0; i<n; i++){
int start = 0;
int end = n-1;
if(sumRow<sumCol) {
while (start < end) {
int temp = randMatrix[i][start];
randMatrix[i][start] = randMatrix[i][end];
randMatrix[i][end] = temp;
start++;
end--;
}
}
}
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
System.out.print(randMatrix[i][j]+"\t");
}
System.out.println();
}
}
public static int sumLastColumn(int n, int[][]randMatrix){
int sumCol = 0;
for(int i=0; i<n; i++){
int[]row = randMatrix[i];
sumCol += row[row.length-1];
}
System.out.println("SumLastCol: "+sumCol);
return sumCol;
}
public static int sumRows(int n, int[][]randMatrix) {
int sumRow = 0;
for (int i=0; i<n; i++) {
sumRow = 0;
for (int j=0; j<n; j++) {
sumRow = sumRow + randMatrix[i][j];
}
System.out.println("SumRow"+(i+1)+": " + sumRow);
}
return sumRow;
}
}
If you know how to do it, please help me:)
Here's an easy way.
int[][] mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
First, compute the sum of the last column.
stream each row
map the last value in the row
and sum them.
int lastColSum = Arrays.stream(mat).mapToInt(s->s[s.length-1]).sum();
Now just iterate across the rows, summing them and comparing to the lastColSum and reverse if required.
for (int[] row :mat) {
if (Arrays.stream(row).sum() < lastColSum) {
reverse(row);
}
}
for (int[] row :mat) {
System.out.println(Arrays.toString(row));
}
prints
[3, 2, 1]
[6, 5, 4]
[7, 8, 9]
Helper method to reverse the row. It works by swapping values at it moves outside toward the middle. This works for even or odd length rows.
public static void reverse(int [] v) {
for(int i = 0; i < v.length/2; i++) {
int t = v[0];
v[0] = v[v.length-i-1];
v[v.length-i-1] = t;
}
}

How to append and prepend 2D arrays in Java without Array copy assuming the column sizes are the same?

I've tried following this one How do you append two 2D array in java properly? removing all of the array copys but something is wrong. I also tried another guide but that only worked if the rows were the same.
public int [][] appendMatrix(int[][]matrix, int [][] matrix2)
{
this.matrix = new int[matrix.length + matrix2.length][matrix[0].length];
for(int i = 0; i < matrix.length; i++)
{
for(int j = 0; j < matrix[i].length; j++)
{
this.matrix[i][j] = matrix[i][j];
}
for(int j = matrix.length; j < matrix.length + matrix2.length; j++)
{
this.matrix[i][j]= matrix2[i-matrix.length][j];
}
}
return this.matrix;**
The important thing to consider is when we go from the final row in our first matrix, we want to keep that value so we can use it to add the first through n'th row of our second matrix to our resulting matrix, without losing track.
Example output: output as an array and visualized as a matrix
package matrix;
// I know you don't want to use imports, this is simply for testing purposes.
import java.util.Arrays;
public class MatrixAddition
{
public static void main(String[] args)
{
int[][] matrix1 =
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
{ 10, 11, 12 } };
int[][] matrix2 =
{
{ 1, 1, 1 },
{ 2, 3, 4 } };
System.out.println("Appending the two matrices results in: ");
System.out.println(Arrays.deepToString(twoDMatrixAppend(matrix1, matrix2)));
printMatrix(twoDMatrixAppend(matrix1, matrix2));
System.out.println("\nPrepending the two matrices results in: ");
System.out.println(Arrays.deepToString(twoDMatrixPrepend(matrix1, matrix2)));
printMatrix(twoDMatrixPrepend(matrix1, matrix2));
}
private static int[][] twoDMatrixAppend(int[][] matrix1, int[][] matrix2)
{
if (matrix1[0].length != matrix2[0].length)
{
return null; // Or throw new incompatible matrices exception
}
int resultingRowLength = matrix1.length + matrix2.length; // The new length of the resulting matrix
int[][] result = new int[resultingRowLength][matrix1[0].length];
int currentRow, col, matrixTwoRowStart;
for (currentRow = 0; currentRow < matrix1.length; currentRow++)
{
for (col = 0; col < matrix1[0].length; col++)
{
result[currentRow][col] = matrix1[currentRow][col];
}
}
for (matrixTwoRowStart = 0; matrixTwoRowStart < matrix2.length; matrixTwoRowStart++, currentRow++)
{
for (col = 0; col < matrix2[0].length; col++)
{
result[currentRow][col] = matrix2[matrixTwoRowStart][col];
}
}
return result;
}
private static int[][] twoDMatrixPrepend(int[][] matrix1, int[][] matrix2)
{
return twoDMatrixAppend(matrix2, matrix1);
}
private static void printMatrix(int[][] arr)
{
System.out.println();
int row, col;
for (row = 0; row < arr.length; row++)
{
for (col = 0; col < arr[0].length; col++)
{
System.out.print(String.format("%4d", arr[row][col]));
}
System.out.println();
}
}
}

How to make two unequal 2D arrays equal by adding zeroes in null positions in java?

lets say my matrix A has order of 3 x 2 and Matrix B has order of 2 x 4. My resultant Matrix should be in the order of 3 x 4 and it should contain the addition of Matrix A and Matrix B. In order to achieve this I must first make Matrix A and Matrix B equal in size (both should be 3 x 4) by appending the necessary zeroes.
EXAMPLE :-
int[][] a = { {1,0}, {1,1}, {1,0} };
int[][] b = { {1,1,0,1}, {1,1,1,1} };
sumArray(a,b) will return: { {2,1,0,1}, {2,2,1,1}, {1,0,0,0} }
what I tried was. (ans.length means the resultant matrix length)
for(int i =0;i<ans.length;i++)
{
for(int j=0;j<ans[i].length;j++)
{
if(arr1[i][j] == null)
{
arr1[i][j]= 0;
}
if(arr2[i][j] == null)
{
arr2[i][j]= 0;
}
}
}
First you have to find the size of your output array.
int h = a.length>b.length?a.length:b.length;
int w = a[0].length>b[0].length?a[0].length:b[0].length;
int[][] result = new int[h][w];
Then do your assignments.
for(int i = 0; i<result.length; i++){
for(int j = 0; j<result[i].length; j++){
if(i<a.length && j < a[i].length){
result[i][j] += a[i][j];
}
if(i<b.length && j < b[i].length){
result[i][j] += b[i][j];
}
}
}
return result;
Use this code. Just make the dimension identifying part dynamic
import java.util.Arrays;
public class Main
{
public static void main (String[]args)
{
System.out.println ("Hello World");
int m1 = 3, n1 = 1, m2 = 2, n2 = 4; // m1 and n1 are matrix 'x' dimensions and m2 & n2 are natrix 'y' dimensions
int x[][] = {
{1},
{2},
{3}
};
int y[][] = {
{1, 2, 1, 2},
{1, 2, 1, 2}};
int op[][] = new int[m1][n2];
for (int[] row: op)// filling empty matrix with zeroes
Arrays.fill(row, 0);
for (int i = 0; i < m1; i++)
{
for (int j = 0; j < n1; j++)
{
op[i][j] = x[i][j];
}
}
int op2[][] = new int[m1][n2];
for (int[] row: op2)// filling empty matrix with zeroes
Arrays.fill(row, 0);
for (int i = 0; i < m2; i++)
{
for (int j = 0; j < n2; j++)
{
op2[i][j] = y[i][j];
}
}
for(int i=0;i<m1; i++)
{
for(int j=0;j<n2;j++)
{
System.out.print((op[i][j]+op2[i][j])+" ");
}
System.out.println();
}
}
}

Sorting an array into a 2nd array in Java

I need to make 2 arrays and sort one into the other in ascending order and display it. I've managed to move ar[] into sorted[], but I can't get it to actually sort.
Here's what I have so far:
public class SortArray
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[7];
for (int i=0; i<ar.length-1; i++)
{
int smallest = 1000000;
int index = 0;
for (int j=i+1; j<sorted.length; j++)
{
if (ar[i] < smallest)
{
smallest=i;
int tmp = ar[i];
ar[i] = sorted[j];
sorted[j] = tmp;
}
}
}
for(int i=0; i<sorted.length; i++)
{
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}
Just try to understand and use java algorithms here. If you have problems with understanding the idea please do not hesitate to ask.
http://www.java2novice.com/java-sorting-algorithms/
They are more efficient and they are not error prone.
Assuming that you are trying to learn sorting algorithms and coding, here is what you are trying to; Please be aware that if there are identical values it will get only one of them.
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[6];
int smallestFound=-1;
for (int i=0; i<ar.length-1; i++)
{
int smallest = 1000000;
for (int j=0; j<sorted.length; j++)
{
if (ar[j] < smallest && ar[j]>smallestFound) {
smallest = ar[j];
}
}
smallestFound=smallest;
sorted[i] = smallest;
}
for(int i=0; i<sorted.length; i++)
{
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
you can use a TreeSet , it sort the element naturally:
public class SortArray
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[7];
List<Integer> sortedList = new TreeSet<Integer>();
for (int i=0; i<ar.length-1; i++) {
sortedList.add(ar[i]);
}
// transform into array
for(int i = 0; i< sortedList.size(); i++) {
sorted[i] = sortedList.get(i)
}
for(int i=0; i<sorted.length; i++)
{
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}

Swapping adjacent numbers in arrays

Here's the problem: Write a method called swapPairs that accepts an array of integers and swaps the elements at adjacent indexes. That is, elements 0 and 1 are swapped, elements 2 and 3 are swapped, and so on. If the array has an odd length, the final element should be left unmodified. For example, the list {10,20,30,40,50} should become {20,10,40,30,50} after a call to your method.
Write method printArray that is passed an array and will print out each element.
Use this method to print the array modified by swapPairs.
This is my code:
public static void swapPairs(int[] a){
int len=a.length;
if(len%2 ==0){
for(int i=0; i<len; i=i+2){
a[i]=a[i+1];
a[i+1]=a[i];
int[] b={a[i]+a[i+1]};
}
}
if(len%2 !=0){
for(int j=0; j<len; j=j+2){
a[j]=a[j+1];
a[j+1]=a[j];
a[len-1]=a[len-1];
int[] b={a[j]+a[j+1]+a[len-1]};
}
}
}
public static void printArray(int[] a){
System.out.println(a);
}
However, what it returns is [I#2a139a55
What you need to print is Arrays.toString(a)
Now, you are just printing the Hashcode of your Array object
First, your swap method could be simplified. Add both numbers together, and then subtract each from the sum (to get the other number). Something like,
public static void swapPairs(int[] a) {
for (int i = 0; i < a.length - 1; i += 2) {
int c = a[i] + a[i + 1];
a[i] = c - a[i];
a[i + 1] = c - a[i + 1];
}
}
Then you could use Arrays.toString(int[]) to get a String. Like,
public static void printArray(int[] a) {
System.out.println(Arrays.toString(a));
}
I tested the above like
public static void main(String[] args) {
int[] t = { 1, 2, 3, 4 };
printArray(t);
swapPairs(t);
printArray(t);
}
And I got
[1, 2, 3, 4]
[2, 1, 4, 3]
After almost breaking my computer several times, here's the actual working code:
public static void swapPairs(int[] a){
int len=a.length;
if(len%2 ==0){
for(int i=0; i<len; i=i+2){
int c=a[i]+a[i+1];
a[i]=c-a[i];
a[i+1]=c-a[i+1];
}
}
if(len%2 !=0){
for(int j=0; j<len-1; j=j+2){
int c=a[j]+a[j+1];
a[j]=c-a[j];
a[j+1]=c-a[j+1];
}
a[len-1]=a[len-1];
}
}
public static void printArray(int[] a){
int len=a.length;
for(int i=0;i<len;i++)
System.out.print(a[i]+" ");
}
public static void swapPairs(int[] arr){
int length = arr.length%2 == 0? arr.length : arr.length-1;
for(int i=0; i<length; i=i+2) {
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
// print the array
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}
public static void swapPairs(int[] a){
int len = a.length - a.length % 2; // if len is odd, remove 1
for(int i = 0; i < len; i += 2) {
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
public static void printArray(int[] a){
System.out.println(Arrays.toString(a));
}
public static void main(String[] args) {
int[] iArr1 = {10, 20, 30, 40, 50};
int[] iArr2 = {10, 20, 30, 40, 50, 60};
swapPairs(iArr1);
swapPairs(iArr2);
printArray(iArr1); // [20, 10, 40, 30, 50]
printArray(iArr2); // [20, 10, 40, 30, 60, 50]
}
final int[] number = new int[] { 1, 2, 3, 4, 5, 6, 7 };
int temp;
for (int i = 0; i < number.length; i = i + 2) {
if (i > number.length - 2) {
break;
}
temp = number[i];
number[i] = number[i + 1];
number[i + 1] = temp;
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j]);
}
import java.util.Scanner;
public class SwapEveryPair {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = scn.nextInt();
}
for (int i = 0; i < (arr.length - 1); i += 2) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
for(int i=0; i< arr.length; i++){
System.out.println(" " + arr[i]);
}
}
}``
I think this should work,
public static void swapAlternate(int[] input){
for(int i=0;i<input.length - 1; i+=2){
int temp = input[i];
input[i] = input[i+1];
input[i+1] = temp;
}
}

Categories