Swapping columns of the Matrix - java

I made this code in order to swap places with the first column and the last column in a 3x3 Matrix. I would need to use 2 different methods, one to print the original matrix and one to print the modified matrix.
I was able to do the first one, but I have problems with the second.
public class SwapMatrix {
public static void main(String[] args) {
int matrix [][] =
{{3, 4, 5},
{7, 8, 9},
{1, 2, 3}};
System.out.println("\n Normal Matrix:");
print(matrix);
//int matrixModified [][] = swap(matrix);
//System.out.println("\n New Matrix:");
//print(matrixModified);
}
public static void print (int matrix[][]){
for (int i=0; i<matriz.length; i++){
for (int j=0; j<matrix[0].length; j++){
System.out.print(matriz [i][j]+ "\t");
}
System.out.println();
}
}
}

If you want to print the matrix backwards, all you have to do is to count reverse in your loop.
public static void printReverse (int matrix[][]){
for (int i=0; i<matrix.length; i++){ // lines
for (int j=matrix[0].length-1; j>=0; j--){ // columns backwards
System.out.print(matrix [i][j]+ "\t");
}
System.out.println();
}
}

You can implement the swap() method in two ways: either by creating a new matrix or by swapping the columns of the given matrix in place.
1. Firstly, you need to create a new matrix.
And then iterate over it with a nested for loop assigning the elements of each row in the new matrix in reversed order. I.e. the value of the first element of the row at position 0 would be assigned to the element at position matrix[0].length - 1 and vice versa (the same hold true for all other elements).
public static int[][] swap(int[][] matrix) {
int[][] result = new int[matrix.length][matrix[0].length];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
result[row][(matrix[0].length - 1) - col] = matrix[row][col];
}
}
return result;
}
2. To swap the given matrix in place, you need to create a nested for loop. Iteration in the inner loop should happen only until the middle of the array representing each row (that's important, if'll iterate over the full length of a row elements will get swapped twice and the matrix will remain the same).
public static int[][] swapInPlace(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length / 2; col++) {
int temp = matrix[row][(matrix[0].length - 1) - col];
matrix[row][(matrix[0].length - 1) - col] = matrix[row][col];
matrix[row][col] = temp;
}
}
return matrix;
}
Sidenote: although int matrix[][] is a valid syntax inherited from the C language, it's not a good practice to use it because this notation mixes two completely different notions: a variable name and a type. The preferred way to define an array int[][] matrix.

Related

Convert two dimensional array to one dimensional array in Java

I'm trying to convert a two-dimensional array to a one-dimensional array in Java.
I cannot use any additional data structures, ArrayLists, collections etc. for temporary storage.
Only one array can be allocated - the one that will be returned from the method.
There are three tests with arrays inputed into the method to validate the program. Test one has a 2D array with 3 rows and columns, test two has a 2D array with 3 rows and 1 column, and test three is empty.
My current code is:
public static int[] twoDConvert(int[][] nums) {
int index = 0;
int[] combined = new int[nums.length*3];
if (nums.length == 0) return combined;
for (int row = 0; row < nums.length; row++) {
for (int col = 0; col < nums.length; col++) {
combined[index] += nums[row][col];
index++;
}
}
return combined;
}
The first test works correctly, but for some reason the 2nd test throws ArrayIndexOutOfBoundsException (Index 1 out of bounds for length 1).
This occurs no matter how large or small the combined array length is.
How can I fix this?
We create a single Integer array with a length determines by the size method. Size takes the 2-dimensional array and finds the sum of all columns in each row and returns that sum. We check if the length is 0, and if so, we return. We then loop through all rows, followed by a loop through all columns in that row. We then assign the value at that row and column to that next index in the array. Unfortunately we can't do any math (to my knowledge) to determine the index based of row/column since they could be variable sizes.
public static int[] twoDConvert(int[][] nums) {
int[] combined = new int[size(nums)];
if (combined.length <= 0) {
return combined;
}
int index = 0;
for (int row = 0; row < nums.length; row++) {
for (int column = 0; column < nums[row].length; column++) {
combined[index++] = nums[row][column];
}
}
return combined;
}
private static int size(int[][] values) {
int size = 0;
for (int index = 0; index < values.length; index++) {
size += values[index].length;
}
return size;
}

