java 数组随机组合,java – 数组的随机混排

这段Java代码展示了如何使用Fisher-Yates洗牌算法(也称为Knuth shuffle)来随机打乱一个整数数组。通过引入ThreadLocalRandom,代码确保了在并发环境中安全且高效的数组元素随机排列。
摘要由CSDN通过智能技术生成

使用集合来随机移动一个原始类型的数组有点过分…

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;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值