【问题标题】:Implement an algorithm to shuffle an array of numbers实现一个算法来打乱一个数字数组
【发布时间】:2013-02-12 05:11:25
【问题描述】:

我为以下问题编写了代码,但它们不起作用。我得到随机数,但随机播放方法不会随机播放它们。你能帮帮我吗?

for( each index i)

   choose a random index j where j>=i.
   swap the elements at index i and j.

我的代码是:

public static void shuffle(int[] a){
   for( int i = 0; i < a.length-1; i++){
       int range = a.length; 
       int j = (int) (Math.random() * range);
       swap(a, i, j);      
  }
}

public static void swap(int[] array, int i, int j){

        if (i != j) {
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }

【问题讨论】:

  • 有什么问题?你的交换方法在哪里?
  • j&gt;=i 要求发生了什么变化?
  • 无论如何,既然可以SHUFFLE,何必洗牌:见stackoverflow.com/questions/8116872/…
  • 我不知道那会是什么代码。

标签: java


【解决方案1】:

将您的数组转换为 Integer Wrapper 类,并通过将 Integer 数组转换为 List 来调用 Collections.shuffle。 sn-p 在下面

您应该可以访问 Apache 语言库,然后您可以像这样使用 ArrayUtils.toObject(int[]) 方法:

int [] array = {1,2,3,4,5,6};
Integer[] newArray = ArrayUtils.toObject(array);
Collections.shuffle(Arrays.asList(newArray));
for (int i = 0; i < newArray.length; i++) {
    System.out.println(newArray[i]);
}

如果你没有 Apcahe Lang 库,那么你可以这样做

Integer[] newArray = new Integer[array.length];
int i = 0;
for (int value : array) {
    newArray[i++] = Integer.valueOf(value);
}

【讨论】:

    【解决方案2】:

    有 java.util.Collections.shuffle 与 List 一起使用。我建议从 src 复制粘贴算法并将其更改为使用 int[]:

    public static void shuffle(int[] a) {
        Random rnd = new Random();
        for (int i = a.length; i > 1; i--) {
            swap(a, i - 1, rnd.nextInt(i));
        }
    }
    
    private static void swap(int[] a, int i, int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
    
    
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        shuffle(a);
        System.out.println(Arrays.toString(a));
    }
    

    打印

    [8, 7, 3, 4, 6, 1, 2, 5, 9]
    

    【讨论】:

    • 在哪里可以找到 java.util.Collections.shuffle ?我在 java API 中看不到它。
    • @user1995200 查找Collections 类,shuffle 是其中的静态方法
    • 我可以看到,但是这里没有代码,只是解释。
    猜你喜欢
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2017-08-15
    • 1970-01-01
    相关资源
    最近更新 更多