Lottery Entry bug


#1

Hello All,
I’m a newcomer to programming and Objective C.
This book has been a great resource to get me started.
I wrote the lottery Entry program with slight variations to match the british national lottery.
The difference being that i use six numbers between 1 and 49.
I came across a slight problem when running it.
Sometimes the lottery numbers can be the same within the week.
I decided to try this code to re-randomize any matching numbers:

[code]-(void)checkForRepeatNumbers
{
if ((firstNumber == secondNumber) || (firstNumber == thirdNumber) ||
(firstNumber == fourthNumber) || (firstNumber == fifthNumber) ||
(firstNumber == sixthNumber))
{
firstNumber = ((int)random()%49)+1;
}

if ((secondNumber == firstNumber) || (secondNumber == thirdNumber) || 
    (secondNumber == fourthNumber)|| (secondNumber == fifthNumber) || 
    (secondNumber == sixthNumber))  
{
    secondNumber = ((int)random()%49)+1;
}

if ((thirdNumber == firstNumber) || (thirdNumber == secondNumber) ||
(thirdNumber == fourthNumber) || (thirdNumber == fifthNumber) ||
(thirdNumber == sixthNumber))
{
thirdNumber = ((int)random()%49)+1;
}

if ((fourthNumber == firstNumber) || (fourthNumber == secondNumber) || 
    (fourthNumber == thirdNumber) || (fourthNumber == fifthNumber) || 
    (fourthNumber == sixthNumber)) 
{
    fourthNumber = ((int)random()%49)+1;
}

if ((fifthNumber == firstNumber) || (fifthNumber == secondNumber) ||
(fifthNumber == thirdNumber) || (fifthNumber == fourthNumber) ||
(fifthNumber == sixthNumber))
{
fifthNumber = ((int)random()%49)+1;
}

if ((sixthNumber == firstNumber) || (sixthNumber == secondNumber) || 
    (sixthNumber == thirdNumber) || (sixthNumber == fourthNumber) || 
    (sixthNumber == fifthNumber)) 
{
    sixthNumber = ((int)random()%49)+1;
}

}[/code]

it seems to do the trick but I was wondering if there is a more elegant solution?
Thanks,
Pete


#2

Hi Pete,

I’m glad to hear the book has been helpful to you. There are a few ways to do such checking in a more graceful manner, and they all revolve around using some form of a collection. The most helpful collection in this case would be a set, since sets can only hold one of each unique value. The only caveat is that sets are unordered, so you would have to do more work if the order in which the numbers were drawn was important.

NSMutableSet *numbers = [NSMutableSet set];
while ([numbers count] < 6)
{
    int n = (random() % 49) + 1;
    [numbers addObject:[NSNumber numberWithInt:n]];
}
int index = 0;
for (NSNumber *number in numbers)
{
    NSLog(@"Number %d is: %d", index, [number intValue]);
    index++;
}

You could also do the same using an NSMutableArray and -containsObject: to test whether each NSNumber value was unique.

Adam


#3

Hi Adam,
using a set certainly does look more graceful with only 8 lines of code compared to my 25. :smiley:
It seems I still have much to learn.
thanks for the reply.
Pete.