• Post Reply Bookmark Topic Watch Topic
  • New Topic

Selecting a random element from an anonymous array  RSS feed

 
Erik Przekop
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that this may not be the clearest code in the world, but when I came across it in a book I thought it was pretty nifty. Please take a look at the following:

char c = new char[] {'a', 'b', 'c', 'z'}[(int)(Math.random() * 4)];

It will grab a random array element from the anonymous array & assign it to the character variable c.

I think that this is pretty cool whenever you have a need for pseudo-random behavior and a relatively short list of elements to choose from. Now if I could think of some way to get the length of the array without having to hard-code it as a multiplier for Math.random()...
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Erik, welcome to the Ranch!

Now if I could think of some way to get the length of the array without having to hard-code it as a multiplier for Math.random()...


Obviously if the code doesn't have to be a one-liner then that's a relatively trivial requirement.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!