Add to Technorati Favorites
Welcome to ThePowerShellGuy.com Sign in | Join | Help

Scripting Games 2007 Advanced PowerShell Event 9

As the Answers to the events 9 and 10 in the Scripting Games 2007, Are Posted,

I will again post my solutions here on my blog:

 

Event 9: Get Me the Operator, Please

PS Answer: Get Me the Operator, Please

 

My answer to Event 9 is a bit shorter as the answer given by the Scripting Guys, but it basically does the same, using 4 nested loops to enumerate all Possibilities

 

$op = '+','-','*','/'
Foreach ($1 in $op) {
  Foreach ($2 in $op) {
    Foreach ($3 in $op) {
      Foreach ($4 in $op) {
        if (Invoke-Expression "12  $1 8 $2  4 $3  2 $4  9 -eq 23") {
          "12  $1 8 $2  4 $3  2 $4  9 = 23"
        }
      }
    }
  }
}

 And the Answer is :

 

PoSH> C:\scripts\Event9.ps1
12 + 8 - 4 - 2 + 9 = 23

 

Enjoy,

Greetings /\/\o\/\/

Published Friday, February 23, 2007 11:26 AM by admin

Comments

# re: Scripting Games 2007 Advanced PowerShell Event 9

Here´s my solution. I´ve made a script to search one possibility and stop in the first... but for any kind of numbers. I use stack for manipulation...

function change-op([system.collections.stack]$stack) {

if($stack.count -eq 1) {

return $false

}

$elem = $stack.pop()

$op = $stack.pop()

switch($op) {

'+' {

$op = '-'

$stack.push($op)

$stack.push($elem)

return $true

break

}

'-' {

$op = '*'

$stack.push($op)

$stack.push($elem)

return $true

break

}

'*' {

$op = '/'

$stack.push($op)

$stack.push($elem)

return $true

break

}

'/' {

$op = '+'

$resultado = change-op($stack)

if($resultado) {

$stack.push($op)

$stack.push($elem)

return $true

}

else {

return $false

}

}

}

}

function print-stack([system.collections.stack]$stk) {

$stack = $stk.clone()

$result = ''

#inverting the stack to print

$aux = new-object System.Collections.Stack

while($stack.count -ne 0) {

$aux.push($stack.pop())

}

$stack = $aux.clone()

while($stack.count -ne 0) {

$result += $stack.pop()

}

$result

}

"Please, type the numbers and the final result separated by spaces"

"Ex: 12 4 6 2 (when you want 12-4-6=2)"

$entrada = (read-host).split()

$numeros = $entrada[0..(($entrada.length)-2)]

$soma = $entrada[-1]

$stack = new-object System.Collections.Stack

#filling the stack

for($i=0; $i -lt $numeros.length-1; $i++) {

$stack.push($numeros[$i])

$stack.push('+')

}

$stack.push($numeros[-1])

$str = print-stack($stack)

while((invoke-expression $str) -ne $soma) {

change-op($stack) |  out-null

$str = print-stack($stack)

}

$str = print-stack($stack)

'' + $str + ' = ' + $soma

Friday, February 23, 2007 7:06 PM by Vinicius Canto - MVP Scripting
Anonymous comments are disabled