Randomizing collections: one-liners

August 11, 2008

5 comments

I found a cool way HERE to shuffle/reorder array elements without using the random class.

Generally you provide Sort-Object an object property to sort on, only now the property is in the form of a Globally Globally Unique Identifier (GUID), which is a random generated 128-bit integer.

 

PS > 1..5 | sort-object { [guid]::newGuid() }
2
5
3
1
4

 

To select one or more random objects from the collection, pipe the above to Select-Object and use the -First (or -Last) parameter:

PS > 1..5 | sort-object { [guid]::newGuid() } | select-object -first 3
4
1
3

 

These techniques are also available on collections you use everyday with PowerShell, not just numbers. For instance, selecting 4 random lines from a text file (contain 10 numbered lines), you get the idea 馃檪

PS > Get-Content lines.txt | sort-object { [guid]::newGuid() } | select-object -last 4
Line 3
Line 4
Line 2
Line 5
Add comment
facebook linkedin twitter email

Leave a Reply to Jakob Bindslet Cancel Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

5 comments

  1. Greg LyonAugust 11, 2008 讘 22:04

    Very cool. Makes a nice function.

    function Sort-Random( $obj )

    {

       $obj | Sort-Object { [GUID]::NewGuid() }

    }

    Reply
  2. Joel "Jaykul" BennettAugust 14, 2008 讘 16:57

    I know the Random class is frustrating because you have to create an instance, but just for the record, generating GUIDs is rather more expensive than using the random number generator… 馃檪 Might not matter for simple scripts, but for something like that Sort-Random, you’re better off with something like

    function Sort-Random ($obj) {
    $rand = new Random
    $obj | Sort-Object {$rand.Next()}
    }

    Reply
  3. Jakob BindsletAugust 15, 2008 讘 06:24

    May I suggest something more like:

    function sort-random {

       process {

           [array]$x = $x + $_

       }

       end {

           $x | sort-object {(new-object Random).next()}

       }

    }

    Or, as a oneliner:

    function sort-random {process {[array]$x = $x + $_}; end {$x | sort-object {(new-object Random).next()}}}

    Reply
  4. Greg LyonAugust 15, 2008 讘 22:10

    Jaykul,

    function Sort-Random( $obj )
    {
    $obj | Sort-Object { Get-Random }
    }

    works too.

    Reply
  5. LunaticExperimentalistAugust 17, 2008 讘 20:19

    If you happen to have PSCX installed then it could be simplified.

    1..5 | sort {random}

    Reply