String[] indexValue = {"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42"};
随机取数组里面的值,但是个数可以是1到42位。
比如说第一次取 出来的值是1,2,3
第二次就可以是,123456789101112.。。
你定义的数组有问题,我帮你改过来了,你试下我写的
public static void main(String[] args)
{
int[] indexValue = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42};
int count = (int)(Math.random() * 42);
System.out.println("取出数字个数:" + count);
int[] resultIndex = new int[count];
for (int i = 0; i < count; i++)
{
int index = (int)(Math.random() * 42);
if (!containValue(resultIndex, index))
{
resultIndex[i] = index;
}
else
{
i--;
}
}
for (int i = 0; i < resultIndex.length; i++)
{
System.out.print(indexValue[resultIndex[i]]);
System.out.print(" ");
}
}
private static boolean containValue(int[] resultIndex, int index)
{
for (int j = 0; j < resultIndex.length; j++)
{
if (index == resultIndex[j])
{
return true;
}
}
return false;
}
使用随机数rand,将随机数转化为1~42的正整数,再取出随机数数目的值。也有可以用时间标记随机数,实现不同时间取得的随机数不一样
产生一个1-42的随机数,然后从1到那个随机数,去获取数据
public class Rand{
public static void mian(String[] args){
String[] indexValue = {"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42"};
int flag=Math.random()*42;//产生随机数
for(int i=0;i<flag;i++)
{
int num=Math.random()*42;
System.out.print(indexValue[num]);
}
}
}
代码你试试吧 有问题私聊我
能不能重复,按不按顺序 这些条件说清楚才好下手
每次都是 从1取么?
使用随机数rand,将随机数转化为1~42的正整数,再取出随机数数目的值。也有可以用时间标记随机数,实现不同时间取得的随机数不一样
public static void getNum(Integer random){
// 存取取出来的值,判定是否重复需要
Map map = new HashMap();
// 取随机数
List list = new ArrayList();
// 设定跳出循环
boolean b = true;
do{
// 存入map(因为map不会存在两个重复的键位)
int result = new Random().nextInt(42)+1;
// 存入map
if(!map.containsKey(result) && list.size() < random.intValue()){
map.put(result, "");
list.add(result);
} else if(list.size() >= random.intValue()) {
b = false;
}
}while(b);
// 取出来的随机出
System.out.println(list);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("随机数的个数:");
// 随机数的个数
int n = scanner.nextInt();
getNum(n);
scanner.close();
}
数字可以自己加,想随机多少都没问题,不会重复,如果要排序,再加个排序方法就行
这方面Ruby非常在行
def choose(array)
rand(array.size).times do
array.delete_at(rand(array.size))
end
return array
end
array = (1..42).to_a
p choose(array)
楼主你参考下我的代码,我也是新手,这个代码不重复和排序都可以做到,我也把注释写在上面了(缺点也写了)
// 排序需要调用的函数 function d(e, f) { return e - f; } // 声明空数组,用来存放随机产生的数据b var a = []; // 打印出的数组需要几个数据,就循环几次 for (var i = 0; i < 5; i++) { //5=》代表数组个数,数组的个数(5随便改)可以改 // 产生随机数(1-42) var b = Math.ceil(Math.random() * 42); // 遍历a的数组, for (var j = 0; j < a.length; j++) { // 如果数组a里面有跟随机数b有相同的数据,就把按a数组里面的相同的数据干掉 if (a[j] == b) { a.splice(j, 1); } } // 如果数组a里面没有跟随机数b有相同的数据,就把随机数b放在a数组里面 if (a.indexOf(b) == -1) { a.push(b); } } // 排序 console.log(a.sort(d));用push 和pop 的方法
用一个random取随机数
你试试使用随机数rand,将随机数转化为1~42的正整数,再取出随机数数目的值。也有可以用时间标记随机数,实现不同时间取得的随机数不一样