Saturday, February 5, 2011

PowerShell doesn't cure insomnia

Had a bit of trouble sleeping last night, when I noticed that there was a perceptible difference in the amount of light the digital clock emanates.


It got me wondering what time displays the most light. Sure I could have manually figured it out, but isn't more exciting to write a script?

Here it is:
<#   Define a lookup table for the amount of light "bars" each number displays. #>           
$hash = @{"1"=2;"2"=5;"3"=5;"4"=4;     
"5"=5;"6"=6;"7"=3;"8"=7;
"9"=5;"0"=6;":"=0}
$max=0
for ($hour = 1; $hour -le 12; $hour++) {
for ($minute = 0;$minute -lt 60; $minute++) {
$time = "{0}:{1:0#}" -f $hour, $minute
$timeArray = $time.ToCharArray()
$sum=0
foreach ($char in $timeArray) {
$sum+= $hash[[string]$char]
}
if ($sum -gt $max) {
$max, $maxTime =$sum, $time
}
}
}
"{0}`t{1}"-f $max, $maxTime
Enjoy!

Project Euler 112

A brute force attack on Project Euler #112. I suspect there is a more efficient algorithm for this (not using string conversions), but this works.
function Test-Bouncy {          
param([int]$num)
$up=$down=$false
$numArray = $num.ToString().ToCharArray()
$length = $numArray.Length
for($i=1; $i -lt $length; $i++) {
if ($numArray[$i-1] -lt $numArray[$i]) {
$up = $true
}
elseif ($numArray[$i-1] -gt $numArray[$i]) {
$down = $true
}
if ($up -and $down) {
return $true
}
}
return $false
}

$isBouncy = $ratio = 0
$x = 1
while ($ratio -lt .99) {
if(Test-Bouncy $x) {
$isBouncy++
$ratio = $isBouncy/$x
}
$x++
}

"{0}`t{1}" -f ($x-1),$ratio
Enjoy!