Adding elements from one 2d array to another 2d array Java - java

I'm trying to add specific elements from one 2d array to another , the process of adding is that I'm choosing the smallest element in the first row of the array and add that element to the other 2d array at the same position so for example :
2 22 3
5 1 54
7 3 10
20 22 21
here the smallest element in the first row is 2 so 2 should be added to the other 2d array at the same position , and for the second row 1 is the smallest element so we add 1 to the other 2d array as well , the smallest element in the third row is 3 , and the final row the fourth row the smallest element is 20 but we cannot pick 20 as the smallest because we check the sum of columns in the second 2d array which was initialized with 0's , so here if we pick 20 then the sum of its column is 21 because 20 + 1 + 0 + 0 = 21 , if we pick 22 then 22 + 3 + 1 + 0 = 26 and if we pick 21 then 21 + 0 + 0 + 0 = 21 ,so here 21 is the smallest because the sum of its column is the smallest :
1 0 0
0 1 0
0 3 0
0 0 21
and the process goes on for the other rows and columns if there are any.
This is what I've made so far :
import java.util.Arrays;
public class Main
{
//Method which finds the sum of columns
public static int[] sumOfCol(int[][] tempArr){
int size = tempArr[0].length; // Replace it with the size of maximum length inner
array
int temp[] = new int[size];
for (int i = 0; i < tempArr.length; i++){
for (int j = 0; j < tempArr[i].length; j++){
temp[j] += tempArr[i][j];
}
}
System.out.println(Arrays.toString(temp));
return temp;
}
//The algorithm
public static void algorithm(int[][] tempArr,int[][] tempArr2){
for (int i = 0; i < tempArr.length; i++) {
int minimum = tempArr[i][0];
for (int j = 0; j < tempArr[0].length; j++) {
if (tempArr[i][j] < minimum) {
minimum = tempArr[i][j];
tempArr2[i][j] = minimum;
}
}
}
}
//To generate teh Array
public static void generateArray(int[][] arr){
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
arr[i][j] = (int) ((Math.random() * (25 - 1)) + 1);
}
}
}
//To print an array
public static void printArray(int[][] arr){
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int [][] tempArr = new int [5][3];
int[][] tempArr2 = new int[tempArr.length][tempArr[0].length];
//Initilise second array with 0's
for (int i = 0; i < tempArr2.length; i++) {
for (int j = 0; j < tempArr2[0].length; j++) {
tempArr2[i][j] = 0;
}
}
generateArray(tempArr);
System.out.println("Array before executing the algorithm : ");
printArray(tempArr);
algorithm(tempArr,tempArr2);
System.out.println("Array after executing the algorithm : ");
printArray(tempArr2);
}
}

I wasn't able to find the error in your code but found another way to do what you are looking for:
//The algorithm
public static int[][] algorithm(int[][] tempArr){
// create the empty array.
int[][] modifiedArr = new int[tempArr.length][tempArr[0].length];
for (int i = 0; i < modifiedArr.length; i++) {
for (int j = 0; j < modifiedArr[0].length; j++) {
modifiedArr[i][j] = 0;
}
}
// loop through all rows and change one value in each row on modifiedArr in a way that leads to the column sum being miniumum.
for (int i = 0; i < tempArr.length; i++) {
setMinimumColumn(tempArr,modifiedArr,i);
}
return modifiedArr;
}
static void setMinimumColumn(int[][] originalArr, int[][] modifiedArr, int row){
int minColumn = 0;
int minColumnSum = Integer.MAX_VALUE;
for (int i=0; i <originalArr[row].length ;i++){
modifiedArr[row][i] = originalArr[row][i];
int columnSum = getColumnSum(modifiedArr,i);
if (columnSum < minColumnSum) {
minColumn = i;
minColumnSum = columnSum;
}
modifiedArr[row][i] = 0;
}
modifiedArr[row][minColumn] = originalArr[row][minColumn];
}
static int getColumnSum(int[][] arr, int column){
int sum = 0;
for (int i = 0; i<arr.length; i++){
for (int j = 0; j<arr[0].length; j++) {
if (j == column){
sum+=arr[i][j];
}
}
}
return sum;
}
public static void main(String[] args) {
int [][] tempArr = new int [5][3];
generateArray(tempArr);
System.out.println("Array before executing the algorithm : ");
printArray(tempArr);
System.out.println("Array after executing the algorithm : ");
printArray(algorithm(tempArr));
}
Basically, you start by looping through the rows. Every row is given to the setMinimumColumn method, which loops through all element in that row and tries putting them in modifiedArr in a way that minimizes the column sum. Doing this for all columns gives you the answer.

Related

Printing the even numbers in the columns of 2D array

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]);
}
}

Transposing a 2D Array Only Works For Rectangular Arrays - Java

