I'm trying to create a list of "sentences" of 1-8 "words", provided a list of words, where I don't care about uniqueness as I can just filter out duplicates later. I decided that a recursive function would be the best method, particularly in case I wanted to change the maximum length at a later time.
When I ran this code, I came back with an empty result. When I debugged and stepped through it, I found that $sents would contain data right before a return statement, then have no data immediately after returned to the $sents variable in the first else statement.
This is the second recursive function I've written for PowerShell and neither worked. The first I ended up breaking down and wrote 4 nested foreach statements. This one would be 8 nested statements (I do not wish to do that) just to build a String array of sentences so I can process them.
Any help would be appreciated. Thank you!
function make-sentences ($ws, $ml, [String[]] $sent = @(), [String[]] $sents = @()) {
[String[]] $nws = @()
$sent += $ws[0]
if ($sent.length -ge $ml) {
$sents += ($sent -join ",")
return $sents
} elseif ($ws.length -le 1) {
$sents += ($sent -join ",")
return $sents
} else {
for ($i = 1; $i -lt $ws.length; $i++) { $nws += $ws[$i] }
$sents += make-sentences $nws $ml $sent $sents
}
[String[]] $nws = @()
if ($ws.length -le 1) {
$sents += ($sent -join ",")
return $sents
} else {
$sent = @()
for ($i = 1; $i -lt $ws.length; $i++) { $nws += $ws[$i] }
$sents += make-sentences $nws $ml $sent $sents
}
}
$words = ("acfj","acfk","adfk","aefj","aefk","aegi","aehi","afgh")
[String[]] $sentences = make-sentences $words 8
$sentences