【问题标题】:Shuffling list randomly Java随机洗牌列表Java
【发布时间】:2012-07-13 02:07:05
【问题描述】:

我正在尝试随机打乱列表。每次我尝试测试代码时,它基本上什么都不做,也没有结束。我想知道我到底错过了什么或做错了什么。

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

获取项目

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

【问题讨论】:

  • 只要使用java.util.Collections.shuffle(myList)
  • getItem() 的代码在哪里?
  • 我需要使用 Math.random() 因为我想学习如何使用它。
  • head != nulllist 总是null 的条件下可能会导致无限循环,因为您永远不会更新将发送到getItem()head2 变量。
  • 如果您想要更好的熵和更独特的随机数,请考虑使用 SecureRandom。

标签: java random linked-list shuffle


【解决方案1】:

错字! 您永远不会更新您在循环条件中使用的 head

【讨论】:

  • 我也没有。我认为您的算法没有多大意义。但是循环没有结束的原因是因为head 永远不会是null,因为你永远不会将它更新为任何东西。它始终是您作为参数传递给shuffle 的任何内容。
【解决方案2】:

不确定 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);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 2015-10-30
    • 2016-04-26
    • 1970-01-01
    相关资源
    最近更新 更多