I have a class with a method that transposes an array given the array, rows, and columns
public class Transpose {
public static void main(String[] args) {
int[][] array = new int[6][5];
System.out.println("Original:");
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] += i+1;
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println();
transpose(array, 6, 5);
}
public static void transpose(int[][] array, int arrayRows, int arrayColumns)
{
int[][] transposedArray = new int[arrayRows][arrayColumns];
System.out.println("Transposed:");
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
transposedArray[i][j] = array[j][i];
System.out.print(transposedArray[i][j] + " ");
}
System.out.println();
}
}
}
The output I get looks like this:
Original:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
6 6 6 6 6
Transposed:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
I realized that the method only works when the values of arrayRows and arrayColumns are the same value, for example: 6, 6 or 5, 5. I tried to place the values opposite of each other, the rows in columns and vice versa, however it did not work. How can I get the method to work for non-rectangular/square arrays?
See line comments for explanation. Those are the only lines I modified.
public static void transpose(int[][] array, int arrayRows, int arrayColumns) {
int[][] transposedArray = new int[arrayColumns][arrayRows]; //swap number of rows and columns
System.out.println("Transposed:");
for (int i = 0; i < transposedArray.length; i++) { //take the length of transposedArray, not array
for (int j = 0; j < transposedArray[i].length; j++) { //take the length of transposedArray, not array
transposedArray[i][j] = array[j][i];
System.out.print(transposedArray[i][j] + " ");
}
System.out.println();
}
}
You need to swap the places of arrayRows and arrayColumns in the transposed matrix, because the new matrix is supposed to be a [5][6] instead of a [6][5].
So your line of
int[][] transposedArray = new int[arrayRows][arrayColumns];
becomes
int[][] transposedArray = new int[arrayColumns][arrayRows];
We also need to swap i and j in the following statement, because the loops are following the indices of the original matrix:
transposedArray[i][j] = array[j][i];
to
transposedArray[j][i] = array[i][j];
And lastly, you can't print the transposed matrix while you're creating it as you're doing now, because you're just re-printing the original matrix that way. I suggest printing the matrix after you're done creating it.
With these changes, your code ends up like this:
public static void main(String[] args) {
int[][] array = new int[6][5];
System.out.println("Original:");
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] += i+1;
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println();
transpose(array, 6, 5);
}
public static void transpose(int[][] array, int arrayRows, int arrayColumns)
{
int[][] transposedArray = new int[arrayColumns][arrayRows];
System.out.println("Transposed:");
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
transposedArray[j][i] = array[i][j];
}
}
for(int i = 0; i < transposedArray.length; i++) { //print the transposed matrix
for(int j = 0; j < transposedArray[i].length; j++) {
System.out.print(transposedArray[i][j] + " ");
}
System.out.println();
}
}
You can see a working example here.
for(int i = 0; i < array.length; i++)
// should count the number of rows. = 6
iterating from 0 ... 5
for(int j = 0; j < array[i].length; j++) // should count the number of columns = 5
iterate from 0..4
transposedArray[i][j] = array[j][i];
to access 6 ... you need j=5 ; i = 0...4
your loops are not able to access the values

Need some help using Java with matrix

I am studying and have a little trouble.
I have to build matrix like this on the picture
Matrix
But i can't put a stars in that places.
public static void main(String[] args) {
int[][] twoD = new int[5][5];
int i, j, k = 1;
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++) {
twoD[i][j] = k;
k++;
}
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++)
System.out.print(twoD[i][j] + " ");
System.out.print("\n");
}
}
Here is my code, please help to find
You can take the answer from a previous question and slightly modify it like so
public static void printCross(int size, char display)
{
int count = 0; //add a counter
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
count++; //increment each index we come across
if (row == col || row + col == size - 1) {
//print out the X using teh given display character
System.out.print(String.format("%-3s", display));
} else {
//print out the current count
System.out.print(String.format("%-3s", count));
}
}
System.out.println();
}
}
Output
X 2 3 4 X
6 X 8 X 10
11 12 X 14 15
16 X 18 X 20
X 22 23 24 X
I have found the easiest way i think.
public static void main(String args[]){
String[][] Matrix = { {" *"," 2"," 3"," 4"," *"} , {" 6"," *"," 8"," *","10"} , {"11","12"," *","14","15"} , {"16"," *","18"," *","20"} , {" *","22","23","24"," *"}};
for(int i=0; i< Matrix.length; i++){
for(int j=0;j < Matrix.length; j++){
System.out.print(Matrix[i][j]+" ");
}
System.out.println("");
}
}

convert a String array to a 2d array

I have a String array like this
3
1 5 5
2 -2 -3
15 -100 20
how can i convert this to a 2d array
1 5 5
2 -2 -3
15 -100 20
3 is the size of 2d
public static class convert(String[] lines){
int n = Integer.parseInt(lines[0]);
int[][] matrix = new int[n][n];
for (int j = 1; j < n; j++) {
String[] currentLine = lines[j].split(" ");
for (int i = 0; i < currentLine.length; i++) {
matrix[j][i] = Integer.parseInt(currentLine[i]);
}
}
}
Sin,
You have a couple of Off-by-one errors.
Try this:
int n = Integer.parseInt(lines[0]);
int[][] matrix = new int[n][n];
for (int j = 1; j <= n; j++) {
String[] currentLine = lines[j].split(" ");
for (int i = 0; i < currentLine.length; i++) {
matrix[j-1][i] = Integer.parseInt(currentLine[i]);
}
}
Please let me know if you have any questions!
Since arrays are 0-indexed in Java, you should change your loop initialization variable j to start at 0.
Change:
for (int j = 1; j < n; j++) {
to
for (int j = 0; j < n; j++) {
Also, it seems you want a method to do the conversion, not a class so you should remove this from your method signature and put void since you aren't returning anything from the method.
Change:
public static class convert(String[] lines)
To:
public static void convert(String[] lines)
Also, you should use a different variable to iterate through the string array to make things more cleaner. Since you are trying to use j, you can do that to. Instead of initializing j to 1, you initialize it to 0 as I've said and use j+1 as the index for accessing the lines array.
Here is how your code could look like:
public static void convert(String[] lines)
int n = Integer.parseInt(lines[0]);
int[][] matrix = new int[n][n];
for (int j = 0, k = 1; j < n; j++) {
String[] currentLine = lines[j + 1].split(" ");
for (int i = 0; i < currentLine.length; i++) {
matrix[j][i] = Integer.parseInt(currentLine[i]);
}
}
}

Reverse the rows of a 2d array

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();
}

Categories

Resources