0

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

当我尝试在我自己的代码中部署它时,我无法让它工作......

谁能帮我解决这个代码?

对我来说,似乎没有调用 shuffle 函数..?

这是我的代码:

// // 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
4

2 回答 2

4

您的问题是您正在重新声明puzzles数组。它是类上的一个 ivar,但由于您的方法中有NSMutableArray * puzzles = ...viewDidLoad它会覆盖实例变量。如果您要NSLog(@"%@", puzzles);使用 shuffle 方法,您会看到它记录了(null).

简单的解决方法是删除方法NSMutableArray *中的viewDidLoad

编辑

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

于 2010-03-12T17:50:13.027 回答
0

这是我使用的:

- (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];
    }
}
于 2010-03-13T10:42:07.937 回答