double row length of 2D array - java

I'm trying to double the length of a 2D array as I add values to it. I know for a 1D an array the code for this is:
int oneD[] = new int[10];
//fill array here
oneD = Arrays.copyOf(oneD, 2 * oneD.length);
so if I have a 2D array and only want to double the amount of rows while keeping say 2 columns I figured I would just do this:
int twoD[][] = new int[10][2];
//fill array here
twoD = Arrays.copyOf(twoD, 2* twoD.length);
This however does not seem to work for the 2D array. How does one go about doubling the length of a 2D array. In this case to make it [20][2] instead.

A 2D array in Java is an array of arrays. For doubling it, you'll have to manually iterate over each row in the array and copy all of its columns in turn.

In your case something like this would do the job:
public static <T> T[][] copyOf(T[][] array, int newLength) {
// ensure that newLength >= 0
T[][] copy = new T[newLength][];
for (int i = 0; i < copy.length && i < array.length; i++) {
copy[i] = Arrays.copyOf(array[i], array[i].length);
// this should also work, just not create new array instances:
// copy[i] = array[i];
}
return copy;
}
And you could call this method, just like you called Arrays.copyOf()

Related

Converting 2D array to 1D Array without using ArrayList

Create Function for Convert 2d array into 1D array
But at Declaration time the size of 1D array how to give size to the new 1D array
int[] convert(int[][] input){
int[] result;
int z=0;
for(int row=0;row<input.length;row++) {
for(int col=0;col<input[row].length;col++) {
result[z]=input[row][col];
z++;
}
}
return result;/* Error comes here For Initialization. How to initialize before Knowing size*/
}
if rows and columns are balanced
int result[] = new int[input.length * input[0].length];
otherwise, you have to loop through the whole array while keeping a count of length
int len = 0;
for(int[] a : input){
len+=a.length;
}
int[] result = new int[len];
You can simply compute the size this way (i.e number of rows * number of columns):
int[] result = new int[input.length * input[0].length] ;
1)If it is rectangular 2D array, compute the size this way
int array[] = new int[input.length * input[0].length];
2)If it is not rectangular, iterate through each row and add the length of each sub-array
int size = 0;
for(int i=0;i<input.length;i++){
size += input[i].length;
}
Or you could just use streams with out to have to take care of size by yourself:
int[] convert(int[][] input){
return Stream.of(input).flatMapToInt(x -> Arrays.stream(x)).toArray();
}

JAVA: Creating a new array that has the same number of rows/columns in parameter?

I'm having a bit of trouble understanding how arrays work, specifically when the array is not given a specific size. For example, if I'm given the code:
public int [][] someMethodHere(int [][] myNewArray) {
//code here
}
I want to know how I can create another array within the method with the same number of rows and columns in the parameter (WITHOUT just adding in some numerical value in the parameter and then just writing the same value in the new array. Thanks!)
An array has a fixed size that you set when you create the array.
This is different to many other data structures like List or Map that are "smart" and can handle resizing themselves when the need arises.
So when you create an array you must tell the compiler how big it is:
// create the original array with 10 slots
int[] originalArray = new int[10];
If you want to create a new array of the same size, you can use the length property of the Array type.
// create a new array of the same size as the original array
int[] newArray = new int[originalArray.length];
In your case of a 2-dimensional array, you could do it like this:
// create the original array
int[][] originalArray = new int[10][20];
// create a new array of the same size as the original array
int[][] newArray = new int[originalArray.length][originalArray[0].length];
Notice that when specifying the length of the second dimension, I get the length of the first element in the original array. This works as long as all the rows have the same length.
If the rows are of different length you could set the length of each row in the new array by iterating over the first dimension of the array like this:
// create a new array where the first dimension is the same size as the original array
int[][] newArray = new int[originalArray.length][];
// set the size of the 2nd dimension on a per row basis
for(int i = 0; i < originalArray.length; i++) {
newArray[i] = new int[originalArray[i].length];
}
You can make a copy of the array and clear the new array.
public static int[][] someMethodHere(int[][] src) {
int length = src.length;
int[][] target = new int[length][src[0].length];
for (int i = 0; i < length; i++) {
System.arraycopy(src[i], 0, target[i], 0, src[i].length);
Arrays.fill(target[i], 0);
}
return target;
}

Find the dimensions of a 2D array in java

