Frank
Frank

Reputation: 507

How to make random height with some space between previous and next height in Objective-C?

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);

Upvotes: 1

Views: 173

Answers (3)

Cœur
Cœur

Reputation: 38727

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;
}

Upvotes: 0

mohitdream4u
mohitdream4u

Reputation: 166

This will Give You correct height

float _randomHight = arc4random() % 900 + 101;

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122458

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;

Upvotes: 4

Related Questions