I have this three-dimensional array named bands. I need to do 4 copies of it, so I can work in parallel with all of them.
int bands[][][] = new int[param][][];
I need the array to keep being a three dimensional array, as it is the input for some methods that needs an int [][][]
How could I do such copies? I was thinking about using an arrayList like this:
List<Integer[][][]> bandsList = new ArrayList<Integer[][][]>();
bandsList.add(bands);
but I get this error on the last line: The method add(Integer[][][]) in the type List<Integer[][][]> is not applicable for the arguments (int[][][])
so what should I do??
The errors is because int[][][] is not the same as Integer[][][].
int[][][] is an 3D array of primitive int.
Integer[][][] is an 3D array of object Integer, which is the wrapper class of int.
Well, technically a 3D array is an array of pointers to a 2D array, which is an array of pointers to a 1D array which is an array of primitives or pointers to objects.
Use List<int[][][]> bandsList = new ArrayList<int[][][]>(); instead.
Also note that
bandsList.add(bands);
bandsList.add(bands);
will simply add 2 pointers to the same array, changing one will also change the other.
You'll need to manually copy them:
int[][][] getCopy(int[][][] bands)
{
int[][][] newBands = new int[bands.length][][];
for (int i = 0; i < bands.length; i++)
{
newBands[i] = new int[bands[i].length];
for (int j = 0; j < bands[i].length; j++)
{
newBands[i][j] = new int[bands[i][j].length];
System.arraycopy(bands, 0, newBands, 0, bands[i][j].length))
}
}
return newBands;
}
// to add
bandsList.add(getCopy(bands));
in this way you aren't doing a copy of the array, you have to do this 4 times:
int cloneList[][][] = new int[param][..][..];
for(int i = 0; i<bands.length; i++) {
int arr1[][] = bands[i];
for(int j = 0; j<arr1.length; j++) {
int arr2[] = arr1[j];
for(int k = 0; k<arr2.length; k++) {
int x = arr2[k];
cloneList[i][j][k] = x;
}
}
}
Related
I'm trying to make a static 2D array object. I came up with one where it has to be initialized by the user but for my purposes I want it to be already initialized.
String str;
int temp = 0;
int check = 0;
Plot[][] farm = new Plot[4][3];
ExperimentalFarm p = new ExperimentalFarm(farm);
for (int i = 0; i < farm.length; i++) {
for (int j = 0; j < farm[i].length; j++) {
str = JOptionPane.showInputDialog("Name the crop");
temp = Integer.parseInt(JOptionPane.showInputDialog("What is the yield"));
farm[i][j] = new Plot(str, temp);
}
}
I'm also trying to return an object from a class to the client. For example, I want to get which player did the best. I want to have their name and their score. How do I return that.
Well, you're doing it. Plot[][] farm = new Plot[4][3]; makes a new 2D array (technically, java does not have 2D arrays. At all. What you can do, however, is a 1D array, whose elements are themselves arrays, which is exactly what that does: farm is of type: "An array whose component types are arrays whose component types are Plot objects", and new Plot[4][3] initializes this array to contain 3 sub-arrays, and each sub-array is initialized to contain an array capable of holding 4 plots.
But that just makes room for plots, it doesn't instantiate 12 plot objects, you have to do that yourself. You are doing just that in the code you pasted: That loop structure ends up running the stuff within ("Name the crop", etc) a grand total of 12 times, meaning, new Plot is executed 12 times, you want that to happen.
Here's how to e.g. do it yourself:
Plot[][] farm = new Plot[4][3];
for (int i = 0; i < farm.length; i++) {
for (int j = 0; j < farm[i].length; j++) {
farm[i][j] = new Plot("barren", 0);
}
}
I am passing 2 arrays to the controller with different lengths, I want to execute a for loop and length of that will be the max of the length of 2 arrays.
I am not getting how to execute that. I tried Math.max but its giving me error as cannot assign a value to the final variable length.
String[] x =0;
x.length = Math.max(y.length,z.length);
for(int i=0; i < x.length; i++)
The no of elements in x and y are not fixed. it changes what we are passing from the front end.
Initialize the new array with the desired length:
String[] x = new String[Math.max(y.length,z.length)];
In case you don't need to create an array, just use the result of Math.max as conditional to stop your loop:
for (int i = 0; i < Math.max(y.length,z.length); i++) {
//...
}
Just bring your Math.max() operation into the array's initialization.
String[] x = new String[Math.max(y.length, z.length)];
Here's an expansion for clarity:
int xLength = Math.max(y.length, z.length);
String[] x = new String[xLength];
Edit: Unless, OP, you're not interested in creating another array...
I want to execute a for loop and length of that will be the max of the length of 2 arrays
Just bring your Math.max() operation into your for loop:
for(int i=0; i < Math.max(y.length, z.length); i++){
//code here
}
Set a variable to the maximum length of the arrays, create a new array with that length and then loop until that point.
int maxLen = Math.max(y.length, x.length);
String[] array = new String[maxLen];
for(int i = 0; i < maxLen; i++){
// Loop code here
}
int max_length = Math.max(y.length,z.length);
for(int i=0; i < max_length ; i++){
//...
}
you can use that max_length to create a new String[] if you are trying to create an array with total length of y and z arrays, like
String[] newArray = new String[max_length];
So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.
So the problem I'm working on solving involves an array list of array list of integers
. What is known: The number of elements in each ArrayList of integers. What is NOT known: How many ArrayList of Integers there actually are. I need suggestions for an algorithm that would sum the (ordered) elements of these arrays in every combination possible OF the arrays. In order to clarify what I mean by this let me give an example:
AoA = [[1,0,1,0],[0,1,0,1],[1,1,1,1],[0,0,0,0]];
Sum the elements of AoA[0] + AoA[1]; AoA[0]+AoA[2]; AoA[0]+AoA[3]; AoA[1]+AoA[2]; AoA[1]+AoA[3]; AoA[2]+AoA[3];
(4 choose 2)
So if anyone could code this simple version I'd be grateful as I'm struggling to do it. If anyone could code the more complex example where there's an unknown number of arrays in the AoA (so N choose 2), you'd be my hero.
TL;DR/edit
I need an algorithm to take n-choose-2 arrays from an array of arrays; sum the arrays (e.g. [1,2,3] + [1,2,3] = [2,4,6]); put the add the new summed array into an array of arrays.
If the 2 is fixed then the easiest thing I can think about is just generating the new array with N*(N-1)/2 rows, one for each sum and then using two variables to iterate through the original array with something like:s
int c = 0;
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
for (int k = 0; k < M; k++) {
sums[c][k] = AoA[i][k] + AoA[j][k];
}
c++;
}
}
Here's what I've got, took me a while but this will do what I was looking for:
it takes each combination of the arrays (t1, t2, t3, t4) and adds their elements and returns whatever combinatorial you choose for n, (in this example i left it as 3).
If there's any more optimizations you can see please feel free to add it. I'm a perl guy so making this work at all in Java was a real task.
import java.util.ArrayList;
public class testnCk {
public static void main(String[] args) {
ArrayList<int[]> sums = new ArrayList<int[]>();
int [] t1 = {1,1,0,0};
int [] t2 = {1,0,0,1};
int [] t3 = {0,0,0,0};
int [] t4 = {0,0,1,1};
ArrayList<int[]> testing = new ArrayList<int[]>();
testing.add(t1);
testing.add(t2);
testing.add(t3);
testing.add(t4);
int n = 3;
int i = -1;
int[] array = new int[4];
ArrayList<int[]> whatever = nCk(testing, sums, array, i, n);
for (int[] test1 : whatever)
{
for (int j = 0; j < test1.length; j++) {
System.out.print(test1[j]);
}
System.out.println();
}
}
public static ArrayList<int[]> nCk (ArrayList<int[]> arrayOfDiffPatterns, ArrayList<int[]> solutions, int[] tempsums, int i, int n)
{
n--;
for (int j=i+1; j<arrayOfDiffPatterns.size(); j++){
int[] array = tempsums.clone();
for (int k=0; k<arrayOfDiffPatterns.get(0).length; k++){
array[k] += arrayOfDiffPatterns.get(j)[k];
}
if(n>0){
nCk(arrayOfDiffPatterns, solutions, array, j, n);
}
else{
solutions.add(array);
}
}
return solutions;
}
}
I am trying to create a method that removes duplicates from a 2d array. the outside array conains point indexes and the inner array contains their coordinates. It looks like i have to use an arraylist in order to remove elements without ending up with null values in the array. I would then like to convert the arraylist back into a 2D array in order to return it in the format i require. The problem is that the arraylsit contains an array of objects so i can't cast it into an array designed for floats. what is the correct syntax for filtering the floats from my array list. my code follows:
public class rem_duplicates {
public float [][] rem_geo_duplicates(float a[][]){
ArrayList<float[]> al = new ArrayList<float[]>();
float no_points = a.length;
int count = 0;
for (int i = 0; i < no_points-1; i++){
if((a[i][0] == a[i+1][0])&&(a[i][1] == a[i+1][1])){
a[i] = null;
count ++;
}
for (int j = 0; j < no_points; j++){
if (a[j] != null){
al.add(a[j]);
}
}
//how do i get the arraylist 'al' into this array b[][]?
float b[][] = new float [a.length-count][3];
b = al.toArray();
}
}
return b
}
Try using the following:
float b[][] = new float [a.length-count][3];
b = al.toArray(b);
This is the generic version of toArray() which in your case will return a float[][]. Keep in mind that float[] is an object, so there are no issues of boxing/unboxing here.
I notice several basic issues with your code however - I recommend trying to compile it and resolving the errors.
It works fine if you pass your newly created array as parameter:
float b[][] = new float[a.length-count][];
b = al.toArray(b);