Skip to content

Instantly share code, notes, and snippets.

@jdhitsolutions
Last active June 24, 2017 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jdhitsolutions/1a05db07a3bc1b5c93728755f631b34e to your computer and use it in GitHub Desktop.
Save jdhitsolutions/1a05db07a3bc1b5c93728755f631b34e to your computer and use it in GitHub Desktop.
A PowerShell function to find anagrams from a word list.
#you will need a text file of words like this list from https://github.com/dwyl/english-words
Function Get-Anagram {
[cmdletbinding()]
Param(
[Parameter(Position = 0, Mandatory)]
[ValidateNotNullorEmpty()]
[Alias("word")]
[string]$Text,
[ValidateNotNullorEmpty()]
[ValidateScript( {
if (Test-Path $_) {
$True
}
else {
Throw "Cannot validate path $_"
}
})]
[string]$WordList = 'c:\scripts\dictionary.txt'
)
Begin {
Write-Verbose "[BEGIN ] Starting: $($MyInvocation.Mycommand)"
Write-Verbose "[BEGIN ] Loading word list: $wordlist"
} #begin
Process {
Write-Verbose "[PROCESS] Finding anagrams for: $Text"
#set word to all lowercase so it sorts properly
$a = ($text.ToLower().GetEnumerator() | Sort-Object) -join ''
Write-Verbose "[PROCESS] Filtering for words $($text.length) characters long [$a]"
Write-Host "Please wait...this may take several minutes" -foregroundcolor Green
#mark the time so we can report on how long the filtering took
$start = Get-Date
#it was slightly faster to filter out the original word in a second Where filter
$anagrams = Get-Content -Path $WordList |
Where-object {($_.length -eq $text.Length) -AND ((($_.ToLower().GetEnumerator() | Sort-Object) -join '') -eq $a)}
$end = Get-Date
Write-Verbose "[PROCESS] Process time: $($end - $start)"
#filter out the original word
$results = $anagrams | Where-Object {$_ -ne $text}
Write-Verbose "[PROCESS] Found $($results.count) anagrams"
#write a custom object to the pipeline
[pscustomobject]@{
Word = $text
Anagrams = $results
}
} #process
End {
Write-Verbose "[END ] Ending: $($MyInvocation.Mycommand)"
} #end
} #close Get-Anagram function
@jdhitsolutions
Copy link
Author

This function is described at http://bit.ly/2tXoBsA

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment