ios - Generate a Swift array of nonrepeating random numbers -


i'd generate multiple different random numbers in swift. here procedure.

  1. set empty array
  2. generate random number
  3. check if array empty
    a. if array empty, insert random number
    b. if array not empty, compare random number numbers in array
    i. if numbers same, repeat 2
    ii. if numbers not same, insert random number , repeat 2

    import uikit   //the random number generator func randomint(min: int, max:int) -> int {     return min + int(arc4random_uniform(uint32(max - min + 1))) }  var temp = [int]() var = 0; i<4; i++ {   var randomnumber = randomint(1, 5)   if temp.isempty{     temp.append(randomnumber)   } else {   //i don't know how continue...  } } 

if use method problem is, create new random-number each time. possibly have same random-number 4 times , array have 1 element.

so, if want have array of numbers within specific range of numbers (for example 0-100), in random order, can first fill array numbers in 'normal' order. example loop etc:

var min = 1 var max = 5 var = min; i<= max; i++ {     temp.append(i) } 

after that, can use shuffle method shuffle elements of array shuffle method this answer:

func shuffle<c: mutablecollectiontype c.index == int>(var list: c) -> c {     let count = countelements(list)     in 0..<(count - 1) {         let j = int(arc4random_uniform(uint32(count - i))) +         swap(&list[i], &list[j])     }     return list } 

ater can that:

shuffle(temp)        // e.g., [3, 1, 2, 4, 5] 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -