【问题标题】:Java: Random permutation without importing java.utilJava:不导入 java.util 的随机排列
【发布时间】:2020-03-02 08:49:23
【问题描述】:

互联网上有许多不同的指令来进行随机排列,但它们都使用库。有没有办法在不使用任何内置库的情况下进行随机排列?我知道如何使用Math.random() 生成随机数。生成随机排列是否与Math.random() 有关?洗牌对我来说看起来很复杂。

我的目标是如果我通过“java randompermutation 3”运行程序,那么程序返回 1,2,3 或 1,3,2,或 3,1,2,或 3,2,1,或2,3,1 或 2,1,3

【问题讨论】:

  • 您认为简单的方法是什么?
  • 使用回溯here查看我的证明。
  • “我知道如何使用 Math.random() 生成随机数” - 已经在使用内置库了。
  • 导入有什么问题?我不是想惹人讨厌,我只是好奇。
  • @studenthahahoho java.util 是一个标准的 java 库,它不是一个外部库。听起来您不想使用 java 的功能。对我来说,这听起来像是在说“我怎样才能在不使用汽车雨刷的情况下将雨水从汽车挡风玻璃上去除?”

标签: java permutation shuffle knuth


【解决方案1】:

你能像下面的例子那样做吗

public class Main {
    public static void main(String[] args) throws Exception {
        Integer[] input = new Integer[] { 1, 2, 3 };
        Integer[] shuffleInput = shuffle(input);

        for (int i=0; i<shuffleInput.length; i++) {
            System.out.print(shuffleInput[i]);
        }
    }

    public static Integer[] shuffle(Integer[] input) {
        Integer[] inputCopy = input.clone();;
        Integer[] output = new Integer[input.length];

        for (int i=0; i<output.length; i++) {
            // Find and get a random element
            int randPicker = (int)(System.currentTimeMillis() % inputCopy.length);
            output[i] = inputCopy[randPicker];

            // Remove selected element from copy
            Integer[] aux = new Integer[inputCopy.length - 1];
            System.arraycopy(inputCopy, 0, aux, 0, randPicker);
            if (inputCopy.length != randPicker) {
                System.arraycopy(inputCopy, randPicker + 1, aux, randPicker, inputCopy.length - randPicker - 1);
            }
            inputCopy = aux;
        }

        return output;
    }
}

此代码将任意大小的Integer 列表作为输入,并返回包含混合值的列表。

如果列表总是 3 个数字,它可能是一个更简单的版本。

已编辑:此版本不使用Math.random() 或任何其他java.util

【讨论】:

  • 感谢您的回复。我的意思是说我不想使用 java.util
  • 试试这个没有任何 java.util 的新版本。您可以随时检查方法的实现并直接复制它。
【解决方案2】:

对数组进行排序的一种算法是基于选择排序的,称为选择 shuffle。遍历数组并为每个索引选择一个随机索引并交换这两个索引。由于这看起来有点像家庭作业,我将避免给出任何实际代码,但这是一个解决方案。

【讨论】:

    猜你喜欢
    • 2014-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 2011-05-31
    • 2018-09-17
    • 2021-09-26
    相关资源
    最近更新 更多