PoshCode Logo PowerShell Code Repository

Select-Random v2.1 (modification of post by Joel Bennett view diff)
View followups from Joel Bennett | diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/83"></script>download | new post

Select a user-defined number of random elements from the collection … which can be passed as a parameter or input via the pipeline. An improvement over http://www.powershellcentral.com/scripts/60 which allows you to select more than one item, and doesn’t copy the full collection into RAM. (Also, a bug fix for http://www.powershellcentral.com/scripts/81)

  1. # ---------------------------------------------------------------------------
  2. ### <Script>
  3. ### <Author>
  4. ### Joel "Jaykul" Bennett
  5. ### </Author>
  6. ### <Description>
  7. ### Selects a random element from the collection either passed as a parameter or input via the pipeline.
  8. ### If the collection is passed in as an argument, we simply pick a random number between 0 and count-1
  9. ### for each element you want to return, but when processing pipeline input we want to keep memory use
  10. ### to a minimum, so we use a "reservoir sampling" algorithm[1].
  11. ###
  12. ### [1] http://gregable.com/2007/10/reservoir-sampling.html
  13. ###
  14. ### The script stores $count elements (the eventual result) at all times. It continues processing
  15. ### elements until it reaches the end of the input. For each input element $n (the count of the inputs
  16. ### so far) there is a $count/$n chance that it becomes part of the result.
  17. ### * For each previously selected element, there is a $count/($n-1) chance of it being selected
  18. ### * For the ones selected, there's a ($count/$n * 1/$count = 1/$n) chance of it being replaced, so a
  19. ###   ($n-1)/$n chance of it remaining ... thus, it's cumulative probability of being among the selected
  20. ###   elements after the nth input is processed is $count/($n-1) * ($n-1)/$n = $count/$n, as it should be.
  21. ###
  22. ### </Description>
  23. ### <Usage>
  24. ### $arr = 1..5; Select-Random $arr
  25. ### 1..10 | Select-Random -Count 2
  26. ### </Usage>
  27. ### <Version>2.1.0.0</Version>
  28. ### </Script>
  29. # ---------------------------------------------------------------------------
  30. param([int]$count=1, [array]$inputObject=$null)
  31.  
  32. BEGIN {
  33.    if ($args -eq '-?') {
  34. @"
  35. Usage: Select-Random [[-Count] <int>] [-inputObject] <array> (from pipeline) [-?]
  36.  
  37. Parameters:
  38. -Count      : The number of elements to select.
  39. -Collection : The collection from which to select a random element.
  40. -?          : Display this usage information and exit
  41.  
  42. Examples:
  43. PS> $arr = 1..5; Select-Random $arr
  44. PS> 1..10 | Select-Random -Count 2
  45.  
  46. "@
  47. exit
  48.    }
  49.    elseif ($inputObject)
  50.    {
  51.       ### If you're accepting $args, you need to pass those in...
  52.       # Write-Output $io | &($MyInvocation.InvocationName) $args;
  53.       Write-Output $inputObject | &($MyInvocation.InvocationName) -Count $count
  54.       break;
  55.    }
  56.    else
  57.    {
  58.       $seen = 0
  59.       $selected = new-object object[] $count
  60.       $rand = new-object Random
  61.    }
  62. }
  63. PROCESS {
  64.    if($_) {
  65.       $seen++
  66.       if($seen -lt $count) {
  67.          $selected[$seen-1] = $_
  68.       } ## For each input element $n there is a $count/$n chance that it becomes part of the result.
  69.       elseif($rand.NextDouble() -lt ($count/$seen))
  70.       {
  71.          ## For the ones previously selected, there's a 1/$n chance of it being replaced
  72.          $selected[$rand.Next(0,$count)] = $_
  73.       }
  74.    }
  75. }
  76. END {
  77.    if (-not $inputObject)
  78.    {  ## DO ONCE: (only on the re-invoke, not when using -inputObject)
  79.       Write-Verbose "Selected $count of $seen elements"
  80.       Write-Output $selected
  81.       # foreach($el in $selected) { Write-Output $el }
  82.    }
  83. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me