having trouble replacing default zeros in 2d array with white spaces

My goal to to make three different 2D arrays, and for the last two replace all zeroes in the array values for blank spaces instead. I've tried using printf("%s","[]") but instead of replacing the zeros they just add the brackets above the array. i believe it has something to do with the placement of my else statement.
public class arrayprgm1{
public static int[][] Table(int x, int y){//creating first 2D array
int[][] array = new int[x][y];
for (int row= 0; row < array.length; row++){// using for loop to create array
for (int column=0;column<array[row].length;column++){//nested for loop
array[row][column]=(row+column)*3;// algorithm used for first 2D array
}
}
int sum = 0;//declaring integer to sum up all of the values created by array
for (int row=0; row < array.length; row++){
for (int column=0; column < array[row].length; column++){
sum = sum + array[row][column];// algorithm used to sum up values of first array
}
}
System.out.printf("The total of all the numbers added together is: %2d\n", sum);// using format print to display sum
return array;//return array created to the main method
}//end of Table method
public static int[][] Odds(int x, int y){//creating second 2D array
int[][]array = new int[x][y];
for (int row= 0; row < array.length; row++){// using for loop to create array
for (int column=0;column<array[row].length;column++){//nested for loop
{
if ((row + column)%2 !=0){ // if statement used to determine if value is odd or even
array[row][column]=(row+column)*3;// algorithm used for second array
}
else
System.out.printf("%s","[]");
}
}
}
int sum = 0;//declaring integer to sum up all of the values created by array
for (int row=0; row < array.length; row++){
for (int column=0; column < array[row].length; column++){
sum = sum + array[row][column];// algorithm used to sum up all odd values
}
}
for(int row=0; row< array.length;row++){
for(int column=0;column<array[row].length;column++){
}
}System.out.printf("The total of all the odd numbers added together is: %2d\n", sum);//format print used to display sum of all odd numbers
return array;
}//end of Odds Method
public static int[][] Evens(int x, int y){ //Creating the third 2D array that will hold all even values
int[][] array = new int[x][y];
for (int row= 0; row < array.length; row++){//for loop to create array
for (int column=0;column<array[row].length;column++){//nested for loop
{
if ((row + column)%2 ==0){//if statement used to determine if value is odd or even
array[row][column]=(row+column)*3;//algorithm used for third array
}
else
System.out.printf("%s","[]");
}
}
}
int sum = 0;// declaring integer to sum up all the even values
for (int row=0; row < array.length; row++){//for loop to create array
for (int column=0; column < array[row].length; column++){//nested for loop
sum = sum + array[row][column];// algorithm used to sum up all even numbers
}
}
System.out.printf("The total of all the even numbers added together is: %2d\n", sum);// format print used to display sum of all even numbers
return array;
}//end of Evens method
public static void main(String[] args){//main method
int[][]array = new int[15][15];//create array to pass to arrays method
array = Table(15,15);
for(int row=0; row < array.length; row++){ //for loop to properly display array in a square
for(int column=0; column<array[row].length;column++){//nested for loop
System.out.printf("%4d",array[row][column]);//format the print
}
System.out.printf("\n");
}
System.out.printf("\n");
array = Odds(15,15);
for(int row=0; row < array.length; row++){//for loop to properly display array in square
for(int column=0; column<array[row].length;column++){//nested for loop
System.out.printf("%4d",array[row][column]);//format the print
}
System.out.printf("\n");
}
System.out.printf("\n");
array = Evens(15,15);
for(int row=0; row < array.length; row++){//for loop to properly display array in square
for(int column=0; column<array[row].length;column++){//nested for loop
System.out.printf("%4d",array[row][column]);//format the print
}
System.out.printf("\n");
}
}//end of main method
}//end of public class arrayprgm1
You can't replace a zero with a character like space in an array containing integers as you intend to do it. Instead what you need to do this is handle this when you output the array and check for zero values there.
For instance
for(int row=0; row < array.length; row++){
for(int column=0; column<array[row].length;column++){
int value = array[row][column];
if (value == 0) {
System.out.printf(" ");
else {
System.out.printf("%4d",value);
}
}
}

Copy 2D array and increase size to fill new values

I would like to first apologize if my question is worded badly. I have an exam tmmrw and the prof gave a sample final exam for us to practice with. He unfortunately isn't responding with the solutions on the forum so I am trying to provide solutions on there. I seem to be stuck on this question. I have to write a method that accepts and NxM array filled with integer values as a parameter. The method is to return an (N+1)x(M+1) array which contains the contents of the original array in the first N rows and M columns plus a count of items greater than or equal to zero in each row/column at the end of that row/column and put the value -1 in the bottom right corner. for example.
1 -2 0 returns 1 -2 0 2
3 -4 -5 3 -4 -5 1
2 0 1 -1
I seem to be able to copy the array yet I am puzzled as to how I can enter the values in the outer parts of the new array. Here is what I have so far.
public static void main(String[] args) {
int[][] arr = { { 1, -2, 0 }, { 3, -4, -5 } };
int[][] newMatrix = processing2D(arr);
printArray(newMatrix);
}
//Method where I am having problems
public static int[][] processing2D(int[][] arr) {
int[][] matrix = new int[arr.length][arr[0].length];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
matrix[row][col] = arr[row][col];
}
}
// assign the corner -1 here
return matrix;
}
public static void printArray(int[][] list) {
for (int row = 0; row < list.length; row++) {
for (int col = 0; col <= list.length; col++) {
System.out.print(list[row][col] + " ");
}
System.out.println();
}
}
First off you are initializing the new array wrong it should be
int[][] matrix = new int[arr.length+1][arr[0].length+1];
You don't want it to be the same length you want it to be the length +1. Also in your for loops you want to go by the length of arr not matrix since thats what you're taking from. While putting the values into the new N+1xM+1 array, increment the value of the corresponding last element in that row and column by 1 if it is >=0.
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
if(arr[row][col]>=0){
matrix[row][matrix[row].length-1] = matrix[row][matrix[row].length-1] + 1;
matrix[matrix.length-1][col]= matrix[matrix.length-1][col] + 1;
}
matrix[row][col] = arr[row][col];
}
After putting all the values back into the new N+1xM+1 array you should now take the values in the n sized and m sized arrays and put them into the corresponding slot in the N+1xM+1 array. After that just put the -1 in the bottom right slow manually.
matrix[matrix.length-1][matrix[0].length-1]=-1;
In your process2D method start off by creating an array with the correct size which has 1 more row and 1 more column than the original:
int[][] matrix = new int[arr.length+1][arr[0].length+1];
Then to populate the matrix array you do like you were doing before, but you need to take care not to reference an index of the arr array that is out of bounds. Because your matrix index is bigger than arr. If you are populating the new indexes then you can just use random numbers.
if(row < arr.length && col < arr[0].length)
{
matrix[row][col] = arr[row][col];
}
else
{
matrix[row][col] = new Random().nextInt(10);
}
So here is the full method process2D:
public static int[][] processing2D(int[][] arr) {
int[][] matrix = new int[arr.length+1][arr[0].length+1];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
if(row < arr.length && col < arr[0].length)
{
matrix[row][col] = arr[row][col];
}
else
{
matrix[row][col] = new Random().nextInt(10);
}
}
}
// assign the corner -1 here
return matrix;
}

