Raised This Month: $ Target: $400
 0% 

Random numbers without repeating


  
 
 
Thread Tools Display Modes
Prev Previous Post   Next Post Next
Bugsy
AMX Mod X Moderator
Join Date: Feb 2005
Location: NJ, USA
Old 05-08-2016 , 13:55   Re: Random numbers without repeating
Reply With Quote #7

I know this is already answered but I was bored and put this together.

You must first call PrepRandom() for any min/max combo prior to calling GetRandom() for that min/max combo. Once you call PrepRandom(), you can repeatedly call GetRandom() and you will always get a unique random until all numbers have been used. Once all are used, you will then begin getting the numbers again, and they will be unique until you again use up all the numbers.

Like this. But you cannot cannot call GetRandom on a particular min/max until you first call PrepRandom for that min/max set.
PHP Code:
PrepRandom10 );
GetRandom10 );
GetRandom10 );
GetRandom10 );
GetRandom10 );

PrepRandom500 );
GetRandom500 );
GetRandom500 );
GetRandom500 );
GetRandom500 ); 
PHP Code:

#include <amxmodx>

new const Version[] = "0.1";

//Set this to the absolute max random number that you will attempt to generate.
const MaxRandom 20;

new 
AllNumbers[ ( MaxRandom >> ) + ];

public 
plugin_init()
{
    
register_plugin"Random Number No Dupes" Version "bugsy" );
    
    
PrepRandom20 );
    
    for ( new 
<= 100 i++ )
        
server_print"[%d] Random=%d" GetRandom20 ) );
}

PrepRandomiRanMin iRanMax )
{
    for ( new 
iRanMin <= iRanMax i++ )
        
AllNumbers>> ] |= ( << );
}

public 
GetRandomiRanMin iRanMax )
{    
    static 
UsedNumbers[ ( MaxRandom >> ) + ];
    new 
iRandom bool:bAllUsed=true;
    
    if ( 
iRanMax MaxRandom )
        
set_fail_state"Must increase MaxRandom value: %d > %d" iRanMax MaxRandom );
    
    
//Check if all numbers have already bee nused, if so this will reset the 'used' variable.
    
for ( new sizeofUsedNumbers ) ; i++ )
    {
        if ( 
AllNumbers] && ( AllNumbers] != UsedNumbers] ) )
        {
            
bAllUsed false;
            break;
        }
    }

    
//If all random numbers have already been used, reset variable so they can be re-used.
    
if ( bAllUsed )
        
arraysetUsedNumbers sizeofUsedNumbers ) );
    
    
//Find random number
    
do
    {
        
iRandom random_numiRanMin iRanMax );
    }
    while ( ( 
UsedNumbersiRandom >> ] & ( << iRandom ) ) )  
    
    
//Set current random number as used
    
UsedNumbersiRandom >> ] |= ( << iRandom );
    
    
//Return random number
    
return iRandom;

__________________

Last edited by Bugsy; 05-08-2016 at 14:08.
Bugsy is offline
 



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 18:43.


Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Theme made by Freecode