Foxx
Foxx

Reputation: 43

Getting the code to randomly choose one of x amount of choices

I used to program with a language where, if I wanted a number from a set of different numbers, I could go x=choose(0,-1,2,5) and then it would randomly choose one of those options and give me a result. But since I've been working with Android and Java, I don't know a way to replicate that function as there's nothing I can find in the Android SDK that is like it.

Upvotes: 0

Views: 324

Answers (3)

craftsman
craftsman

Reputation: 15623

Assume that your numbers are placed in an integer array:

int[] numbers = {0, -1, 2, 5};

You can put a random number into x as:

int x = numbers[Random.nextInt(4)];

EDIT:

Probably creating a static function in a class would make this solution more like the one you used with your previous language:

public class MyUtil{
    private static Random random = new Random();
    public static int choose(int ... numbers){
        return numbers[random.nextInt(numbers.length)];
    }
}

You can use this function anywhere in your code as:

int x = MyUtil.choose(0, -1, 2, 5);

Upvotes: 1

Eyal Schneider
Eyal Schneider

Reputation: 22446

You can use the varargs feature:

private static Random random = new Random();

public static int choose(int ... numbers){
        return numbers[random.nextInt(numbers.length)];
}

This will make your code very similar to what you expect. The array creation is implicit:

int x = choose(1,5,20,4);

Upvotes: 0

Falmarri
Falmarri

Reputation: 48577

Use the random function to generate an integer. That integer can be an index to a list of your options.

Upvotes: 0

Related Questions