[Swift] 如何取出「不重複」的整數陣列?

最近遇到了一個例子,在許多的題目中,要隨機取出題目。而這一題我的想法是,先取出不重複的整數陣列。 而這個想法真的非常棒,但怎麼取出「不重複」的整數陣列呢?這時我們可以使用 Swift 內建的語法 random。接下來就讓我們看一下如何取值吧!

swift

首先,先看來一下這個擴充怎麼寫吧!

extension Int {
 
  static func random(in range: ClosedRange<Int>, excluding data: [Int]?) -> Int {
    let random = Int.random(in: range)
    if data?.contains(random) ?? false {
      return Int.random(in: range, excluding: data)
    }
    return random
  }
 
  static func random(in range: ClosedRange<Int>, count: Int) -> [Int] {
 
    var randomValue = [Int]()
    while randomValue.count < count {
      randomValue.append(Int.random(in: range, excluding: randomValue))
    }
    return randomValue
  }
}

再來,假設我們要取 1~30 中的隨機整數,而陣列大小為 4,只要寫以下的程式碼就可以了,是不是相當簡單呢?

 let data = Int.random(in: 1...30, count: 4)

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments