RosettaCodeData/Task/ABC-problem/PowerShell/abc-problem.psh

118 lines
3.0 KiB
Plaintext

<#
.Synopsis
ABC Problem
.DESCRIPTION
You are given a collection of ABC blocks. Just like the ones you had when you were a kid.
There are twenty blocks with two letters on each block. You are guaranteed to have a
complete alphabet amongst all sides of the blocks
blocks = "BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"
The goal of this task is to write a function that takes a string and can determine whether
you can spell the word with the given collection of blocks.
The rules are simple:
1.Once a letter on a block is used that block cannot be used again
2.The function should be case-insensitive
3. Show your output on this page for the following words:
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
Using the examples below you can either see just the value or
status and the values using the verbose switch
.EXAMPLE
test-blocks -testword confuse
.EXAMPLE
test-blocks -testword confuse -verbose
#>
function test-blocks
{
[CmdletBinding()]
# [OutputType([int])]
Param
(
# word to test against blocks
[Parameter(Mandatory = $true,
ValueFromPipelineByPropertyName = $true)]
$testword
)
$word = $testword
#define array of blocks
[System.Collections.ArrayList]$blockarray = "BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"
#send word to chararray
$chararray = $word.ToCharArray()
$chars = $chararray
#get the character count
$charscount = $chars.count
#get the initial count of the blocks
$blockcount = $blockarray.Count
#find out how many blocks should be left from the difference
#of the blocks and characters in the word - 1 letter/1 block
$correctblockcount = $blockcount - $charscount
#loop through the characters in the word
foreach ($char in $chars)
{
#loop through the blocks
foreach ($block in $blockarray)
{
#check the current character against each letter on the current block
#and break if found so the array can reload
if ($char -in $block[0] -or $char -in $block[1])
{
write-verbose "match for letter - $char - removing block $block"
$blockarray.Remove($block)
break
}
}
}
#get final count of blocks left in array to determine if the word was
#correctly made
$finalblockcount = $blockarray.count
if ($finalblockcount -ne $correctblockcount)
{
write-verbose "$word : $false "
return $false
}
else
{
write-verbose "$word : $true "
return $true
}
}
#loop all the words and pass them to the function
$wordlist = "a", "bark", "book", "treat", "common", "squad", "confuse"
foreach ($word in $wordlist)
{
test-blocks -testword $word -Verbose
}