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
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..