Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Exclude array index in shuffle

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?

like image 529
Rapharlo Avatar asked Dec 03 '22 21:12

Rapharlo


2 Answers

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);
like image 67
Jhanvi Avatar answered Dec 16 '22 17:12

Jhanvi


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.

like image 45
Eduardo Avatar answered Dec 16 '22 17:12

Eduardo