我找到了这篇文章: 洗牌Nsmutablearray的最佳方法是什么?

当我尝试通过自己的代码部署它时,我无法使其正常工作...

谁能帮助我解决此代码?

对我来说,看起来不称为洗牌功能。

这是我的代码:

// // shuffle2ViewController.h // shuffle2

#import

@interface shuffle2ViewController : UIViewController {
NSMutableArray *puzzles; 
int *randomSort;
}

- (void)shuffle;
@end

//=============================

// shuffle2ViewController.m

´#import "shuffle2ViewController.h"

@implementation shuffle2ViewController

(void)viewDidLoad { 
[super viewDidLoad];

NSMutableArray *puzzles = [NSMutableArray arrayWithObjects:@"1",@"2",@"3", @"4",@"5",@"6",@"7",@"8",@"9", @"10",@"11",@"12", nil];

// Call the shuffle function
[self shuffle];

// print to log

int i;

NSLog(@"NEW OLD");

NSLog(@"=================");

for (i = 0; i < 12; ++i) NSLog(@" %2i %@", i + 1, [puzzles objectAtIndex:i]); }

int randomSort(id obj1, id obj2, void *context ) {
// returns random number -1 0 1
return (random()%3 - 1); }

(void)shuffle { // call custom sort function

[puzzles sortUsingFunction:randomSort context:nil]; 
}

给出这个结果:

NEW OLD
=================
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 11
12 12
有帮助吗?

解决方案

您的问题是您正在重新保证 puzzles 大批。这是班上的ivar,但是由于您有 NSMutableArray * puzzles = ... 在你的 viewDidLoad 方法,它覆盖了实例变量。如果你要 NSLog(@"%@", puzzles); 在您的洗牌方法中,您会看到它的记录 (null).

简单的修复是删除 NSMutableArray * 在你的 viewDidLoad 方法。

编辑

(正如彼得在评论中提到的那样)不要忘记 retain 数组。

其他提示

这是我使用的:

- (void) shuffle
{
    // Use the Fisher-Yates shuffle method (http://en.wikipedia.org/wiki/Fisher-Yates_shuffle):
    /*
     Random rng = new Random();   // i.e., java.util.Random.
     int n = array.length;        // The number of items left to shuffle (loop invariant).
     while (n > 1) 
     {
     int k = rng.nextInt(n);  // 0 <= k < n.
     n--;                     // n is now the last pertinent index;
     int temp = array[n];     // swap array[n] with array[k] (does nothing if k == n).
     array[n] = array[k];
     array[k] = temp;
     }
     */

    NSUInteger n = [_cards count];
    while(1 < n) {
        NSUInteger k = random() % n;
        n--;
        [_cards exchangeObjectAtIndex:n withObjectAtIndex:k];
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top