I have created 3D ArrayList. I know initialization is done using this code
ArrayList<ArrayList<ArrayList>> ll=new ArrayList<ArrayList<ArrayList>>();
for(int j=0;j<n;j++){
ll.add(new ArrayList(new ArrayList()));
}
But I dont know how insert values in it.
I am familiar with 2D arraylist in which inserting value b at a index is done using
ll.get(a).add(b);
but I dont know how to insert value into 3D arrayList.
I am solving question http://www.spoj.com/problems/BENEFACT/
in which I think longest distance in tree is the answer. I used 3D ArrayList
here, 2dimension to store connection of places and 3rd dimension to store distance
Is this correct approach? Is Any other approach possible in which solution is obtained easier than using 3d ArrayList?
I think if you want to access an object at index i,j,k you can do it by
ll.get(i).get(j).get(k)
Or
ll.get(i).get(j).add(k,newObject)
Depending on your need, you probably don't want that. I didn't read the full description of the problem to solve (the link), but you just need 6 points in 3D space.
I'd suggest creating a Point3D class with x, y, and z, and then just a simple List<Point3D>.
Related
I need some help here - I want to do a little card game for learning reasons.
I have a class (Tree/Baum) and an ArrayList "TreeList" of several trees of object Tree.
Now I want to load different random objects of that class in a new ArraList called "PlayersHand".
To do this I have created a for-loop with a tmpObj of type Tree which loads a random index from ArrayList"TreeList" of all Trees. After that it modifies some values of the tmpObj by random (f.e. tree height). Then it adds this whole tmpObject to the ArrayList "PlayersHand".
The Problem is, that when I read out the values of the objects inside PlayersHand the modified values don't show the right way. They always show the last value of the treetype, so f.e. if the last tree of type ACER was 20m high, all the previous trees of type ACER are 20m high too.
It seems like all the objects in the ArrayList "playersHand" are just pointers to the different objects of ArrayList "TreeList".
But why ? And how can I fix it?
The code where the objects are copied:
//"PlayersHand get cards
for(int i=0;i<amountOfCards;i++)
{
int randomNr = (int)(Math.random()* TreeList.size());
Tree tmpTree = TreeList.get(randomNr);
tmpTree.modifyValues();
playersHand.add(tmpTree);
for(int y=0; y<playersHand.size();y++)
{
Tree tmpTree2 = playersHand.get(y);
System.out.println(" - different values of that object shown here - ");
}
}
Edit: Previously I had a more complex scenario. I tried to reduce complexity for better understanding.
I solved it - If someone has the same issue :
You have to use a copy constructor.
I'm trying to study about neural networks, following a great guide:
http://neuralnetworksanddeeplearning.com/chap1.html
Currently I've reached this code snippet which I'm trying to understand and write in Java:
class Network(object):
def __init__(self, sizes):
self.num_layers = len(sizes)
self.sizes = sizes
self.biases = [np.random.randn(y, 1) for y in sizes[1:]]
self.weights = [np.random.randn(y, x)
for x, y in zip(sizes[:-1], sizes[1:])]
I managed to figure out what everything means except for the last line:
[np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[1:])]
As far as I can understand: create a matrix with y rows and x columns, for each pair x,y which can be found in the matrix zip which is created by the merging of the two "sizes" arrays. I understand that sizes[1:] means taking all elements from sizes starting from index 1, but sizes[:-1] makes no sense to me.
I read online that s[::-1] means getting the reverse of the array, but in the above case we only have one colon, while in the formula for the reverse array there seems to be two colons.
Sadly, I have no idea how Python works and I got pretty far along with the online book to give it up now (I also truly like it), so can someone say if I'm right until now, correct me if needed, or straight out explaining that final line?
sizes[:-1] is a list slice which returns a copy of the sizes list but without the last item.
I am trying to use OpenMaple with Java interface to simply turn a matrix into reduced row echelon form. Ultimately I want to find the inverse of a matrix. I am not sure how to take a 2-d array in my program and make it interact with engine objects.
Some basic examples are here.http://www.maplesoft.com/support/help/Maple/view.aspx?path=OpenMaple/Java/Engine/evaluate
I basically want this: t.evaluate( "with(LinearAlgebra): A:=<<2,4,8>|<8,2,4>|<4,8,2>>; ReducedRowEchelonForm(A);" );
Problem 1: getting a 2-d matrix I made into that statement.
Problem 2: somehow making it output into another 2-d array as a result.
I don't know much about OpenMaple, therefore I come here. Thanks!
I used to use matrix in octave to store data from data set, in Java how can I do that? Assume I have 10-20 columns and large data, I don't think
int [][]data;
would be the best option. Is nested map the only solution?
You could create a class Coordinate that takes an X and Y values and properly implement hashCode and equals.
Then create a HashMap<Coordinate, Data> and work with it.
Depends on what you need to do. If you know the size of the lists, then an array is definitely ideal since it means you will have instant access (read/write time) to any position in the array, this is very useful for speed.
Maps are better if you dont know the size and it needs to be able to adapt.
And finally, as I discovered in a previous question, if you have a TON of data, and a lot of it will be "0" you might want to also consider using a Sparse Martrix
This answer merges some of gnomed's answer and SJuan76's answer contents.
At a quick glance, I'd suggest you to use bidimentional arrays such as int[][].
It's not a very huge amount of data (we're speaking of ≈500 ints) so it's not a bad idea.
Advantages: It's the simpler, ideal (from the data-structuring side) way to go,
especially if every “slot” of the matrix contains data.
The inconvenient: You have to know the size of the matrix before constructing it.
Anyway, you can resize it later using the Arrays utilities.
If you want more effective handling of the data, you can use a single point-map.
That is, the key of every entry is a java.awt.Point that defines where is the value located.
Advantages: It's more effective than having a 2D array,
especially if part of your matrix doesn't contain data.
And it's adaptative; you don't need to know any sizes to construct/resize it.
The inconvenient: If every “slot” of your matrix contains data,
you'll loose (a lot of) space and performance. A 2D-array is more effective then.
Want more? If your data is really huge you can use a sparse matrix.
See this question for more details.
I would not discard multidimensional arrays so far: have you tried them? Are you finding specific limitations? IMHO as long as your data fits in memory, arrays can be good.
If your data is very sparse though, you may want to look at maps indeed.
Related question btw: Making a very large Java array
You can use multidimensional arrays or you can try any pairs like HashMap
I think multi-dimentional arrays are the best choice! They should serve your purpose. If your data set is only integers, int [] [] is an ideal choice.
Well, if your indices are small integers, you can certainly use nested arrays.
In a matrix class, you may want to use a plain array, like so: (assuming n is the number of columns)
double get(int i, int j) { return data[i*n + j]; }
For a general table (sparse matrix), you can use nested maps, but consider using com.google.common.collect.Table implementations from the Google Guava library.
Basically I am amidst a friendly code optimisation battle (to get the fastest program), I am trying to find a way that is faster to access a dictionary of hard coded data than a multidimensional array.
e.g to get the value for x:
int x = array[v1][v2][v3] ;
I have read that nested switch statements in a custom array may possibly be faster. Or is there a way I can possibly access memory more directly similar to pointers in C. Any ideas appreciated!
My 'competitor' is using a truth table and idea is to find something faster!
Many Thanks
Sam
If the array is regular in shape (i.e. MxNxK for some fixed M, N and K), you could try flattening it to achieve better locality of reference:
int array[] = new int[M*N*K];
...
int x = array[v1*N*K + v2*K + v3];
Also, if the entire array doesn't fit in the CPU cache, you might want to examine the patterns in which the array is accessed, to perhaps re-order the indices or change your code to make better use of the caches.