PowerShell/Scripts/list-anagrams.ps1

61 lines
1.8 KiB
PowerShell
Raw Normal View History

2021-02-09 19:30:45 +01:00
#!/bin/powershell
2020-12-29 15:14:21 +01:00
<#
.SYNTAX ./list-anagrams.ps1 [<word>] [<columns>]
.DESCRIPTION lists all anagrams of the given word
.LINK https://github.com/fleschutz/PowerShell
.NOTES Author: Markus Fleschutz / License: CC0
#>
2020-12-22 11:42:32 +01:00
2020-12-29 15:14:21 +01:00
param([string]$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 {
2020-12-25 11:30:43 +01:00
write-error "ERROR in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
2020-12-22 11:42:32 +01:00
exit 1
}