forループ内でこれを試した配列から乱数を生成する必要があります
rnd = arc4random_uniform(arr.count);
それは乱数を生成しましたが、いくつかの数字が繰り返され、math.h でRandom()も試しましたが、それでも同じ問題が解決しません。助けてください..よろしくお願いします..
forループ内でこれを試した配列から乱数を生成する必要があります
rnd = arc4random_uniform(arr.count);
それは乱数を生成しましたが、いくつかの数字が繰り返され、math.h でRandom()も試しましたが、それでも同じ問題が解決しません。助けてください..よろしくお願いします..
もし私が理解したら
「配列から乱数を生成する必要があります」
正しくは、数値を配列からランダムに取得する必要がある場合は、最初に数値を 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];
}
私があなたの問題を理解していれば、乱数は必要ありません。配列内の要素をシャッフルする必要がありますか?
次に、このメソッドを使用する必要があります。
-(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];
}
}
次の方法を試してください
-(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;
}
#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];
編集
Bingo.少し考えた後、私はそれを機能させました
-(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;
}
このrandomizeArray:
メソッドは、ランダム化された配列全体を提供します