[REP++] Generating some numbers
#1

I need some help in generating some random numbers.

For example i have a var which defines the number of generations. For example 5, if it's 5 then i need 5 generated random numbers from 1-10 but distinct numbers.

Any ideas?

Thanks.
Reply
#2

Use random function and a loop
Reply
#3

Quote:
Originally Posted by Eoussama
Посмотреть сообщение
Use random function and a loop
And how about making them distinct?
Reply
#4

Check if the number is already attributed?
Reply
#5

Quote:
Originally Posted by buburuzu19
Посмотреть сообщение
And how about making them distinct?
add each generated values to an array. On each generation check the value present in array or not.If it present do generation process again (loop).
Reply
#6

I'm pretty sure it's optimizable :
PHP код:
DistinctNumber(number)
{
    new
        
string[50],
        
count,
        
bool:sameNB false;
    do
    {
        
string[count] = random(number);
        for(new 
inumberi++)
        {
            if(
count == i)
                continue;
            if(
string[count] == string[i])
                
sameNB true;
        }
        if(!
sameNB)
            
count++;
        
sameNB false;
    }
    while(
count != number);
    return 
string;

Also, change 50 by the max number you will generate in your script
Reply
#7

Quote:
Originally Posted by Dayrion
Посмотреть сообщение
I'm pretty sure it's optimizable :
PHP код:
DistinctNumber(number)
{
    new
        
string[50],
        
count,
        
bool:sameNB false;
    do
    {
        
string[count] = random(number);
        for(new 
inumberi++)
        {
            if(
count == i)
                continue;
            if(
string[count] == string[i])
                
sameNB true;
        }
        if(!
sameNB)
            
count++;
        
sameNB false;
    }
    while(
count != number);
    return 
string;

Also, change 50 by the max number you will generate in your script
break from the loop if the match is found as further iteration is not required.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)