Skip to content

Instantly share code, notes, and snippets.

@pohatu
Created June 18, 2013 20:00
Show Gist options
  • Save pohatu/5808755 to your computer and use it in GitHub Desktop.
Save pohatu/5808755 to your computer and use it in GitHub Desktop.
function Roll-Dice {
param(
[Parameter(
Mandatory = $true,
#Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[string]$ndm
)
#should probably check for input not matching ndm pattern
if (-not ($ndm -match "\dd\d")){
Write-Error -Message "Invalid Input, format must be ndm where 1<=n<=100 and 2<=m<=200." -Category InvalidArgument;
return $null
}
[system.int32]$n = $ndm.split("d")[0]
[system.int32]$m = $ndm.split("d")[1]
#validate input
if (($n -lt 1) -or ($n -gt 100) -or ($m -lt 2) -or ($m -gt 100)){
Write-Error -Message "Invalid Input, format must be ndm where 1<=n<=100 and 2<=m<=200." -Category InvalidArgument
return $null
}
$result = @();
while ($i++ -lt $n){$result += Get-Random -Minimum 1 -Maximum ($m+1) }
return $result
}
#region UnitTests
function verify-diceroll($n, $m) {
$output = roll-dice ("" + $n + "d" + $m)
if ($output -eq $null) {write-error "FAIL OUTPUT NULL"; return; }
if ($output.count -ne $n) { Write-Error "FAIL! number of rolls doesn't match input: actual:$output.count. expected:$n."; return;}
foreach($a in $output) {
if (($a -gt $m) -or ($a -lt 1)){ write-error "FAIL Resulting roll result ($a) is out of expected bounds 1..$m."; return;}
}
write-host "looks good"
}
function test-ValidateOutput() {
Write-Host "Test Valid Values"
verify-diceroll 1 2 #min
verify-diceroll 1 100 #max
verify-diceroll 100 100 #max
verify-diceroll 2 6 #most common
}
function test-invalidinputs() {
#invalid
write-host "Test Invalid Values"
"abd" | Roll-Dice
"0d6" | Roll-Dice
"101d6" | ROll-Dice
"2d1" | Roll-Dice
"2d101" | Roll-Dice
}
function test-PipelineInputs(){
Write-Host "Test Pipeline Inputs"
"2d6" | Roll-Dice
"1d2" | Roll-Dice
"100d100" | Roll-Dice
}
function Run-Tests()
{
test-PipelineInputs
test-invalidinputs
test-ValidateOutput
}
#endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment