初心者は、アレイのシャッフェルの助けが必要です
-
19-09-2019 - |
質問
この投稿を見つけました: 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];
}
}
所属していません StackOverflow