0

I have two strings which are mentioned below -

HelloWorld 
GoodBye

How do I randomly select any one of the strings?

Below is an enum which contains the above two strings and I am supposed to use below enums to randomly select any one of the string between HelloWorld and GoodBye

public enum StringEnum {
    HelloDavid, HelloWorld, GoodBye;

    private static final Map<Integer, StringEnum> BY_CODE_MAP = new LinkedHashMap<Integer, StringEnum>();

    static {
    for (StringEnum rae : StringEnum.values()) {
        BY_CODE_MAP.put(rae.ordinal(), rae);
    }
    }

    public static String forCode(int code) {
    return BY_CODE_MAP.get(code).name();
    }
}

Any idea how this can be done efficiently by getting the strings from enum?

1 Answers1

1

Usually you would put all the elements you want to choose from in some data structure like an array and then select a random index to fetch.

In your example this could look something like this: (I assume, that you actually want to choose from all enum values and you want back the enum value rather than the String)

int idx = new Random().nextInt(StringEnum.values().length);
StringEnum random = StringEnum.values()[idx];

Also see questions like "Random element for string array" for more information about generally selecting random elements.

For the simpler case of really only choosing between the two mentioned elements, you could just retrieve one random integer and decide based on whether it is positive (including 0) or negative:

StringEnum random = (new Random().nextInt() < 0) ? 
                    StringEnum.HelloWorld : StringEnum.Goodbye;
Community
  • 1
  • 1
s1lence
  • 2,188
  • 2
  • 16
  • 34