Skip to content

Instantly share code, notes, and snippets.

@mysteriouspants
Created August 5, 2011 14:08
Show Gist options
  • Save mysteriouspants/1127603 to your computer and use it in GitHub Desktop.
Save mysteriouspants/1127603 to your computer and use it in GitHub Desktop.
Magic 8 Ball
// clang -o magic8ball -framework Foundation magic8ball.m
#import <Foundation/Foundation.h>
#include <stdio.h>
NSUInteger randomUnder(NSUInteger topPlusOne);
int main()
{
srandomdev(); // rather important
NSAutoreleasePool * pool0 = [[NSAutoreleasePool alloc] init];
NSArray * answers = [NSArray arrayWithObjects:
@"It is certain",
@"It is decidedly so",
@"Without a doubt",
@"Yes - definitely",
@"You may rely on it",
@"As I see it, yes",
@"Most likely",
@"Outlook good",
@"Signs point to yes",
@"Yes",
@"Reply hazy, try again",
@"Ask again later",
@"Better not tell you now",
@"Cannot predict now",
@"Concentrate and ask again",
@"Don't count on it",
@"My reply is no",
@"My sources say no",
@"Outlook not so good",
@"Very doubtful",
nil];
NSUInteger items = [answers count];
NSUInteger item = randomUnder(items);
printf("%s\n", [[answers objectAtIndex:item] UTF8String]);
[pool0 release];
return 0;
}
/* see http://www.mikeash.com/pyblog/friday-qa-2011-03-18-random-numbers.html */
NSUInteger randomUnder(NSUInteger topPlusOne)
{
unsigned two31 = 1U << 31;
unsigned maxUsable = (two31 / topPlusOne) * topPlusOne;
while(1)
{
unsigned num = random();
if(num < maxUsable)
return num % topPlusOne;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment