Select a random object from pipeline effectively


Problem

Select a random object from the input pipeline without knowing the number of objects and without collecting the entire input.

Solution

There is a beautiful and perfectly simple algorithm. The example in Perl and details are here: "Picking a Random Line from a File".


PowerShell script

##
## Author   : Roman Kuzmin
## Synopsis : Select a random object from input pipeline
## Modified : 2006.09.21
##
## Returns a selected random object
## -Seed: seed for System.Random; negative ~ time based; default: -1
##

param([int]$Seed = -1)

begin
{
    $random = $(if ($Seed -ge 0) {New-Object Random $Seed} else {New-Object Random})
    $object = $null
    $number = 0
}
process
{
    if ($random.Next(++$number) -eq 0) {
        $object = $_
    }
}
end
{
    $object
}

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: