0

I have an array of names and an array of numbers.

My Person class has a property for both the name and the number. I want to assign the random values to random people.

Suppose I have an array with the strings @"mary" , @"Jack" and @"ABhraham" and another array with the numbers 122, 378, 987, I want to assign them these values randomly. I used the arc4random() method but it sometimes returns the same value again.

Unheilig
  • 16,196
  • 193
  • 68
  • 98
methi1999
  • 25
  • 6
  • @Reformer No, that's not the one the methi1999 is looking for (although the title suggests that he is). He's actually looking for FY-shuffle. – Sergey Kalinichenko Dec 22 '13 at 17:55
  • Are your arrays sized in 10s, 100s, 1000s? Then you can use a more brutish method, like a loop, trying to assign unless it was already assigned. The benefit is you don't have to read up on FY and you can get on with your project. The downside is you miss learning something cool. – danh Dec 22 '13 at 18:08

2 Answers2

2

Use Fisher–Yates shuffle. Create an array that has numbers zero through N-1, inclusive, where N is the number of elements in your arrays; this will be the array of indexes. Then apply Fisher-Yates shuffle to the array of indexes. Now you can use number[index[i]] for each name[i].

Here is a link to an answer that provides a Fisher-Yates Shuffle implementation in Objective-C.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

1: Use dictionaries, set keys for each person.

OR

2: Use mutable arrays for both, removing each object as you assign it.

while(arrayOfNumberTags.count>0){
    float randomIndex = arc4random() % arrayOfNumberTags.count;
    int tagForPerson = [arrayOfNumberTags objectAtIndex:randomIndex];
    //Create the Person object with the tag and any person
    [arrayOfNumberTags removeObjectAtIndex:randomIndex];

}
Oscar Apeland
  • 6,422
  • 7
  • 44
  • 92