Combining elements in jagged 2D arrays into one new jagged 2D array (Deep Copy issue)

Given two jagged arrays: a & b where a + b will always have the same # of rows:
int[][] a = { {1,2}, {4,5,6} };
int[][] b = { {7}, {8,9,0} };
how exactly can I manipulate a new jagged array c to return:
{ {1,2,7}, {4,5,6,8,9,0} }?
Here's what I have so far:
int[][] c = null;
for(int i = 0; i<a.length; i++){
c = new int[a.length][a[i].length + b[i].length];
}
//rest of my code for assigning the values into the appropriate position works.
The trouble arises, as you all can see, that I am performing a deep copy, which, on the second iteration of the for-loop, is setting ALL rows to a length of the length of the current row on the step of the iteration.
Flaw in your approach
You are creating a new 2D array object each iteration of your loop. Each time through, you are reassigning c, thus throwing out all of your previous work. Additionally, placing a number in both set of brackets at the same time results in each row having the same length.
Using your example, the first time through the loop, c is assigned to a 2D array with two rows, each of length three. The second time through the loop, you throw out your previous 2D array and create a new one having two rows, each of length six.
But what you need to be doing is creating a new row each time through the loop, not the entire 2D array.
Solution
First, we create a 2D array called c and specify that it has a.length rows. We don't put a value in the second bracket, because that would indicate that all of the rows are of the same length. So at this point, c does not know about row length. It just knows how many rows it can have. Keep in mind: c doesn't actually have any rows yet, just a capacity for a.length rows.
Next, we must create the rows and assign a length/capacity to them. We set up our loop to run as many times as there are rows. The current row index is denoted by i, and therefore, c[i] refers to a specific row in the 2D c array. We use new int[] to create each individual row/array, but inside the brackets, we must specify the length of the current row. For any row c[i], its length is given by the sum of the lengths of a[i] and b[i]; that is, a[i].length + b[i].length.
What we are left with is an array c that contains rows/arrays, each with a set length/capacity that matches the sum of the corresponding rows lengths in a and b.
Keep in mind that c still does not contain any integer values, only containers that are of the correct size to hold the values in a and b. As you mentioned, you already have code to populate your array with values.
int[][] c = new int[a.length][];
for (int i = 0; i < a.length; i++) {
c[i] = new int[a[i].length + b[i].length];
}
When initialize Java 2D array, lets consider it as a table; you only have to give the number of rows and in each row of your table can have different number of columns.
Eg. Say we have a 2D array call c defined as follows,
int[][] c = new int[10][];
It says you defined c contains 10 of int[] elements. But in order to use it you have to define the number of columns each row has.
Eg. Say we have 3 columns in the second row
int c[1] = new int[3];
So in this example you have to add the column values of 2D arrays a and b to calculate the resultant array which is c.
c[i] = new int[a[i].length + b[i].length];
This will give you what you expected.
int[][] a = { {1,2}, {4,5,6} };
int[][] b = { {7}, {8,9,0} };
int[][] c = new int[a.length][];
for(int i = 0; i<a.length; i++){
c[i] = new int[a[i].length + b[i].length];
for (int j=0;j< a[i].length; j++) {
c[i][j] = a[i][j];
}
int length = a[i].length;
for (int j=0;j< b[i].length; j++) {
c[i][length+j] = b[i][j];
}
}
Try c[i] = new int[a[i].length + b[i].length]
int[][] c = new int[a.length][];
for(int i = 0; i < c.length; i++){
c[i] = new int[a[i].length + b[i].length];
int x = 0;
for (int num : a[i]) {
c[i][x] = num;
x++;
}
for (int num : b[i]) {
c[i][x] = num;
x++;
}
}
or even simpler...
int[][] c = new int[a.length][];
for(int i = 0; i < c.length; i++){
c[i] = new int[a[i].length + b[i].length];
System.arraycopy(a[i], 0, c[i], 0, a[i].length);
System.arraycopy(b[i], 0, c[i], a[i].length, b[i].length);
}
Try this one:
int[][] c = new int[a.length][];
for(int i = 0; i<a.length; i++){
c[i] = new int [a[i].length + b[i].length];
int j;
for(j=0; i < a[i].length; j++){
c[i][j] = a[i][j];
}
for(int k=0; i < b[i].length; k++){
c[i][j+k] = b[i][j];
}
}
public static void main(String [] args) {
int[][] a = { {1,2}, {4,5,6} };
int[][] b = { {7}, {8,9,0} };
int[][] c = null;
for(int i = 0; i<a.length; i++){
c = new int[a.length][a[i].length + b[i].length];
}
for(int i = 0; i<a.length; i++){
for (int j = 0; j < a[i].length+b[i].length; j++) {
if(j< a[i].length){
c[i][j]=a[i][j];
}
if(j< a[i].length+b[i].length && j>= a[i].length){
c[i][j]=b[i][j-a[i].length];
}
}
}
for(int i = 0; i<a.length; i++){
for (int j = 0; j < a[i].length+b[i].length; j++) {
System.out.print(c[i][j]);
}
System.out.println();
}
}
This works in my system ...........

