4

my requirement is generating a random point in a given area, i.e i have an Cg Rectangle of some space and I need to generate a random point in this rectangle ..

how can I proceed in this scenario?

Cœur
  • 37,241
  • 25
  • 195
  • 267

5 Answers5

10
- (CGPoint)randomPointInRect:(CGRect)r
{
    CGPoint p = r.origin;

    p.x += arc4random_uniform((u_int32_t) CGRectGetWidth(r));
    p.y += arc4random_uniform((u_int32_t) CGRectGetHeight(r));

    return p;
}
Quxflux
  • 3,133
  • 2
  • 26
  • 46
  • 5
    + 1, but you should use [`arc4random_uniform(u_int32_t upper_bound)`](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/arc4random_uniform.3.html). Reason as per doc: `"arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two."` ;) – HAS Nov 01 '13 at 11:04
5

The original question asks specifically for Objective-C, but a Swift solution might help someone.

extension CGRect {
    func randomPointInRect() -> CGPoint {
        let origin = self.origin
        return CGPointMake(CGFloat(arc4random_uniform(UInt32(self.width))) + origin.x, CGFloat(arc4random_uniform(UInt32(self.height))) + origin.y)
    }
}
Ishan Handa
  • 2,271
  • 20
  • 25
0

First, check out this post for generating random numbers: Generating random numbers in Objective-C

Then use CGPointMake(x,y) to create your point using random numbers:

int x = RandomNumberGenerator1Output;
int y = RandomNumberGenerator2Output;

CGPoint myPoint = CGpointMake(x, y);
Community
  • 1
  • 1
Amos
  • 868
  • 1
  • 10
  • 22
0

Same as any random number generator. You need two random numbers, x and y. Just generate x between 0 and rect.size.width and y between 0 and rect.size.height

Add rect.origin.x or rect.origin.y respectively. Random number generation is well covered elsewhere. Look for the arc4random family of functions.

uchuugaka
  • 12,679
  • 6
  • 37
  • 55
0

To generate a random point in a rectangle to need to generate random X and Y between Start and End coordinates of your rectangle.

if RECT is your rectangle then -

X = Random (RECT-Origion-X,RECT-Size-Width)
Y = Random (RECT-Origion-y,RECT-Size-Height)

If you want to know how to generate a random number between two numbers then you can go here - Generate Random Numbers Between Two Numbers in Objective-C

Community
  • 1
  • 1
saadnib
  • 11,145
  • 2
  • 33
  • 54