DCSIMG
Randomizing collections: one-liners - Shay Levy

Shay Levy

If you repeat it, PowerShell it!

Randomizing collections: one-liners


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

Comments

Greg Lyon said:

Very cool. Makes a nice function.

function Sort-Random( $obj )

{

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

}

# August 11, 2008 10:04 PM

Joel "Jaykul" Bennett said:

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()}

}

# August 14, 2008 4:57 PM

Jakob Bindslet said:

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()}}}

# August 15, 2008 6:24 AM

Greg Lyon said:

Jaykul,

function Sort-Random( $obj )

{

  $obj | Sort-Object { Get-Random }

}

works too.

# August 15, 2008 10:10 PM

LunaticExperimentalist said:

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

1..5 | sort {random}

# August 17, 2008 8:19 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: