2

配列内の数値をランダム化しようとしています。私はそれを使用してそれを行うことができますarc4random() % [indexes count]

私の問題は-配列が20個のアイテムで構成されている場合、配列がシャッフルされるたびに、5つのバッチで異なる数が表示されるはずです。例 :

最初のシャッフル:1、4、2、5、6。

2番目のシャッフル:7、12、9、15、3

-(IBAction)randomNumbers:(UIButton *)sender
{
    int length = 10; // int length = [yourArray count];

    NSMutableArray *indexes = [[NSMutableArray alloc] initWithCapacity:length];
    for (int i=0; i<5; i++)
        [indexes addObject:[NSNumber numberWithInt:i]];

    NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:length];

    while ([indexes count])
    {
        int index = arc4random() % [indexes count];
        [shuffle addObject:[indexes objectAtIndex:index]];
        [indexes removeObjectAtIndex:index];
    }

    //    for (int i=0; i<[shuffle count]; i++)
    NSLog(@"%@", [shuffle description]);
}
4

4 に答える 4

2

要件に応じて....このコードを確認してください

これをプロパティにする

@synthesize alreadyGeneratedNumbers;

これらのメソッドを.mに追加します

-(int)generateRandomNumber{

    int TOTAL_NUMBER=20;

    int low_bound = 0;
    int high_bound = TOTAL_NUMBER;
    int width = high_bound - low_bound;
    int randomNumber = low_bound + arc4random() % width;

    return randomNumber;
}


-(IBAction)randomNumbers:(UIButton *)sender
{

    NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:5];

    BOOL contains=YES;
    while ([shuffle count]<5) {
        NSNumber *generatedNumber=[NSNumber numberWithInt:[self generateRandomNumber]];
        //NSLog(@"->%@",generatedNumber);

        if (![alreadyGeneratedNumbers containsObject:generatedNumber]) {
            [shuffle addObject:generatedNumber];
            contains=NO;
            [alreadyGeneratedNumbers addObject:generatedNumber];
        }
    }

    NSLog(@"shuffle %@",shuffle);
    NSLog(@"Next Batch");


    if ([alreadyGeneratedNumbers count] >= TOTAL_NUMBER) {
        NSLog(@"\nGame over, Want to play once again?");//or similar kind of thing.
        [alreadyGeneratedNumbers removeAllObjects];
    }


}

それでも私はあなたが次のようないくつかの変更が必要だと感じています

正しい値が得られますが、ユーザーが5回押した場合はどうなりますか?

すでに5つの数字の4つのセットを選んだ20の数字から、6回目には次の数字のセットを検索するためにループになり、無限になります。

したがって、できることは、シャッフルを追跡し、制限に達したら、つまり20/5=4でランダムボタンを無効にすることです。

于 2012-11-30T06:41:14.683 に答える
1

拡張子またはヘッダーファイルにすでに生成された番号を含む配列を宣言します

@property (strong, nonatomic)NSMutableArray *existingNums;
@property (assign, nonatomic)NSInteger maxLimit;
@property (assign, nonatomic)NSInteger minLimit;

次に、実装ファイルに指定されたコードを実装します

@synthesize existingNums;
@synthesize maxLimit;
@synthesize minLimit;

- (NSInteger)randomNumber {

    if(!existingNums)
        existingNums = [NSMutableArray array];

    while (YES) {

        NSNumber *randonNum = [NSNumber numberWithInteger:minLimit+arc4random()%maxLimit];

        if([existingNums containsObject:randonNum]) {

            if([existingNums count] == (maxLimit - minLimit))
                return -1; // All possible numbers generated in the given range

            continue;
        }

        [existingNums addObject:randonNum];

        return [randonNum integerValue];
    }

    return -1;   // return error
}

これがお役に立てば幸いです:)

于 2013-04-28T20:14:21.567 に答える
1

これは私のために働きます:

    NSMutableArray *numbers = [NSMutableArray new];
    BOOL addElement = YES;
    int limit = 100; // Range from 0 to 36
    int numElem = 10; // Number of elements
    do
    {
        int ranNum = (arc4random() % limit) +1;
        if ([numbers count] < numElem) {
            for (NSNumber *oneNumber in numbers) {
                addElement =([oneNumber intValue] != ranNum) ? YES:NO;
                if (!addElement) break;
            }
            if (addElement) [numbers addObject:[NSNumber numberWithInt:ranNum]];
        } else {
            break;
        }
    } while (1);
    NSLog(@"%@",numbers);
于 2013-12-30T13:37:58.610 に答える
0

これらすべての回答の問題は、以前に生成された乱数を確認する必要があり、多数の乱数が必要な場合は余分な時間がかかることです。

別の解決策は、暗号化を使用することです。

  1. ランダムキーを生成する
  2. 0..nの間で繰り返します
  3. 各整数を暗号化し、関数の出力に使用する選択肢の数を法として適用します。

あなたのケースには関係ない、考慮すべきいくつかの追加の詳細があります。

于 2013-12-30T13:54:45.840 に答える