你能告诉我如何随机打印所有字符串数组,但没有重复。我不想使用Lists,Collecton.shuffle。
我试试:
String names[] = { "name1", "name2", "name3", "name4", "name5" };
System.out.println(names[rand.nextInt(groupMembers.length - 1)]);
我想打印所有名字,但只是洗牌一次。 像这样:
name4,name1,name2,name5,name3
答案 0 :(得分:0)
这是代码,但你要问的是不必要的代码复杂化:
public static void main(String [] args) {
String names[] = { "name1", "name2", "name3", "name4", "name5" };
int upper = names.length;
int lower = 0;
int r=0;
Set<Integer> uniqueList = new HashSet<Integer>();//This is the set which is used to make sure elements in the array are printed only once
for(int count=0;count<names.length;count++){
uniqueList.add(count);
}
while(!uniqueList.isEmpty()){
r = (int) (Math.random() * (upper - lower)) + lower;//generate a random number
if(uniqueList.contains(r)){//if the random number lies between array length, then print the random name and remove it from set so that it wont print duplicate
uniqueList.remove(r);
System.out.println(names[r]);
}
}
}
答案 1 :(得分:0)
尝试使用javascript解决此问题,对此逻辑非常有趣。
这是我正在尝试的算法: 找到
此算法将仅使用单个数组,并且在打印所有项目之后,我们将获得一个与打印顺序相反的更新列表。
var names = ["name1", "name2", "name3", "name4", "name5"];
function switchItem(arr, from, to) {
let temp = arr[from];
arr[from] = arr[to];
arr[to] = temp;
return names;
}
function getRandomUniqueValues(values) {
for(var i = 0; i < values.length; i++) {
let randomPosition = Math.floor(Math.random() * Math.floor(values.length - i -1));
console.log(values[randomPosition]);
values = switchItem(values,randomPosition,values.length - 1 - i)
}
}
getRandomUniqueValues(names);