|
|
#1 |
|
Random int not so random
I have a switch set up to select random values like this...
Code:
- (IBAction)randomResultGenerator {
int rNumber = rand() % 20;
switch (rNumber) {
case 0:
result.text = @"A.J.";
break;
case 1:
result.text = @"Abacus";
break;
etc...
__________________
MemeFire.com - You can has LOL |
|
|
|
0
|
|
|
#2 |
|
You haven't seeded the random number generator.
__________________
Sponsor me to cycle 100Km round London in the dark |
|
|
|
0
|
|
|
#3 |
|
Why not try the srand() function?
|
|
|
|
0
|
|
|
#4 |
|
Random numbers do not exist in programs. What is offered instead is a pseudo-random algorithm or function rand that generates a vast range of distribution values. This rand function is fully deterministic given the input value. This input value begins with the seeded value (0 by default) and is set by another function called srand. Most programmers attain another level of pseudo-random sequence by seeding the function using the system clock (theoretically never the same value for the lifespan of the application or by then it will never be noticeable.) This seeding is done like srand( time( 0 ) );.
Next is the distribution of this randomness. The quick (both CPU cyclewise and coding) is to modulo the return value of rand by the maximum value (and 0 being the minimum.) However, to get a uniform distribution over the range (the quick approach favors lower numbers), it would require a floating-point math operation of dividing the return value of rand by the MAX_RAND constant (which is platform specific!) So to get a random number from minimum to maximum inclusively: Quick: Code:
srand( time( 0 ) ); // Do once at start-up and never again. int randomInt = minimum + rand() % ( maximum - minimum + 1 ); // Integer between 0 and max Code:
srand( time( 0 ) ); // Do once at start-up and never again. int randomInt = minimum + (int)( ( maximum - minimum + 1) * ( rand() / ( 1.0 + (double)RAND_MAX ) ) ); |
|
|
|
0
|
|
|
#5 |
|
If you want random numbers everytime just use arc4random()
__________________
2.4 MacBook Aluminum 480GB SSD/750GB Optibay 8GB RAM CE | MacBook 2.4 SR 4GB, 320GB HD | PB G4 1.67 | 15 TiBook-DVI 800 iPhone 4S 16GB | iPhone 5 32GB
|
|
|
|
0
|
![]() |
|
«
Previous Thread
|
Next Thread
»
| Thread Tools | Search this Thread |
| Display Modes | |
|
|
Similar Threads
|
||||
| thread | Thread Starter | Forum | Replies | Last Post |
| iPhone 4 ringer not working | Causality | iPhone Tips, Help and Troubleshooting | 3 | Oct 20, 2012 01:07 AM |
| Youtube not working in Safari? | Hyde244 | Mac Applications and Mac App Store | 12 | Nov 16, 2011 11:12 PM |
| A random download from a not so random site? | vevierta | Mac OS X | 1 | Dec 18, 2010 06:39 AM |
| Random play not so random? | Eric S. | iPod | 2 | Dec 22, 2009 03:47 PM |
| Random play not so random | Mark16q | iPod | 0 | Jan 30, 2008 01:52 PM |
All times are GMT -5. The time now is 02:30 AM.







Linear Mode

