Created
          August 23, 2012 13:02 
        
      - 
      
 - 
        
Save tmcw/3436381 to your computer and use it in GitHub Desktop.  
    Floyd's Algorithm for Random Subsets
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | function sample(list, m) { | |
| var n = list.length; | |
| if (m > n) return void console && | |
| console.log('list length must be > sample'); | |
| var sampleList = []; | |
| for (var i = n - m; i < n; i++) { | |
| var item = list[~~(Math.random() * i)]; | |
| if (sampleList.indexOf(item) !== -1) | |
| sampleList.push(list[i]); | |
| else | |
| sampleList.push(item); | |
| } | |
| return sampleList; | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
When the arraylist is already given there is a better algorithm of strict
O(n)complexity (see below) The Floyd algorithm hasO(n^2)worst-case complexity (due to the use of searches/hashmaps etc..)Actually one can safely assume the arraylist as given always, since the selection eventually must be applied to some existing arraylist, so it is no major assumption to make nor drawback
see also Abacus where this and many other combinatorialalgorithms are given