• 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: 4280
106
  • 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 Hand
Posts: 519
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: 4339
270
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: 11706
190
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.
 
Sheriff
Posts: 57838
178
  • 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.
 
Bartender
Posts: 3864
47
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
Sheriff
Posts: 57838
178
  • 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 Hand
Posts: 519
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 !
 
Too many men are afraid of being fools - Henry Ford. Foolish tiny ad:
Thread Boost - a very different sort of advertising
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!