How to call Collections.Shuffle on only part of an array Java - java

So I have the following array:
String [] randomList = new String [16];
randomList[0]="Dog";
randomList[1]="Dog";
randomList[2]="Cat";
randomList[3]="Cat";
randomList[4]="Mouse";
randomList[5]="Mouse";
randomList[6]="Car";
randomList[7]="Car";
randomList[8]="Phone";
randomList[9]="Phone";
randomList[10]="Game";
randomList[11]="Game";
randomList[12]="Computer";
randomList[13]="Computer";
randomList[14]="Toy";
randomList[15]="Toy";
I want to shuffle only the first 9 elements of this array. I used the following code but it shuffles the entire array.
Collections.shuffle(Arrays.asList(randomList));
How would I shuffle only a part of the array rather than the whole thing? I am making quite a simple program so I would like to keep using the Collections class however all solutions are welcome. Thanks

You can use the List type's subList method to get a List object with a view of a particular range of elements from the original list. I haven't tested this, but I think it should work:
Collections.shuffle(Arrays.asList(randomList).subList(startIndex, endIndex));

You can also try the below. However, more cleaner code would be as suggested by templatetypedef. List<String> newList = new ArrayList<String>();
for(int i=0; i<randomList.size()-ValuePreferred; i++){
newList.add(randomList.get(i));
}
Collections.shuffle(newList);
randomList.removeAll(newList);
newList.addAll(randomList);
Also, i hear about memory leak issue with Sublist in arrays. Not sure if that got rectified. If someone can provide any useful information regarding that would be great. Remember specifically calling value in between the List will cause IndexOutOfBoundsIssue(). That should be handled.

Related

Way to save vectors in a list

