mercredi 23 novembre 2016

random numbers from an array into another array with different occurences rules in java

I need help for an exercice in school.

I need to create an array with 6 random integers from the following array : montab[] = {1,2,3,4,5,6,7,8,9,10,25,50,75,100} and with the following rules :

  1. numbers 25,50,75,100 can only occur once each in the array
  2. numbers 1 to 10 can only occur twice each in the array

I tried the first rule for now but in rare cases I still get the number more than once.

Here is my code :

public class Exo7bis {
public static void main (String[] args){
    Random random = new Random();
    int montab[] = {1,2,3,4,5,6,7,8,9,10,25,50,75,100};
    int[] ar1 = new int[6];
    int j = 0, compteur25 = 0, compteur50 = 0, compteur75 = 0, compteur100 = 0;
        for (int i = 0; i < ar1.length; i++) {
            ar1[i] = (montab[new Random().nextInt(montab.length)]);
            if (ar1[i] == 25) {
                compteur25++;
                if (compteur25 > 1) {
                    while (ar1[i] == 25)
                        ar1[i] = (montab[new Random().nextInt(montab.length)]);
                }
            }
            if (ar1[i] == 50) {
                compteur50++;
                if (compteur50 > 1) {
                    while (ar1[i] == 50)
                        ar1[i] = (montab[new Random().nextInt(montab.length)]);
                }
            }
            if (ar1[i] == 75) {
                compteur75++;
                if (compteur75 > 1) {
                    while (ar1[i] == 75)
                        ar1[i] = (montab[new Random().nextInt(montab.length)]);
                }
            }
            if (ar1[i] == 100) {
                compteur100++;
                if (compteur100 > 1) {
                    while (ar1[i] == 100)
                        ar1[i] = (montab[new Random().nextInt(montab.length)]);
                }
            }
        }

        for (int i = 0; i < ar1.length; i++) {
            System.out.print(ar1[i] +" ⎢ " + "\t");
        }
    }
}

I know that my tests are not totally right, I identified the problem but I can't find the proper solution.

If someone could help me or advise me, that would be cool.

Thanks in advance!

Jeremy




Aucun commentaire:

Enregistrer un commentaire