-7

Is it possible to generate random number only by given values. For example if I have numbers: 4,100,2,20->2

4,100,2,20->20 Thanx

LanMan
  • 211
  • 1
  • 3
  • 9

1 Answers1

1

Put your values in an array or List and randomise the index value...for example

public int randomValue(int... values) {
    int index = (int)Math.round(Math.random() * values.length);
    return values[index];
}

You could also use a List and use Collections.shuffle

For example...

public class Test {

    public static void main(String[] args) {
        int[] values = {4,100,2,20};
        System.out.println(randomValue(values));

        List<Integer> listOfValues = new ArrayList<Integer>(values.length);
        for (int value : values) {
            listOfValues.add(value);
        }
        Collections.shuffle(listOfValues);
        System.out.println(listOfValues.get(0));
    }

    public static  int randomValue(int... values) {
        int index = (int)Math.round(Math.random() * values.length);
        return values[index];
    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366