2010-03-12 207 views
0

我发现这个职位:What's the Best Way to Shuffle an NSMutableArray?新手需要帮助的shuffeling阵列

,当我尝试在我自己的代码部署此,我不能得到它的工作...

谁能帮我解决这个代码?

对我来说,它看起来像洗牌函数不被称为..?

这里是我的代码:

// // 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 
+2

Nooooooo !!!!不要使用'-sort'来实现洗牌。使用Fisher-Yates shuffle,它运行在O(n)而不是O(n log n)中,并可能生成更一致的结果(http://en.wikipedia.org/wiki/Fisher-Yates_shuffle)。 – kennytm

+0

更好的维基百科链接:http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle –

+1

steffen Myklebust:为什么不使用该问题的评分最高的答案? http://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray/56656#56656这并不理想('int'通常是在Cocoa中使用的错误类型),但这比把你的洗牌放在一个不明身份的地方要好。 –

回答

4

您的问题是,你重新声明的puzzles阵列。这是该课堂上的一名ivar,但由于您的viewDidLoad方法中有NSMutableArray * puzzles = ...,因此它将覆盖实例变量。如果您在洗牌方法中使用NSLog(@"%@", puzzles);,则会看到它记录了(null)

简单的修复方法是删除viewDidLoad方法中的NSMutableArray *

编辑

而且(如彼得在评论中提到),不要忘了retain阵列。

+2

简单地删除该类型,从而将声明更改为语句,会导致欠保留问题,因为=右侧的表达式不会分配或保留该数组。 –

+0

@彼得哎呀,谢谢你的发现。 –

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]; 
    } 
}