PowerShell: 145 103
Changes from original
Removed error quelch per comment from asker.
Code:
"$([array]::IndexOf(($s=(read-host)-split''|?{$_}),($x=$s|?{$_%2-eq0}|?{$_-gt0}|sort|select -f 1))),$x"
Walkthrough:
"
..."
Everything within the quotes will be included in the output.
$(
...)
Everything between the parenthesis will be treated as a commands, and the output of that code will be included instead of the commands themselves.
[array]::IndexOf(
...)
This is used to get the index of an element with the array. Its first parameter is the array object to be searched. The second parameter is the object to be found. This only outputs the index of the first matching element. I tried simply using an IndexOf
method directly against $s
(e.g.: $s.IndexOf($x)
, but this fails for some reason I've yet to figure out - it claims the method doesn't exist on that object.
(
...)
Expression within the parenthesis will be the first parameter for IndexOf
.
$s=
$s will be a variable to store the user input.
(read-host)-split''
Gets user input, and splits it into an array of characters.`
|?{$_}
Filters out extra empty array elements that are generated by -split''
.
,(
...)
Expression within the parenthesis will be the second parameter for IndexOf
.
$x=
$s will be a variable to store the lowest even digit from the user input.
$s|?{$_%2-eq0}
Pulls out the even numbers from $s.
|?{$_-gt0}
Invalidates zero.
|sort
Sorts the remaining objects, default order is ascending.
|select -f 1
Picks the first object, which will by now be the lowest even digit.
,$x
The above code will output the index of our lowest even digit. This adds a comma, and then outputs the digit itself.
Notes:
This is perhaps stretching rule #4 a little bit. If there is no even digit, the output will not include a second number.
Also, this will throw some non-terminating errors if the input includes non-numeric elements. The script will still run and give proper output, but you might want to set $ErrorActionPreference
to 'SilentlyContinue'
before running it.