Reputation: 97
I wrote a function that finds the greatest difference among all elements of the array. But I need the restriction on the input elements array [-5..20]. Unfortunately it does not support UInt32. What are similar to a solution to fill the array randomly from the range [-5..20]?Thank you!
func highDifferenceV ( n: Int) ->String{
var a = [Int]() //array
var dif = 0 // max difference
var k = 0
for _ in 0..<n {
a.append(Int(arc4random_uniform(UInt32(20)))) // fill array
}
while k < a.count { //search the greatest difference
for i in 0..<n {
if a[k] - a[i] > dif {
dif = a[k] - a[i]
}
}
k++
}
print(a)
return "Maximum difference =\(dif)"
}
highDifferenceV(75)
Upvotes: 0
Views: 167
Reputation: 154681
To fill an array with values from -5...20
, generate an number in the range 0...25
and then subtract 5
:
for _ in 0..<n {
a.append(Int(arc4random_uniform(UInt32(26)))-5) // fill array
}
In general, to generate a value in the range min...max
, call arc4random_uniform
with max - min + 1
and then add min
.
Upvotes: 3