Pick a random value from an enum?
The only thing I would suggest is caching the result of values()
because each call copies an array. Also, don't create a Random
every time. Keep one. Other than that what you're doing is fine. So:
public enum Letter {
A,
B,
C,
//...
private static final List<Letter> VALUES =
Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static Letter randomLetter() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}
How can i pick Random Value from an Enum?
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;
}
}
How to generate random value from enum and put it in array?
An enum should be named in the singular, and should start with an uppercase letter.
enum Item { KARTE, MONSTERBALL, MONSTERDEX, FAHRRAD, VM03, HYPERHEILER, AMRENABEERE, TOPGENESUNG, ANGEL, TOPSCHUTZ }
And I suggest you work at devising a more descriptive name than “Item”.
Get an array of all the enum objects by calling values
.
Item[] allItems = Item.values() ;
Generate a random number. Use that number as the index into your array of all items.
int randomIndex = ThreadLocalRandom.current().nextInt( 0 , allItems.length ) ; // ( inclusive , exclusive )
Item rando = allItems[ randomIndex ] ;
Or perhaps you meant to randomly sort (shuffle) all the elements of the enum. If so, make a List
backed by the array. Call Collections.shuffle
. Changes made to the list also affect the backing array. So the array is shuffled.
Item[] allItems = Item.values() ;
List< Item > list = Arrays.asList( allItems );
Collections.shuffle( list );
More briefly:
Item[] allItems = Item.values() ;
Collections.shuffle( Arrays.asList( allItems ) );
See this code run live at Ideone.com.
[MONSTERBALL, TOPSCHUTZ, KARTE, FAHRRAD, VM03, MONSTERDEX, ANGEL, AMRENABEERE, TOPGENESUNG, HYPERHEILER]
How to randomly select an enum value?
// get an array of all the cards
private Card[]cards=Cards.values();
// this generates random numbers
private Random random = new Random();
// choose a card at random
final Card random(){
return cards[random.nextInt(cards.length)];
}
generating random enums
How about:
enum my_type {
a, b, c, d,
last
};
void f() {
my_type test = static_cast<my_type>(rand() % last);
}
How to get random value from assigned enum in c++?
There is no way to enumerate the values of an enum.
You can use a table:
std::vector<int> colors = {red, black, pink, rainbow};
and then pick a random element from it.
Picking a random element left as an exercise.
Is it possible to get a random element from an enum class in Kotlin?
You can get a random enum value by doing:
val randomAnswer = Answer.values().toList().shuffled().first().text
Keep in mind that it goes for convenience over performance.
Remember to expose the text
property with val
. For now, it's just a constructor param:
enum class Answer(val text: String)
How to get random value of attribute of Enum on each iteration?
I tried a way with metaclasses. And it works!
import random
import enum
class RANDOM_ATTR(enum.EnumMeta):
@property
def RANDOM(self):
return random.choice([Gender.MALE, Gender.FEMALE])
class Gender(enum.Enum,metaclass=RANDOM_ATTR): #this syntax works for python3 only
FEMALE = 'female'
MALE = 'male'
print(Gender.RANDOM) #prints male or female randomly
Here by making RANDOM_ATTR
the metaclass of Gender
, Gender
is like an object of class RANDOM_ATTR
, so Gender
has the property RANDOM
.
However,the below code you described in your question doesn't work the way you expect.
def full_name(gender=Gender.RANDOM):
...
The RANDOM
property will be called only once. To know why, please read this answer. Default arguments are like attributes to function, which will be initialised only once.
For that i would suggest you do something like this:
def full_name(gender=None):
gender = gender or Gender.RANDOM
...
Using random enum to generate objects in java
you can generate random number and select all values
import java.util.Random;
public class ScenarioGenerator {
public Person getRandomPerson() {
Random rand = new Random();
// max age
int age = rand.nextInt(100);
// no of profession - 1
int profession = rand.nextInt(8);
// no of gender - 1
int gender = rand.nextInt(2);
// no of bodyType - 1
int bodyType = rand.nextInt(3);
int pragnency = rand.nextInt(2);
//need age, gender, bodyType, profession, pregnancy
Person people = new Person(age, Profession.values()[profession], Gender.values()[gender],BodyType.values()[bodyType], pragnency == 1 ? true : false);
return people;
}
}
Java get a random value from 3 different enums
A simple way is to collect all the enum members into a single Object[]
, then take a random element from it.
Note that an enum can also implement an interface, so you can even have some shared API across all the enums. Typically you'll find yourself writing a lot of switch
statements on the value of the enum; those can mostly be replaced by dynamic dispatch against such interface methods. Further note that each enum member can provide its own method implementation.
Related Topics
When Is C++ Covariance the Best Solution
How to Avoid Errors While Using Crtp
Equivalent of "Using Namespace X" for Scoped Enumerations
Lifetime of Object Is Over Before Destructor Is Called
How to Find the Size of All Files Located Inside a Folder
C++11 Std::Mutex in Visual Studio 2012 Deadlock When Locked from Dllmain()
How to Pass a Std::Function Object to a Function Taking a Function Pointer
Delete Calling Destructor But Not Deleting Object
How to Parse CSV Using Boost::Spirit
Why Does Int8_T and User Input via Cin Shows Strange Result
Erasing Vector::End from Vector
When Pass a Variable to a Function, Why the Function Only Gets a Duplicate of the Variable
Ramifications of C++20 Requiring Two's Complement
Removing '#Include <Algorithm>' Doesn't Break the Code