PowerShell/Scripts/list-anagrams.ps1

66 lines
1.8 KiB
PowerShell
Raw Normal View History

2021-08-26 10:46:12 +02:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
list-anagrams.ps1 [<word>] [<columns>]
.DESCRIPTION
2021-08-29 17:50:03 +02:00
Lists all anagrams of the given word.
2021-07-13 21:10:02 +02:00
.EXAMPLE
PS> .\list-anagrams.ps1 Markus
2021-08-29 17:50:03 +02:00
.NOTES
Author: Markus Fleschutz · License: CC0
2021-07-13 21:10:02 +02:00
.LINK
https://github.com/fleschutz/PowerShell
2020-12-29 15:14:21 +01:00
#>
2020-12-22 11:42:32 +01:00
2021-07-15 15:51:22 +02: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 {
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
}