This question already has answers here:
combinations of a set with given number elements
(2 answers)
Closed 9 years ago.
I have 9 tiles labeled 1-9 with corresponding values. Tile 1=1, tile 6=6, etc. A user can press down tiles that equal the sum of the die. When they press confirm move, those tales can not be used anymore.
I need to compute every possible combination of numbers to check whether or not the user can go again. Currently I am computing it like this, but I'm sure there has to be a better way.
allTiles contains the tiles that are still available to be computed.
What would be the best way to check for all combinations?
- (void) getCombinations {
NSMutableArray *combinations = [[NSMutableArray alloc] init];
for (int i = 0; i < [allTiles count]; i++) {
for (int j = i + 1; j < [allTiles count]; j++) {
for (int k = i+2; k < [allTiles count]; k++) {
TileView *first = [allTiles objectAtIndex:i];
TileView *second = [allTiles objectAtIndex:j];
TileView *third = [allTiles objectAtIndex:k];
NSNumber *total = [NSNumber numberWithInt:first.getTileValue + second.getTileValue];
NSNumber *total2 = [NSNumber numberWithInt:
first.getTileValue +
second.getTileValue +
third.getTileValue];
[combinations addObject:[NSNumber numberWithInt:first.getTileValue]];
[combinations addObject:[NSNumber numberWithInt:second.getTileValue]];
[combinations addObject:[NSNumber numberWithInt:third.getTileValue]];
[combinations addObject:total];
[combinations addObject:total2];
}
}
}
if ([combinations containsObject:[NSNumber numberWithInt:[self diceTotal]]]) {
NSLog(#"STILL COMBINATION AVAILABLE");
}
else {
NSString *message = [NSString stringWithFormat:#"Your score: %i", player1Score];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"No more combinations left."
message: message
delegate:self
cancelButtonTitle:#"Go to player2"
otherButtonTitles: nil];
[alert show];
[alert release];
}
}
Here is a a screenshot of one of scenarios where my method doesn't work.
In your example, there are four tiles available to the player. Whether or not to include a tile is a binary choice (YES or NO), and there are 4 such choices in this example, so there are 2×2×2×2 = 24 possible combinations of tiles. In general, there are 2n combinations where there are n tiles available.
The simplest way to check for a combination that sums to your target is simply to enumerate the integers from 0 through 2n. For each integer i, write i in binary and add up the tile values of the tiles corresponding to the 1's of the binary representation.
We'll cache the tile values in a local array to avoid sending the tileValue message over and over.
static int selectedNumbersSum(unsigned int selector, int const *numbers) {
int sum = 0;
for (int i = 0; selector != 0; i += 1, selector >>= 1) {
if (selector & 1) {
sum += numbers[i];
}
}
return sum;
}
static BOOL tilesCanMakeTarget(NSArray *tiles, int target) {
NSUInteger count = tiles.count;
int numbers[count];
for (int i = 0; i < count; ++i) {
numbers[i] = [tiles[i] tileValue];
}
for (unsigned int step = 0, maxStep = 1 << count; step < maxStep; ++step) {
if (selectedNumbersSum(step, numbers) == target)
return YES;
}
return NO;
}
- (void)checkForEndOfPlayer1Turn {
if (tilesCanMakeTarget(allTiles, self.diceTotal)) {
NSLog(#"STILL COMBINATION AVAILABLE");
} else {
NSString *message = [NSString stringWithFormat:#"Your score: %i",
player1Score];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"No more combinations left."
message:message delegate:self cancelButtonTitle:#"Go to player 2"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
Incidentally, we don't usually start our getter method names with get. Your getCombinations method should probably be called checkCombinations (or something like that) since it's not even a getter. And your getTileValue method should just be called tileValue.
Related
I am writing a recursive Sudoku solver and I am having some issues with 2D array handling. I included the function which is giving the trouble. There are some unnecessary lines I was using for debugging in there.
- (Stack *)successors
{
Stack *stack = [[Stack alloc] init];
NSMutableArray *temp = [[NSMutableArray alloc] init];
NSMutableArray *test = [[NSMutableArray alloc] init];
temp = [self.board copy];
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
if ([self.board[x][y] isEqualToString:#""] ||
[self.board[x][y] isEqualToString:#"."]) {
NSLog(#"%d %d", x, y);
for (int i = 1; i < 10; i++) {
NSLog(#"%d", i);
[temp[x] setObject:[NSString stringWithFormat:#"%d", i] atIndex:y];
State *tempState = [[State alloc] initWithBoard:temp];
if ([tempState legal]) {
NSMutableArray *input = [NSMutableArray arrayWithArray:temp];
[stack push:input];
[stack push:input];
[test addObject:input];
}
}
NSLog(#"test %#", test);
int p = [stack size];
for (int i = 0; i < p; i++) {
NSLog(#"%#", [stack pop]);
}
return stack;
}
}
}
return stack;
}
essentially, it begins at the top of the array and if the space is empty, it tries putting in the number 1 through 9 and if it is legal, based on another function I wrote previously, it will input it in the temp array and add it to the stack. I checked this and it works great. However, after adding them all together, I NSLog to check the stack and find that all of the stacked arrays now begin with the number 9, the last number checked in the temp array. I believe I am having some issue with keeping reference to the temp array, but I cannot figure it out. Any help is great.
I've stored 4 unique numbers inside an NSMutableArray from 1-4. i've done that by using this code:
storeArray = [[NSMutableArray alloc] init];
BOOL record = NO;
int x;
for (int i=1; [storeArray count] < 4; i++) //Loop for generate different random values
{
x = arc4random() % 4;//generating random number
if(i==1)//for first time
{
[storeArray addObject:[NSNumber numberWithInt:x]];
}
else
{
for (int j=0; j<= [storeArray count]-1; j++)
{
if (x ==[[storeArray objectAtIndex:j] intValue])
record = YES;
}
if (record == YES)
{
record = NO;
}
else
{
[storeArray addObject:[NSNumber numberWithInt:x]];
}
}
}
I can then print the numbers out using storeArray[1] and so on.
the problem is i want to print the numbers inside this.
[option1 setTitle:questions[r][storeArray[0]] forState: UIControlStateNormal];
[option2 setTitle:questions[r][storeArray[1]] forState: UIControlStateNormal];
[option3 setTitle:questions[r][storeArray[2]] forState: UIControlStateNormal];
[option4 setTitle:questions[r][storeArray[3]] forState: UIControlStateNormal];
How can i do this?, cause i when i do this i get thread sigbrt error?
The problem is that your algorithm is faulty and when there are collisions because you are trying to keep the numbers unique, you don't record anything so your array might not always be the expected length. Actually there is a 91% chance of this happening in your case so it looks like it happens all the time.
Instead of trying to write your own algorithm, just use the existing classes. Simply use an NSSet to guarantee the uniqueness of the numbers in your array.
NSMutableSet *set = [[NSMutableSet alloc] init];
while(set.count < 4) {
int x = arc4random() % 4;
[set addObject:[NSNumber numberWithInteger:x]];
}
NSArray * storeArray = [set allObjects];
I am trying to make an add method that works like long addition, so I want to start the addition from the end and work my way backwards so I can get the carrys right and etc. So I am currently trying to start working backwards over the array.
For example what im trying to do.
two arrays with the character 123456789
and i want to add them starting at 9 + 9 then move to 8+8
So I'm pretty sure I'm using the right way to iterate backwards over an array, but everytime I try I get just the runtime error, index out of bounds, and I can't figure out why. Any help would be great, I just cant figure out why it keeps throwing the exception.
-(MPInteger *) add: (MPInteger *) x
{
NSMutableArray *a = self->intString;
NSMutableArray *b = x->intString;
NSMutableArray *c = [NSMutableArray arrayWithCapacity:100];
//for (int i = 0; i < [a count]; i++) {
for (NSInteger i = [a count] - 1; i > 0; i--) {
int num = 10;
NSNumber *ourNum = [NSNumber numberWithInt:num];
NSNumber *total = [NSNumber numberWithInt:[[a objectAtIndex:i] intValue] + [[b objectAtIndex:i] intValue]];
if ([total intValue] >= [ourNum intValue]) {
total = [NSNumber numberWithInt:([total intValue] - [ourNum intValue])];
[c addObject:[NSNumber numberWithInt:([total intValue])]];
} else {
[c addObject:[NSNumber numberWithInt:[[a objectAtIndex:i] intValue]+[[b objectAtIndex:i] intValue]]];
}
NSLog(#"%#", c[i]);
}
return x;
}
First, let's clean up this code.
- (MPInteger *)add:(MPInteger *)x {
NSMutableArray *a = self->intString;
NSMutableArray *b = x->intString;
NSMutableArray *c = [NSMutableArray arrayWithCapacity:100];
for (NSInteger i = [a count] - 1; i > 0; i--) {
int num = 10;
NSNumber *ourNum = #(num);
NSNumber *total = #([a[i] intValue] + [b[i] intValue]);
if ([total intValue] >= [ourNum intValue]) {
total = #([total intValue] - [ourNum intValue]);
[c addObject:#([total intValue])];
} else {
[c addObject:#([a[i] intValue] + [b[i] intValue])];
}
NSLog(#"%#", c[i]);
}
return x;
}
Next, let's remove redundant/duplicate code.
- (MPInteger *)add:(MPInteger *)x {
NSMutableArray *a = self->intString;
NSMutableArray *b = x->intString;
NSMutableArray *c = [NSMutableArray arrayWithCapacity:100];
for (NSInteger i = [a count] - 1; i > 0; i--) {
int num = 10;
NSNumber *total = #([a[i] intValue] + [b[i] intValue]);
if ([total intValue] >= num) {
total = #([total intValue] - num);
}
[c addObject:total];
NSLog(#"%#", c[i]);
}
return x;
}
Now we can clearly see all of the issues.
You're going from [a count] - 1 to 1. You should be going all the way to 0.
a and b might have different sizes, so if you only do [a count] - 1 to 0, then if for example [b count] < [a count], you'll get an index out of bounds error when you try to access b[i].
You're adding stuff to the end of c, but you should be adding it to the beginning of c since you're iterating backwards.
You don't store the carry anywhere.
You are accessing c[i], which doesn't exist.
You are starting with an empty array 'c', and you NSLog c[i] which is obviously out of bounds on the first iteration.
I am trying to randomize numbers in an array. I am able to do that using arc4random() % [indexes count]
My problem is - If an array consists of 20 items, every time the array shuffles, in a batch of 5, different number should appear. Example :
first shuffle: 1,4,2,5,6.
second shuffle: 7,12,9,15,3
-(IBAction)randomNumbers:(UIButton *)sender
{
int length = 10; // int length = [yourArray count];
NSMutableArray *indexes = [[NSMutableArray alloc] initWithCapacity:length];
for (int i=0; i<5; i++)
[indexes addObject:[NSNumber numberWithInt:i]];
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:length];
while ([indexes count])
{
int index = arc4random() % [indexes count];
[shuffle addObject:[indexes objectAtIndex:index]];
[indexes removeObjectAtIndex:index];
}
// for (int i=0; i<[shuffle count]; i++)
NSLog(#"%#", [shuffle description]);
}
As per your requirement....kindly check this code
Make this a property
#synthesize alreadyGeneratedNumbers;
Add these methods in your .m
-(int)generateRandomNumber{
int TOTAL_NUMBER=20;
int low_bound = 0;
int high_bound = TOTAL_NUMBER;
int width = high_bound - low_bound;
int randomNumber = low_bound + arc4random() % width;
return randomNumber;
}
-(IBAction)randomNumbers:(UIButton *)sender
{
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:5];
BOOL contains=YES;
while ([shuffle count]<5) {
NSNumber *generatedNumber=[NSNumber numberWithInt:[self generateRandomNumber]];
//NSLog(#"->%#",generatedNumber);
if (![alreadyGeneratedNumbers containsObject:generatedNumber]) {
[shuffle addObject:generatedNumber];
contains=NO;
[alreadyGeneratedNumbers addObject:generatedNumber];
}
}
NSLog(#"shuffle %#",shuffle);
NSLog(#"Next Batch");
if ([alreadyGeneratedNumbers count] >= TOTAL_NUMBER) {
NSLog(#"\nGame over, Want to play once again?");//or similar kind of thing.
[alreadyGeneratedNumbers removeAllObjects];
}
}
Still I feel you need to some changes like
it will give you correct value, but what if user pressed 5th time?
out of 20 numbers you already picked 4 sets of 5 number, on on 6th time it will be in loop to search for next set of numbers and will become infinite.
So what you can do is, keep the track of shuffle and once it reaches the limit i.e, 20/5=4 disable the random button.
Declare array that contains already generated number in extension or header file
#property (strong, nonatomic)NSMutableArray *existingNums;
#property (assign, nonatomic)NSInteger maxLimit;
#property (assign, nonatomic)NSInteger minLimit;
Then implement given code in implementation file
#synthesize existingNums;
#synthesize maxLimit;
#synthesize minLimit;
- (NSInteger)randomNumber {
if(!existingNums)
existingNums = [NSMutableArray array];
while (YES) {
NSNumber *randonNum = [NSNumber numberWithInteger:minLimit+arc4random()%maxLimit];
if([existingNums containsObject:randonNum]) {
if([existingNums count] == (maxLimit - minLimit))
return -1; // All possible numbers generated in the given range
continue;
}
[existingNums addObject:randonNum];
return [randonNum integerValue];
}
return -1; // return error
}
Hope this will help you :)
This one works for me:
NSMutableArray *numbers = [NSMutableArray new];
BOOL addElement = YES;
int limit = 100; // Range from 0 to 36
int numElem = 10; // Number of elements
do
{
int ranNum = (arc4random() % limit) +1;
if ([numbers count] < numElem) {
for (NSNumber *oneNumber in numbers) {
addElement =([oneNumber intValue] != ranNum) ? YES:NO;
if (!addElement) break;
}
if (addElement) [numbers addObject:[NSNumber numberWithInt:ranNum]];
} else {
break;
}
} while (1);
NSLog(#"%#",numbers);
The problem with all these answers is that you need to review your previous generated random numbers and that takes extra time if you need a large number of random integers.
Another solution is using cryptography:
Generate a random key
Iterate between 0..n
Encrypt each integer and apply modulo the number of alternatives do you want to use to the output of the function.
There are some extra details to take into account that don't matter for your case.
I have a maybe simple problem. I am going to generate 3 random numbers ranging from 0 to 2 and I want to determine if there are any duplicates.
Any ideas?
if (num1 == num2) {
}
else if (num1 == num3) {
}
else if (num2 == num3) {
}
else {
//There are no dups.
}
Checks if there is a duplicate.
if (num1 == num2) {
counter++;
}
if (num1 == num3) {
counter++;
}
if (num2 == num3) {
counter++;
}
This finds how many duplicates there are (for an added bonus).
EDIT:
For x amount of numbers you might want to do this (using 10 as my example amount of ints):
int counter = 0;
int i[10] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
for (int g = 0; g < 10; g++)
{
for (int j = g+1; j < 10; j++)
{
if(i[g] == i[j])
{
counter++;
printf(#"%d\n", counter);
//If this if statement is true then there is a dup... In this case none are found.
}
}
}
How about this?
NSArray *randomNumbers = [[NSArray alloc] initWithObjects:#"0",#"1",#"1",#"2",nil];
NSMutableDictionary *occurenceDict = [[NSMutableDictionary alloc] init];
for (NSString *number in randomNumbers)
{
if ([occurenceDict objectForKey:number] == nil) {
[occurenceDict setValue:[NSNumber numberWithInt:[number intValue]] forKey:number];
int occOfNum = 0;
for (int i = 0; i < [randomNumbers count]; i++) {
NSString *currentNumber = [randomNumbers objectAtIndex:i];
if ([currentNumber compare:number] == NSOrderedSame) {
occOfNum++;
}
}
[occurenceDict setValue:[NSNumber numberWithInt:occOfNum] forKey:number];
}
}
for (NSString *key in occurenceDict) {
NSString *occurrences = [occurenceDict objectForKey:key];
NSLog(#"Number %d is contained %d times", [key intValue], [occurrences intValue]);
}
[randomNumbers release];
[occurenceDict release];
Output:
Number 0 is contained 1 times
Number 1 is contained 2 times
Number 2 is contained 1 times
Edit: Incase you want to know how this works, here is the same version but with comments to help you understand it:
// Create array with the numbers that we have randomly generated
NSArray *randomNumbers = [[NSArray alloc] initWithObjects:#"0",#"1",#"1",#"2",nil];
NSMutableDictionary *occurenceDict = [[NSMutableDictionary alloc] init];
for (NSString *number in randomNumbers)
{
// If this number has not been added to the dictionary
if ([occurenceDict objectForKey:number] == nil) {
// Add it
[occurenceDict setValue:[NSNumber numberWithInt:[number intValue]] forKey:number];
// Find how many times the number occurs with the "randomNumbers" array
int occOfNum = 0;
for (int i = 0; i < [randomNumbers count]; i++) {
NSString *currentNumber = [randomNumbers objectAtIndex:i];
if ([currentNumber compare:number] == NSOrderedSame) {
// We found this number at this index, so increment the found count
occOfNum++;
}
}
// Save the number of times which "number" occurs in the dictionary for later
[occurenceDict setValue:[NSNumber numberWithInt:occOfNum] forKey:number];
}
}
// Iterate through all items in the dictionary and print out the result
for (NSString *key in occurenceDict) {
NSString *occurrences = [occurenceDict objectForKey:key];
NSLog(#"Number %d is contained %d", [key intValue], [occurrences intValue]);
}
// Release alloc'ed memory
[randomNumbers release];
[occurenceDict release];
Crikey, these answers are long-winded! Put your random generated numbers into an NSIndexSet. Test the set before inserting a number and you'll know that the number is already present, and so is a dupe.