Convert two dimensional array to one dimensional array in Java - 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;
}

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.

Insert value to 2d array

I have a loop to loop through 0-200 and if the number matches the number in the list. I will put it inside the freq[][]. However, I'm having problem into putting the numbers I found into the freq[][] considering that it needs to be in the size of [10][20].
public static void example(List<Integer> numbers, List<Integer> elements, int[][] list){
int index = 0;
int[][] freq = new int[10][20];
for (int i = 0; i < 200; i++){
for (int x = 0; x < list.length; x++){
for (int y = 0; y < list[x].length; y++){
if (list[x][y] == i){
freq[][index] = i;
}
}
}
}
}
Keep it as
if (list[x][y]== i){
freq[x][y] = i;
}
else {
freq[x][y] = 0; // if not matched
}
So that freq will be a two dimensional array with 10rows and 20 columns .
-Element at 5th index position in the list will be in 0*5th position in the 10*20 array.
-Element at 199 th index position in the list will be in 9*19th position in the 10*20 array.
first, you make a loop to read 200 numbers inside this loop you want to loop 2d array to compare its elements by every number and make condition if a number exist in list but it in freq[][] this code put every number Achieves the condition in freq array and otherwise but 0
for (int i = 0; i <= 200; i++) {
for (int j = 0; j < list.length; j++) {
for (int k = 0; k < list[j].length; k++) {
if(list[j][k]==i)
freq[j][k]=i;
}
}
}
if you use `
else
freq[j][k]=0;
`
that mean it start putting in array the number or 0, and finally, you get an array don't match you want, so let if condition only without else I test it and it work for me

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

Java: How to store a 2D array within a 1D array

I trying to store my already found 2D array into a 1D array for faster processing later. However, I keep getting a nullPointerException when I try to fill the 1D array. What happens is a txt file has the number of rows and colums that we read first to get the row and column amount for doing the 2D array. Then each index reads the next data element on the txt file and stores it at that index until all 50 000 integer values are stored. That WORKS fine.
Now I want to take that 2D array and store all the elements into a 1D array for faster processing later when looking for answers without using an array list or put them in order, which is fine,
int [][] data = null;
int[] arrayCount = null;
for (int row = 0; row < numberOfRows; row++)
{
for (int col = 0; col < numberOfCols; col++)
{
data[row][col] = inputFile.nextInt();
}
}
//Doesn't Work gives me excpetion
data[0][0] = arrayCount[0];
I tried this in for loops but no matter what I get a NullPointerException
You haven't initialized the data and arrayCount variables, initialize it as follows :
int[][] data = new int[numberOfRows][numberOfCols];
int[] arrayCount = new int[numberOfRows * numberOfCols];
In your case, to copy from 2D to 1D array you may use something like this :
numberOfRows = data.length;
if (numberOfRows > 0) {
numberOfCols = data[0].length;
} else {
numberOfCols = 0;
}
System.out.println("numberOfRows : "+numberOfRows);
System.out.println("numberOfCols : "+numberOfCols);
for (int row = 0, count = 0; row < numberOfRows; row++) {
for (int col = 0; col < numberOfCols; col++) {
arrayCount[count] = data[row][col];
count++;
}
}

Categories