簡體   English   中英

隨機打印數組元素,直到已打印所有元素

[英]Printing array elements at random until all elements have been printed

我正在嘗試創建一種方法,該方法接受3個int數組並從每個數組中打印出一個元素,直到所有三個數組的所有元素都至少打印了一次。 第一個數組包含10個元素,第二個數組包含7個,第三個數組包含2個。元素是隨機選擇和打印的。 任何幫助,將不勝感激。 想法是查看至少打印一次所有元素需要進行多少次迭代。 我不知道為這樣的大規模迭代設置條件。 到目前為止,我的代碼(僅使用一個數組作為參數):

import java.util.*;

public class calculateAverage{

  private static int[] x = new int[]{1,2,3,4,5,6,7,8,9,10};
  private static int[] y = new int[]{1,2,3,4,5,6,7};
  private static int[] z = new int[]{1,2};



  public static void main(String[] args){    
    calculate(x);

  }

  public static void calculate(int a[]){
    Random random = new Random();
    for(int i = 0;i < a.length; i++){
      System.out.print(a[random.nextInt(a.length)] + " ");
    }
    System.out.println();
  }

}

代碼輸出:7 2 4 1 8 10 3 10 7 3

您可以使用諸如Set類的Set來跟蹤已選擇的索引。 每次生成隨機數時,首先要檢查該隨機數是否已存在於Set中。 如果不是,則打印數組中的值並將索引號添加到集合中。

當該集合的大小等於數組的大小時,循環將結束。

一種陣列的解決方案:

public static int calculate(int a[]){
    Random random = new Random();
    HashSet<Integer> remaining = new HashSet<Integer>();
    for (int i = 0; i < a.length; i++) {
        remaining.add(i);
    }
    int i = 0;
    while (!remaining.isEmpty()) {
        int index = random.nextInt(a.length);
        System.out.print(a[index] + " ");
        remaining.remove(index);
        i++;
    }
    System.out.println();
    System.out.println("Finished after " + i + " iterations.");
    return i;
}
int a[] = {4, 6, 3, 2, 9, 1, 5};        
Set<Integer> set = new TreeSet<Integer>();
int counter = 0;
Random rand = new Random();
while(set.size() != a.length){
    set.add(a[rand.nextInt(a.length)]);
    counter ++;
}
System.out.println("Total Iterations : "+counter);
return counter;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM