-4

I was trying to solve a problem.I have to define an array with 5 elements on it and define a random generator method with 3 defined integersi1,i2,i3 that would be different from each other.So when the variables will be generated they have to be different .I hope that i am clear.Can anybody please help me ,or any suggestion would be welcome.

import java.util.*;


public class Array {

    public static void main(String[] arg) {
        int[] v = { 1, 2, 3, 4, 5 };
        DisplayArray(v);
        Array n = new Array();

        n.randomGenerator();
    }

    private static void DisplayArray(int[] arr) {
        for (int x : arr)
            System.out.print(x + " ");
        System.out.println();
    }

    public int[] randomGenerator() {

        int[] a = new int[3];
        int i1;
        int i2;
        int i3;

        for (int i = 0; i < a.length; i++) {
            a[i] = (int) (Math.random() * 5);
        }
        i1 = a[0];
        i2 = a[1];
        i3 = a[2];

        if (i1 != i2 && i2 != i3 && i1 != i3) {
            System.out.println(i1 + "," + i2 + "," + i3);
        } else {
            if (i1 == i2 && i2 == i3 && i1 == i3) {

            }
        }

        return a;
    }
}
Danielson
  • 2,605
  • 2
  • 28
  • 51
  • Tip: Do a search here on SO, because this question has been asked many times before. :) – WonderWorld Mar 20 '15 at 18:44
  • What you're describing is very unclear. It's best if you show what you're trying to do with code and expalin what the specific problem is. – tnw Mar 20 '15 at 18:45
  • possible duplicate of [Generating random integers in a range with Java](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java) – Minar Mahmud Mar 20 '15 at 18:47
  • i improved my question...so i am left on that part of else statement in random generator method...hope that you can understand – asiarobywski Mar 20 '15 at 20:22

1 Answers1

-2

There are two options for using this:

One possibility is while generating a new random number check if it's any of the existing random numbers and if so, retry the generation. In theory, this could take a LONG amount of time but in practice it's fast.

Another option would be e.g. if you want to generate random numbers in the range 0-9 (inclusive-inclusive) and if you already have e.g. 3 and 7, to generate Math.random()%8 instead of Math.random()%10 and then if the number is greater than or equal to 3, increment it by one, and if the new number is greater than or equal to 7, increment it by one.

juhist
  • 4,210
  • 16
  • 33
  • Random numbers are seeded. That kind of check isn't necessary. – tnw Mar 20 '15 at 18:46
  • I guess you mean the check that the new random number isn't any of the existing random numbers? Yes, it's necessary because the OP wanted DIFFERENT random numbers and if you do Math.random()%10 two times in a row you may end up with two same values. – juhist Mar 20 '15 at 18:48