1

I want to generate a random number that can be between

-3...-8 and 3...8

I know I could find a roundabout way of doing this by first doing a random integer between 0 and 1 and then picking the range on that:

let zeroOrOne = CGFloat.random(in: 0...1)
if zeroOrOne == 0 {
    randomNum = CGFloat.random(in: -3...-8)
} else {
    randomNum = CGFloat.random(in: 3...8)
}

but I am wondering if there is a better way of doing this.

Slaknation
  • 2,124
  • 3
  • 23
  • 42

2 Answers2

3

I am sure you want to use Bool.random.

One way to write it would be

let randomNum = CGFloat.random(in: 3...8) * (Bool.random() ? 1 : -1)

or

var randomNum = CGFloat.random(in: 3...8)
if Bool.random() {
   randomNum.negate()
}

There is no single correct solution.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
1

There is a general solution for generating a random integer within several nonoverlapping ranges.

  1. Find the number of integers in each range; this is that range's weight (e.g., if each range is a closed interval [x, y], this weight is (y - x) + 1).
  2. Choose a range randomly according to the ranges' weights (see this question for how this can be done in Swift).
  3. Generate a random integer in the chosen range: CGFloat.random(in: range).
Peter O.
  • 32,158
  • 14
  • 82
  • 96