1

I use this code in Objective-C to generate a random height between 100 and 1000.
My problem is, that new height is often near to the previous one and that is not so nice.

So how to make it so, that there is always some space (50px, for example) between previous and next height?

_randomHeight = arc4random() % (1000-100+1);
Cœur
  • 37,241
  • 25
  • 195
  • 267
Frank
  • 497
  • 1
  • 6
  • 11
  • 2
    for having random numbers between `100` and `1000` you need to change your formula to this: `arc4random() % 901 + 100`, the current formula gives you random numbers between `0` and `900`. – holex Jul 10 '14 at 13:27
  • @BhaumikSurani unsure if you were looking for a solution to this problem, but I added my own answer which is, I believe, quite efficient. – Cœur Oct 09 '18 at 13:29

3 Answers3

4

You just have to keep generating values until a value meets your requirement:

CGFloat height;
do {
    height = arc4random() % (1000-100+1);
} while (fabs(_randomHeight - height) < 50.0f);
_randomHeight = height;
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • While in this scenario (900 values, 50 distance) there is roughly 89% chances the loop will not repeat, I would prefer to avoid algorithms using `do {} while (something random)` in favor of algorithms with a fixed execution time if possible. – Cœur Oct 09 '18 at 12:26
0

This will Give You correct height

float _randomHight = arc4random() % 900 + 101;
mohitdream4u
  • 166
  • 10
0

Here is a solution to produce values between 100 and 1000, distant of 50 at least, and using only one call to arc4random to guarantee a fixed execution time:

/// Return a new random height between 100 and 1000, at least 50 space from previous one.
+ (uint32_t)randomHeight {
    /// initial value is given equiprobability (1000 - 100 + 50)
    static uint32_t _randomHeight = 950;

    uint32_t lowValues = MAX(_randomHeight - 50, 0);
    uint32_t highValues = MAX(850 - _randomHeight, 0);
    uint32_t aRandom = arc4random_uniform(lowValues + highValues + 1);
    _randomHeight = aRandom < lowValues ? aRandom : _randomHeight + 50 + aRandom - lowValues;
    return _randomHeight + 100;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • What's so important about fixed execution time? – trojanfoe Feb 05 '19 at 08:56
  • @trojanfoe if the values were different, like in the range from 100 to 200, then your solution may be slower due to the `while` condition. And when `%` is applied with a non-power of two, [there is a modulo bias](https://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator). – Cœur Feb 05 '19 at 14:05
  • You haven’t explained why that is important though. – trojanfoe Feb 05 '19 at 16:38