Take n random elements from a List?

后端 未结 12 1552
天涯浪人
天涯浪人 2020-11-27 16:09

How can I take n random elements from an ArrayList? Ideally, I\'d like to be able to make successive calls to the take() method to get an

12条回答
  •  情深已故
    2020-11-27 16:17

    All of these answers require a modifiable list or run into performance issued

    Here's a swift snippet that required O(k) additional space and is guaranteed to run in O(k) time and doesn't need a modifiable array. (Performs shuffles in a map)

      func getRandomElementsFrom(array: [Int], count: Int = 8) -> [Int] {
        if array.count <= count {
            return array
        }
    
        var mapper = [Int: Int]()
        var results = [Int]()
    
        for i in 0..

提交回复
热议问题