Reputation: 89
Is it possible to exclude array indexes in a shuffle?
My insight in this question:
Array[0,1,2,3,4,5,6,7,8]
Exclude Array index 2 and 7 in shuffle.
Shuffle Array.
Array[3,5,2,1,6,8,0,7,4]
This is my what I used in my shuffle:
List<Pokemon>list = Arrays.asList(pkm);
Collections.shuffle(list);
EDIT:
Thanks, @Jhanvi! I studied your code and it gave me some ideas. I tried to play around with yours and @Rohit Jain's codes and created a sample:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class Example {
public static void main(String[]args){
String[] x = {"a","b","c","d","e","f","g","h"};
List<String> list = new ArrayList<String>(Arrays.asList(x));
System.out.println("Before shuffling, ArrayList contains : " + list);
Object obj = list.remove(7);
Object obj1 = list.remove(2);
Collections.shuffle(list);
list.add(2, obj1);
list.add(7, obj);
System.out.println("After shuffling, ArrayList contains : " + list);
}
}
Annoyingly it gives me an error: cannot find symbol method add(int,java.lang.Object) on both my list.add().
I checked that there exists a .add(int,Object)
method for List, thinking that it will work. What part did I miss?
Upvotes: 4
Views: 2063
Reputation: 5139
You can try something like this:
ArrayList arrayList = new ArrayList();
arrayList.add(0);
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.add(5);
arrayList.add(6);
arrayList.add(7);
System.out.println("Before shuffling, ArrayList contains : " + arrayList);
Object obj = arrayList.remove(7); // remove by index!
Object obj1 = arrayList.remove(2);
Collections.shuffle(arrayList);
arrayList.add(2, obj1);
arrayList.add(7, obj);
System.out.println("After shuffling, ArrayList contains : " + arrayList);
Upvotes: 15
Reputation: 8392
You could create a shuffle yourself: just pick two indexes at random, making sure you exclude the ones you want to exclude, and swap the array elements in those positions. Repeat enough times.
Upvotes: 2