Storage Informer
Storage Informer

Fun with PowerShell – Calculate Permutations

by on Jun.13, 2009, under Storage

Fun with PowerShell – Calculate Permutations

I got sidetracked on Twitter tonight with a conversation between @jasonboche and @vmdoug, and since my wife is out of town visiting family I figured what better way to spend a Saturday night than to write a quick PowerShell script that can calculate the number of unique permutations based on 2 criteria.

First is the total number of available elements.  in this case, we were looking at the number of available URL combinations on bit.ly before they would “run out”.  Without spending any more than 15 seconds investigating, I determined that bit.ly uses only alphanumeric keys, but is case sensitive.  That means we have 26 uppercase letters, 26 lowercase letters, and 10 integers (0-9).  That gives us 62 total elements.

The second criteria is the number of total elements used in the combination.  In this case, bit.ly still uses 5 character URL strings.

The math behind this is something that I actually still remembered from high school oh so many years ago and is P = n!/(n-r)! where P is the number of Permutations, n is the total number of available elements, and r is the number of elements used in the combination.

Borrowing a function from stackoverflow.com (The nested loop calculation was pissing me off so I had to cheat), I was able to put together the following PowerShell script that can rather quickly do basic permutation calculations.

function factorial( [int] $f ) 

$result = 1
if ( $f -gt 1){
$result = $f * ( factorial ( $f – 1 ) )  
}
$result
}
 
function permutation( [int] $n, [int] $r )
{
(factorial $n) / (factorial ($n – $r) )
}
[int] $n = Read-Host “Total number of available elements:”
[int] $r = Read-Host “Total number of elements in combination:”
 
if ($n -ge 1 -and ($n – $r) -ge 0) {
permutation $n $r
}
else{
Write-Host “Invalid input parameters”

 

So, when all is said and done, by using this script we can determine that when using 62 total elements in 5 element combinations, bit.ly currently has 776,520,240 URL combinations available.  if they were to change to a 6 character URL, the number jumps to 44,261,653,680, in addition to the 776,520,240 combinations from their 5 character URLs.  I think its safe to say that as long as the bit.ly database can handle the load, we don’t need to worry about them running out of URLs any time soon.

URL: http://www.vmguru.com/index.php/articles-mainmenu-62/scripting/101-fun-with-powershell-calculate-permutations

:, , , , , , ,

Leave a Reply

Powered by WP Hashcash

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...