error while trying to get a sum

I am trying to get the sum of my array called matrix. However when I compile it I receive this error: bad operand types for binary operator '+' first type: int; second type:int[]. I do not understand why this is causing an error. Please help me understand, here is my code:
/**
Sophia Ali
1. Matrix, getSumMatrix, getSumMatrixDiag:
Email just Matrix.java.
Write a class called Matrix that contains a private 2-dimensional int
array called 'matrix' that can be up to 10 rows by 10 columns maximum.
Use two constants MAXROWS=10 and MAXCOLS=10 to construct 'matrix.'
The Matrix class will also need the following attributes:
private int rows; // number of rows to use in matrix
private int cols; // number of cols to use in matrix
The rows and cols will contains values that are less than equal to
MAXROWS and MAXCOLS.
Write a default Matrix class constructor that constructs the 'matrix'
array with the following values:
{{1,2,4,5},{6,7,8,9},{10,11,12,13}, {14,15,16,17}}
The constructor must also set the rows and cols variables to match the
above matrix.
Write a method 'getSumMatrix' that returns the sum of all the integers
in the array 'matrix'.
Write a method 'getSumMatrixDiag' that returns the sum of all the
integers in the major diagonal of the array 'matrix'. A major diagonal is
the diagonal formed from the top left corner to the bottom right corner of
the matrix.
You do not have to write a TestMatrix class to test the Matrix class.
Just use the BlueJ object creation and testing feature.
*/
public class Matrix
{
static final int MAXROWS = 10;
static final int MAXCOLS = 10;
private int rows;
private int cols;
private int [][] matrix = new int [MAXROWS][MAXCOLS];
public Matrix()
{
int matrix[][] =
{
{1, 2, 4, 5},
{6, 7, 8, 9},
{10, 11, 12, 13},
{14, 15, 16, 17}};
getSumMethod(matrix);
getSumMatrixDiag(matrix);
}
public int getSumMethod(int[][] matrix)
{
int sum = 0;
for (int i = 0; i < matrix.length; i++) {
sum += matrix[i];
}
return sum;
}
/*
int i, result;
result = 0;
for(i=0; i < matrix.length; i++)
{
i++;
result = result + i;
}
return result;
}
*/
public int getSumMatrixDiag(int[][] matrix)
{
int sum = 0;
for (int i =0; i< matrix.length; i++)
{
i++;
sum = (int)(sum + matrix[i][i]);
}
return sum;
}
}
When summing a multidimensional matrix, you must loop over all dimensions. So in your case you have a two dimensional array, therefore you need two nested loops to traverse both arrays.
Your loop:
int sum = 0;
for (int i = 0; i < matrix.length; i++) {
sum += matrix[i];
}
return sum;
Should look like:
int sum = 0;
for(int i =0; i < matrix.length){
for(int j = 0; j < matrix[i].length; j++){
sum += matrix[i][j];
}
}
return sum;

Categories