从数组挑选随机元素,但独特的 [英] Pick random element from array, but unique

查看:127
本文介绍了从数组挑选随机元素,但独特的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的国家阵列。我想选择从我的数组列表5个随机的国家,但我希望他们是唯一的。
这是我到目前为止有:

 字符串allCountries [] = {芬兰,拉脱维亚,波兰,阿富汗,阿尔巴尼亚,阿尔及利亚};字符串= COUNTRY1(allCountries [新的随机()nextInt(allCountries.length)。]);
字符串COUNTRY2 =(allCountries [新的随机()nextInt(allCountries.length)。]);
字符串COUNTRY3 =(allCountries [新的随机()nextInt(allCountries.length)。]);
字符串country4 =(allCountries [新的随机()nextInt(allCountries.length)。]);
字符串country5 =(allCountries [新的随机()nextInt(allCountries.length)。]);

什么是同时生成随机元素来比较这些字符串的最佳方式?

编辑:

我前pressed自己不好。我的问题是,我不想串国家1,国家2等是相同的,所以,我希望他们能总是不同的。

解决方案:

  Col​​lections.shuffle(Arrays.asList(allCountries));


解决方案

shuffle的数组,然后切片前5个元素。

这将保证5唯一的随机元素。

I have array of countries. I want to pick 5 random countries from my array list, but I want them to be unique. This is what I have so far:

String allCountries[] = {"Finland", "Latvia", "Poland", "Afghanistan", "Albania", "Algeria"};

String country1 = (allCountries[new Random().nextInt(allCountries.length)]);
String country2 = (allCountries[new Random().nextInt(allCountries.length)]);
String country3 = (allCountries[new Random().nextInt(allCountries.length)]);
String country4 = (allCountries[new Random().nextInt(allCountries.length)]);
String country5 = (allCountries[new Random().nextInt(allCountries.length)]);

What is the best way to compare those strings while generating random elements?

Edit:

I expressed myself bad. The problem I have is that I don't want string country1, country 2 etc. to be same... so I want them to be always different.

Solution:

Collections.shuffle(Arrays.asList(allCountries));

解决方案

Shuffle the array and then slice the first 5 elements.

This will guarantee 5 unique random elements.

这篇关于从数组挑选随机元素,但独特的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