0

I was wondering how I can convert the below java code to Swift 4.

int randomNoteIndex = myArray[0] + (int) (Math.random() * (myArray[1] - myArray[0] + 1));

Here is what i tried but I always get the same number myArray[0] everytime

 let randomNoteIndex = myArray[0] +  Int(arc4random_uniform(1) * (UInt32(myArray[1]) - UInt32(myArray[0]) + UInt32(1)))
james
  • 2,595
  • 9
  • 43
  • 70
  • 1
    You should investigate what API actually does before blindly converting code. See [there](https://stackoverflow.com/questions/24132399/how-does-one-make-random-number-between-range-for-arc4random-uniform), that should help. – M. Prokhorov Dec 07 '17 at 11:15
  • Thanks for the link @M.Prokhorov it helped clear things up – james Dec 07 '17 at 11:33

2 Answers2

0

arc4random_uniform returns a random value between 0 and the argument passed in -1. Therefore if you pass in 1, you'll only ever get 0 out.

The behaviour you want can be achieved by passing in the array count. For example:

let randomIndex = Int(arc4random_uniform(Int32(myArray.count)))

Note the casts, this is because arc4random_uniform is C derived so requires explicit typing.

Jacob King
  • 6,025
  • 4
  • 27
  • 45
0

lowerBound + (int) (Math.random() * (upperBound - lowerBound + 1)) returns a uniformly distributed random number in range [lowerBound, upperBound].

arc4random_uniform(upperBound) returns a uniformly distributed random number less than upperBound. Thus what you're asking should be:

lowerBound + arc4random_uniform(upperBound - lowerBound + 1)

As Jacob stated, arc4random_uniform(myArray.count) returns a random "index", not number in range. Probably he deduced this from the naming of your variable.

Dorukhan Arslan
  • 2,676
  • 2
  • 24
  • 42
  • I accepted your answer because it was more in line with what I needed. However Jacob's answer helped me understand the issue. I was able to use your answer and get it to work. – james Dec 07 '17 at 11:52