Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 170
  • Last Modified:

random number generation

hello,
How can I write a perl program to generate a random number between 1 and 6 and print it out. The condition is every time the program is executed,the random number should be different.(occasionally same is acceptable).  i have tried function rand() ,but it doesnot do the work.
Thanks
0
tian
Asked:
tian
  • 2
  • 2
  • 2
  • +2
1 Solution
 
mlevCommented:
What was wrong with rand()?
The following works for me:

$x = 1 + int(rand(6));
print  "$x\n"
0
 
tianAuthor Commented:
every time you execute it, it will produce the same output.
0
 
martinagCommented:
What if you type
srand;
at the beginning of your script?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
ozoCommented:
If you upgrade to 5.004, the srand; at the beginning would be done for you automatically.
Before 5.004, srand; would still give you the same number if you execute the program twice in the same second.
srand($$+time); should alleviate that problem.
(although a truly random number would still give you the same number about one out of six times)
0
 
tianAuthor Commented:
Thanks all of you. But I think ozo's "srand($$+time); " is perfect solution.You want to submit it?  
0
 
b2piCommented:
you could also get a module (ReallyRandom, I think) from cpan, and use that for the seed)

0
 
b2piCommented:
Oh, I forgot.  If you need truly, heavy-duty random, you can always use http://lavarand.sgi.com

Way cool, man
0
 
ozoCommented:
5.004 seems a more perfect solution.
martinag's solution may be adequate if you don't run it too often.
srand($$+time); should suffice otherwise.
http://lavarand.sgi.com is indeed cool, but even slower than Math::TrulyRandom :-)
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 2
  • 2
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now