PowerShell/Scripts/list-anagrams.ps1

60 lines
1.7 KiB
PowerShell
Raw Normal View History

2020-12-29 15:14:21 +01:00
<#
2021-04-07 15:17:49 +02:00
.SYNTAX list-anagrams.ps1 [<word>] [<columns>]
2021-03-22 20:10:18 +01:00
.DESCRIPTION lists all anagrams of the given word
.LINK https://github.com/fleschutz/PowerShell
.NOTES Author: Markus Fleschutz / License: CC0
2020-12-29 15:14:21 +01:00
#>
2020-12-22 11:42:32 +01:00
2021-02-18 20:17:55 +01:00
param($Word = "", [int]$Columns = 8)
2020-12-22 11:42:32 +01:00
2020-12-29 15:14:21 +01:00
function GetPermutations {
2020-12-22 11:42:32 +01:00
[cmdletbinding()]
Param(
[parameter(ValueFromPipeline=$True)]
[string]$String = 'the'
)
Begin {
2020-12-22 11:53:15 +01:00
Function NewAnagram { Param([int]$NewSize)
if ($NewSize -eq 1) {
2020-12-22 11:42:32 +01:00
return
}
2020-12-22 11:53:15 +01:00
for ($i=0;$i -lt $NewSize; $i++) {
NewAnagram -NewSize ($NewSize - 1)
if ($NewSize -eq 2) {
2020-12-22 11:42:32 +01:00
New-Object PSObject -Property @{
Permutation = $stringBuilder.ToString()
}
}
2020-12-22 11:53:15 +01:00
MoveLeft -NewSize $NewSize
2020-12-22 11:42:32 +01:00
}
}
2020-12-22 11:53:15 +01:00
Function MoveLeft { Param([int]$NewSize)
2020-12-22 11:42:32 +01:00
$z = 0
$position = ($Size - $NewSize)
[char]$temp = $stringBuilder[$position]
2020-12-22 11:53:15 +01:00
for ($z=($position+1);$z -lt $Size; $z++) {
2020-12-22 11:42:32 +01:00
$stringBuilder[($z-1)] = $stringBuilder[$z]
}
$stringBuilder[($z-1)] = $temp
}
}
Process {
$size = $String.length
$stringBuilder = New-Object System.Text.StringBuilder -ArgumentList $String
2020-12-22 11:53:15 +01:00
NewAnagram -NewSize $Size
2020-12-22 11:42:32 +01:00
}
End {}
}
try {
if ($Word -eq "" ) {
$Word = read-host "Enter word"
2020-12-22 11:53:15 +01:00
$Columns = read-host "Enter number of columns"
2020-12-22 11:42:32 +01:00
}
2020-12-22 11:53:15 +01:00
GetPermutations -String $Word | Format-Wide -Column $Columns
2020-12-22 11:42:32 +01:00
exit 0
} catch {
2021-05-02 21:30:48 +02:00
write-error "⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
2020-12-22 11:42:32 +01:00
exit 1
}