Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 随机洗牌列表_Java_Random_Linked List_Shuffle - Fatal编程技术网

Java 随机洗牌列表

Java 随机洗牌列表,java,random,linked-list,shuffle,Java,Random,Linked List,Shuffle,我正在尝试随机洗牌一个列表。每次我尝试测试代码时,它实际上什么也不做,也不会结束。我想知道我到底错过了什么或做错了什么 public static ListElement shuffle(ListElement head){ int n= ListUtils.getLength(head); ListElement head2= null; while( head != null) { int random = (int) Math.random()

我正在尝试随机洗牌一个列表。每次我尝试测试代码时,它实际上什么也不做,也不会结束。我想知道我到底错过了什么或做错了什么

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;       
}
打字错误!
您永远不会更新循环条件中使用的
head

不确定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);
  }
}
public void随机化(列表myList){
int n=myList.size();
for(int i;i
只需使用
java.util.Collections.shuffle(myList)
getItem()的代码在哪里?我需要使用Math.random(),因为我想学习如何使用它。可能会导致该条件下的无限循环
head!=NUL/<代码>和<代码>列表< /代码>始终<代码> NUL/<代码>,因为您从不更新将发送到 GeTimeTo()/代码>的<代码>头2>代码>变量。如果您想要更好的熵和更为独特的RANDOM,请考虑使用SoCurrand。我也不认为您的算法有太多的意义。但是循环没有结束的原因是,
head
永远不会为
null
,因为您从未将其更新为任何内容。它将始终是作为参数传递给
shuffle
的任何内容。
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);
  }
}