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

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

Related

How do I compare a number in a certain index from two different 2d arrays?

So this program starts by initializing two 2d arrays that are 4 by 4. the arrays are filled with random numbers between 9 and 0. I already did those methods, and they print correctly. then, i need to compare each number in those two using enhanced for loops ONLY. whichever one is bigger will print, creating a new array. I know how to do this with regular for loops, but how would do this? hopefully this makes sense. I don't even know where to start with this, honestly.
my instance variables are:
private int[][] matrix1 = new int[4][4]; //
private int[][] matrix2 = new int[4][4];
public static int[][] solve(int[][] matrix1, int[][] matrix2) {
// ignore matrix1 has same size with matrix2
int[][] res = new int[matrix1.length][matrix1[0].length];
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[0].length; j++) {
res[i][j] = Math.max(matrix1[i][j], matrix2[i][j]);
}
}
return res;
}

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

How you decompress an array of shorts[][] using for loops?

I have to create a decompress method that is passed a compressed array of shorts created from another method in my program. It's basically RLE, with the first value being the number of times a value is repeated and the second being the value itself.
I'm not the best with for loops or arrays - I'm really trying to get better - so this last part of my assignment is throwing me off. Can anyone help or point me in the right direction?
public static short[][] decompress(short[][] cmpArray){
int position = 1;
short[][] dcmpArray = new short[cmpArray.length][cmpArray.length];
for(int i=0; i<cmpArray.length; i++){
for(int j=0; j<cmpArray[0].length; j++){
}
}
return dcmpArray;
}
I know that I have to assign the incoming values to the new array - "dcmpArray" - and that should be done inside the for loop. I'm having problems on separating the values and then determining how many times the value should be printed in the new array. I was going to use "position" to determine the position in which index the value should be printed, but I'm having a brain fart..
I'm not sure why your array would be 2 dimensional, but for a 1-dimensional array containing a series of shorts with RLE like you specify, this would be how to decompress it:
public static short[] decompress(short[] input) {
int outputLength = 0;
/* First we need to figure out how long the output is
going to be when uncompressed, so we iterate through
the input like we are would normally, but write no output,
instead computing the output length */
//note the += 2; we want to skip the actual output
for(int i = 0; i < input.length; i += 2) {
outputLength += input[i]; //increment target length
}
/* Now that we know what the output size will be,
we can create an array to store it. */
short[] output = new short[outputLength];
/* Now iterate over the input, putting every other input short
into the output, duplicated the number of times of the current input
AKA: decompression of RLE */
for(int i = 0, outOffset = 0; i< input.length; i += 2) {
for(int ii = 0; ii < input[i]; ii++)
output[ii + outOffset++] = input[i + 1];
}
return output;
}
If your 2-dimensional array is simply an array of input arrays, then simply perform that procedure on each of the input arrays.

2d char array from a file

