限制重复的随机数

时间:2014-02-11 13:57:08

标签: java arrays random

我只想知道如何限制随机数出现的次数。我已生成1到10的随机数,并希望限制每个数字出现4次。

myArray[i][j] = rand.nextInt(11);

for (int i=0; i < myArray.length; i++) {
   for (int j=0; j < myArray[i].length; j++) {
       myArray[i][j] = rand.nextInt(11);
       System.out.print(" " + myArray[i][j]);

上面的代码创建了randoms数字。只是想限制它们。

6 个答案:

答案 0 :(得分:3)

由于您只能使用10 * 4 = 40个数字,因此您可以使用列表并随机化索引:

List<Integer> numbers = new ArrayList<Integer>();
for (int i = 1; i < 11; ++i) {
   for (int j = 0; j < 4; ++j) 
      numbers.add(i);
}

然后当你指定一个随机数时:

int i = rand.nextInt(numbers.size());
myArray[i][j] = numbers.get(i);
numbers.remove(i);

这假设您的二维不包含超过40个数字

答案 1 :(得分:1)

我的解决方案将结果存储在arrayList:

public class Example {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    final int range = 10;
    int[] numbers = new int[range + 1];
    int sum = 0;
    final int noOfOccurances = 4;
    final int size = range * noOfOccurances;
    Arrays.fill(numbers, 0);
    Random generator = new Random();
    List<Integer> numbersArray = new ArrayList<>();
    while (sum != size) {
        int randomNumber = generator.nextInt(range) + 1;
        if (numbers[randomNumber] != noOfOccurances) {
            numbers[randomNumber]++;
            sum++;
            numbersArray.add(randomNumber);
        }
    }
    System.out.println(numbersArray);
}
}

答案 2 :(得分:0)

如何将生成的int的计数存储在数组,Map或其他内容中?

Map<Integer, Integer> randomCounts = new HashMap<Integer, Integer>(); 
... your for loops
myArray[i][j] = rand.nextInt(11);
if (randomCounts.containsKey(myArray[i][j])) { 
   randomCounts.put(myArray[i][j],randomCounts.get(myArray[i][j])+1);
} else {
   randomCounts.put(myArray[i][j],1);
}

如果你想检查它们,只需遍历你的地图,然后就可以了。 :)

答案 3 :(得分:0)

您可以创建一种方法来检查生成的数字在数组中是否存在4次以上,如果存在,则创建一个新的随机数。它应该是这样的:

import java.util.Random;

public class rndNumberGenerator {

    public static void main (String[] args) {

        int[][] myArray = new int[2][5];
        Random rand = new Random();
        int randomNumber;

        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 5; j++) {

                do {
                    randomNumber = rand.nextInt(11);
                } while(overMax(myArray, randomNumber) == true);

                myArray[i][j] = randomNumber;

                System.out.print(" " + myArray[i][j]);

            }
        }

    }

    public static boolean overMax(int[][] array, int number) {

        int max = 4;
        int count = 0;

        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 5; j++) {

                if (array[i][j] == number) {
                    count++;
                }

            }
        }

        if (count >= max)
            return true;
        else
            return false;

    }
}

希望这对你有所帮助,如果你有任何其他问题随时可以问。

答案 4 :(得分:0)

我接受 pshemek 的建议(投票结果):改为ArrayList,我使用Set,因为它不能包含重复的数字,而且您有&# 39;而不是控制。

实施:副本{右,左} 属于 pshemek ,我只是扩展了这个想法:)

public class Example {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int[] numbers = new int[11];
        int sum = 0;
        final int range = 10;
        final int noOfOccurances = 4;
        Arrays.fill(numbers, 0);
        Random generator = new Random();
        Set<Integer> numbersArray = new TreeSet<Integer>();
        while (sum != range * noOfOccurances) {
            int randomNumber = generator.nextInt(range) + 1;
            sum++;//correction for first comment
            numbersArray.add(randomNumber); // randomNumber will never be twice: a Set cointains ever one and only one instance of an determinated element
        }
        System.out.println(numbersArray);
    }

  }//end class

答案 5 :(得分:0)

你可以写自己的:

public static class CountedRandom {
    // My rng.
    Random rand = new Random();
    // Keeps track of the counts so far.
    Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
    // The limit I must apply.
    final int limit;

    public CountedRandom(int limit) {
        this.limit = limit;
    }

    public int nextInt(int l) {
        int r;
        do {
            // Keep getting a new number until we hit one that has'n been overused.
            r = rand.nextInt(l);
        } while (count(r) >= limit);
        return r;
    }

    private int count(int r) {
        // How many times have we seen this one so far.
        Integer counted = counts.get(r);
        if ( counted == null ) {
            // Never!
            counted = new Integer(0);
        }
        // Remember the new value.
        counts.put(r, counted + 1);
        // Returns 0 first time around.
        return counted;
    }
}

public void test() {
    CountedRandom cr = new CountedRandom(4);
    for ( int i = 0; i < 50; i++ ) {
        System.out.print(cr.nextInt(4)+",");
    }
    System.out.println();
}

请注意,如果您要求的范围太小(例如我在测试中),那么将会挂起

打印

2,0,1,2,1,1,3,3,0,3,0,2,2,0,1,3,

然后挂起。