[英]how select randomly from an int array, then remove the selected element
我試圖從數組中隨機選擇來打印它,然后從數組中刪除它,以避免兩次打印出相同的數字。 我是一個 Java 新手,所以想知道是否有人可以指出我哪里出錯了。
public static void main(String[] args) {
int[] colm = { 1, 2, 3, 4, 5, 67, 87 };
Random rand = new Random();
for (int i = 0; i < 5; i++)
System.out.println(" " + colm[rand.nextInt(colm.length)]);
}
謝謝
隨機不提供唯一編號的保證。 您可以改為執行以下操作。
public static void main(String[] args) {
int[] colm = { 1, 2, 3, 4, 5, 67, 87 };
List l = new ArrayList();
for(int i: colm)
l.add(i);
Collections.shuffle(l);
for (int i = 0; i < 5; i++)
System.out.println(l.get(i));
}
您缺少刪除部分。 嘗試這樣的事情:
public static void main(String[] args)
{
Integer [] colm = {1,2,3,4,5,67,87};
final List<Integer> ints = new ArrayList<Integer>(Arrays.asList(colm));
Random rand = new Random();
for(int i = 0; (i<5) && (ints.size() > 0); i ++) {
final int randomIndex = rand.nextInt(ints.size());
System.out.println(" " + ints.get(randomIndex));
ints.remove(randomIndex);
}
}
您最好使用 Set 或 Map 來保存數據,然后創建屬於 set/map 長度的隨機數,並使用該(隨機)索引刪除。
public static void removeElements(int[] arr) {
Random random = new Random();
List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
int length = arr.length;
while (length > 0) {
System.out.println("Size: " + list.size());
if (list.size() == 1) {
int randomIndex = random.nextInt(list.size());
list.remove(randomIndex);
System.out.println("Size:--> " + list.size());
break;
}else {
int randomIndex = random.nextInt(list.size() - 1);
if (arr == null || randomIndex > arr.length) {
System.out.println("No Elements to be deleted");
}
list.remove(randomIndex);
System.out.println("Removed Element: " + list.get(randomIndex));
length--;
if (length == 0)
break;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.