2012-07-13 122 views
0

我试图随机洗牌的列表。每次我尝试测试代码时,它基本上什么都不做,并且不会结束。我想知道我到底错过了什么或做错了什么。洗牌列表中随机的Java

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); 
    } 
} 
+11

只需使用java.util.Collections.shuffle(myList)' – 2012-07-13 02:07:52

+0

getItem()'的代码在哪里? – 2012-07-13 02:10:12

+0

我需要使用Math.random(),因为我想学习如何使用它。 – user1513323 2012-07-13 02:13:05

回答

1

错字! 你永远不会更新head,你在循环条件中使用它。

+0

我不知道如何在最后更新头部。 :( – user1513323 2012-07-13 02:27:59

+0

我也不知道。我不认为你的算法做出太大的意义。但是,为什么循环还没有结束的原因是因为'head'永远'null'因为你永远不将其更新到任何东西,它会总是作为“洗牌”的参数传递。 – Jochen 2012-07-13 03:09:30

1

不知道是什么的getItem方法在做for循环。

,如果你想使用的Math.random(另一种解决方案)是要经过整个列表,并为它会与列表中的每个交换元素的随机指标。

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); 
    } 
}