繁体   English   中英

如何在不使用集合的情况下随机播放ArrayList

[英]How to shuffle an ArrayList without collections

我有一个“令牌”的数组列表。 我可以用整数填充它们,没问题。 但是,我在不使用内置列表类的情况下随机重新排列它们时遇到了麻烦。 有什么建议么?

TopSpinArray<Integer> al = new TopSpinArray<Integer>(numTokens, spinSize);

    //fills ArrayList with tokens
    for(int i = 1; i <= numTokens; i++) {
        al.add(i);
    }

您可以使用以下代码。

  public static void shuffleList(List<Integer> a) { int n = a.size(); Random random = new Random(); random.nextInt(); for (int i = 0; i < n; i++) { int change = i + random.nextInt(n - i); swap(a, i, change); } } private static void swap(List<Integer> a, int i, int change) { int helper = a.get(i); a.set(i, a.get(change)); a.set(change, helper); } 

请注意,这已从以下链接复制

http://www.vogella.com/articles/JavaAlgorithmsShuffle/article.html

希望能帮助到你

如果您可以改组您的班级(可能是因为不是列表:那么您可以填充一个列表,请改组该列表,最后将已改组的数据添加到您的班级中:

    final List<Integer> tempList = new ArrayList<Integer>();


    //fills ArrayList with tokens
    for(int i = 1; i <= numTokens; i++) {
        tempList.add(i);            

    }

    Collections.shuffle(tempList);

    for(Integer i: tempList) {
        al.add(i);
    }

基于@Jabir的答案

用于交换任何类型的对象(不仅仅是Integer)

public static <T> void shuffleList(List<T> a) {
    int n = a.size();
    for (int i = 0; i < n; i++) {
      int change = i + Random.nextInt(n - i);
      swap(a, i, change);
    }
  }

  private static <T> void swap(List<T> a, int i, int change) {
    T helper = a.get(i);
    a.set(i, a.get(change));
    a.set(change, helper);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM