-4

This might be a lame question and even have already answered in SO.i have even searched about this but could not understand in a proper way. what is happening here..??please help me out to understand this.

    let size =  Double(arc4random_uniform(5)) + 1



   for index in 0..<ITEM_COUNT
{
    let y = Double(arc4random_uniform(100)) + 50.0
    let size =  Double(arc4random_uniform(5)) + 1
    entries.append(ChartEntry(x: Double(index) + 0.5, y: y, size: CGFloat(size)))
}
iron
  • 715
  • 1
  • 6
  • 15
  • 3
    Possible duplicate of [Arc4random modulo biased](http://stackoverflow.com/questions/17640624/arc4random-modulo-biased) – MwcsMac May 17 '17 at 14:25
  • 3
    `man arc4random_uniform` in Terminal.app, or look at the documentation of it from XCode? The question is about "different random" (there are different ways to do it) or explanation of that piece of code? – Larme May 17 '17 at 14:25
  • ok i have added the more codes above please refer it :) – iron May 17 '17 at 14:30
  • 1
    `y` will be a Double randomly ranging from `50...149` and `size` from `1...5` – Leo Dabus May 17 '17 at 14:32
  • 1
    Thank you @LeoDabus – iron May 17 '17 at 14:34
  • `arc4random_uniform(n)` => Random number between 0 and n-1. So, add it 50, it's then a random number between 50 and 149 (that's how we change the interval/range of the random number, by adding/substracting and other manipulation) – Larme May 17 '17 at 14:35

1 Answers1

0

arc4random_uniform(x) returns a random value between 0 and x-1

Examples:

  • arc4random_uniform(2) -> returns 0 or 1 randomly

  • arc4random_uniform(2) == 0 returns true or false randomly

  • arc4random_uniform(6) + 1 returns a number between 1 and 6 (like a dice roll)

There are a multitude of reasons that arc4random_uniform(5) returns a number between 0 and 5, but the main one is that this is a basic functionality in programming, where numbers start at zero. An example of why this would be useful would be returning a random value from an array. Example:

func randomArrayValue(array: [Int]) -> Int {
    let index = arc4random_uniform(array.count)
    return array[index]
}

let arrayOfInt = [10,20,30]
print("Random Int: \(randomArrayValue(array: arrayOfInt))")

//"Random Int: 10"
//"Random Int: 20"
//"Random Int: 30"

For these three lines of code in your questions:

let y = Double(arc4random_uniform(100)) + 50.0
let size =  Double(arc4random_uniform(5)) + 1
entries.append(ChartEntry(x: Double(index) + 0.5, y: y, size: CGFloat(size)))
  • y is a random variable between 50 and 149

  • size is a random variable between 1 and 5

  • you then add an item onto an array that goes onto a chart. The value being added specifies the x location (the index) and the y location (the random y value). Size is some code specific requirement, which we wouldn't be able to help with without seeing the functionality.

Alec O
  • 1,697
  • 1
  • 18
  • 31