简体   繁体   English

随机打印数组元素,直到已打印所有元素

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

I'm trying to create a method that takes in 3 int arrays and prints out one element from each array until all the elements of all three arrays have been printed at least once. 我正在尝试创建一种方法,该方法接受3个int数组并从每个数组中打印出一个元素,直到所有三个数组的所有元素都至少打印了一次。 The first array has 10 elements, the second has 7, and the third has 2. The elements are selected and printed at random. 第一个数组包含10个元素,第二个数组包含7个,第三个数组包含2个。元素是随机选择和打印的。 Any help would be appreciated. 任何帮助,将不胜感激。 The idea is to see how many iterations it would take to print out all the elements at least once. 想法是查看至少打印一次所有元素需要进行多少次迭代。 I don't know the conditions to set for a large scale iteration like this. 我不知道为这样的大规模迭代设置条件。 My code so far (with just one array as a parameter): 到目前为止,我的代码(仅使用一个数组作为参数):

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();
  }

}

code output: 7 2 4 1 8 10 3 10 7 3 代码输出:7 2 4 1 8 10 3 10 7 3

You could use a collection like Set to keep track of indexes that were already picked. 您可以使用诸如Set类的Set来跟踪已选择的索引。 Each time you generate a random number you would first check if it already exist in the Set. 每次生成随机数时,首先要检查该随机数是否已存在于Set中。 If not, print the value in array and add the index number to the set. 如果不是,则打印数组中的值并将索引号添加到集合中。

Your loop would end when size of that set equals size of the array. 当该集合的大小等于数组的大小时,循环将结束。

Solution for one array: 一种阵列的解决方案:

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