开发者社区> 问答> 正文

数组的随机改组

我需要随机调整以下数组:

int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1}; 有功能吗?

展开
收起
保持可爱mmm 2020-01-16 16:07:57 457 0
1 条回答
写回答
取消 提交回答
  • 使用Collections改组原始类型的数组有点矫kill过正...

    使用例如Fisher-Yates shuffle本身就很容易实现该功能:

    import java.util.*; import java.util.concurrent.ThreadLocalRandom;

    class Test { public static void main(String args[]) { int[] solutionArray = { 1, 2, 3, 4, 5, 6, 16, 15, 14, 13, 12, 11 };

    shuffleArray(solutionArray);
    for (int i = 0; i < solutionArray.length; i++)
    {
      System.out.print(solutionArray[i] + " ");
    }
    System.out.println();
    

    }

    // Implementing Fisher–Yates shuffle static void shuffleArray(int[] ar) { // If running on Java 6 or older, use new Random() on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } } 问题来源于stack overflow

    2020-01-16 16:08:13
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载