Get a random unique element from an Array until all elements have been picked in Swift

前端 未结 5 1462
不思量自难忘°
不思量自难忘° 2020-12-12 08:32

I have the following array:

var notebookCovers = [\"cover1\", \"cover2\", \"cover3\", \"cover4\", \"cover4\", \"cover6\", \"cover7\", \"cover8\", \"cover9\"         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 08:45

    Copy the array. Shuffle the copy. Now just keep removing the first element until the copy is empty. When it is empty, start over.

    Example:

    let arr = [1,2,3,4,5]
    var copy = [Int]()
    for _ in 1...30 { // just to demonstrate what happens
        if copy.isEmpty { copy = arr; copy.shuffle() }
        let element = copy.removeFirst() ; print(element, terminator:" ")
    }
    // 4 2 3 5 1 1 5 3 2 4 4 1 2 3 5 1 4 5 2 3 3 5 4 2 1 3 2 4 5 1
    

提交回复
热议问题