Random number generation problem
BlitzPlus Forums/BlitzPlus Beginners Area/Random number generation problem
| ||
Hi all , Wondering if anyone will have any ideas to solve a problem im having with a random number generating prog I want to generate a set of numbers randomly and store them in an array for use later on from a specific amount of numbers I have attempted to write a little bit of code ,which i have included below... and it sort of does something along the lines im looking for , but, with results that are puzzling me. Help :) Graphics 640,480,0,2 ;set a Graphics mode. z=1 ;Setup a few Var's. Dim a(50) Dim p(12) z=50 c=1 For n=1 To z ;Populate Array 'A' with 50 numbers. a(n)=n Next For n=z To 39 Step -1 ;Was hoping this would populate the 'P' Array x=Rnd (n) p(c)=a(x) ;with 12 rand numbers from the 'A' Array. c=c+1 a(x)=a(n) Next For f=1 To 12 ;Prints the 12 numbers from 'P' Array to test. Text 100,100+f*10,p(f) Flip Next WaitKey () ;Wait for keypress to end prog. |
| ||
The first thing is that you're using Rnd when you probably want Rand (Rnd returns floating-point results; obviously arrays can only be indexed by whole numbers - it can work, but it will behave oddly). Also, Rnd isn't documented as supporting only one input, so... I would avoid this and always give it both. Secondly, the parameters to the random number functions determine the range in which the result will fall. If you want it to fairly choose a number from array a, you probably don't want to be changing the range each iteration of the loop: instead, use a constant value that covers the whole array. That said, the code works for me: it populates p with numbers. What's unexpected about the behaviour you were getting? |
| ||
Hi, thx for the reply the code does produce a set of 12 numbers as is asked...... But always the same set. using rnd gives ... 8 49 28 34 48 16 31 16 36 35 26 40 using rand gives ... 21 11 34 8 27 47 48 16 20 25 40 41 im still puzzling why . |
| ||
As Yasha said, I'm unsure what behavior is unexpected. I'm assuming the problem is that each time you run the program, you get the same numbers. That is hardly random. That's because Rnd() or Rand() are being seeded with the same number each time. To change the seed to something a little more random place SeedRnd MilliSecs() at the top of your program. That will seed your random number generator with the last digit of your current machine time. That will get you as random as you should ever need. |
| ||
feeble1 is the genius :) thank you |
| ||
No problem. I've just been down the path you're on. Good luck to you and stick with it. |