我的Android Eclipse项目中有一个包含5个字符串的ArrayList,如下所示:
//ArrayList<String> Declaration
ArrayList<String> al= new ArrayList<String>();
//add method for String ArrayList
al.add("1st_string");
al.add("2nd_string");
al.add("3rd_string");
al.add("4th_string");
al.add("5th_string");
我想根据以下计划随机选择没有重复的字符串:
我将有一个名为string_selection
的变量和一个Textview来保存名为displayed_string
的结果
1)string_selection == 0
---&gt;显示TextView displayed_string中的第一个元素(下次选择剩下的4个字符串)
2)string_selection == 1
---&gt;显示TextView displayed_string中的第二个元素(下次选择剩下的3个字符串)
最后
3)string_selection == 2
---&gt;在TextView shown_string中显示第3个元素(,就是它。只需设置string_selection == 0
)
我该怎么办?
答案 0 :(得分:0)
随机选择时删除项目(如果需要保留原始字符串,请将字符串存储在单独的数组中):
项目= 1,2,3,4,5
随机选择:2
使用items[2]
并删除。
items = 1,2,4,5
随机选择:1
使用items[1]
并删除。
items = 1,4,5
所以......
答案 1 :(得分:0)
private List<SameType> randomList (List<Type> targetList){
List<TypeAsTarget> newUniqueList = new ArrayList<>(targetList.size());
newUniqueList.add(0, targetList.get(new Random().nextInt(targetList.size())));
newUniqueList.add(1, targetList.get(new Random().nextInt(targetList.size())));
newUniqueList.add(2, targetList.get(new Random().nextInt(targetList.size())));
newUniqueList.add(3, targetList.get(new Random().nextInt(targetList.size())));
newUniqueList.add(4, targetList.get(new Random().nextInt(targetList.size())));
while (newUniqueList.get(1) == newUniqueList.get(0))
newUniqueList.set(1, targetList.get(new Random().nextInt(targetList.size())));
while (newUniqueList.get(2) == newUniqueList.get(0) || newUniqueList.get(2) == newUniqueList.get(1))
newUniqueList.set(2, targetList.get(new Random().nextInt(targetList.size())));
while (newUniqueList.get(3) == newUniqueList.get(0) || newUniqueList.get(3) == newUniqueList.get(1) || newUniqueList.get(3) == newUniqueList.get(2))
newUniqueList.set(3, targetList.get(new Random().nextInt(targetList.size())));
while (newUniqueList.get(4) == newUniqueList.get(0) || newUniqueList.get(4) == newUniqueList.get(1) || newUniqueList.get(4) == newUniqueList.get(2) || newUniqueList.get(4) == newUniqueList.get(3))
newUniqueList.set(4, targetList.get(new Random().nextInt(targetList.size())));
return newUniqueList;
}
答案 2 :(得分:0)
如果不需要,您可以从数组中随机删除字符串,也可以使用一些集合来跟踪已使用的随机索引。
1)删除
String getRandom(List<String> strings) {
return strings.remove(new Random().nextInt(strings.size()));
}
2)跟踪使用的索引:
String getRandom(List<String> strings, Set<Integer> used) {
int next;
do {
next = new Random().nextInt(strings.size());
} while (used.contains(next));
used.add(next);
return strings.get(next);
}