user1513323
user1513323

Reputation: 51

Shuffling list randomly Java

I'm attempting to randomly shuffle a list. Each time I attempt to test the code it essentially does nothing and doesn't end. I was wondering what exactly am I missing or doing wrong.

public static ListElement shuffle(ListElement head){
    int n= ListUtils.getLength(head);
    ListElement head2= null;
    while( head != null) {  
        int random = (int) Math.random() *  n;
        for(int i=0;i<random;i++){
            ListElement list= new ListElement(); 
            list=getItem(head2,n);
            list.getNext();
            head2=list;

        }
    }
    return head2;       
}

GetItem

public static ListElement getItem(ListElement head, int n){
    if(n == 0){                 
        return head;            
    }else if(head == null){     
        return null;
    }else{                      
        return getItem(head.getNext(),n-1);
    }
}

Upvotes: 0

Views: 1121

Answers (2)

JackDev
JackDev

Reputation: 11173

Not sure what getItem method does in the for loop.

An alternative solution if you want to use Math.random() is to go through the whole list, and generate a random index for each element which it will swap with in the list.

public void randomize(List<String> myList){
  int n= myList.size();
  for(int i; i < n; i++){
    int randIdx = (int) Math.random() *  n;
    swap(myList, i, randIdx);
  }
}

private void swap(List<String> list, int idx1, int idx2){
  if(idx1 != idx2){ //don't do swap if the indexes to swap between are the same - skip it.
    String tmp = list.get(idx1);
    list.set(idx1, list.get(idx2));
    list.set(idx2, tmp);
  }
}

Upvotes: 1

Jochen
Jochen

Reputation: 2295

Typo! You are never updating head, which you use in your loop condition.

Upvotes: 1

Related Questions