cog/Playlist/Shuffle.m

42 lines
1007 B
Matlab
Raw Normal View History

2006-01-20 15:34:02 +00:00
//
// Shuffle.m
// Cog
//
// Created by Vincent Spader on 1/14/06.
// 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"
#import "NSArray+ShuffleUtils.h"
2006-01-20 15:34:02 +00:00
@implementation Shuffle
+ (void)initialize
2006-01-20 15:34:02 +00:00
{
static BOOL initialized = NO;
if (!initialized) {
// Call srandom() exactly once.
srandom((unsigned) time(NULL));
initialized = YES;
}
2006-01-20 15:34:02 +00:00
}
+ (NSMutableArray *)shuffleList:(NSArray *)l
{
NSArray* randomLongs = [NSArray arrayWithRandomLongs:[l count]];
// randomLongs is an array of random integers, equal in length to l.
2006-01-20 15:34:02 +00:00
NSArray* pairs = [NSArray zipArray:randomLongs withArray:l];
// randomLongs and l are paired.
2006-01-20 15:34:02 +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.
2006-01-20 15:34:02 +00:00
// Peel the tracks off and return them.
return [[NSArray unzipArray:shuffledPairs] objectAtIndex:1];
2006-01-20 15:34:02 +00:00
}
@end