3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

乱数使って配列の要素を入れ替え

Posted at

思い立って乱数を使って配列の入れ替えをしてみたー。
4回実行して結果が違うことも確認。
arc4randomじゃなくてrandでも同じような結果になるようですが…。

randam
- (void)viewDidLoad
{
    [self MultidimensionalArray];    //多次元配列
    [self MultidimensionalArrayRandom];    //多次元配列
    [self MultidimensionalArrayRandom];    //多次元配列
}

//配列にデータを入れる
-(void)MultidimensionalArray
{
    ar = [[NSMutableArray alloc] init];
    [ar addObject:@"aaa"];
    [ar addObject:@"bbb"];
    [ar addObject:@"ccc"];
    [ar addObject:@"ddd"];
    [ar addObject:@"eee"];
    NSLog(@"ar %@",ar);
}

//配列に入っているデータをランダムに入れ替える
-(void) MultidimensionalArrayRandom
{
    for (int i = (int)[ar count]-1; i>=0; i--) {
        int j = arc4random() % (i+1);
        [ar exchangeObjectAtIndex:i withObjectAtIndex:j];
    }
    NSLog(@"arRan %@",ar);
}

そして結果は以下の通り!

結果1
ar (
    aaa,
    bbb,
    ccc,
    ddd,
    eee
)
arRan (
    eee,
    ddd,
    ccc,
    aaa,
    bbb
)
arRan (
    eee,
    aaa,
    ccc,
    bbb,
    ddd
)
結果2
ar (
    aaa,
    bbb,
    ccc,
    ddd,
    eee
)
arRan (
    bbb,
    ccc,
    ddd,
    aaa,
    eee
)
arRan (
    bbb,
    ddd,
    aaa,
    eee,
    ccc
)
結果3
ar (
    aaa,
    bbb,
    ccc,
    ddd,
    eee
)
arRan (
    aaa,
    ddd,
    bbb,
    eee,
    ccc
)
arRan (
    aaa,
    ddd,
    eee,
    ccc,
    bbb
)
結果4
ar (
    aaa,
    bbb,
    ccc,
    ddd,
    eee
)
arRan (
    aaa,
    ccc,
    bbb,
    eee,
    ddd
)
arRan (
    ccc,
    ddd,
    bbb,
    aaa,
    eee
)

こういうランダムは要素が5つじゃ分かりづらかったですね。反省。

3
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?