Java 为数组生成随机索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4023137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating a random index for an array
提问by W M
I know this for normal integers, but is there for such a thing as indices?
对于普通整数我知道这一点,但是否有索引之类的东西?
Random dice = new Random();
int n = dice.nextInt(6);
System.out.println(n);
采纳答案by Christoffer
What do you mean? Array indices are normal numbers, so you can easily do
你的意思是?数组索引是正常的数字,所以你可以很容易地做到
String names[] = { "One", "Two", "Three", "Four", "Five", "Six" };
Random Dice = new Random();
int n = Dice.nextInt(6);
System.out.println(names[n]);
Or do you mean a random Iterator class? Google is your friend here, thisis the first hit I get.
或者你的意思是一个随机的迭代器类?谷歌是你的朋友,这是我得到的第一个成功。
回答by aioobe
To generate a random index for someArray
you do
为someArray
你生成一个随机索引
int index = new Random().nextInt(someArray.length);
nextInt(n)
returns a number between 0 (inclusive) and n
(exclusive) which is why someArray.length
is given as argument.
nextInt(n)
返回一个介于 0(包含)和n
(不包含)之间的数字,这就是someArray.length
作为参数给出的原因。
回答by Andrew
Another solution would be:
另一种解决方案是:
int randomElement = yourArray[Math.random()*yourArray.length];
Math.random() generates a random number between 0 and 1. If you multiply that number by the length of your array, you will get an random index for the array.
Math.random() 生成一个介于 0 和 1 之间的随机数。如果将该数字乘以数组的长度,您将获得数组的随机索引。
For example: If Math.random() generated .2 and your array had a length of 10, you would get an index of 2.
例如:如果 Math.random() 生成 .2 并且您的数组的长度为 10,您将获得索引 2。
回答by Frank HN
Here is another possibility that worked for me in React js if you want to return the value of that index in an array.
如果您想在数组中返回该索引的值,这是另一种在 React js 中对我有用的可能性。
const myArray = [1,2,5,7,6,87,45,34,23,12]
const rand = myArray[Math.floor(Math.random() * myArray.length)];
console.log('value of the index', rand);
console.log('index in the array',myArray.indexOf(rand));