Middle three digits: Difference between revisions

→‎Tcl: Added implementation
(→‎{{header|JavaScript}}: update output to match code)
(→‎Tcl: Added implementation)
Line 973:
No middle three
No middle three
</pre>
 
=={{header|Tcl}}==
<lang tcl>proc middleThree n {
if {$n < 0} {
set n [expr {-$n}]
}
set idx [expr {[string length $n] - 2}]
if {$idx % 2 == 0} {
error "no middle three digits: input is of even length"
}
if {$idx < 1} {
error "no middle three digits: insufficient digits"
}
set idx [expr {$idx / 2}]
string range $n $idx [expr {$idx+2}]
}</lang>
Demonstrating:
<lang tcl>foreach n {
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0
} {
if {[catch {
set mid [middleThree $n]
} msg]} then {
puts "error for ${n}: $msg"
} else {
puts "found for ${n}: $mid"
}
}</lang>
{{out}}
<pre>
found for 123: 123
found for 12345: 234
found for 1234567: 345
found for 987654321: 654
found for 10001: 000
found for -10001: 000
found for -123: 123
found for -100: 100
found for 100: 100
found for -12345: 234
error for 1: no middle three digits: insufficient digits
error for 2: no middle three digits: insufficient digits
error for -1: no middle three digits: insufficient digits
error for -10: no middle three digits: input is of even length
error for 2002: no middle three digits: input is of even length
error for -2002: no middle three digits: input is of even length
error for 0: no middle three digits: insufficient digits
</pre>
 
Anonymous user