-1

I need to generate random numbers from an array i have tried this inside the for loop

rnd = arc4random_uniform(arr.count); 

it generated random numbers but some numbers get repeated also tried Random() in math.h still the same problem persists please help me out.. Thanks in advance..

Agent Chocks.
  • 1,312
  • 8
  • 19
  • Have you tried `int r = arc4random() % 5;` like if you want `0` to `4` ? – Buntylm Jun 05 '13 at 06:06
  • Ofcourse there will be repetitions, because they are generated `randomly`. If there was a pattern followed for generation then it wouldn't be called random right? – Praveen S Jun 05 '13 at 06:10
  • Do you mean you need to feel an array by the unique numbers in random order? Some more code could help to get your idea – voromax Jun 05 '13 at 06:12
  • @PraveenS how could i get unique random numbers.. – Agent Chocks. Jun 05 '13 at 06:14
  • Also [same random number should not generate again and again?](http://stackoverflow.com/q/6302620/77567) – rob mayoff Jun 05 '13 at 06:28
  • There's no guarantee whatsoever that ar4random_uniform() won't repeat. Think about it for a second -- you're asking it to produce a number between 0 and 103. If you do that one hundred and five times, it has no choice but to repeat one of its earlier selections. How could the function know how many times you're going to request a number? [1](http://stackoverflow.com/questions/10233517/non-repeating-arc4random-uniform) – Parag Bafna Jun 05 '13 at 06:30

7 Answers7

2

if i understood

"I need to generate random numbers from an array"

correctly, you want the numbers to be taken from an array randomly, if so then first store the numbers in an NSMutableArray

NSMutableArray *arr=//store your numbers in this array.

-(void)getRandomNumberFromArray:(NSMutableArray *)arr{
int r = arc4random() % arr.count;
int number=[arr objectAtIndex:r];
[arr removeObjectAtIndex:r];
}
Bonnie
  • 4,943
  • 30
  • 34
1

Generate a random number for each element, and then check to make sure it's not the same as one of the existing ones. If it already exists, try again.

for(int i = 0; i < arr.count;i++)
{
   BOOL isRandom = YES;
   int rand = -1;
   while(!isRandom )
   (
     isRandom = YES;
     rand = arc4random() % 5;
     for(int j = 0; j < i; j++)
     {
        int existingNumber = arr[j];
        if(existingNumber == rand)
        {
           isRandom = NO;
           break;
        }
     }
  }
  arr[i] = rand;
}

Another option is to first just assign them to have incrementing values, and then shuffle the mutable array. What's the Best Way to Shuffle an NSMutableArray?

Community
  • 1
  • 1
Liron
  • 2,012
  • 19
  • 39
1

If I understood your problem , then you dont need random numbers , you need to shuffle the elements in the Array ?

Then you need to use this method ,

-(void)shuffleWithArray:(NSArray*)cardsArray
{

    NSMutableArray *shuffleArray =[[NSMutableArray alloc]initWithArray:cardsArray];


   // NSUInteger count1=[shuffleArray count];
   for (NSUInteger i= 0; i<[shuffleArray count]; i++) 
    {

    int nElement=[shuffleArray count] -i;
    int n=(arc4random()%nElement + i);
    [shuffleArray exchangeObjectAtIndex:i withObjectAtIndex:n];

  }

}
Dushyant Singh
  • 721
  • 4
  • 13
0

Check the below Tutorial. it must help for you.

iOS Random Number generator

0
#include <stdlib.h>


int r = 0;
if (arc4random_uniform != NULL)
    r = arc4random_uniform (arr.count);
else
    r = (arc4random() % arr.count);

int randomNumberFromArray=[arr objectAtIndex:r];

EDIT

Bingo.After some thinking i made it working

-(NSArray *)randomizeArray:(NSArray *)inputArray
{
    NSMutableArray *checkArray=[[NSMutableArray alloc]initWithCapacity:3];
    NSMutableArray *outputArray=[[NSMutableArray alloc]initWithCapacity:3];

    while ([outputArray count]<[inputArray count])
    {
        int r=[self getRandomNumber:[inputArray count]];
        if ([checkArray containsObject:[NSNumber numberWithInt:r]])
        {


        }
        else
        {
            [checkArray addObject:[NSNumber numberWithInt:r]];
            [outputArray addObject:[inputArray objectAtIndex:r]];
        }
    }
    return outputArray;
}


-(int)getRandomNumber:(int)maxValue
{
    int r = 0;
    if (arc4random_uniform != NULL)
        r = arc4random_uniform (maxValue);
    else
        r = (arc4random() % maxValue);
    return r;
}

This randomizeArray: method will give you the whole array randomized

Lithu T.V
  • 19,955
  • 12
  • 56
  • 101
0

You can make use of the following function.

@property (nonatomic,strong) NSMutableArray * numbers;


- (NSInteger) nonRepeatedNumber
{

   if(_numbers == nil)
    {
       _numbers = [[NSMutableArray alloc]init];
    } 

   NSInteger number = arc4random()% arr.count;
   while ([_numbers containsObject:[NSNumber numberWithInt:number]])
   {
       number = arc4random()% arr.count;;
   }
  [_numbers addObject:[NSNumber numberWithInt:number]];

   return number;
}
Vinayak Kini
  • 2,919
  • 21
  • 35
0

Try the following method

 -(NSMutableArray*)randomNumbersfromArray:(NSArray*)array    {
        NSArray *numbers = array;
        int count = [numbers count];
        NSMutableArray *addedIndexes = [[NSMutableArray alloc]initWithCapacity:count];
        NSMutableArray *addedObjects = [[NSMutableArray alloc]initWithCapacity:count];
        int i = 0;
        while ([addedIndexes count] != [numbers count]) {

            int random = arc4random() % count ;
            if (![addedIndexes containsObject:[NSString stringWithFormat:@"%i",random]]) {

                [addedIndexes addObject:[NSString stringWithFormat:@"%i",random]];
                [addedObjects addObject:[numbers objectAtIndex:random]];
                i++;
            }

        }
        return addedObjects;
    }
Agent Chocks.
  • 1,312
  • 8
  • 19
manujmv
  • 6,450
  • 1
  • 22
  • 35