• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Random sorting
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Random sorting


  • Subject: Re: Random sorting
  • From: Greg Titus <email@hidden>
  • Date: Sun, 5 Jan 2003 23:22:19 -0800

Using a sorting algorithm just feels like the wrong way to go about this to me, although your method will probably work (given the caveats already mentioned by someone else about only calling srand() once, and using random() instead of rand()). For one thing, a compare method is supposed to meet the test that if A < B and B < C then A < C, which your method obviously does not. While I doubt this would matter with the built in sorting methods on NSArray when you are after a random result, I can imagine sorting algorithms which do depend upon this assumption to hold to even complete.

So even though you should be fine, it "feels wrong". A random permutation like the following should be more efficient anyway:

@implementation NSMutableArray (CodeWrittenInMailSoDontBlameMeIfItDoesntWork)

- (void)randomizeOrder
{
int index = [self count];

while (index--)
[self exchangeObjectAtIndex:index withObjectAtIndex:(random() % (index+1))];
}

@end

It's a lot more compact code, too...

Hope this helps,
- Greg

On Sunday, January 5, 2003, at 08:42 PM, Andrew Merenbach wrote:

I would like to add a random-sorting algorithm for arrays to my
program, and figured that the easiest way would be to add a category to
NSString that would return a random result. Here's my "algorithm":

- (NSComparisonResult)randomCompare:(NSString *)otherString
{
int n;

srand(rand()%time(NULL));
n = rand()%3;

switch(n) {
case 0: return NSOrderedAscending; break;
case 1: return NSOrderedSame; break;
case 2: return NSOrderedDescending; break;
}

return NSOrderedSame;
}

Is this a "bad" (or inefficient) way of randomly sorting an array of
strings?

Take care,
Andrew
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.

References: 
 >Random sorting (From: Andrew Merenbach <email@hidden>)

  • Prev by Date: Re: Ignoring an empty field in the address book (bug?)
  • Next by Date: Re: How to get a NSSavePanel feature in a NSOpenPanel
  • Previous by thread: Re: Random sorting
  • Next by thread: Re: Random sorting
  • Index(es):
    • Date
    • Thread