2006-01-20 15:34:02 +00:00
|
|
|
//
|
|
|
|
// Shuffle.m
|
|
|
|
// Cog
|
|
|
|
//
|
2006-09-04 18:46:18 +00:00
|
|
|
// Created by Vincent Spader on 1/14/06.
|
2008-02-16 02:46:19 +00:00
|
|
|
// Revised by Eric Hanneken on 2/14/08.
|
|
|
|
// Copyright 2008 Vincent Spader. All rights reserved.
|
2006-01-20 15:34:02 +00:00
|
|
|
//
|
|
|
|
|
|
|
|
#import "Shuffle.h"
|
2008-02-16 02:46:19 +00:00
|
|
|
#import "NSArray+ShuffleUtils.h"
|
2006-01-20 15:34:02 +00:00
|
|
|
|
|
|
|
@implementation Shuffle
|
|
|
|
|
2022-02-07 05:49:27 +00:00
|
|
|
+ (void)initialize {
|
2008-02-16 02:46:19 +00:00
|
|
|
static BOOL initialized = NO;
|
2022-02-07 05:49:27 +00:00
|
|
|
if(!initialized) {
|
2008-02-16 02:46:19 +00:00
|
|
|
// Call srandom() exactly once.
|
2022-02-07 05:49:27 +00:00
|
|
|
srandom((unsigned)time(NULL));
|
2008-02-16 02:46:19 +00:00
|
|
|
initialized = YES;
|
|
|
|
}
|
2006-01-20 15:34:02 +00:00
|
|
|
}
|
|
|
|
|
2022-02-07 05:49:27 +00:00
|
|
|
+ (NSMutableArray*)shuffleList:(NSArray*)l {
|
2008-02-16 02:46:19 +00:00
|
|
|
NSArray* randomLongs = [NSArray arrayWithRandomLongs:[l count]];
|
|
|
|
// randomLongs is an array of random integers, equal in length to l.
|
2022-02-07 05:49:27 +00:00
|
|
|
|
2008-02-16 02:46:19 +00:00
|
|
|
NSArray* pairs = [NSArray zipArray:randomLongs withArray:l];
|
|
|
|
// randomLongs and l are paired.
|
2022-02-07 05:49:27 +00:00
|
|
|
|
2008-02-16 02:46:19 +00:00
|
|
|
NSArray* shuffledPairs = [pairs sortedArrayUsingSelector:@selector(compareFirsts:)];
|
|
|
|
// The numbers from randomLongs are sorted in ascending order; the tracks from l
|
|
|
|
// are in random order.
|
2022-02-07 05:49:27 +00:00
|
|
|
|
2008-02-16 02:46:19 +00:00
|
|
|
// Peel the tracks off and return them.
|
|
|
|
return [[NSArray unzipArray:shuffledPairs] objectAtIndex:1];
|
2006-01-20 15:34:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@end
|