Link to home
Start Free TrialLog in
Avatar of Blowfelt82
Blowfelt82

asked on

Calculate all possible permutations of characters in a set.

Say I have a character array with each character from a-z (lowercase only), how could I find each possible combination of three letters that is possible? For each character in the three letter combination I can reuse the full set. So I could have

aaa
abc
adf
...
zzz

Also is there a mathmatical formula anyone knows of that could validate the algorithm?
Avatar of d-glitch
d-glitch
Flag of United States of America image

There are 26 choices for the first character, 26 for the second, and 26 for the third.

So the total number of 3-character strings is 26^3  or 17,576
ASKER CERTIFIED SOLUTION
Avatar of Sean Stuber
Sean Stuber

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You may try the Get-StringPermutation function from following article..
http://learn-powershell.net/2013/02/21/fun-with-powershell-and-permutations/
Avatar of Sean Stuber
Sean Stuber

permutations aren't the same thing as combinations though.
I wrote a little script to generate combinations. It's essentially the same thing as the nested foreach above, the nesting is done through a recursive call here.
Function Get-Combinations {
  <#
    .Synopsis
      Generates combinations from an array of multi-dimensional arrays
    .Description
      Get-Combinations is a recursive function designed to return combination sets from defined arrays. All arrays are passed as a single parameter.
    .Parameter Object
      The multi-dimensional input array. All elements within the array are cast to System.String.
    .Parameter Seperator
      Joins each element using the specified character.
    .Parameter CurIndex
      The current outer-array index, used in recursion.
    .Parameter Return
      A composite return value, used in recursion.
    .Example
      Get-Combinations @($Array1, $Array2, $Array3)
    .Example
      Get-Combinations @("site", @("web", "app"), @("01", "02"))
  #>
      
  Param(
   [Object[]]$Object,
   [String]$Seperator,
   [UInt32]$CurIndex = 0,
   [String]$Return = ""
  )

  $MaxIndex = $Object.Count - 1
  $Object[$CurIndex] | ForEach-Object {
    [Array]$NewReturn = "$($Return)$($Seperator)$($_)".Trim($Seperator)
    If ($CurIndex -lt $MaxIndex) {
      $NewReturn = Get-Combinations $Object -CurIndex ($CurIndex + 1) -Return $NewReturn
    }
    $NewReturn
  }
}

$CharacterSet = ([Int][Char]"A")..([Int][Char]"Z") | ForEach-Object { [Char]$_ }

Get-Combinations @($CharacterSet, $CharacterSet, $CharacterSet)

Open in new window

I never managed to find a better way to do this so I formalised what I did have.

Chris