samedi 26 mars 2016

[Swift 2.2]: analog arc4random for range with negative numbers

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)




Aucun commentaire:

Enregistrer un commentaire