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.

4
  • 1
    If anything, replace let zeroOrOne = CGFloat.random(in: 0...1) with let posOrNeg = Bool.random(). Commented Apr 15, 2019 at 18:18
  • 1
    You might also use let randomNum = CGFloat.random(in: 3...8) * (Bool.random() ? 1 : -1) Commented Apr 15, 2019 at 18:19
  • 4
    let randomNum: CGFloat = .random(in: .random() ? -8 ... -3 : 3 ... 8) You can even omit the Bool type Commented Apr 15, 2019 at 18:33
  • 1
    @LeoDabus ok that is cool Commented Apr 15, 2019 at 18:41

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.