• Post Reply Bookmark Topic Watch Topic
  • New Topic

Any easy explanation for randoms please  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm analyzing this code but find it hard to understand the random section. Whats the purpose of this?

 
Saloon Keeper
Posts: 4090
98
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The purpose apparently is to select a random word from each of the word lists. If you haven't done so yet, start by reading the javadocs of Math.random() so you know what it returns. Maybe that makes it clearer what values rand1/2/3 can take - they are being used as indexes into arrays, after all, so they can't take on just any old value.
 
Ranch Foreman
Posts: 470
3
Android Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Value for arr1Length is 5.
It means generating a number between 1 to 4.



 
Marshal
Posts: 4137
247
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, for the purposes of copyright and correct attribution, please state where you have gotten this code from?
 
Sheriff
Posts: 11594
185
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

John Joe wrote:Value for arr1Length is 5.
It means generating a number between 1 to 4.


That's only half correct. The expression will give 0 to 4.
 
Marshal
Posts: 56871
174
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

What your program doesn's tell you is that there is a better way to get a “random” number in the range 0...n − 1. There is a detailed discussion about that here. That was before Java8 which has methods for getting multiple “random” numbers in a Stream.
 
Saloon Keeper
Posts: 3458
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is the same as this, using the Random class.
 
Campbell Ritchie
Marshal
Posts: 56871
174
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But using a Random object is much less error‑prone and may run slightly faster because you don't need arithmetic to turn two ints into a double and then do more arithmetic to turn it back into an int.
 
John Joe
Ranch Foreman
Posts: 470
3
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:That's only half correct. The expression will give 0 to 4.


Thanks for the correction !
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!