I have a problem with the TSP algorithm
. I'm going to insert code and explain:
List listOfPermutations = new ArrayList();
while (cont.compareTo(deleteRutes) < 0) {
listOfPermutations.add(indexOfCities);
nextPermutation(indexOfCities);
....
The problem I have is the following,
my idea was to insert all possible permutations (arrays) in a list, but the problem is that the list always takes the same values ​​of the array, it is logical since the indexOfCities array is only one. I've been giving it back for a while and I do not know how to solve it. Can someone help me?
indexOfCities holds a reference to an array. This same reference is added as item to listOfPermutations with
listOfPermutations.add(indexOfCities);
in each loop iteration.
Then the array is modified with
nextPermutation(indexOfCities);
in each loop iteration. So the stored references all point to the same modified array.
To solve this, add a copy of the array in indexOfCities to listOfPermutations instead. E.g. like so:
int[] indexOfCitiesAux = indexOfCities.clone();
listOfPermutations.add(indexOfCitiesAux);

Java - A loop in a loop and the format gets lost

I'm French so excuse my English not necessarily correct.
I explain the context, I currently have a String array list named "tempCustomerDrugsIdsList" (var1) and another string array list named "tempDrugsTableList"(var2).
When I make a loop "For" on "var1" then another one in "var2","var2" loses its format, i. e. upper case is replaced by lower case and spaces are deleted.
I tested with another loop with the same type of variables (but empty), the result being the same I think the problem comes from my way of using java. Being on vb. net before, I must have taken some bad habits !
I don't know how to solve this problem, I've only been working in java for 2 weeks.
Thank you for helping me.
[EDIT]
My problem was:
List<String[]> tempDrugsTableList = otherList;
But this code doesn't duplicate the list.
AxelH gave me the following solution:
List<String[]> tempDrugsTableList = new ArrayList<String[]>(otherList);
Well, you are not doing a "copy" of the list
tempDrugsTableListCopy = tempDrugsTableList; // Get copy of original tempDrugsTableList for comparate
but sharing the reference, every update done in the tempDrugsTableListCopy will be done in the original list (same reference, same adress in memory). Since you are updating that copy in the following loops ... you update the original list too. What you want is to clone the list.
You could do it simply with copyList = new ArrayList(originalList); or for a deep clone, you need to iterate each element to duplicate those. (array need to be duplicated too if you change the value in those)
"String[]" tmpCustomerIds means you are getting a string array from a string array, which you would be using in a 2d array. Try it with just "String" in the for each loops. I am assuming you are using 1d arrays in this case.

Java: Concatenating not specified number of 2d Arrays dinamically

I know that there were other questions related to this topic.
But this is a little different.
Immagine that you have a program that gets every some amount of time an 2d Object (Object[][]) from the excel and it pass this to one method; this method needs to concatenate this 2d Object, so when it gets a flag that there is no more input, it passes this potentially big 2d object as a result to some other method...
1) You don't know how many excel documents will be sent , so how many 2d object will you get
2) every 2d object can have different num of columns and rows (ok this is not a big problem)
Is there a way in java to concatenate 2d objects into one? Wihout "killing" the memory.
Looking at this accepted anwer
How do you append two 2D array in java properly?
there is an append method, but each time it is called (and in this described case we don't know how many times could be called), it recreates an 2d array, and in my opition is not a best practice for this solution.
Looking at this accepted solution How to concatenate two-dimensional arrays in Java there is used an arraycopy solution, which how i understood is something similar to the previous solution... maybe a little better.
I know that would be possible to use some lists that could somehow rappresents this 2d object, or be parsed at the end in the 2d object, but:
is there any way in java (good practice) to concatenate dinamically unown number of 2d object into 1?
tnx
It look like you need ArrayList< ArrayList < Object > > instead of Object[][]. If you use ArrayList, the different num of columns and rows aren't problems at all, and you not "killing" the memory if you use addAll method. Moreover, you could use a core Java methods to concat ot ArrayLists without create your own manual methods.
For example, you can use something like this:
public List<ArrayList<Object>> concat (List<ArrayList<Object>> list1, List<ArrayList<Object>> list2) {
if(list1.size() > list2.size()) {
List<ArrayList<Object>> listBig = new ArrayList(list1); // or just list1 if we can change list1
List<ArrayList<Object>> listSmall = list2;
} else {
List<ArrayList<Object>> listBig = new ArrayList(list2); // or just list1 if we can change list1
List<ArrayList<Object>> listSmall = list1;
}
for(int i = 0; i < listSmall.size(); i++) {
listBig[i].addAll(listSmall[i]);
}
return listBig;
}

Attempting to set location in String Array, getting out of bounds exception thrown

I'm trying to 'add' to my String[].
I'm reading a file with a BufferedFileReader. I have my code set up to return a String[], lets call it list. Essentially my code loops through the file until it's empty (well null), adds each line to a string, then out of the loop I split() the string into my list.
I fear that because I do that the list has an immutable size, which is why I'm getting the Exception thrown.
How do I go about writing the following code the 'correct' way?
Code
note the list below isn't instantiated like that, just for labeling purposes.
String[] list;
int length = list.length;
list[length + 1] = (method that returns a string);
list[length + 2] = (method that returns a string);
It goes on for 5 spaces.
I'm going about this because I'm attempting to save fields to a file, and in order to avoid overwriting a file I'd like to add to it instead.
TL;DR:
Essentially trying to add to a String[] or find a better alternative because I can't change the length.
Your question is not so Clear.
If I am correct you want to define array size by dynamically
You better use java.util.ArrayList .. Where you can dynamically change the length of the Array .
String[] or find a better alternative because I can't change the
length.
You better use ArrayList for this.
ArrayList<String> ar=new ArrayList<String>(put capacity if you want);
you can remove search in arraylist easily.
List<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
return list.toArray();

Which Array / List should I use to keep an static index?

I usually use HashMap<Integer, Object> to keep an array of objects where you can get items by Integer.
I'm showing you an example so you can understand.
HashMap<Integer,String>:
[0] - Hello
1 - How are you doing
[2] - Bye
So with a HashMap, I can remove items avoiding the rest moving from their indexes.
hashmap.remove(0)
[0] - null
1 - How are you doing
[2] - Bye
But HashMap shouldn't be used for indexes with an Integer. So... Which kind of array should I use to perform actions like the ones I am explaining above?
Edit: About the part of "shouldn't be used", this is what Android Eclipse is telling me:
You can use a simple Array. They can be pointed by integer. And other than calling remove you can set null to the specific place. If you really want to call remove write your own wrapper method which does that for you.
I your indices are dense (no big holes in a range [0..n], the most efficient approach would be to use a plain array of String:
final String[] lup = new String[3];
lup[0] = "Hello";
lup[1] = "How are you doing";
lup[2] = "Bye";
// to remove elements just set the index to `null`:
lup[0] = null;
You can use SparseArray which is similar to HashMap<Integer,String>
SparseArray<String> arr=new SparseArray<String>();
arr.put(0, "Hello");
If you already know the total size, then go with Arrays. But if you don't then go with ArrayList.
Now, I don't see a purpose of mapping here.
Hashmap is a Map data structure. Like a list each item that is stored in a hashmap is stored at a particular index. This index is called a hash and it is generated using a hash function. Hash functions accept the object to be stored as an argument and generate a number that is unique to it. Different hashing functions have different trade-offs. A function that is too sparse will use up more space than required(your case). while one that is not sparse enough will suffer from collisions where objects use the same hash.
Further Reading if interested: Look at Android's SparseArray implementation for inspiration.
View the source by downloading AOSP's source code here http://source.android.com/source/downloading.html.
It is highly optimized for integers!
Actually, you can use a simple array of strings.
String arr[] = new String[size];
After reading a little bit, I guess the answer is the following:
1.- I can't use plain arrays. Reason: I might not know the final size of it.
2.- Lists doesnt fit, as when you remove an item, the following items fits to the new index. I don't want index move.
So as a global answer, using HashMap is OK, however using SparseArray is recommended as it is more efficient.

Categories