I am trying to read in a string from a file, extract individual characters and use those characters to fill a 2D char array. So far I have been able to do everything except fill the array. I keep getting an Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: error message. Any help would be appreciated. This is my first time working with 2D arrays. Thanks.
Here are the contents of the test.txt. Each word on a new line. The first 2 integers are the dimensions of the array
4 4
FILE
WITH
SOME
INFO
public class acsiiArt
{
public static void main(String[] args) throws IOException
{
File file = new File("test.txt");
Scanner inputFile = new Scanner(file);
int x = inputFile.nextInt();
int y = inputFile.nextInt();
while (inputFile.hasNext())
{
char [][] array = new char [x][y];
//char c = words.charAt(i);
for (int row =0; row<x;row++)
{
for (int col =0; col<y;col++)
{
String words = inputFile.nextLine();
for (int i=0; i<words.length(); i++)
array[x][y]=words.charAt(i);
}
}
}
}
}
for (int row =0; row<x;row++)
{
for (int col =0; col<y;col++)
{
String words = inputFile.nextLine();
for (int i=0; i<words.length(); i++)
array[x][y]=words.charAt(i);
}
}
The total number of indices in array is x * y. Below, you are filling all the possible indices
for (int row =0; row<x;row++)
{
for (int col =0; col<y;col++)
So when you add this:
for (int i=0; i<words.length(); i++)
you multiplying another factor words.length. So you need x * y * words.length number of indices, but you only have x * y. Thats why you're getting ArrayIndexOutOfBoudsException
I've seen problems like this and I'm assuming that x and y are being initialized to the first two characters which represent the number of rows and the number of columns. If that is the case, then third for loop for (int i=0; i<words.length(); i++) is unnecessary. You can just reffer to the col variable for the word at that point, since it should represent how many characters there are.
All of this is only applicable if the chars are in a rectangular pattern, meaning that there are the same number of columns in every row. Otherwise you will get an IndexOutOfBoundsError as soon as one of the lines is shorter than the the column value initially given.
Edit: If you're final 2d char array is not meant to be rectangular and instead "jagged," a different implementation is required. I'd recommend either a 2d arrayList (an arrayList of arrayLists).
Or you can keep your current implementation with the third for loop, but you have to be sure that the original x value represents the longest row/most amount of columns, and then you'd be able to deal with each row indivually with words.length. You'd also have to be fine with the extra portions of the lines that have a length>x having spaces initialized to null.
ArrayIndexOutOfBoundsException means you are using array beyond its limit. So in your case:
char [][] array = new char [x][y];
//char c = words.charAt(i);
for (int row =0; row<x;row++) {
for (int col =0; col<y;col++){
String words = inputFile.nextLine();
for (int i=0; i<words.length(); i++)
array[x][y]=words.charAt(i);
}
}
Problem may be because your array size is less then input words. problem is because you are putting extra loop, and your loop it self is not correct. Please seen code below.
So you can do 2 things.
change value of y large enough so that any word string can store.
rather than looping on size of word you can loop on your array size like.
.
for (int row =0; row<x;row++) {
String words = inputFile.nextLine();
int size = Math.min(words.length(),y);
for (int i=0; i< size; i++)
array[row][i]=words.charAt(i);
}
The easiest way to do this is with an ArrayList<char[]>. All you have to do is add a new char[] for each new line read:
ArrayList<char[]> chars = new ArrayList<>();
while (inputFile.hasNext()){
chars.add(inputFile.nextLine().toCharArray());
}
char[][] array = chars.toArray(new char[chars.size()][]);
An ArrayList is basically an array of changeable size. This code takes each line in the file, turns it into a char[], then adds it to the ArrayList. At the end, it converts the ArrayList<char[]> into a char[][].
If you can't or don't want to use ArrayList, you could always do this:
char[][] array = new char[1][];
int a = 0;
while(inputFile.hasNext()){
//read line and convert to char[]; store it.
array[a] = inputFile.nextLine().toCharArray();
//if there are more lines, increment the size of the array.
if (inputFile.hasNext()){
//create a clone array of the same length.
char[][] clone = new char[array.length][];
//copy elements from the array to the clone. Note that this can be
//done by index with a for loop
System.arraycopy(array, 0, clone, 0, array.length);
//make array a new array with an extra char[]
array = new char[array.length + 1][];
//copy elements back.
System.arraycopy(clone, 0, array, 0, clone.length);
a++;
}
}
If you know the dimensions of the array beforehand:
char[][] array = new char[dimension_1][];
int a = 0;
while (inputFile.hasNext()){
array[a] = inputFile.nextLine().toCharArray();
a++; //don't need to check if we need to add a new char[]
}
In response to comment:
We know that a char[][] cannot be printed with Arrays.toString() (if we want the contents) because we will get a lot of char[].toString(). However, a char[][] can be printed with one of the following methods:
public static String toString(char[][] array){
String toReturn = "[\n";
for (char[] cArray: array){
for (char c: cArray){
toReturn += c + ",";
}
toReturn += "\n";
}
return toReturn + "]";
}
I personally prefer this one (requires import java.util.Arrays):
public static String toString(char[][] array){
String toReturn = "[\n";
for (char[] cArray: array){
toReturn += Arrays.toString(cArray) + "\n";
}
return toReturn + "]";
}

double row length of 2D array

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

Categories

Resources