【问题标题】:Novice needing help on shuffeling an array新手在洗牌方面需要帮助
【发布时间】:2010-03-12 17:38:55
【问题描述】:

我发现了这个帖子:What's the Best Way to Shuffle an 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

【问题讨论】:

  • 不!!!!不要使用-sort 来实现洗牌。使用 Fisher-Yates shuffle,它在 O(n) 而不是 O(n log n) 中运行,并且可能产生更统一的结果 (en.wikipedia.org/wiki/Fisher–Yates_shuffle)。
  • steffen Myklebust:为什么不使用该问题中评价最高的答案? stackoverflow.com/questions/56648/… 这并不理想(int 通常是在 Cocoa 中使用的错误类型),但它比基于未识别排序的随机播放要好。
  • 感谢大家的意见。这是我最终得到我想要的结果的结果。 -(void)shuffle { NSUInteger n = [拼图数]; while(1

标签: iphone objective-c cocoa cocoa-touch shuffle


【解决方案1】:

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

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

编辑

另外(正如 Peter 在 cmets 中提到的)不要忘记 retain 数组。

【讨论】:

  • 简单地删除类型,从而将声明更改为语句,会导致保留不足的问题,因为 = 右侧的表达式不会分配或保留数组。跨度>
【解决方案2】:

这是我使用的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    相关资源
    最近更新 更多