Copy 2D array and increase size to fill new values - java

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

Related

Swapping columns of the Matrix

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.

How to fix the following error java.lang.ArrayIndexOutOfBoundsException

I wanted to ask a question of code that has grated ja, I have the following code, I am going through a 10x5 array to fill it with number 1, to 49 for a primitive and the function that is responsible for making ticket gives me very rare errors. Index On Bound in theory the function would not have to go out of the way but I do not know what to do if someone can hit me.
// It is this part that gives me an error, I have a fly
int ,c=0;
int m[][]= new int[10][5];
for (int i=0;i<m.length;i++) {
for (int x=0;x<m.length;x++,i++) {
m[x][i]=c;
}
}
// This part of code I only have to check if the data output
// does them correctly
for(int i=0;i<m[0].length;i++) {
for(int x=0;x<m.length;x++) {
System.out.print(" "+m[i][x]+" ");
}
System.out.println(" ");
}
}
El error que me da es siguiente:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at provas/provas.main.main(main.java:11)
Looks like you want to fill given array with numbers from 1 to 49. So you have to pay attention on:
int[][] arr = new int[10][5] creates an int array with 10 rows and 5 columns
arr.length gives you a total rows amount
arr[0].length given you a total columns amount at row 0 (each row could have different length).
public static int[][] fillArray(int[][] arr) {
int i = 1;
for (int row = 0; row < arr.length; row++)
for (int col = 0; col < arr[row].length; col++)
arr[row][col] = i++;
return arr;
}
And finally to print an array:
public static void printArray(int[][] arr) {
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++)
System.out.format("%3d", arr[row][col]);
System.out.println();
}
}
You original method could be like this:
int[][] arr = fillArray(new int[10][5]);
printArray(arr);

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

Change int to string in a matrix

I want to convert some integers into a * based on a rule. I can determine which places in the matrix it should convert, but cannot convert it.
I give the program the first matrix and it should return the second matrix:
5 4 5 5 8
5 4 6 4 1
3 4 5 4 6
7 8 4 3 6
5 4 5 5 *
5 4 * 4 1
3 4 5 4 6
7 * 4 3 6
my code is this:
for(int i=1; i<r-1; i++) {
for(int a=1; a<c-1; a++){
if(matrix[i-1][a] < matrix[r][a] && matrix[i+1][a] < matrix[r][a] && matrix[i][a-1] < matrix[r][a] &&
matrix[i][a+1] < matrix[r][a]) {
matrix[r][a] = *;
}
}
}
Edit:
The matrix is an int type. I can determine which locations in the matrix should be converted, however the convertion itself does not work.
I get this error: Error: Syntax error on token "*", invalid Expression
you can use matrix of type Integer instead of int and then mark a * cell with null
Then when printing or using matrix show null values with *
You could leave int[][] matrix, and e.g. mark a * cells with some illegal number (e.g. Integer.MAX_VALUE). And when you print or use this matrix, do like: System.out.print(matrix[i][k] != Integer.MAX_VALUE ? matrix[i][k] : '*')
public static void main(String... args) {
int[][] matrix = new int[5][5];
modifyMatrix(matrix);
print(matrix);
}
public static void modifyMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++)
for (int col = 0; col < matrix[row].length; col++)
if (isStar(row, col, matrix))
matrix[row][col] = Integer.MAX_VALUE;
}
private static boolean isStar(int row, int col, int[][] matrix) {
// TODO your condition to place a '*'
return false;
}
private static void print(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0, max = matrix[row].length; col < msx; col++) {
System.out.print(matrix[row][col] != Integer.MAX_VALUE ? matrix[row][col] : '*');
System.out.println(col != max - 1 ? ' ' : '\0');
}
System.out.println();
}
}
In an int matrix you can't put characters or symbols(like '*')
The easiest thing to do is to change the type of the matrix. You should use char instead of int.
char[][] matrix = new char[r][c];
If you want to use an element from the matrix for equations you can use the
Character.getNumericValue(matrix[i][j]);
With this code it will return the number and if it has not numeric value it will return -1
You can check this link for the getNumericValue
click here
you should create an new array of strings the size of your matrix.
then run trough your matrix and either add the number or change it into a string, like this:
public String[] convert(int[] matrix,int rule) {
String[][] arr = new String[matrix.length][matrix[0].length];
for(int i = 0;i<matrix.length;i++) {
for(int j = 0; j<matrix[i].length;j++) {
if(matrix[i][j] == rule)
arr[i][j] = "*";
else
arr[i][j] = String.valueOf(matrix[i][j]);
return arr;

How to count the numbers of letters for each column in a String [][]?

I want to count the number of letters in a String [][] by column , so far my code is this :
for(int j = 0 ; j<matrix[0].length ;j++){
for(int i = 0 ; i< matrix.length ;i++ )
if (Character.isLetter(matrix[j][i].charAt(j)))
countChar++;
}
System.out.println(countChar + "letters");
return countChar;
but the output of the program counts how many elements the string has
for example if the String is :
String [][] C = {
{"abc", "abcd" , "abcd"},
{"oroeo", "kakakak" , "alsksjk"},
{"abcdef", "asdasdasdasd", "asdasdasdasd"},
};
the result is 9 , but should be 14 (number of letters by column )
Any help is greatly apreciated thank you !
You can define a 2D matrix as an array of rows or an array of columns. I'm assuming you have defined it as an array of rows and now want to get the values in a certain column.
So your data looks like this:
abc abcd abcd
oroeo kakakak alsksjk
abcdef asdasdasdasd asdasdasdasd
three rows and three columns.
to get for example the values in the middle column (with index 1) you would need to get the array elements:
matrix[0][1]
matrix[1][1]
matrix[2][1]
I think you are trying to count the total of the lengths of all values in each column. That would go like this:
// assume that the matrix has at least one row and thas the same number of columns in each row
// take the number of columns in the first row for reference
int numberOfColumns = matrix[0].length;
for(int col = 0; col < numberOfColumns; col++) {
int count = 0;
// iterate over all the rows
for(String[] row : matrix) {
// count the length of the element in position col of this row
count += row[col].length();
}
System.out.printf("%s characters in column %s", count, col);
}
int n = 0;
// iterate row by row
for (int i = 0; i < C.length; i++) {
n += C[i][0].length();
// get the string at index 0 (or 1 or 2.. whichever you want) of the array and append its length
// if you expect the string to contain numbers, then
// run a for-loop on the string and check if its a letter
}
System.out.println(n);
Try below the problem is with your for loop for which the no. of iterations are limited to the size of your matrix:
for(int i = 0 ; i<C[0].length ;i++) {
String matrixElement = C[i][0];
System.out.println(matrixElement);
for(int k =0 ;k < matrixElement.length();k++)
if (Character.isLetter(matrixElement.charAt(k)))
countChar++;
}
Please, format out your code and brush up the loop:
private static int countByColumn(String[][] matrix, int column) {
if (column < 0)
return 0; // Or throw exception
int countChar = 0;
for (String[] line : matrix) {
//DONE: jagged array: it may appear that the line is too short
if (line.length <= column)
continue;
String item = line[column];
for (int i = 0; i < item.length; ++i)
if (Character.isLetter(item.charAt(i)))
countChar += 1;
}
return countChar;
}
Test:
// 14
int test = countByColumn(C, 0);

Categories