0

I'm pretty new to coding, I've been looking for similar questions but none fits my needs. I'm working in a dice rolling app, and I need a a random number generator to "roll" the dice. arc4random seems perfect, but the problems that I can't have the same face occurring twice in a row. I have a method firing when I press the button with a timer

- (IBAction)dieRoll:(id)sender {

self.currentFace = 1;

_timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(roll) userInfo:nil repeats:YES];;

}

but I have to implement the 'roll' method where I get a random number different from the one already selected (the property self.currentFace).

any clue?

Riccardo
  • 51
  • 1
  • 1
  • 7

3 Answers3

4

this is how your implementation could look like:

@interface ViewController ()

@property (assign, nonatomic) NSInteger currentFace;

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  self.currentFace = -1;
}

- (IBAction)diceRoll:(id)sender {
  NSInteger newFace = -1;
  do {
    newFace = arc4random_uniform(6) + 1;
  } while (newFace == self.currentFace);

  self.currentFace = newFace;
}

@end
André Slotta
  • 13,774
  • 2
  • 22
  • 34
1

A simple solution would be to just remember the last rolled number and roll the dice until you get a different one. Pretty simple and you can keep arc4random.

An example:

- (NSUInteger)rollDiceWithLastFaceNumber:(NSUInteger)lastFaceNumber
{
    NSUInteger currentFaceNumber;

    do {
        currentFaceNumber = (arc4random_uniform(6) + 1);
    } while (currentFaceNumber == lastFaceNumber);

    return currentFaceNumber;
}

and how to use it:

[self rollDiceWithLastFaceNumber:3];
o15a3d4l11s2
  • 3,969
  • 3
  • 29
  • 40
1

This solution avoids an unknown number of iterations until you get your result.

- (void)roll {
    NSUInteger next = [self nextFaceWithPreviousFace:self.currentFace];
    NSLog(@"%lu", next);
    self.currentFace = next;
}

- (NSUInteger)nextFaceWithPreviousFace:(NSUInteger)previous {
    NSMutableArray *candidates = [NSMutableArray arrayWithObjects:@1, @2, @3, @4, @5, @6, nil];
    [candidates removeObject:@(previous)];
    NSUInteger index = arc4random_uniform((unsigned)candidates.count);
    return [candidates[index] unsignedIntegerValue];
}