Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 686 Vote(s) - 3.53 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What's the Best Way to Shuffle an NSMutableArray?

#11
From iOS 10, you can use [NSArray `shuffled()` from GameplayKit](

[To see links please register here]

). Here is an helper for Array in Swift 3:

import GameplayKit

extension Array {
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
func shuffled() -> [Element] {
return (self as NSArray).shuffled() as! [Element]
}
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
mutating func shuffle() {
replaceSubrange(0..<count, with: shuffled())
}
}

Reply

#12
A slightly improved and concise solution (compared to the top answers).

The algorithm is the same and is described in literature as "[Fisher-Yates shuffle](

[To see links please register here]

;.

In Objective-C:

@implementation NSMutableArray (Shuffle)
// Fisher-Yates shuffle
- (void)shuffle
{
for (NSUInteger i = self.count; i > 1; i--)
[self exchangeObjectAtIndex:i - 1 withObjectAtIndex:arc4random_uniform((u_int32_t)i)];
}
@end

In Swift 3.2 and 4.x:

extension Array {
/// Fisher-Yates shuffle
mutating func shuffle() {
for i in stride(from: count - 1, to: 0, by: -1) {
swapAt(i, Int(arc4random_uniform(UInt32(i + 1))))
}
}
}

In Swift 3.0 and 3.1:

extension Array {
/// Fisher-Yates shuffle
mutating func shuffle() {
for i in stride(from: count - 1, to: 0, by: -1) {
let j = Int(arc4random_uniform(UInt32(i + 1)))
(self[i], self[j]) = (self[j], self[i])
}
}
}

Note: [A more concise solution in Swift is possible from iOS10 using `GameplayKit`.](

[To see links please register here]

)

Note: [An algorithm for unstable shuffling (with all positions forced to change if count > 1) is also available](

[To see links please register here]

)
Reply

#13
If you import `GameplayKit`, there is a `shuffled` API:

[To see links please register here]


let shuffledArray = array.shuffled()
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through