PoshCode Logo PowerShell Code Repository

Select-Random v2.0 (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/81"></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.

  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.0.0.0</Version>
  28. ### </Script>
  29. param([int]$count=1, [array]$inputObject=$null)
  30.  
  31. BEGIN {
  32.    if ($args -eq '-?') {
  33. @"
  34. Usage: Select-Random [[-Count] <int>] [-inputObject] <array> (from pipeline) [-?]
  35. Parameters:
  36. -Count      : The number of elements to select.
  37. -Collection : The collection from which to select a random element.
  38. -?          : Display this usage information and exit
  39. Examples:
  40. PS> $arr = 1..5; Select-Random $arr
  41. PS> 1..10 | Select-Random -Count 2
  42. "@
  43. exit
  44.    }
  45.    elseif ($inputObject)
  46.    {
  47.       ### If you're accepting $args, you need to pass those in...
  48.       # Write-Output $io | &($MyInvocation.InvocationName) $args;
  49.       Write-Output $inputObject | &($MyInvocation.InvocationName) -Count $count
  50.       break;
  51.    }
  52.    else
  53.    {
  54.       $seen = 0
  55.       $selected = new-object object[] $count
  56.       $rand = new-object Random
  57.    }
  58. }
  59. PROCESS {
  60.    if($_) {
  61.       $seen++
  62.       if($seen -lt $count) {
  63.          $selected[$seen-1] = $_
  64.       } ## For each input element $n there is a $count/$n chance that it becomes part of the result.
  65.       elseif($rand.NextDouble() -gt $count/$seen)
  66.       {
  67.          ## For the ones previously selected, there's a 1/$n chance of it being replaced
  68.          $selected[$rand.Next(0,$count)] = $_
  69.       }
  70.    }
  71. }
  72. END {
  73.    if (-not $inputObject)
  74.    {  ## DO ONCE: (only on the re-invoke, not when using -inputObject)
  75.       Write-Verbose "Selected $count of $seen elements"
  76.       Write-Output $selected
  77.       # foreach($el in $selected) { Write-Output $el }
  78.    }
  79. }

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