0001    //
0002    //  shuffleinplace.swift
0003    //
0004    //  Created by Guillaume Lessard on 2014-08-28.
0005    //  Copyright (c) 2014 Guillaume Lessard. All rights reserved.
0006    //
0007    
0008    #if os(Linux)
0009    import func Glibc.random
0010    #else
0011    import func Darwin.C.stdlib.arc4random_uniform
0012    #endif
0013    
0014    extension MutableCollectionType where Self.Index: SignedIntegerType
0015    {
0016      mutating public func shuffle()
0017      {
0018        var index = startIndex
0019        let count = endIndex - index
0020    
0021        while index != endIndex
0022        {
0023    #if os(Linux)
0024          // with slight modulo bias
0025          let j = index + numericCast(random() % numericCast(count-index))
0026    #else
0027          let j = index + numericCast(arc4random_uniform(numericCast(count-index)))
0028    #endif
0029    
0030          if index != j
0031          {
0032            (self[index], self[j]) = (self[j], self[index])
0033          }
0034    
0035          index = index.successor()
0036        }
0037      }
0038    }
0039    
0040    extension MutableCollectionType where Self.Index: UnsignedIntegerType
0041    {
0042      mutating public func shuffle()
0043      {
0044        var index = startIndex
0045        let count = endIndex - index
0046    
0047        while index != endIndex
0048        {
0049    #if os(Linux)
0050          // with slight modulo bias
0051          let j = index + numericCast(random() % numericCast(count-index))
0052    #else
0053          let j = index + numericCast(arc4random_uniform(numericCast(count-index)))
0054    #endif
0055    
0056          if index != j
0057          {
0058            (self[index], self[j]) = (self[j], self[index])
0059          }
0060    
0061          index = index.successor()
0062        }
0063      }
0064    }
0065    
0066    extension MutableCollectionType
0067    {
0068      mutating public func shuffle()
0069      {
0070        for (i, j) in zip(indices, IndexShuffler(indices))
0071        {
0072          (self[j], self[i]) = (self[i], self[j])
0073        }
0074      }
0075    }
0076