I'm playing around with Arrays in Java and had this doubt. How do I find the dimensions of a 2D array in java? For example, I get an array input from System.in and pass it in another method like this:
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
arr[i][j] = in.nextInt();
}
}
findSize(arr);
/*
*
*Other code
*
*/
findSize(int[] inputArr){
//I want to find the dimensions of the array here
}
Both dimensions of the array are greater than 0. Appreciate the help.
This method:
findSize(int[] inputArr){
//I want to find the dimensions of the array here
}
is getting as parameter a 2 dimentional array
hence you should do:
findSize(int[][] inputArr){
int heiht = inputArr.length;
int width = inputArr[0].length;
}
I just need to access the 0th element of the array like this:
int size = inputArr[0].length;
This would do the trick!
A 2-dimensional array is an array of arrays. To get the actual length of the second dimension (which can be different for each array entry of the first dimension) do this:
int[] findSize(int[][] inputArr) {
int[] size = new int[inputArr.length];
for (int i = 0; i < inputArr.length; i++) {
size[i] = inputArr[i].length;
}
return size;
}
To get 2D-Array dimension 1:
int size_1 = inputArr.length;
To get 2D-Array dimension 2:
int[] size_2 = findSize(inputArr);

Java array with empty second brackets

In Java you can do this
int[][] i = new int[10][];
Does this just create 10 empty arrays of int? Does it have other implications?
It creates a 10-entry array of int[]. Each of those 10 array references will initially be null. You'd then need to create them (and because Java doesn't have true multidimensional arrays, each of those 10 int[] entries can be of any length).
So for instance:
int i[][] = new int [10][];
i[0] = new int[42];
i[1] = new int[17];
// ...and so on
Executing your code creates an array of size 10, each element of which can hold a reference to a int[], but which are all initialized to null.
In order to use the int[]s, you would have to create new int[] for each of the element, something like this:
for (int n = 0; n < 10; n++)
i[n] = new int[10]; // make them as large as you need
Yes, it does; however, each of those arrays are null. You have to then initialize each of those sub-arrays, by saying int[10][0] = new int[MY_SIZE], or something similar. You can have arrays with different lengths inside the main array; for example, this code would work:
int[][] i = new int[10][];
for(int ind = 0; ind<10;ind++){
i[ind]=new int[ind];
}
It is just an array of arrays.
Here you create ten new int[0] arrays. You have to manually initialize it, it's useful when you don't need square matrix:
int[][] array = new int[10][];
for (int i = 0; i < array.length; i++) {
array[i] = new int[i];
}
If you need square matrix you can do:
int[][] array = new int[10][10];
And it will be initialized with default values.
That is just the declaration, you need to initialize it. The 10 arrays would be null initially.

java: How to split a 2d array into two 2d arrays

I'm writing a program to multiply matrices (2d arrays) as efficiently as possible, and for this i need to split my two arrays into two each and send them off to a second program to be multiplied. The issue I have is how to split a 2d array into two 2d arrays, at specific points (halfway). Does anyone have any ideas?
Lets say you have a 2d array of strings like so
String[][] array= new String[][]
{
{"a","b","c"},
{"d","e","f"},
{"h","i","j"},
{"k","l","m"}
};
Now you need a way to split these arrays at the half way point. Lets get the halfway point. Figure out how big the array is and then cut it in half. Note that you also must handle if the array is not an even length. Example, length of 3. If this is the case, we will use the Math.floor() function.
int arrayLength = array.length;
int halfWayPoint = Math.floor(arrayLength/2);
//we also need to know howmany elements are in the array
int numberOfElementsInArray = array[0].length;
Now we have all the info we need to create two 2d arrays from one. Now we must explicitly copy create and copy the data over.
//the length of the first array will be the half way point which we already have
String [][] newArrayA = new String[halfWayPoint][numberOfElementsInArray];
//this copies the data over
for(int i = 0; i &lt halfWayPoint; i++)
{
newArrayA[i] = array[i];
}
//now create the other array
int newArrayBLength = array.length - halfWayPoint;
String[][] newArrayB = new String[newArrayBLength][numberOfElementsInArray];
/*
* This copies the data over. Notice that the for loop starts a halfWayPoint.
* This is because this is where we left of copying in the first array.
*/
for(int i = halfWayPoint; i &lt array.length; i++)
{
newArrayB[i] = array[i];
}
And your done!
Now if you want to do it a little nicer, you could do it like this
int half = Math.floor(array/2);
int numberOfElementsInArray = array[0].length;
String [][] A = new String[half][numberOfElementsInArray];
String [][] B = new String[array.length - half][numberOfElementsInArray];
for(int i = 0; i &lt array.length; i++)
{
if(i &lt half)
{
A[i] = array[i];
}
else
{
B[i] = array[i];
}
}
And lastly, if you dont want to do it explicitly, you can use the built in functions. System.arraycopy() is one example. Here is a link to its api System.arraycopy()
int half = Math.floor(array/2);
int numberOfElementsInArray = array[0].length;
String [][] A = new String[half][numberOfElementsInArray];
String [][] B = new String[array.length - half][numberOfElementsInArray];
System.arraycopy(array,0,A,0,half);
System.arraycopy(array,half,B,0,array.length - half);

Categories

Resources