How can i pick Random Value from an Enum?

Viewed 1798

I want to learn how can i pick a string value from enum and run in for-each loop.

Let me write the Assignment here:

"Write a static method generateRandomZoo (n).

The method should have the parameter int n and the result should be an animal array of length n, the randomly chosen animal contains.

Proceed as follows:

  • First create one empty array of corresponding length.
  • Loop through the array.
  • Generate in a random value r for each run using the static method RandomTools.randomValue between 0 and Animal.values​​().length (exclusive).
  • Assign this to the current array position Enumeration element with the corresponding ordinal number for (Animal.values ​​() [r]). You can assume that n is positive."

What I've done is as follows:

First of all enum class looks like:

package main;

public enum Animal{

    ELEPHANT,LION, TIGER, WASP, SNAKE,MONKEY,  EMU;

}

and the main coding part is so:

public static void main(String[] args) {

    Animal[] zoo = generateRandomZoo(100);
}

private static Animal[] generateRandomZoo() {
    // TODO Auto-generated method stub

    Animal [] animals= new Animal [100];
    for(Animal a : Animal.values()){
        System.out.println("Random Animals"+ "-" + a + "-" +(a.ordinal()+1));

        for (int i = 0; i < 100; i++) {
            animal[i] = random animal
            System.out.println(i);
        }

        private static   RandomTools.randomValue();

    }

Could you please tell me where I am wrong and how to correct it ?

(By the way I am pretty beginner please describe in a way that i can understand:))

3 Answers

To generate the random number, use ThreadLocalRandom.current().nextInt(0, Animal.values().length) and retrieve the value from the enum using Animal.values()[randomNumber], although it appears you're provided with RandomTools.randomValue. I've written my own for completeness.

Declare Animal[] values = Animal.values() once, outside your loop and perform the operations on that to avoid values() being called more than once.

It should look something like this:

import java.util.concurrent.ThreadLocalRandom;

public class SOExample {
    private enum Animal {
        ELEPHANT, LION, TIGER, WASP, SNAKE, MONKEY, EMU
    }

    // It's not clear from the question if you're provided with this or if you have to write it
    private static class RandomTools {
        public static int randomValue(int start, int end) {
            return ThreadLocalRandom.current().nextInt(start, end);
        }
    }

    public static void main(String[] args) {
        Animal[] zoo = generateRandomZoo(100);
        // Printing to STDOUT to check results
        for (int i = 0; i < zoo.length; i++) {
            System.out.println(zoo[i]);
        }
    }

    private static Animal[] generateRandomZoo(int numberOfAnimals) {
        Animal[] animals = new Animal[numberOfAnimals];
        Animal[] values = Animal.values();
        for (int i = 0; i < animals.length; i++) {
            int random = RandomTools.randomValue(0, values.length);
            animals[i] = values[random];
        }
        return animals;
    }
}
enum Animal {
    ELEPHANT, LION, TIGER, WASP, SNAKE, MONKEY, EMU
}

Animal[] generateRandomZoo(int n) {

    // possible animal values from enum Animal
    // This array will be of size 7.
    // It has values - ELEPHANT, LION, TIGER, WASP, SNAKE, MONKEY, EMU
    Animal[] animalsOptions = Animal.values();

    // Will be used to generate Random values
    Random random = new Random();

    // Array of size n to store animals to be generated
    Animal[] animals = new Animal[n];

    for (int i = 0; i < n; i++) {

        // animalsOptions.length = 7
        // index will have random value between 0 to 6
        int index = random.nextInt(animalsOptions.length);

        // we take a random animal from animalsOptions and store it in animals
        animals[i] = animalsOptions[index];
    }

    return animals;
}

Then you can call this method to get all random animals

Animal[] animals = generateRandomZoo(100);
for (Animal animal: animals) {
    System.out.println(animal);
}

I will give you the whole code, but make sure you go through it and understand what's happening.

    public static void main(String[] args) {
    Instant start = Instant.now();
    Main m = new Main();
    m.main();
    Instant finish = Instant.now();
    long timeElapsed = Duration.between(start, finish).toMillis();
    System.out.println();
    System.out.println(timeElapsed / 1000.0 + " seconds!");
}


public enum Animal {

    ELEPHANT, LION, TIGER, WASP, SNAKE, MONKEY, EMU;

}

public void main() {
    Animal[] zoo = generateRandomZoo(5); // gets the array
    Arrays.stream(zoo).forEach(System.out::println); // prints the array using the java8 Stream API.
}

private static Animal[] generateRandomZoo(int numAnimals) {
    Animal[] animals = new Animal[numAnimals]; // the array that you want to return
    int size = Animal.values().length; // number of different animals
    Animal[] differentAnimals = Animal.values();
    for (int i = 0; i < numAnimals; i++) {// going through the array of size numAnimals, which is the method
                                          // parameter
        animals[i] = differentAnimals[RandomTools.randomValue(size)];// you get the random value between 0 and number
                                                                    // of different animals and you get that animal.
                                                                    // Then you put it in the array of animals
    }
    return animals;// this is where you return your array.
}

static class RandomTools {
    public static int randomValue(int size) {
        return ThreadLocalRandom.current().nextInt(0, size);
    }
}

So this code calls the function you want to create. The function's role is to take a number (in this case numAnimals = 5) and use it to create an array of size numAnimals. So the next step is to populate the array. You take a for loop and iterate from 0 to numAnimals, because arrays start at 0. In that loop you assign a value to each index of the animals array starting at 0. So animals[0] = random animal; You can see how that happens in the code, and after you do it, you return the array and the code that called the method now has access to the values of that array. That means that means that the variable Animals[] zoo in the main method now holds that generated array. This code then prints all the elements in that array.

Go through it a couple of times and try to modify it. Make it print only animals that are on even indeces in the Animals enum or something like that. Good luck

Related