Middle three digits: Difference between revisions

m
(→‎{{header|Perl 6}}: using a regular expression)
imported>Arakov
 
(117 intermediate revisions by 55 users not shown)
Line 2:
 
;Task:
:“''Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.''”
 
:<small>''Note: The order of the middle digits should be preserved''.</small>
Note: The order of the middle digits should be preserved.
 
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
Line 12 ⟶ 13:
Show your output on this page.
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F middle_three_digits(i)
V s = String(abs(i))
assert(s.len >= 3 & s.len % 2 == 1, ‘Need odd and >= 3 digits’)
R s[s.len I/ 2 - 1 .+ 3]
 
V passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
V failing = [1, 2, -1, -10, 2002, -2002, 0]
L(x) passing [+] failing
X.try
V answer = middle_three_digits(x)
print(‘middle_three_digits(#.) returned: #.’.format(x, answer))
X.catch AssertionError error
print(‘middle_three_digits(#.) returned error: ’.format(x)‘’String(error))</syntaxhighlight>
 
{{out}}
<pre>
middle_three_digits(123) returned: 123
middle_three_digits(12345) returned: 234
middle_three_digits(1234567) returned: 345
middle_three_digits(987654321) returned: 654
middle_three_digits(10001) returned: 000
middle_three_digits(-10001) returned: 000
middle_three_digits(-123) returned: 123
middle_three_digits(-100) returned: 100
middle_three_digits(100) returned: 100
middle_three_digits(-12345) returned: 234
middle_three_digits(1) returned error: Need odd and >= 3 digits
middle_three_digits(2) returned error: Need odd and >= 3 digits
middle_three_digits(-1) returned error: Need odd and >= 3 digits
middle_three_digits(-10) returned error: Need odd and >= 3 digits
middle_three_digits(2002) returned error: Need odd and >= 3 digits
middle_three_digits(-2002) returned error: Need odd and >= 3 digits
middle_three_digits(0) returned error: Need odd and >= 3 digits
</pre>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<syntaxhighlight lang="action!">INCLUDE "H6:REALMATH.ACT"
INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit
 
PROC MiddleThreeDigits(REAL POINTER n CHAR ARRAY res)
REAL r
CHAR ARRAY s(15)
BYTE i
 
RealAbs(n,r)
StrR(r,s)
i=s(0)
IF i<3 OR (i&1)=0 THEN
res(0)=0
ELSE
i==RSH 1
SCopyS(res,s,i,i+2)
FI
RETURN
 
PROC Test(CHAR ARRAY s)
REAL n
CHAR ARRAY res(4)
 
ValR(s,n)
MiddleThreeDigits(n,res)
IF res(0) THEN
PrintF("%9S -> %S%E",s,res)
ELSE
PrintF("%9S -> error!%E",s)
FI
RETURN
 
PROC Main()
Put(125) PutE() ;clear the screen
 
Test("123") Test("12345")
Test("1234567") Test("987654321")
Test("10001") Test("-10001")
Test("-123") Test("-100")
Test("100") Test("-12345")
Test("1") Test("2")
Test("-1") Test("-10")
Test("2002") Test("-2002")
Test("0")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Middle_three_digits.png Screenshot from Atari 8-bit computer]
<pre>
123 -> 123
12345 -> 234
1234567 -> 345
987654321 -> 654
10001 -> 000
-10001 -> 000
-123 -> 123
-100 -> 100
100 -> 100
-12345 -> 234
1 -> error!
2 -> error!
-1 -> error!
-10 -> error!
2002 -> error!
-2002 -> error!
0 -> error!
</pre>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Middle_Three_Digits is
Line 57 ⟶ 166:
end loop;
 
end Middle_Three_Digits;</langsyntaxhighlight>
 
{{out}}
Line 79 ⟶ 188:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">void
m3(integer i)
{
Line 85 ⟶ 194:
 
s = itoa(i);
if (character(s, [0)] == '-') {
s = delete(s, 0);
}
 
if (length(~s) < 3) {
v_integer(i);
v_text(" has not enough digits\n");
} elif (length(~s) & 1) {
o_wintegero_form(9"/w9/: ~\n", i, cut(s, ~s - 3 >> 1, 3));
o_text(": ");
o_text(cut(s, length(s) - 3 >> 1, 3));
o_byte('\n');
} else {
v_integer(i);
Line 122 ⟶ 228:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre> 123: 123
Line 144 ⟶ 250:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.6.win32}}
<langsyntaxhighlight lang="algol68"># we define a UNION MODE so that our middle 3 digits PROC can #
# return either an integer on success or a error message if #
# the middle 3 digits couldn't be extracted #
 
MODE EINT = UNION( INT # success value #, STRING # error message # );
 
 
# PROC to return the middle 3 digits of an integer. #
# if this is not possible, an error message is returned #
# instead #
 
PROC middle 3 digits = ( INT number ) EINT:
BEGIN
 
# convert the absolute value of the number to a string with the #
# minumum possible number characters #
STRING digits = whole( ABS number, 0 );
INT len = UPB digits;
 
 
IF len < 3
THEN
# number has less than 3 digits #
# return an error message #
 
"number must have at least three digits"
 
ELIF ( len MOD 2 ) = 0
THEN
# the number has an even number of digits #
# return an error message #
 
"number must have an odd number of digits"
 
ELSE
# the number is suitable for extraction of the middle 3 digits #
 
INT first digit pos = 1 + ( ( len - 3 ) OVER 2 );
 
# the result is the integer value of the three digits #
 
( ( ( ABS digits[ first digit pos ] - ABS "0" ) * 100 )
+ ( ( ABS digits[ first digit pos + 1 ] - ABS "0" ) * 10 )
+ ( ( ABS digits[ first digit pos + 2 ] - ABS "0" ) )
)
 
FI
 
END; # middle 3 digits #
 
 
 
main: (
 
# test the middle 3 digits PROC #
 
[]INT test values = ( 123, 12345, 1234567, 987654321
, 10001, -10001, -123, -100
Line 206 ⟶ 292:
, 1, 2, -1, -10, 2002, -2002, 0
);
 
FOR test number FROM LWB test values TO UPB test values
DO
 
CASE middle 3 digits( test values[ test number ] )
IN
( INT success value ): # got the middle 3 digits #
 
printf( ( $ 11z-d, " : ", 3d $
, test values[ test number ]
Line 220 ⟶ 303:
)
,
( STRING error message ): # got an error message #
 
printf( ( $ 11z-d, " : ", n( UPB error message )a $
, test values[ test number ]
Line 228 ⟶ 309:
)
)
 
ESAC;
 
print( ( newline ) )
 
OD
)</syntaxhighlight>
 
)</lang>
{{out}}
<pre>
Line 256 ⟶ 333:
0 : number must have at least three digits
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% record structure that will be used to return the middle 3 digits of a number %
% if the middle three digits can't be determined, isOk will be false and message %
% will contain an error message %
% if the middle 3 digts can be determined, middle3 will contain the middle 3 %
% digits and isOk will be true %
record MiddleThreeDigits ( integer middle3; logical isOk; string(80) message );
 
% finds the middle3 digits of a number or describes why they can't be found %
reference(MiddleThreeDigits) procedure findMiddleThreeDigits ( integer value number ) ;
begin
integer n, digitCount, d;
 
n := abs( number );
% count the number of digits the number has %
digitCount := if n = 0 then 1 else 0;
d := n;
while d > 0 do begin
digitCount := digitCount + 1;
d := d div 10
end while_d_gt_0 ;
if digitCount < 3 then MiddleThreeDigits( 0, false, "Number must have at least 3 digits" )
else if not odd( digitCount ) then MiddleThreeDigits( 0, false, "Number must have an odd number of digits" )
else begin
% can find the middle three digits %
integer m3;
m3 := n;
for d := 1 until ( digitCount - 3 ) div 2 do m3 := m3 div 10;
MiddleThreeDigits( m3 rem 1000, true, "" )
end
end findMiddleThreeDigits ;
 
% test the findMiddleThreeDigits procedure %
for n := 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0 do begin
reference(MiddleThreeDigits) m3;
i_w := 10; s_w := 0; % set output formating %
m3 := findMiddleThreeDigits( n );
write( n, ": " );
if not isOk(m3) then writeon( message(m3) )
else begin
% as we return the middle three digits as an integer, we must manually 0 pad %
if middle3(m3) < 100 then writeon( "0" );
if middle3(m3) < 10 then writeon( "0" );
writeon( i_w := 1, middle3(m3) )
end
end for_n
 
end.</syntaxhighlight>
{{out}}
<pre>
123: 123
12345: 234
1234567: 345
987654321: 654
10001: 000
-10001: 000
-123: 123
-100: 100
100: 100
-12345: 234
1: Number must have at least 3 digits
2: Number must have at least 3 digits
-1: Number must have at least 3 digits
-10: Number must have at least 3 digits
2002: Number must have an odd number of digits
-2002: Number must have an odd number of digits
0: Number must have at least 3 digits
</pre>
 
=={{header|Amazing Hopper}}==
<p>VERSION 1:</p>
<syntaxhighlight lang="c">
#include <basico.h>
 
algoritmo
n=0, c=""
temp = 0, candidatos={}
'123, 12345, 1234567, 987654321, 10001, -10001,-123'
'-100, 100, -12345,1, 2, -1, -10, 2002, -2002, 0'
enlistar en 'candidatos'
decimales '0'
 
#basic{
temp = string(candidatos * sign(candidatos))
n = len( temp )
c = replicate (temp, n>=3 && not(is even(n)))
toksep(NL)
print (cat( lpad(" ",11,string(candidatos)), cat(" : ", copy( 3, (n/2-1), c ))),NL)
}
terminar
 
</syntaxhighlight>
{{out}}
<pre>
123 : 123
12345 : 234
1234567 : 345
987654321 : 654
10001 : 000
-10001 : 000
-123 : 123
-100 : 100
100 : 100
-12345 : 234
1 :
2 :
-1 :
-10 :
2002 :
-2002 :
0 :
 
</pre>
<p>VERSION 2:</p>
<syntaxhighlight lang="c">
#include <basico.h>
 
algoritmo
n=0, c="",
temp = 0, candidatos={}
'123, 12345, 1234567, 987654321, 10001, -10001,-123'
'-100, 100, -12345,1, 2, -1, -10, 2002, -2002, 0'
enlistar en 'candidatos'
decimales '0'
tomar 'candidatos', quitar el signo
convertir a cadena ---retener---, obtener largo, mover a 'n',
guardar en 'temp'
guardar ' replicar ( temp, #(n>=3 && not(is even(n))))' en 'c'
token.separador(NL)
justificar derecha(11,#(string(candidatos))), " : ", concatenar esto
#( copy( 3, (n/2-1), c ) ), unir esto
luego imprime
terminar
</syntaxhighlight>
{{out}}
<pre>
123 : 123
12345 : 234
1234567 : 345
987654321 : 654
10001 : 000
-10001 : 000
-123 : 123
-100 : 100
100 : 100
-12345 : 234
1 :
2 :
-1 :
-10 :
2002 :
-2002 :
0 :
</pre>
 
<p>VERSION 3:</p>
<syntaxhighlight lang="c">
#include <basico.h>
 
algoritmo
n=0, c="", m=0,
candidatos={}
'123, 12345, 1234567, 987654321, 10001, -10001,-123'
'-100, 100, -12345,1, 2, -1, -10, 2002, -2002, 0'
enlistar en 'candidatos'
decimales '0'
para cada elemento (v,candidatos,17)
tomar'v' ---copiar en 'm'---, quitar el signo
guardar en 'v'
#(len( c:=(string(v)) ) ), mover a 'n'
"Num: ",justificar derecha(10,#(string(m))),"(",n,")\t"
si ' #( n>=3 && not(is even(n))) '
" puede ser procesado : "
tomar si ( #(n==3), 'c', #( copy( 3, (n/2-1), c )) ), NL
sino
"no puede ser procesado\n"
fin si
luego imprime
siguiente
 
terminar
</syntaxhighlight>
{{out}}
<pre>
Num: 123(3) puede ser procesado : 123
Num: 12345(5) puede ser procesado : 234
Num: 1234567(7) puede ser procesado : 345
Num: 987654321(9) puede ser procesado : 654
Num: 10001(5) puede ser procesado : 000
Num: -10001(5) puede ser procesado : 000
Num: -123(3) puede ser procesado : 123
Num: -100(3) puede ser procesado : 100
Num: 100(3) puede ser procesado : 100
Num: -12345(5) puede ser procesado : 234
Num: 1(1) no puede ser procesado
Num: 2(1) no puede ser procesado
Num: -1(1) no puede ser procesado
Num: -10(2) no puede ser procesado
Num: 2002(4) no puede ser procesado
Num: -2002(4) no puede ser procesado
Num: 0(1) no puede ser procesado
 
</pre>
 
=={{header|AppleScript}}==
===Procedural===
987654321 is too large to be represented as an AppleScript integer, so "integer value" is taken here to refer to the numeric value rather than to the language class. AppleScript automatically coerces numeric text and single-item lists to appropriate number classes where necessary and possible, so these are acceptable as parameters too.
 
<syntaxhighlight lang="applescript">on middle3Digits(n)
try
n as number -- Errors if n isn't a number or coercible thereto.
set s to n as text -- Keep for the ouput string.
if (n mod 1 is not 0) then error (s & " isn't an integer value.")
if (n < 0) then set n to -n
if (n < 100) then error (s & " has fewer than three digits.")
-- Coercing large numbers to text may result in E notation, so extract the digit values individually.
set theDigits to {}
repeat until (n = 0)
set beginning of theDigits to n mod 10 as integer
set n to n div 10
end repeat
set c to (count theDigits)
if (c mod 2 is 0) then error (s & " has an even number of digits.")
on error errMsg
return "middle3Digits handler got an error: " & errMsg
end try
set i to (c - 3) div 2 + 1
set {x, y, z} to items i thru (i + 2) of theDigits
return "The middle three digits of " & s & " are " & ((x as text) & y & z & ".")
end middle3Digits
 
-- Test code:
set testNumbers to {123, 12345, 1234567, "987654321", "987654321" as number, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0}
set output to {}
repeat with thisNumber in testNumbers
set end of output to middle3Digits(thisNumber)
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"The middle three digits of 123 are 123.
The middle three digits of 12345 are 234.
The middle three digits of 1234567 are 345.
The middle three digits of 987654321 are 654.
The middle three digits of 9.87654321E+8 are 654.
The middle three digits of 10001 are 000.
The middle three digits of -10001 are 000.
The middle three digits of -123 are 123.
The middle three digits of -100 are 100.
The middle three digits of 100 are 100.
The middle three digits of -12345 are 234.
middle3Digits handler got an error: 1 has fewer than three digits.
middle3Digits handler got an error: 2 has fewer than three digits.
middle3Digits handler got an error: -1 has fewer than three digits.
middle3Digits handler got an error: -10 has fewer than three digits.
middle3Digits handler got an error: 2002 has an even number of digits.
middle3Digits handler got an error: -2002 has an even number of digits.
middle3Digits handler got an error: 0 has fewer than three digits."</syntaxhighlight>
 
===Functional===
<syntaxhighlight lang="applescript">-------------------- MID THREE DIGITS ---------------------
 
-- mid3digits :: Int -> Either String String
on mid3digits(n)
-- Either a message explaining why
-- no "mid 3 digits" are defined for n,
-- or the mid 3 digits themselves.
set m to abs(n)
if 100 > m then
|Left|("Less than 3 digits")
else if maxBound(1) < m then
|Left|("Out of AppleScript integer range")
else
set s to m as string
set intDigits to length of s
if even(intDigits) then
|Left|("Even digit count")
else
|Right|((items 1 thru 3 of ¬
items (1 + ((intDigits - 3) div 2)) thru -1 of s) as string)
end if
end if
end mid3digits
 
 
-------------------------- TEST ---------------------------
on run
set ints to map(readInt, splitOn(", ", ¬
"123, 12345, 1234567, 987654321, 10001, -10001, " & ¬
"-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0"))
script showResult
on |λ|(x)
either(my bracketed, my str, x)
end |λ|
end script
fTable("Mid three digits:", str, showResult, mid3digits, ints)
end run
 
 
------------------------ GENERICS -------------------------
 
-- Left :: a -> Either a b
on |Left|(x)
{type:"Either", |Left|:x, |Right|:missing value}
end |Left|
 
 
-- Right :: b -> Either a b
on |Right|(x)
{type:"Either", |Left|:missing value, |Right|:x}
end |Right|
 
 
-- abs :: Num -> Num
on abs(x)
-- Absolute value.
if 0 > x then
-x
else
x
end if
end abs
 
 
-- even :: Int -> Bool
on even(x)
0 = x mod 2
end even
 
 
-- maxBound :: a -> a
on maxBound(x)
set c to class of x
if text is c then
character id 65535
else if integer is c then
(2 ^ 29 - 1)
else if real is c then
1.797693E+308
else if boolean is c then
true
end if
end maxBound
 
 
-------------------- GENERICS FOR TEST AND DISPLAY ---------------------
 
-- bracketed :: String -> String
on bracketed(s)
"(" & s & ")"
end bracketed
 
 
-- compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
on compose(f, g)
script
property mf : mReturn(f)
property mg : mReturn(g)
on |λ|(x)
mf's |λ|(mg's |λ|(x))
end |λ|
end script
end compose
 
 
-- either :: (a -> c) -> (b -> c) -> Either a b -> c
on either(lf, rf, e)
if missing value is |Left| of e then
tell mReturn(rf) to |λ|(|Right| of e)
else
tell mReturn(lf) to |λ|(|Left| of e)
end if
end either
 
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
 
 
-- fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String
on fTable(s, xShow, fxShow, f, xs)
set ys to map(xShow, xs)
set w to maximum(map(my |length|, ys))
script arrowed
on |λ|(a, b)
justifyRight(w, space, a) & " -> " & b
end |λ|
end script
s & linefeed & unlines(zipWith(arrowed, ¬
ys, map(compose(fxShow, f), xs)))
end fTable
 
 
-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller, strText)
if n > length of strText then
text -n thru -1 of ((replicate(n, cFiller) as text) & strText)
else
strText
end if
end justifyRight
 
 
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
end if
end |length|
 
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
 
-- maximum :: Ord a => [a] -> a
on maximum(xs)
script
on |λ|(a, b)
if a is missing value or b > a then
b
else
a
end if
end |λ|
end script
foldl(result, missing value, xs)
end maximum
 
 
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
 
 
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
 
 
-- readInt :: String -> Int
on readInt(s)
s as integer
end readInt
 
 
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if 1 > n then return out
set dbl to {a}
repeat while (1 < n)
if 0 < (n mod 2) then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
 
 
-- splitOn :: String -> String -> [String]
on splitOn(pat, src)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, pat}
set xs to text items of src
set my text item delimiters to dlm
return xs
end splitOn
 
 
-- str :: a -> String
on str(x)
x as string
end str
 
 
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines
 
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
if 1 > lng then
return {}
else
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end if
end zipWith</syntaxhighlight>
{{Out}}
<pre>Mid three digits:
123 -> 123
12345 -> 234
1234567 -> 345
9.87654321E+8 -> (Out of AppleScript integer range)
10001 -> 000
-10001 -> 000
-123 -> 123
-100 -> 100
100 -> 100
-12345 -> 234
1 -> (Less than 3 digits)
2 -> (Less than 3 digits)
-1 -> (Less than 3 digits)
-10 -> (Less than 3 digits)
2002 -> (Even digit count)
-2002 -> (Even digit count)
0 -> (Less than 3 digits)</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">middleThree: function [num][
n: to :string abs num
if 3 > size n -> return "Number must have at least three digits"
if even? size n -> return "Number must have an odd number of digits"
 
middle: ((size n)/2)- 1
return slice n middle middle+2
]
 
samples: @[
123, 12345, 1234567, 987654321, 10001, neg 10001, neg 123, neg 100, 100, neg 12345,
1, 2, neg 1, neg 10, 2002, neg 2002, 0
]
 
loop samples 's [
print [pad to :string s 10 ":" middleThree s]
]</syntaxhighlight>
 
{{out}}
 
<pre> 123 : 123
12345 : 234
1234567 : 345
987654321 : 654
10001 : 000
-10001 : 000
-123 : 123
-100 : 100
100 : 100
-12345 : 234
1 : Number must have at least three digits
2 : Number must have at least three digits
-1 : Number must have at least three digits
-10 : Number must have at least three digits
2002 : Number must have an odd number of digits
-2002 : Number must have an odd number of digits
0 : Number must have at least three digits</pre>
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
#include
"share/HATS/atspre_staload_libats_ML.hats"
//
(* ****** ****** *)
//
extern
fun
int2digits(x: int): list0(int)
//
(* ****** ****** *)
 
implement
int2digits(x) =
loop(x, list0_nil) where
{
//
fun
loop
(
x: int, res: list0(int)
) : list0(int) =
if x > 0 then loop(x/10, list0_cons(x%10, res)) else res
//
} (* end of [int2digits] *)
 
(* ****** ****** *)
 
extern
fun
Middle_three_digits(x: int): void
 
(* ****** ****** *)
 
implement
Middle_three_digits
(x0) = let
//
val x1 =
(
if x0 >= 0 then x0 else ~x0
) : int
//
fun
skip
(
ds: list0(int), k: int
) : list0(int) =
if k > 0 then skip(ds.tail(), k-1) else ds
//
val ds =
int2digits(x1)
//
val n0 = length(ds)
//
in
//
if
(n0 <= 2)
then
(
println! ("Middle-three-digits(", x0, "): Too small!")
)
else
(
if
(n0 % 2 = 0)
then
(
println!
(
"Middle-three-digits(", x0, "): Even number of digits!"
)
)
else let
val ds =
skip(ds, (n0-3)/2)
val-list0_cons(d1, ds) = ds
val-list0_cons(d2, ds) = ds
val-list0_cons(d3, ds) = ds
in
println! ("Middle-three-digits(", x0, "): ", d1, d2, d3)
end // end of [else]
)
//
end // end of [Middle_three_digits]
 
(* ****** ****** *)
 
implement
main0() =
{
//
val
thePassing =
g0ofg1
(
$list{int}
(
123
, 12345
, 1234567
, 987654321
, 10001, ~10001
, ~123, ~100, 100, ~12345
)
)
val
theFailing =
g0ofg1($list{int}(1, 2, ~1, ~10, 2002, ~2002, 0))
//
val () = thePassing.foreach()(lam x => Middle_three_digits(x))
val () = theFailing.foreach()(lam x => Middle_three_digits(x))
//
} (* end of [main0] *)
 
(* ****** ****** *)
</syntaxhighlight>
{{out}}
<pre>Middle-three-digits(123): 123
Middle-three-digits(12345): 234
Middle-three-digits(1234567): 345
Middle-three-digits(987654321): 654
Middle-three-digits(10001): 000
Middle-three-digits(-10001): 000
Middle-three-digits(-123): 123
Middle-three-digits(-100): 100
Middle-three-digits(100): 100
Middle-three-digits(-12345): 234
Middle-three-digits(1): Too small!
Middle-three-digits(2): Too small!
Middle-three-digits(-1): Too small!
Middle-three-digits(-10): Too small!
Middle-three-digits(2002): Even number of digits!
Middle-three-digits(-2002): Even number of digits!
Middle-three-digits(0): Too small!</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Numbers:="123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0"
Loop, parse, Numbers, `,
{
Line 269 ⟶ 1,121:
log := log . A_LoopField . "`t: " . SubStr(n,((d-3)//2)+1,3) . "`n"
}
MsgBox % log</langsyntaxhighlight>
{{out}}
<pre>123 : 123
Line 290 ⟶ 1,142:
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk">#!/bin/awk -f
# use as: awk -f middle_three_digits.awk
 
Line 318 ⟶ 1,170:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 342 ⟶ 1,194:
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">100 DEF FN L(N) = LEN(STR$(INT(ABS(N))))
110 DEF FN N(N) = VAL(MID$(STR$(INT(ABS(N))),(FN L(N)-1)/2,3))
120 DEF FN EVEN(N) = INT(N/2) = N/2
Line 364 ⟶ 1,216:
300 DATA123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345
310 DATA1,2,-1,-10,2002,-2002,0
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 385 ⟶ 1,237:
0: ?ONLY 1 DIGIT
</pre>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="vb">function middleThreeDigits(n)
if n < 0 then n = -n
if n < 100 then return "" ## error code
if n < 1000 then return string(n)
if n < 10000 then return ""
ns = string(n)
if length(ns) mod 2 = 0 then return "" ## need to have an odd number of digits for there to be 3 middle
return mid(ns, length(ns) \ 2, 3)
end function
 
dim a = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -123451, 2, -1, -10, 2002, -2002, 0}
 
print "The 3 middle digits of the following numbers are : "
print
for i = 0 to 15
result = middleThreeDigits(a[i])
print a[i]; chr(9); " => ";
if result <> "" then
print result
else
print "Error: does not have 3 middle digits"
end if
next</syntaxhighlight>
{{out}}
<pre>Similar to FreeBASIC entry.</pre>
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic">REM >midthree
FOR i% = 1 TO 17
READ test%
Line 407 ⟶ 1,286:
OTHERWISE
= MID$(n$, LEN n$ / 2, 3)
ENDCASE</langsyntaxhighlight>
{{out}}
<pre> 123 -> 123
Line 428 ⟶ 1,307:
 
==={{header|FBSL}}===
<langsyntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
DIM numbers AS STRING = "123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0"
Line 472 ⟶ 1,351:
RETURN m
END IF
END FUNCTION</langsyntaxhighlight>
Output
<pre> 123 --> 123
Line 493 ⟶ 1,372:
 
Press any key to continue...</pre>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 INPUT PROMPT "Number: ":N
120 PRINT MIDDLE$(N)
130 DEF MIDDLE$(N)
140 LET N$=STR$(ABS(N))
150 IF LEN(N$)<3 THEN LET MIDDLE$="Not enough digits":EXIT DEF
160 IF MOD(LEN(N$),2)=0 THEN LET MIDDLE$="Even number of digits":EXIT DEF
170 LET P=(LEN(N$)-3)/2
180 LET MIDDLE$=N$(P+1:P+3)
190 END DEF</syntaxhighlight>
 
 
==={{header|PureBasic}}===
<langsyntaxhighlight lang="purebasic">Procedure.s middleThreeDigits(x.q)
Protected x$, digitCount
 
Line 522 ⟶ 1,413:
Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre> 123 : 123
Line 543 ⟶ 1,434:
 
==={{header|Run BASIC}}===
<langsyntaxhighlight lang="runbasic">x$ = "123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0"
 
while word$(x$,i+1,",") <> ""
Line 555 ⟶ 1,446:
end if
wend
end</langsyntaxhighlight>
<pre>123 123
234 12345
Line 573 ⟶ 1,464:
-2002 length < 3 or is even
0 length < 3 or is even</pre>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="vb">sub middleThreeDigits$ (n)
if n < 0 n = -n
if n < 100 return "" // error code
if n < 1000 return str$(n)
if n < 10000 return ""
ns$ = str$(n)
if mod(len(ns$), 2) = 0 return "" // need to have an odd number of digits for there to be 3 middle
return mid$(ns$, len(ns$) / 2, 3)
end sub
 
dim a(16)
a(0) = 123 : a(1) = 12345 : a(2) = 1234567
a(3) = 987654321 : a(4) = 10001 : a(5) = -10001
a(6) = -123 : a(7) = -100 : a(8) = 100
a(9) = -123451
a(10) = 2 : a(11) = -1 : a(12) = -10
a(13) = 2002 : a(14) = -2002 : a(15) = 0
 
print "The 3 middle digits of the following numbers are : \n"
 
for i = 1 to 16
result$ = middleThreeDigits$(a(i))
print a(i), "\t => ";
if result$ <> "" then
print result$
else
print "Error: does not have 3 middle digits"
fi
next</syntaxhighlight>
{{out}}
<pre>Similar to FreeBASIC entry.</pre>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
Line 620 ⟶ 1,544:
)
goto :EOF
%==/The Procedure ==%</langsyntaxhighlight>
{{Out}}
<pre>123: 123
Line 641 ⟶ 1,565:
 
Press any key to continue . . .</pre>
 
 
=={{header|Befunge}}==
Reads the integer value from stdin and writes the middle three digits (or an error message) to stdout.
 
<langsyntaxhighlight lang="befunge">>&>:0`2*1-*0>v
v+*86%+55:p00<
>\55+/:00g1+\|
Line 653 ⟶ 1,576:
2^,+55_,#!>#:<
>/>\#<$#-:#1_v
>_@#<,+55,,,$<</langsyntaxhighlight>
 
{{out}} (multiple runs)
Line 692 ⟶ 1,615:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ( middle3
= x p
. @(!arg:? [?p:? [(1/2*!p+-3/2) %?x [(1/2*!p+3/2) ?)
Line 707 ⟶ 1,630:
&
);
</syntaxhighlight>
</lang>
Output:
<pre>123
Line 729 ⟶ 1,652:
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="blsq">
blsq ) {123 12345 1234567 987654321 -10001 -123}{XX{~-}{L[3.>}w!m]\[}m[uN
123
Line 737 ⟶ 1,660:
000
123
</syntaxhighlight>
</lang>
 
<tt>m]\[</tt> and <tt>uN</tt> are just for displaying it nicely.
Line 743 ⟶ 1,666:
=={{header|C}}==
This code is followed by its output.
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 775 ⟶ 1,698:
}
return 0;
}</langsyntaxhighlight>
 
<pre>
Line 799 ⟶ 1,722:
===Alternative Version===
This code has been extensively rewritten. The original was purely interactive and had to be invoked each time from the console. It also did not produce the correct answer.
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 855 ⟶ 1,778:
}
}</langsyntaxhighlight>
 
{{out}}
Line 879 ⟶ 1,802:
Error, 0 is too short.
The middle three digits of 1234567890 are 456.
</pre>
 
=={{header|C_sharp|C#}}==
<lang csharp>using System;
 
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();
Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3));
}
}
}</lang>
{{out}}
<pre>123:123
12345:234
1234567:345
987654321:654
10001:000
-10001:000
-123:123
-100:100
100:100
-12345:234
 
1:Error
2:Error
-1:Error
-10:Error
2002:Error
-2002:Error
0:Error
</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
 
std::string middleThreeDigits(int n)
Line 944 ⟶ 1,832:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>middleThreeDigits(123): 123
Line 963 ⟶ 1,851:
middleThreeDigits(-2002): even number of digits
middleThreeDigits(0): less than three digits</pre>
 
=={{header|C_sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
 
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
string text = Math.Abs(int.Parse(Console.ReadLine())).ToString();
Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3));
}
}
}</syntaxhighlight>
{{out}}
<pre>123:123
12345:234
1234567:345
987654321:654
10001:000
-10001:000
-123:123
-100:100
100:100
-12345:234
 
1:Error
2:Error
-1:Error
-10:Error
2002:Error
-2002:Error
0:Error
</pre>
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">(defn middle3
<lang Clojure>
(defn middle3 [v]
(let [nodigit-str (str (Math/abs v))
digitslen (strcount nodigit-str)]
len (count digits)]
(cond
(< len 3) :too_shorttoo-short
(even? len) :no_middle_in_even_no_of_digitseven-digit-count
:else (let [midhalf (/ len 2)]
(subs digit-str (- half start1) (-+ midhalf 2)])))))
(apply str
(take 3
(nthnext digits start)))))))
 
(clojure.pprint/print-table
(def passes '(123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345))
(for [i [123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
(def fails '(1 2 -1 -10 2002 -2002 0))
1 2 -1 -10 2002 -2002 0]]
 
{:i i :middle-3 (middle3 i)}))
</lang>
</syntaxhighlight>
 
{{out}}
<pre>
| :i | :middle-3 |
user=> (map middle3 passes)
|-----------+-------------------|
("123" "234" "345" "654" "000" "000" "123" "100" "100" "234")
| 123 | 123 |
user=> (map middle3 fails)
| 12345 | 234 |
(:too_short :too_short :too_short :too_short :no_middle_in_even_no_of_digits :no_middle_in_even_no_of_digits :too_short)
| 1234567 | 345 |
| 987654321 | 654 |
| 10001 | 000 |
| -10001 | 000 |
| -123 | 123 |
| -100 | 100 |
| 100 | 100 |
| -12345 | 234 |
| 1 | :too-short |
| 2 | :too-short |
| -1 | :too-short |
| -10 | :too-short |
| 2002 | :even-digit-count |
| -2002 | :even-digit-count |
| 0 | :too-short |
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">middle_three_digits = proc (n: int) returns (string)
signals (too_small, even_length)
s: string := int$unparse(int$abs(n))
if string$size(s) < 3 then signal too_small end
if string$size(s) // 2 = 0 then signal even_length end
return(string$substr(s, string$size(s)/2, 3))
end middle_three_digits
 
start_up = proc ()
po: stream := stream$primary_output()
tests: sequence[int] := sequence[int]$
[123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,
1,2,-1,-10,2002,-2002,0]
for test: int in sequence[int]$elements(tests) do
stream$putright(po, int$unparse(test) || ": ", 11)
stream$putl(po, middle_three_digits(test))
except
when too_small: stream$putl(po, "Too small")
when even_length: stream$putl(po, "Even length")
end
end
end start_up</syntaxhighlight>
{{out}}
<pre> 123: 123
12345: 234
1234567: 345
987654321: 654
10001: 000
-10001: 000
-123: 123
-100: 100
100: 100
-12345: 234
1: Too small
2: Too small
-1: Too small
-10: Too small
2002: Even length
-2002: Even length
0: Too small</pre>
 
=={{header|COBOL}}==
<langsyntaxhighlight COBOLlang="cobol">identification division.
program-id. middle3.
environment division.
Line 1,083 ⟶ 2,062:
add 1 to digit-counter
end-perform.
exit paragraph.</langsyntaxhighlight>
Output
<pre> 123 --> 123
Line 1,103 ⟶ 2,082:
0 --> Number too small</pre>
Optimised version
<langsyntaxhighlight lang="cobol">identification division.
program-id. middle3.
environment division.
Line 1,175 ⟶ 2,154:
end-if.
 
</syntaxhighlight>
</lang>
Output
<pre> 123 --> 123
Line 1,197 ⟶ 2,176:
 
=={{header|Common Lisp}}==
===Solution #1===
<lang lisp>
<syntaxhighlight lang="lisp">
(defun mid3 (n)
(let ((a (abs n))
Line 1,210 ⟶ 2,190:
((evenp hmd) (need "odd number of"))
(t (nbr (mod (truncate a (expt 10 (/ (- hmd 3) 2))) 1000)))))))
</syntaxhighlight>
</lang>
 
Test code:
 
<langsyntaxhighlight lang="lisp">
(loop as n in '(123 12345 1234567 987654321
10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0)
do (format t "~d:~12t~a~%" n (mid3 n)))
</syntaxhighlight>
</lang>
{{out}}
<pre>123: 123
Line 1,238 ⟶ 2,218:
-2002: Need odd number of digits, not 4.
0: Zero is 1 digit</pre>
 
===Solution #2===
<syntaxhighlight lang="lisp">
(defun mid3 (i)
(let ((ch-vec (coerce (format nil "~A" (abs i)) 'vector)))
(when (evenp (length ch-vec))
(return-from mid3
(format nil "Error: The number representation must have an odd ~
number of digits.")))
 
(when (and (< i 100)
(> i -100))
(return-from mid3
(format nil "Error: Must be >= 100 or <= -100.")))
(let ((half (/ (1- (length ch-vec)) 2)))
(return-from mid3 (format nil "~A~A~A"
(elt ch-vec (1- half))
(elt ch-vec half)
(elt ch-vec (1+ half))))
)))
</syntaxhighlight>
 
Test code:
 
<syntaxhighlight lang="lisp">
(defun test-mid3 ()
(let ((test-lst (list 123
12345
1234567
987654321
10001
-10001
-123
-100
100
-12345
1
2
-1
-10
2002
-2002
0
)))
(labels
((run-tests (lst)
(cond ((null lst)
nil)
 
(t
(format t "~A ~15T ~A~%" (first lst) (mid3 (first lst)))
(run-tests (rest lst))))))
 
(run-tests test-lst)))
(values)
)
</syntaxhighlight>
{{out}}
<pre>
123 123
12345 234
1234567 345
987654321 654
10001 000
-10001 000
-123 123
-100 100
100 100
-12345 234
1 Error: Must be >= 100 or <= -100.
2 Error: Must be >= 100 or <= -100.
-1 Error: Must be >= 100 or <= -100.
-10 Error: The number representation must have an odd number of digits.
2002 Error: The number representation must have an odd number of digits.
-2002 Error: The number representation must have an odd number of digits.
0 Error: Must be >= 100 or <= -100.
</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.traits, std.conv;
 
string middleThreeDigits(T)(in T n) pure nothrow if (isIntegral!T) {
Line 1,260 ⟶ 2,317:
foreach (immutable n; failing)
writefln("middleThreeDigits(%s): %s", n, middleThreeDigits(n));
}</langsyntaxhighlight>
{{out}}
<pre>middleThreeDigits(123): 123
Line 1,286 ⟶ 2,343:
===Alternative Version===
This longer version gives a stronger typed output, and it tries to be faster avoiding conversions to string.
<langsyntaxhighlight lang="d">import std.stdio, std.traits, std.math, std.variant;
 
/// Returns a string with the error, or the three digits.
Line 1,372 ⟶ 2,429:
writefln("middleThreeDigits(cast(short)%d): %s", n, mtd);
}
}</langsyntaxhighlight>
{{out}}
<pre>middleThreeDigits(123): 123
Line 1,421 ⟶ 2,478:
 
middleThreeDigits(cast(short)-32768): 276</pre>
 
=={{header|Dart}}==
<syntaxhighlight lang="text">
import'dart:math';
int length(int x)
{
int i,y;
for(i=0;;i++)
{
y=pow(10,i);
if(x%y==x)
break;
}
return i;
}
int middle(int x,int l)
{
int a=(x/10)-((x%10)/10);
int b=a%(pow(10,l-2));
int l2=length(b);
if(l2==3)
{
return b;
}
if(l2!=3)
{
return middle(b,l2);
}
return 0;
}
 
main()
{
int x=-100,y;
if(x<0)
x=-x;
int l=length(x);
if(l.isEven||x<100)
{print('error');}
if(l==3)
{print('$x');}
if(l.isOdd&& x>100)
{
y=middle(x,l);
print('$y');
}
}
</syntaxhighlight>
 
=={{header|DCL}}==
<syntaxhighlight lang="text">$ list = "123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0"
$ i = 0
$ loop:
Line 1,437 ⟶ 2,544:
$ endif
$ i = i + 1
$ goto loop</langsyntaxhighlight>
{{out}}
<pre>$ @middle_three_digits
Line 1,457 ⟶ 2,564:
-2002: has no middle three
0: has no middle three</pre>
 
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Middle_three_digits#Pascal Pascal].
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
func$ midThreeDigits num .
trueNumber$ = abs num
if (len trueNumber$ < 3) or (len trueNumber$ mod 2 = 0)
r$ = "error"
else
r$ = substr trueNumber$ ((len trueNumber$ - 3) / 2 + 1) 3
.
return r$
.
numbers[] = [ 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0 ]
for i in numbers[]
print midThreeDigits i
.
</syntaxhighlight>
{{out}}
<pre>
123
234
345
654
000
000
123
100
100
234
error
error
error
error
error
error
error
</pre>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 1,521 ⟶ 2,668:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,542 ⟶ 2,689:
The middle three digits of 0 are: Not enough digits.
 
</pre>
 
=={{header|Elena}}==
ELENA 6.x :
<syntaxhighlight lang="elena">import system'routines;
import extensions;
middleThreeDigits(int n)
{
string s := n.Absolute.toString();
int len := s.Length;
if(len<3)
{
InvalidArgumentException.new("n must have 3 digits or more").raise()
}
else if(len.isEven())
{
InvalidArgumentException.new("n must have an odd number of digits").raise()
};
int mid := len / 2;
^ s.Substring(mid-1,3)
}
public program()
{
new int[]{123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0}
.forEach::(n)
{
console.printLine("middleThreeDigits(",n,"):",middleThreeDigits(n) \\ on::(e => e.Message))
}
}</syntaxhighlight>
{{out}}
<pre>
middleThreeDigits(123):123
middleThreeDigits(12345):234
middleThreeDigits(1234567):345
middleThreeDigits(987654321):654
middleThreeDigits(10001):000
middleThreeDigits(-10001):000
middleThreeDigits(-123):123
middleThreeDigits(-100):100
middleThreeDigits(100):100
middleThreeDigits(-12345):234
middleThreeDigits(1):n must have 3 digits or more
middleThreeDigits(2):n must have 3 digits or more
middleThreeDigits(-1):n must have 3 digits or more
middleThreeDigits(-10):n must have 3 digits or more
middleThreeDigits(2002):n must have an odd number of digits
middleThreeDigits(-2002):n must have an odd number of digits
middleThreeDigits(0):n must have 3 digits or more
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight Elixirlang="elixir">defmodule Middle do
def three(num) do
n = num |> abs |> to_string
Line 1,574 ⟶ 2,773:
e -> IO.puts e.message
end
end)</langsyntaxhighlight>
 
{{out}}
Line 1,598 ⟶ 2,797:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">%
-module(middle_three_digits).
-export([main/0]).
Line 1,637 ⟶ 2,836:
loop(X,N) when X>0 ->
loop(X-1, N div 10).
</syntaxhighlight>
</lang>
{{out}}
<pre>123
Line 1,660 ⟶ 2,859:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM MIDDLE
 
Line 1,705 ⟶ 2,904:
END FOR
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,725 ⟶ 2,924:
-2002 ?EVEN
0 ?ONLY 1 DIGITS
</pre>
 
=={{header|Factor}}==
<syntaxhighlight lang="text">USING: combinators formatting io kernel math math.parser
sequences ;
IN: rosetta-code.middle-three-digits
 
CONSTANT: test-values {
123 12345 1234567 987654321 10001 -10001
-123 -100 100 -12345 1 2 -1 -10 2002 -2002 0
}
 
: (middle-three) ( str -- str' )
[ midpoint@ [ 1 - ] [ 2 + ] bi ] [ subseq ] bi ;
: too-short ( -- )
"Number must have at least three digits." print ;
: number-even ( -- )
"Number must have an odd number of digits." print ;
 
: middle-three ( n -- )
abs number>string {
{ [ dup length 3 < ] [ drop too-short ] }
{ [ dup length even? ] [ drop number-even ] }
[ (middle-three) print ]
} cond ;
: main ( -- )
test-values [ dup "%9d : " printf middle-three ] each ;
 
MAIN: main</syntaxhighlight>
{{out}}
<pre>
123 : 123
12345 : 234
1234567 : 345
987654321 : 654
10001 : 000
-10001 : 000
-123 : 123
-100 : 100
100 : 100
-12345 : 234
1 : Number must have at least three digits.
2 : Number must have at least three digits.
-1 : Number must have at least three digits.
-10 : Number must have at least three digits.
2002 : Number must have an odd number of digits.
-2002 : Number must have an odd number of digits.
0 : Number must have at least three digits.
</pre>
 
=={{header|Forth}}==
This is a problem, which is easily solved in Forth. It converts the number to a string and checks it length. If the number does not represent a printable string, it returns an empty string.
<langsyntaxhighlight lang="forth">: middle3 ( n1 -- a n2)
abs s>d <# #s #> dup 2/ 0<> over 1 and 0<> and
if 2/ 1- chars + 3 else drop 0 then
;</langsyntaxhighlight>
 
=={{header|Fortran}}==
Please find compilation instructions along with the output for the examples in the comments at the beginning of the file. This program was produced in an Ubuntu distribution of the GNU/linux system.
<syntaxhighlight lang="fortran">
<lang FORTRAN>
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sat Jun 1 14:48:41
Line 1,809 ⟶ 3,060:
 
end program MiddleMuddle
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function middleThreeDigits (n As Integer) As String
If n < 0 Then n = -n
If n < 100 Then Return "" '' error code
If n < 1000 Then Return Str(n)
If n < 10000 Then Return ""
Dim ns As String = Str(n)
If Len(ns) Mod 2 = 0 Then Return "" '' need to have an odd number of digits for there to be 3 middle
Return Mid(ns, Len(ns) \ 2, 3)
End Function
 
Dim a(1 To 16) As Integer => _
{123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -123451, 2, -1, -10, 2002, -2002, 0}
 
Dim As Integer i
Dim As String result
 
Print "The 3 middle digits of the following numbers are : "
Print
For i = 1 To 16
result = middleThreeDigits(a(i))
Print a(i), " => ";
If result <> "" Then
Print result
Else
Print "Error: does not have 3 middle digits"
End If
Next
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
The 3 middle digits of the following numbers are :
 
123 => 123
12345 => 234
1234567 => 345
987654321 => 654
10001 => 000
-10001 => 000
-123 => 123
-100 => 100
100 => 100
-123451 => Error: does not have 3 middle digits
2 => Error: does not have 3 middle digits
-1 => Error: does not have 3 middle digits
-10 => Error: does not have 3 middle digits
2002 => Error: does not have 3 middle digits
-2002 => Error: does not have 3 middle digits
0 => Error: does not have 3 middle digits
</pre>
 
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn MiddleThreeDigits( n as NSInteger ) as CFStringRef
CFStringRef testStr, resultStr
NSInteger length, middle
testStr = fn StringWithFormat( @"%ld", n )
testStr = fn StringByReplacingOccurrencesOfString( testStr, @"-", @"" )
length = len(testStr)
if length < 3 then resultStr = fn StringWithFormat( @"%10ld -> Error: Less than three digits.", n ) : exit fn
if length == 3 then resultStr = fn StringWithFormat( @"%10ld -> %@", n, testStr ) : exit fn
length = len(testStr)
if ( length mod 2 == 0 )
resultStr = fn StringWithFormat( @"%10ld -> Error: Even length; needs odd.", n )
else
middle = length / 2
resultStr = fn StringWithFormat( @"%10ld -> %@", n, mid( testStr, middle -1, 3 ) )
end if
end fn = resultStr
 
window 1, @"Middle Three Digits", ( 0, 0, 400, 300 )
 
NSUInteger i, count
CFArrayRef testArr
CFNumberRef tempNum
 
testArr = @[@123,@12345,@1234567,@987654321,@10001,@-10001,¬
@-123,@-100,@100,@-12345,@1,@2,@-1,@-10,@2002,@-2002,@0]
 
count = fn ArrayCount( testArr )
for i = 0 to count - 1
print fn MiddleThreeDigits( fn NumberIntegerValue( testArr[i] ) )
next
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre style="font-size: 13px">
123 -> 123
12345 -> 234
1234567 -> 345
987654321 -> 654
10001 -> 000
-10001 -> 000
-123 -> 123
-100 -> 100
100 -> 100
-12345 -> 234
1 -> Error: Less than three digits.
2 -> Error: Less than three digits.
-1 -> Error: Less than three digits.
-10 -> Error: Less than three digits.
2002 -> Error: Even length; needs odd.
-2002 -> Error: Even length; needs odd.
0 -> Error: Less than three digits.
</pre>
 
 
 
 
 
 
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=ed25e84978446d65895ccd909fc092fa Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim iList As Integer[] = [123, 12345, 1234567, 987654321, 10001,
-10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0] 'Array of integers to process
Dim sTemp As String 'Temp string
Dim siCount As Short 'Counter
Dim sAnswer As New String[] 'Array, resons for failure or 'middle three digits'
 
For siCount = 0 To iList.Max 'Loop through the integers
sTemp = Str(Abs(iList[siCount])) 'Convert integer to positive and place in sTemp as a string
If Len(sTemp) < 3 Then 'If sTemp has less than 3 characters then..
sAnswer.Add("This integer has less than 3 characters") 'Place text in sAnswers
Else If Even(Len(sTemp)) Then 'Else If sTemp is of even length then
sAnswer.Add("This integer has an even length") 'Place text in sAnswers
Else 'Else..
sAnswer.Add(Mid(sTemp, Int(Len(sTemp) / 2), 3)) 'Place the middle 3 digits in sAnswer
Endif
Next
 
For siCount = 0 To iList.Max 'Loop through the integers
Print Space$(10 - Len(Str(iList[siCount]))) &
iList[siCount] & " : " & sAnswer[siCount] 'Print out results
Next
 
End</syntaxhighlight>
Output:
<pre>
12345 : 234
1234567 : 345
987654321 : 654
10001 : 000
-10001 : 000
-123 : 123
-100 : 100
100 : 100
-12345 : 234
1 : This integer has less than 3 characters
2 : This integer has less than 3 characters
-1 : This integer has less than 3 characters
-10 : This integer has less than 3 characters
2002 : This integer has an even length
-2002 : This integer has an even length
0 : This integer has less than 3 characters
</pre>
 
=={{header|Go}}==
Line 1,815 ⟶ 3,233:
 
File m3.go:
<langsyntaxhighlight lang="go">package m3
 
import (
Line 1,840 ⟶ 3,258:
m := len(s) / 2
return s[m-1 : m+2], nil
}</langsyntaxhighlight>
File m3_test.go:
<langsyntaxhighlight lang="go">package m3_test
 
import (
Line 1,900 ⟶ 3,318:
t.Logf("d(%d) returns %q", tc.i, err)
}
}</langsyntaxhighlight>
{{out}}
Output of go test is normally terse:
Line 1,930 ⟶ 3,348:
PASS
ok m3 0.008s
</pre>
 
=={{header|Gosu}}==
<syntaxhighlight lang="gosu">var valid = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345}
valid.each(\ num ->print(middleThree(num)))
 
var errant = {1, 2, -1, -10, 2002, -2002, 0}
errant.each(\ num ->print(middleThree(num)))
 
function middleThree(x: int) : String {
var s = Math.abs(x) as String
if(s.length < 3) return "Error: ${x} has less than 3 digits"
if(s.length % 2 == 0) return "Error: ${x} has an even number of digits"
var start = (s.length / 2) - 1
return s.substring(start, start + 3)
}</syntaxhighlight>
 
{{Output}}
<pre>123
234
345
654
000
000
123
100
100
234
Error: 1 has less than 3 digits
Error: 2 has less than 3 digits
Error: -1 has less than 3 digits
Error: -10 has less than 3 digits
Error: 2002 has an even number of digits
Error: -2002 has an even number of digits
Error: 0 has less than 3 digits
</pre>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def middleThree(Number number) {
def text = Math.abs(number) as String
assert text.size() >= 3 : "'$number' must be more than 3 numeric digits"
Line 1,940 ⟶ 3,393:
int start = text.size() / 2 - 1
text[start..(start+2)]
}</langsyntaxhighlight>
Test Code:
<langsyntaxhighlight lang="groovy">[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0].each { number ->
def text = (number as String).padLeft(10)
try {
Line 1,949 ⟶ 3,402:
println "$text cannot be converted: $error.message"
}
}</langsyntaxhighlight>
Output:
<pre> 123: 123
Line 1,970 ⟶ 3,423:
 
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">------------------- MIDDLE THREE DIGITS ------------------
<lang haskell>import Numeric
 
mid3 :: Integral a => aInt -> Either String String
mid3 n
mid3 n | m < 100 = Left "is too small"
| m < even l100 = Left "has an even number oftoo digitssmall"
| even lng = Left "even number of digits"
| otherwise = Right . take 3 $ drop ((l-3) `div` 2) s
| otherwise = Right . take 3 $ drop ((lng - 3) `div` 2) s
where m = abs n
where
s = showInt m ""
lm = lengthabs sn
s = show m
 
lng = length s
showMid3 :: Integer -> String
showMid3 n = show n ++ ": " ++ either id id (mid3 n)
 
--------------------------- TEST -------------------------
main :: IO ()
main = do
main = mapM_ (putStrLn . showMid3) [
let xs =
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0]</lang>[ 123
, 12345
, 1234567
, 987654321
, 10001
, -10001
, -123
, -100
, 100
, -12345
, 1
, 2
, -1
, -10
, 2002
, -2002
, 0
]
w = maximum $ length . show <$> xs
(putStrLn . unlines) $
(\n ->
justifyRight w ' ' (show n) <>
" -> " <> either (concat . ("(" :) . (: [")"])) id (mid3 n)) <$>
xs
 
justifyRight :: Int -> Char -> String -> String
justifyRight n c = (drop . length) <*> (replicate n c <>)</syntaxhighlight>
Output:
<pre> 123: -> 123
12345: -> 234
1234567: -> 345
987654321: -> 654
10001: -> 000
-10001: -> 000
-123: -> 123
-100: -> 100
100: -> 100
-12345: -> 234
1: is-> (too small)
2: is-> (too small)
-1: is-> (too small)
-10: is-> (too small)
2002: has an 2002 -> (even number of digits)
-2002: has an-> (even number of digits)
0: is-> (too small)</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 2,010 ⟶ 3,489:
The following solution works in both languages.
 
<langsyntaxhighlight lang="unicon">procedure main(a)
every n := !a do write(right(n,15)," -> ",midM(n))
end
Line 2,021 ⟶ 3,500:
else "wrong number of digits"
else "too short"
end</langsyntaxhighlight>
 
with output:
Line 2,046 ⟶ 3,525:
 
=={{header|J}}==
 
A key issue here is that some numbers do not have a "middle 3 digits" -- either because the number is too short, or because it has an even number of digits (or both, two digit numbers).
 
'''Solution:'''
<langsyntaxhighlight lang="j">asString=: ":"0 NB. convert vals to strings
getPfxSize=: [: -:@| 3 -~ # NB. get size of prefix to drop before the 3 middle digits
getMid3=: (3 {. getPfxSize }. ,&'err') :: ('err'"_) NB. get 3 middle digits or return 'err'
getMiddle3=: getMid3@asString@:|</langsyntaxhighlight>
'''Example:'''
<langsyntaxhighlight lang="j"> vals=: 123 12345 1234567 987654321 10001 _10001 _123 _100 100 _12345 1 2 _1 _10 2002 _2002 0
getMiddle3 vals
123
Line 2,070 ⟶ 3,552:
err
err
err</langsyntaxhighlight>
 
Or, expressed more concisely:<syntaxhighlight lang="j"> ({~ 2 1 0 -~ -:@>:@#) ::('err'"_)@":@| vals
123
234
345
654
000
000
123
100
100
234
err
err
err
err
err
err
err</syntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight Javalang="java">public class MiddleThreeDigits {
 
public static void main(String[] args) {
Line 2,099 ⟶ 3,600:
return s.substring(mid - 1, mid + 2);
}
}</langsyntaxhighlight>
<pre>middleThreeDigits(123): 123
middleThreeDigits(12345): 234
Line 2,123 ⟶ 3,624:
 
=={{header|JavaScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">function middleThree(x){
var n=''+Math.abs(x); var l=n.length-1;
if(l<2||l%2) throw new Error(x+': Invalid length '+(l+1));
Line 2,132 ⟶ 3,633:
1, 2, -1, -10, 2002, -2002, 0].forEach(function(n){
try{console.log(n,middleThree(n))}catch(e){console.error(e.message)}
});</langsyntaxhighlight>
 
<pre>123 "123"
Line 2,151 ⟶ 3,652:
-2002: Invalid length 4
0: Invalid length 1</pre>
 
 
Or, using an option type, composing a solution from existing generic primitives, and formatting the output a little:
{{Trans|Python}}
<syntaxhighlight lang="javascript">(() => {
'use strict';
 
// mid3digits :: Int -> Either String String
const mid3digits = n => {
const
m = abs(n),
s = m.toString();
return 100 > m ? (
Left('Less than 3 digits')
) : even(length(s)) ? (
Left('Even digit count')
) : Right(take(3, drop(quot(length(s) - 3, 2), s)));
};
 
// TEST -----------------------------------------------
const main = () => {
const
xs = [
123, 12345, 1234567, 987654321, 10001, -10001, -123,
-100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0
],
w = maximum(map(x => x.toString().length, xs));
return (
unlines(map(
n => justifyRight(w, ' ', n.toString()) + ' -> ' +
either(
s => '(' + s + ')',
id,
mid3digits(n)
),
xs
))
);
};
 
// GENERIC FUNCTIONS ----------------------------------
 
// Left :: a -> Either a b
const Left = x => ({
type: 'Either',
Left: x
});
 
// Right :: b -> Either a b
const Right = x => ({
type: 'Either',
Right: x
});
 
// abs :: Num -> Num
const abs = Math.abs;
 
// drop :: Int -> [a] -> [a]
// drop :: Int -> Generator [a] -> Generator [a]
// drop :: Int -> String -> String
const drop = (n, xs) =>
Infinity > length(xs) ? (
xs.slice(n)
) : (take(n, xs), xs);
 
// either :: (a -> c) -> (b -> c) -> Either a b -> c
const either = (fl, fr, e) =>
'Either' === e.type ? (
undefined !== e.Left ? (
fl(e.Left)
) : fr(e.Right)
) : undefined;
 
// even :: Int -> Bool
const even = n => 0 === n % 2;
 
// foldl1 :: (a -> a -> a) -> [a] -> a
const foldl1 = (f, xs) =>
1 < xs.length ? xs.slice(1)
.reduce(f, xs[0]) : xs[0];
 
// id :: a -> a
const id = x => x;
 
// justifyRight :: Int -> Char -> String -> String
const justifyRight = (n, cFiller, s) =>
n > s.length ? (
s.padStart(n, cFiller)
) : s;
 
// Returns Infinity over objects without finite length.
// This enables zip and zipWith to choose the shorter
// argument when one is non-finite, like cycle, repeat etc
 
// length :: [a] -> Int
const length = xs =>
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
 
// maximum :: Ord a => [a] -> a
const maximum = xs =>
0 < xs.length ? (
foldl1((a, x) => x > a ? x : a, xs)
) : undefined;
 
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
 
// quot :: Int -> Int -> Int
const quot = (n, m) => Math.floor(n / m);
 
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = (n, xs) =>
'GeneratorFunction' !== xs.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
 
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
 
// MAIN ---
return main();
})();</syntaxhighlight>
{{Out}}
<pre>
123 -> 123
12345 -> 234
1234567 -> 345
987654321 -> 654
10001 -> 000
-10001 -> 000
-123 -> 123
-100 -> 100
100 -> 100
-12345 -> 234
1 -> (Less than 3 digits)
2 -> (Less than 3 digits)
-1 -> (Less than 3 digits)
-10 -> (Less than 3 digits)
2002 -> (Even digit count)
-2002 -> (Even digit count)
0 -> (Less than 3 digits)</pre>
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">def middle3:
if . < 0 then -. else . end
| tostring as $s
Line 2,162 ⟶ 3,812:
 
(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0)
| "\(.) => \( .|middle3 )"</langsyntaxhighlight>
Typescript:<langsyntaxhighlight lang="sh"> $ jq -r -n -f Middle_three_digits.jq
123 => 123
12345 => 234
Line 2,180 ⟶ 3,830:
2002 => invalid length: 4
-2002 => invalid length: 4
0 => invalid length: 1 </langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|1.0.3}}
<lang julia>function middle(i)
s = string(abs(i))
l = length(s)
mid = round(Int,(l+1)/2)
l < 3 ?
"error: not enough digits" :
iseven(l) ?
"error: number of digits is even" :
s[mid-1:mid+1]
end
 
<syntaxhighlight lang="julia">using Printf
julia>
 
function middle3(n::Integer)
l = ndigits(n)
iseven(l) && error("n must have an odd number of digits")
l < 3 && error("n must have 3 digits or more")
mid = (l + 1) ÷ 2
abs(n) ÷ 10^(mid-2) % 10^3
end
 
for n = [123, 12345, 1234567, 987654321, 10001, -10001, -123,
-100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0]
println (@sprintfprintf("%10d :-> %s\n", n), middletry middle3(n) catch e e.msg end)
end</langsyntaxhighlight>
 
{{out}}
'''Output'''
<pre> 123 :-> 123
12345 :-> 234
1234567 :-> 345
987654321 :-> 654
10001 :-> 000
-10001 :-> 000
-123 :-> 123
-100 :-> 100
100 :-> 100
-12345 :-> 234
1 :-> error:n notmust enoughhave 3 digits or more
2 :-> error:n notmust enoughhave 3 digits or more
-1 :-> error:n notmust enoughhave 3 digits or more
-10 :-> error:n notmust enoughhave an odd number of digits
2002 :-> error:n must have an odd number of digits is even
-2002 :-> error:n must have an odd number of digits is even
0 :-> error:n notmust enoughhave 3 digits or more</pre>
 
=={{header|K}}==
<syntaxhighlight lang="k">
/ Rosetta code - Middle three digits
/ mid3.k
mid3: {qs:$x;:[qs[0]="-";qs: 1 _ qs];:[(#qs)<3;:"small";(1+#qs)!2;:"even"];p:(-3+#qs)%2;:(|p _|p _ qs)}
</syntaxhighlight>
The output of the session:
{{out}}
<pre>
K Console - Enter \ for help
 
\l mid3
 
mid3' 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10
2002 -2002 0
("123"
"234"
"345"
"654"
"000"
"000"
"123"
"100"
"100"
"234"
"small"
"small"
"small"
"small"
"even"
"even"
"small")
</pre>
 
=={{header|Klingphix}}==
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy
 
( 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0 )
 
len [
get ( dup " : " ) lprint
abs tostr len >ps
tps 3 < ( ["too short" ?]
[ tps 2 mod ( [tps 2 / 3 slice ?] ["is even" ?] ) if]
) if
ps> drop drop
] for
 
" " input
</syntaxhighlight>
{{out}}
<pre>123 : 123
12345 : 234
1234567 : 345
987654321 : 654
10001 : 000
-10001 : 000
-123 : 123
-100 : 100
100 : 100
-12345 : 234
1 : too short
2 : too short
-1 : too short
-10 : too short
2002 : is even
-2002 : is even
0 : too short</pre>
 
=={{header|Klong}}==
<langsyntaxhighlight lang="k">items::[123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0]
 
mid3::{[d k];:[3>k::#$#x;"small":|0=k!2;"even";(-d)_(d::_(k%2)-1)_$#x]}
.p(mid3'items)</langsyntaxhighlight>
Output:
<pre>[123 234 345 654 000 000 123 100 100 234 small small small small even even small]</pre>
 
=={{header|Kotlin}}==
<langsyntaxhighlight klang="scala">fun middleThree(x: Int): Int? {
val s = Math.abs(x).toString()
return when {
s.length < 3 -> return null // throw Exception("too short!")
s.length % 2 == 0 -> return null // throw Exception("even number of digits")
else -> return ((s.length / 2) - 1).let { s.substring(it, it + 3) }.toInt()
}
}
 
fun main(args: Array<String>) {
println(middleThree(12345)) // 234
println(middleThree(123412345)) // null234
println(middleThree(12345671234)) // 345null
println(middleThree(1231234567)) // 123345
println(middleThree(123555123)) //null</lang> 123
println(middleThree(123555)) //null
}</syntaxhighlight>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def S 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0}
-> S
 
{def middle3digits
{lambda {:w}
{let { {:w {abs :w}}
{:l {W.length {abs :w}}}
} {if {= {% :l 2} 0}
then has an even number of digits
else {if {< :l 3}
then has not enough digits
else {W.get {- {/ :l 2} 1} :w}
{W.get {/ :l 2} :w}
{W.get {+ {/ :l 2} 1} :w} }}}}}
-> middle3digits
 
 
{table
{S.map {lambda {:i}
{tr {td {@ style="text-align:right;"}:i:}
{td {middle3digits :i}}}}
{S}} }
->
123: 123
12345: 234
1234567: 345
987654321: 654
10001: 000
-10001: 000
-123: 123
-100: 100
100: 100
-12345: 234
1: has not enough digits
2: has not enough digits
-1: has not enough digits
-10: has an even number of digits
2002: has an even number of digits
-2002: has an even number of digits
0: has not enough digits
</syntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define middlethree(value::integer) => {
local(
pos_value = math_abs(#value),
Line 2,265 ⟶ 4,031:
'<br />'
^}
'</pre>'</langsyntaxhighlight>
'''Output'''
<pre> 123: 123
Line 2,286 ⟶ 4,052:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to middle3digits :n
if [less? :n 0] [make "n minus :n]
local "len make "len count :n
Line 2,304 ⟶ 4,070:
]
 
bye</langsyntaxhighlight>
 
{{Output}}
Line 2,326 ⟶ 4,092:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function middle_three(n)
if n < 0 then
n = -n
Line 2,351 ⟶ 4,117:
print(n, middle_three(n))
end
end</langsyntaxhighlight>
 
{{out}}
Line 2,373 ⟶ 4,139:
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">middleDigits := proc(n)
local nList, start;
nList := [seq(parse(i), i in convert (abs(n), string))];
Line 2,391 ⟶ 4,157:
middleDigits(i);
printf("\n");
end do;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,413 ⟶ 4,179:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">middleThree[n_Integer] :=
Block[{digits = IntegerDigits[n], len},
len = Length[digits];
Line 2,424 ⟶ 4,190:
100, -12345, 1, 2, -1, -10, 2002, -2002, 0};
 
Column[middleThree /@ testData]</langsyntaxhighlight>
{{out}}<pre>123
123
234
345
Line 2,442 ⟶ 4,207:
err: even number of digits
err: even number of digits
err: n too small</pre>
</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function s=middle_three_digits(a)
% http://rosettacode.org/wiki/Middle_three_digits
 
Line 2,460 ⟶ 4,224:
end;
 
s = s((length(s)+1)/2+[-1:1]);</langsyntaxhighlight>
Test with
<langsyntaxhighlight MATLABlang="matlab"> x=[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0];
for k=1:length(x); fprintf(1,'%9i:%s\n',x(k),middle_three_digits(x(k)));end;</langsyntaxhighlight>
Result
<pre>
Line 2,484 ⟶ 4,248:
0:*** error: number of digits must not be smaller than 3 ***
</pre>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">middle3 = function(num)
if num < 0 then num = -num
s = str(num)
if s.len < 3 then return "Input too short"
if s.len % 2 == 0 then return "Input length not odd"
mid = (s.len + 1) / 2 - 1
return s[mid-1:mid+2]
end function
 
for test in [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100,
100, -12345, 1, 2, -1, -10, 2002, -2002, 0]
print test + " --> " + middle3(test)
end for</syntaxhighlight>
{{out}}
<pre>123 --> 123
12345 --> 234
1234567 --> 345
987654321 --> 654
10001 --> 000
-10001 --> 000
-123 --> 123
-100 --> 100
100 --> 100
-12345 --> 234
1 --> Input too short
2 --> Input too short
-1 --> Input too short
-10 --> Input too short
2002 --> Input length not odd
-2002 --> Input length not odd
0 --> Input too short</pre>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П0 lg [x] 3 - x>=0 23 ИП0 1 0
/ [x] ^ lg [x] 10^x П1 / {x} ИП1
* БП 00 1 + x=0 29 ИП0 С/П 0
/</langsyntaxhighlight>
 
''Instruction:'' enter the number in the РX (on display), the result after the execution of the same. In the case of an even or less than 3 number of digits the indicator displays an error message.
Line 2,495 ⟶ 4,292:
=={{header|ML}}==
==={{header|mLite}}===
<langsyntaxhighlight lang="ocaml">
val test_array = ["123","12345","1234567","987654321","10001","~10001","~123","~100","100","~12345","1","2","~1","~10","2002","~2002","0"];
Line 2,520 ⟶ 4,317:
;
map (println o middleThreeDigits) test_array;</langsyntaxhighlight>
Output:
<pre>123 --> 123
Line 2,542 ⟶ 4,339:
=={{header|MUMPS}}==
This sample shows the MUMPS code required to pass the specification.
<langsyntaxhighlight MUMPSlang="mumps">/* MUMPS */
MID3(N) ;
N LEN,N2
Line 2,552 ⟶ 4,349:
 
F I=123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0 W !,$J(I,10),": ",$$MID3^MID3(I)
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 2,576 ⟶ 4,373:
=={{header|NetRexx}}==
This sample goes the extra mile and provides a method that can display the middle N digits from the input value. To satisfy the requirements of this task, a static invocation of this general method is also provided with the value '''<tt>3</tt>''' hard coded as the digit count.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,622 ⟶ 4,419:
end
return text
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 2,652 ⟶ 4,449:
 
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">
<lang NewLISP>
(define (middle3 x)
(if (even? (length x))
Line 2,664 ⟶ 4,461:
 
(map middle3 lst)
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 2,687 ⟶ 4,484:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">proc middleThreeDigits(i: int): string =
<lang nim>import math
 
proc middleThreeDigits(i): auto =
var s = $abs(i)
if s.len < 3 or s.len mod 2 == 0:
Line 2,695 ⟶ 4,490:
let mid = s.len div 2
return s[mid-1..mid+1]
 
const passing = @[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
const failing = @[1, 2, -1, -10, 2002, -2002, 0]
 
for i in passing & failing:
var answer = try: middleThreeDigits(i)
except ValueError: getCurrentExceptionMsg()
echo "middleThreeDigits(", i, ") returned: ", answer</langsyntaxhighlight>
 
Output:
{{out}}
<pre>middleThreeDigits(123) returned: 123
middleThreeDigits(12345) returned: 234
Line 2,723 ⟶ 4,519:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Test {
function : Main(args : String[]) ~ Nil {
Line 2,736 ⟶ 4,532:
}
 
}</langsyntaxhighlight>
 
<pre>
Line 2,760 ⟶ 4,556:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let even x = (x land 1) <> 1
 
let middle_three_digits x =
Line 2,784 ⟶ 4,580:
print_endline "Should fail:";
List.iter print failing;
;;</langsyntaxhighlight>
 
{{out}}
Line 2,812 ⟶ 4,608:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: middle3
| s sz |
abs asString dup ->s size ->sz
sz 3 < ifTrue: [ "Too short" println return ]
sz isEven ifTrue: [ "Not odd number of digits" println return ]
sz 3 - 2 / 1+ dup 2 + s extract ;</langsyntaxhighlight>
 
{{out}}
Line 2,836 ⟶ 4,632:
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.6.0}}
<langsyntaxhighlight lang="parigp">middle(n)=my(v=digits(n));if(#v>2&&#v%2,100*v[#v\2]+10*v[#v\2+1]+v[#v\2+2],"no middle 3 digits");
apply(middle,[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0])</langsyntaxhighlight>
Output:
<pre>%1 = [123, 234, 345, 654, 0, 0, 123, 100, 100, 234, "no middle 3 digits", "no middle 3 digits", "no middle 3 digits", "no middle 3 digits", "no middle 3 digits", "no middle 3 digits", "no middle 3 digits"]</pre>
 
If for some reason you want to see the leading digits, you can run
<langsyntaxhighlight lang="parigp">apply(n-> Strprintf("%03d", n), %)</langsyntaxhighlight>
 
For earlier versions <code>digits</code> can be defined as
<langsyntaxhighlight lang="parigp">digits(n)=eval(Vec(Str(n)))</langsyntaxhighlight>
or more efficiently as
<langsyntaxhighlight lang="parigp">digits(n)=Vec(apply(n->n-48,Vectorsmall(Str(n))))</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free Pascal}}
<langsyntaxhighlight lang="pascal">program Midl3dig;
{$IFDEF FPC}
{$MODE Delphi} //result /integer => Int32 aka longInt etc..
Line 2,886 ⟶ 4,683:
writeln(n:9,': ',GetMid3dig(Test[i]));
end;
end.</langsyntaxhighlight>
{{out}}
<pre> 123: 123
Line 2,906 ⟶ 4,703:
0: got too few digits
</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl
use strict ;
use warnings ;
Line 2,932 ⟶ 4,730:
1, 2, -1, -10, 2002, -2002, 0 ) ;
map { middlethree( $_ ) } @numbers ;
</syntaxhighlight>
</lang>
{{out}}
<pre>Middle 3 digits of 123 : 123 !
Line 2,953 ⟶ 4,751:
</pre>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Perl6>sub middle-three($n) {
<span style="color: #008080;">procedure</span> <span style="color: #000000;">mid3</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
given $n.abs {
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">))</span>
when .chars < 3 { "$n is too short" }
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">3</span>
when .chars %% 2 { "$n has an even number of digits" }
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%10d: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">or</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)?</span><span style="color: #008000;">"error"</span><span style="color: #0000FF;">:</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">k</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">])})</span>
default { "The three middle digits of $n are: ", .substr: (.chars - 3)/2, 3 }
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
}
}
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">123</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12345</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1234567</span><span style="color: #0000FF;">,</span><span style="color: #000000;">987654321</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10001</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">10001</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">123</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,</span><span style="color: #000000;">100</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">12345</span><span style="color: #0000FF;">,</span>
 
<span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2002</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">2002</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}</span>
say middle-three($_) for <
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
<span style="color: #000000;">mid3</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
1 2 -1 -10 2002 -2002 0
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
>;</lang>
<!--</syntaxhighlight>-->
{{out}}
<pre>
<pre>The three middle digits of 123 are: 123
123: 123
The three middle digits of 12345 are: 234
12345: 234
The three middle digits of 1234567 are: 345
1234567: 345
The three middle digits of 987654321 are: 654
987654321: 654
The three middle digits of 10001 are: 000
The three middle digits of -10001 are: 000
-10001: 000
The three middle digits of -123 are: 123
-123: 123
The three middle digits of -100 are: 100
The three middle digits of -100 are: 100
100: 100
The three middle digits of -12345 are: 234
-12345: 234
1 is too short
1: error
2 is too short
2: error
-1 is too short
-1: error
-10 is too short
-10: error
2002 has an even number of digits
2002: error
-2002 has an even number of digits
-2002: error
0 is too short</pre>
0: error
 
</pre>
It is also possible to write a regular expression with a code assertion:
<lang perl6>for [\~] ^10 { say "$_ => $()" if m/^^(\d+) <(\d**3)> (\d+) $$ <?{ $0.chars == $1.chars}> / }</lang>
{{out}}
<pre>01234 => 123
0123456 => 234
012345678 => 345</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php">// 32-bit builds of PHP: Integers can be from -2147483648 to 2147483647
// 64-bit builds of PHP: Integers can be from -9223372036854775808 to 9223372036854775807
 
Line 3,031 ⟶ 4,825:
{
echo $nums.' : '.middlethree($nums). '<br>';
}</langsyntaxhighlight>
Output:
<pre>123 : 123
Line 3,050 ⟶ 4,844:
-2002 : The value must contain an odd amount of digits...
0 : The value must contain at least three digits...</pre>
 
=={{header|Picat}}==
===Prolog-style===
{{trans|Prolog}}
<syntaxhighlight lang="picat">get_middle_f1(Str) = [X,Y,Z] =>
append(Pre,[X,Y,Z],Post,Str),
length(Pre) = length(Post).</syntaxhighlight>
 
===List slice===
<syntaxhighlight lang="picat">get_middle_f2(Str) = Str[Mid-1..Mid+1] =>
Mid = 1 + Str.len div 2.</syntaxhighlight>
 
===Test===
<syntaxhighlight lang="picat">go =>
Success = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345],
Fail = [1, 2, -1, -10, 2002, -2002, 0],
All = Success ++ Fail,
 
test(All, get_middle_f1),
test(All, get_middle_f2).
 
% Test and check for exceptions
test(List,F) =>
printf("\nTesting %w:\n", F),
foreach(N in List)
catch(Middle=apply(get_middle,N,F), E, printf("%d = exception %w\n",N,E)),
if E.var() then
println([n=N,middle=Middle])
end
end,
nl.
 
% Check with the get_middle funcion F
get_middle(N,F) = apply(F,Str) =>
Str = N.abs().to_string(),
Len = length(Str),
if Len mod 2 = 0 then throw $not_odd_length(N)
elseif Len < 3 then throw $number_too_small(N)
end.</syntaxhighlight>
 
{{out}}
<pre>[n = 123,middle = 123]
[n = 12345,middle = 234]
[n = 1234567,middle = 345]
[n = 987654321,middle = 654]
[n = 10001,middle = 000]
[n = -10001,middle = 000]
[n = -123,middle = 123]
[n = -100,middle = 100]
[n = 100,middle = 100]
[n = -12345,middle = 234]
[n = 1,exception = number_too_small(1)]
[n = 2,exception = number_too_small(2)]
[n = -1,exception = number_too_small(-1)]
[n = -10,exception = not_odd_length(-10)]
[n = 2002,exception = not_odd_length(2002)]
[n = -2002,exception = not_odd_length(-2002)]
[n = 0,exception = number_too_small(0)]</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de middle3digits (N)
(let (Lst (chop (abs N)) Len (length Lst))
(tab (10 -2 -30)
Line 3,061 ⟶ 4,913:
((bit? 1 Len)
(head 3 (nth Lst (/ Len 2))) )
(T "even number of digits") ) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(mapc middle3digits
(123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0 ) )</langsyntaxhighlight>
Output:
<pre> 123: 123
Line 3,084 ⟶ 4,936:
-2002: even number of digits
0: not enough digits</pre>
 
=={{header|Pike}}==
{{trans|PHP}}
 
<syntaxhighlight lang="pike">string middlethree(int i) {
i = abs(i);
int length = sizeof((string)i);
if(length >= 3) {
if(length % 2 == 1) {
int middle = (int)floor(length / 2) - 1;
return(((string)i)[middle..middle+2]);
}
else {
return "The value must contain an odd amount of digits...";
}
}
else {
return "The value must contain at least three digits...";
}
}
 
int main() {
array(int) numbers = ({123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0});
 
foreach(numbers, int nums) {
write((string)nums + " : " + middlethree(nums) + "\n");
}
return 0;
}</syntaxhighlight>
{{out}}
<pre>123 : 123
12345 : 234
1234567 : 345
987654321 : 654
10001 : 000
-10001 : 000
-123 : 123
-100 : 100
100 : 100
-12345 : 234
1 : The value must contain at least three digits...
2 : The value must contain at least three digits...
-1 : The value must contain at least three digits...
-10 : The value must contain at least three digits...
2002 : The value must contain an odd amount of digits...
-2002 : The value must contain an odd amount of digits...
0 : The value must contain at least three digits...</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
middle: procedure options (main); /* 29 October 2013 */
declare n fixed (15);
Line 3,111 ⟶ 5,011:
 
end middle;
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,130 ⟶ 5,030:
-2002 not possible
0 not possible
</pre>
 
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">To run:
Start up.
Test 123.
Test 12345.
Test 1234567.
Test 987654321.
Test 10001.
Test -10001.
Test -123.
Test -100.
Test 100.
Test -12345.
Test 1.
Test 2.
Test -1.
Test -10.
Test 2002.
Test -2002.
Test 0.
Wait for the escape key.
Shut down.
 
To get the middle three digits of a number giving a string:
Privatize the number.
De-sign the number.
Convert the number to the string.
If the string's length is less than 3, put "Number has fewer than three digits" into the string; exit.
If the string's length is even, put "Number has no middle" into the string; exit.
Put the string's length divided by 2 into a midpoint number.
Slap a substring on the string.
Put the substring's first plus the midpoint minus 1 into the substring's first.
Put the substring's first plus 2 into the substring's last.
Put the substring into the string.
 
To test a number:
Get the middle three digits of the number giving a string.
Write "" then the number then " -> " then the string on the console.</syntaxhighlight>
{{out}}
<pre>
123 -> 123
12345 -> 234
1234567 -> 345
987654321 -> 654
10001 -> 000
-10001 -> 000
-123 -> 123
-100 -> 100
100 -> 100
-12345 -> 234
1 -> Number has fewer than three digits
2 -> Number has fewer than three digits
-1 -> Number has fewer than three digits
-10 -> Number has fewer than three digits
2002 -> Number has no middle
-2002 -> Number has no middle
0 -> Number has fewer than three digits
</pre>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">function middle3($inp){
 
$str = [Math]::abs($inp)
Line 3,156 ⟶ 5,115:
$sample = 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0
 
foreach ($x in $sample){middle3 $x}</langsyntaxhighlight>
{{Out}}
<pre>123: 123
Line 3,175 ⟶ 5,134:
-2002: [ERROR] even number of digits.
0: [ERROR] too short.</pre>
 
 
=={{header|Prolog}}==
{{works with|SWI-Prolog|6}}
 
<langsyntaxhighlight lang="prolog">
middle_3_digits(Number, [D1,D2,D3]) :-
verify_middle_3_able(Number, Digits),
Line 3,195 ⟶ 5,153:
; true
).
</syntaxhighlight>
</lang>
 
 
Test code:
 
<langsyntaxhighlight lang="prolog">
test_correct :-
TestCases = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345],
Line 3,207 ⟶ 5,165:
format('Middle 3 digits of ~w ~30|: ~w~n', [TestCase, Result])
).
</syntaxhighlight>
</lang>
 
 
Line 3,246 ⟶ 5,204:
 
=={{header|Python}}==
===Procedural===
<lang python>>>> def middle_three_digits(i):
<syntaxhighlight lang="python">>>> def middle_three_digits(i):
s = str(abs(i))
length = len(s)
Line 3,280 ⟶ 5,239:
middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)
>>> </langsyntaxhighlight>
 
===Composition of pure functions===
Using a composable option type as an alternative to error handling:
{{Trans|Haskell}}
<syntaxhighlight lang="python">'''Middle 3 digits'''
 
 
# mid3digits :: Int -> Either String String
def mid3digits(n):
'''Either the middle three digits,
or an explanatory string.'''
m = abs(n)
s = str(m)
return Left('Less than 3 digits') if (100 > m) else (
Left('Even digit count') if even(len(s)) else Right(
s[(len(s) - 3) // 2:][0:3]
)
)
 
 
# TEST ----------------------------------------------------
def main():
'''Test'''
 
def bracketed(x):
return '(' + str(x) + ')'
 
print(
tabulated('Middle three digits, where defined:\n')(str)(
either(bracketed)(str)
)(mid3digits)([
123, 12345, 1234567, 987654321, 10001, -10001, -123,
-100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0
])
)
 
 
# GENERIC -------------------------------------------------
 
# Left :: a -> Either a b
def Left(x):
'''Constructor for an empty Either (option type) value
with an associated string.'''
return {'type': 'Either', 'Right': None, 'Left': x}
 
 
# Right :: b -> Either a b
def Right(x):
'''Constructor for a populated Either (option type) value'''
return {'type': 'Either', 'Left': None, 'Right': x}
 
 
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Function composition.'''
return lambda f: lambda x: g(f(x))
 
 
# either :: (a -> c) -> (b -> c) -> Either a b -> c
def either(fl):
'''The application of fl to e if e is a Left value,
or the application of fr to e if e is a Right value.'''
return lambda fr: lambda e: fl(e['Left']) if (
None is e['Right']
) else fr(e['Right'])
 
 
# even :: Int -> Bool
def even(x):
'''Is x even ?'''
return 0 == x % 2
 
 
# tabulated :: String -> (b -> String) -> (a -> b) -> [a] -> String
def tabulated(s):
'''Heading -> x display function -> fx display function ->
f -> value list -> tabular string.'''
def go(xShow, fxShow, f, xs):
w = max(map(compose(len)(str), xs))
return s + '\n' + '\n'.join(
xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs
)
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
 
 
if __name__ == '__main__':
main()</syntaxhighlight>
{{Out}}
<pre>Middle three digits, where defined:
 
123 -> 123
12345 -> 234
1234567 -> 345
987654321 -> 654
10001 -> 000
-10001 -> 000
-123 -> 123
-100 -> 100
100 -> 100
-12345 -> 234
1 -> (Less than 3 digits)
2 -> (Less than 3 digits)
-1 -> (Less than 3 digits)
-10 -> (Less than 3 digits)
2002 -> (Even digit count)
-2002 -> (Even digit count)
0 -> (Less than 3 digits)</pre>
 
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ 1 & not ] is even ( n --> b )
 
[ over size -
space swap of
swap join ] is justify ( $ n --> $ )
 
[ abs number$
dup size dup 3 < iff
[ 2drop $ "too few digits" ]
done
dup even iff
[ 2drop $ "even digit count" ]
done
dup 3 = iff
drop done
3 - 2 /
tuck split nip
swap negate split drop ] is middle3 ( n --> $ )
 
' [ 123 12345 1234567
987654321 10001 -10001
-123 -100 100 -12345 1
2 -1 -10 2002 -2002 0 ]
 
witheach
[ dup number$ 9 justify echo$
say " --> "
middle3 echo$ cr ]</syntaxhighlight>
 
{{out}}
 
<pre> 123 --> 123
12345 --> 234
1234567 --> 345
987654321 --> 654
10001 --> 000
-10001 --> 000
-123 --> 123
-100 --> 100
100 --> 100
-12345 --> 234
1 --> too few digits
2 --> too few digits
-1 --> too few digits
-10 --> too few digits
2002 --> even digit count
-2002 --> even digit count
0 --> too few digits</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="scheme">#lang racket
(define (middle x)
(cond
Line 3,296 ⟶ 5,416:
 
(map middle (list 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345))
(map middle (list 1 2 -1 -10 2002 -2002 0))</langsyntaxhighlight>
The output:
<langsyntaxhighlight lang="scheme">'("123" "234" "345" "654" "000" "000" "123" "100" "100" "234")
'("error: number too small" "error: number too small" "error: number too small" "error: number too small"
"error: number has even length" "error: number has even length" "error: number too small")</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub middle-three($n) {
given $n.abs {
when .chars < 3 { "$n is too short" }
when .chars %% 2 { "$n has an even number of digits" }
default { "The three middle digits of $n are: ", .substr: (.chars - 3)/2, 3 }
}
}
 
say middle-three($_) for <
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0
>;</syntaxhighlight>
{{out}}
<pre>The three middle digits of 123 are: 123
The three middle digits of 12345 are: 234
The three middle digits of 1234567 are: 345
The three middle digits of 987654321 are: 654
The three middle digits of 10001 are: 000
The three middle digits of -10001 are: 000
The three middle digits of -123 are: 123
The three middle digits of -100 are: 100
The three middle digits of 100 are: 100
The three middle digits of -12345 are: 234
1 is too short
2 is too short
-1 is too short
-10 is too short
2002 has an even number of digits
-2002 has an even number of digits
0 is too short</pre>
 
It is also possible to write a regular expression with a code assertion:
<syntaxhighlight lang="raku" line>for [\~] ^10 { say "$_ => $()" if m/^^(\d+) <(\d**3)> (\d+) $$ <?{ $0.chars == $1.chars}> / }</syntaxhighlight>
{{out}}
<pre>01234 => 123
0123456 => 234
012345678 => 345</pre>
 
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 03.02.2013 Walter Pachl
* 19.04.2013 mid 3 is now a function returning the middle 3 digits
Line 3,331 ⟶ 5,491:
End
End
Return res</langsyntaxhighlight>
Output:
<pre>
Line 3,359 ⟶ 5,519:
<br>So is the value of a &nbsp; '''googol''' &nbsp; and a &nbsp;'''googolplex'''.
<br><br>This REXX version is limited to numbers whose length is &nbsp; <big>≤</big> &nbsp; 100,000 &nbsp; decimal digits.
<br>(The decimal digits limit is defined via the &nbsp; '''numeric digits''' &nbsp; statement withinin the first line of the subroutine/procedure.)
<langsyntaxhighlight lang="rexx">/*REXX program returns the three middle digits of a decimal number (or an error msg).*/
n= '123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345',
'+123 0123 2 -1 -10 2002 -2002 0 abc 1e3 -17e-3 1234567.',
Line 3,375 ⟶ 5,535:
if L<3 then return er "argument is less than three digits."
if L//2==0 then return er "argument isn't an odd number of digits."
return substr(x, (L-3)%2+1, 3)</langsyntaxhighlight>
'''output'''
<pre>
Line 3,405 ⟶ 5,565:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
n = 1234567
middle(n)
Line 3,416 ⟶ 5,576:
but lennr%2=0 see "Number must have an odd number of digits"
else cnr = substr(string(nr),mnr,3) see cnr + nl ok
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
Staying in the real world: no number/string conversion, -1 is returned if input is invalid.
{{works with|Halcyon Calc|4.2.7}}
≪ ABS DUP XPON
'''IF''' DUP 2 < OVER 2 MOD OR
'''THEN''' DROP2 -1
'''ELSE''' 2 / 1 - ALOG / IP 1000 MOD
'''END'''
≫ '<span style="color:blue">→M3D</span>' STO
 
≪ { 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 -10 2002}
→ tl
≪ { }
1 tl SIZE '''FOR''' j
tl j GET <span style="color:blue">→M3D</span> +
'''NEXT'''
≫ ≫ EVAL
{{out}}
<pre>
1: { 123 234 345 654 0 0 123 100 100 234 -1 -1 }
</pre>
 
=={{header|Ruby}}==
 
<langsyntaxhighlight lang="ruby">def middle_three_digits(num)
# minus sign doesn't factor into digit count,
# and calling #abs acts as a duck-type assertion
Line 3,433 ⟶ 5,615:
return str[length/2 - 1, 3].to_i
end</langsyntaxhighlight>
 
Testing program:
 
<langsyntaxhighlight lang="ruby">samples = [
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0
Line 3,450 ⟶ 5,632:
puts e
end
end</langsyntaxhighlight>
{{out}}
<pre>
Line 3,473 ⟶ 5,655:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn middle_three_digits(x: i32) -> Result<String, String> {
let s: String = x.abs().to_string();
let len = s.len();
Line 3,502 ⟶ 5,684:
print_result(*i);
}
}</langsyntaxhighlight>
 
{{Out}}
Line 3,523 ⟶ 5,705:
middle_three_digits(-2002) returned: Failure, Even number of digits
middle_three_digits(0) returned: Failure, Too short</pre>
 
=={{header|S-lang}}==
<pre>Educational Notes:
1) Array-style string manipulations (e.g. as = as[[1:]] ) always use bytes,
not UTF-8 characters. As digits and '-' are all ASCII, all is copacetic.
2) The task doesn't require 64-bit integer support, but I added it, dependant
on whether the S-Lang library compile supports them, which it generally
does. [Main exception would be the current downloadable/installable MS-Win
version of the Jed editor.]
3) S-Lang functions peel arguments off right-to-left, opposite of many
languages. To align the order with other solutions, I enclosed the
parameters in a list. One alternative would have been for m3() to call
_stk_reverse(_NARGS), then pop each arg directly off the stack. Or of
course just list the numbers backwards.
</pre>
<syntaxhighlight lang="s-lang">
define m3(i)
{
variable s = string(i), sabs = s, l;
if (sabs[0] == '-')
sabs = sabs[[1:]];
l = strlen(sabs);
if (l < 3)
print(sprintf("%s doesn't have enough digits", s));
else if (l & 1) {
variable st = (l-3) >> 1;
print(sprintf("%13s: %s", s, sabs[[st:st+2]]));
}
else
print(sprintf("%s has an even number of digits", s));
}
define middle_3(lst)
{
foreach (lst)
m3( () );
}
 
middle_3( { 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345,
#ifexists Int64_Type
6644221335577ll, -11122588999ll,
#endif
1, 2, -1, -10, 2002, -2002, 0 } );
</syntaxhighlight>
{{out}}<pre>
" 123: 123"
" 12345: 234"
" 1234567: 345"
" 987654321: 654"
" 10001: 000"
" -10001: 000"
" -123: 123"
" -100: 100"
" 100: 100"
" -12345: 234"
"6644221335577: 213"
" -11122588999: 258"
"1 doesn't have enough digits"
"2 doesn't have enough digits"
"-1 doesn't have enough digits"
"-10 doesn't have enough digits"
"2002 has an even number of digits"
"-2002 has an even number of digits"
"0 doesn't have enough digits"
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">/**
* Optionally return the middle three digits of an integer.
*
Line 3,546 ⟶ 5,795:
case Some(v) => "%03d".format(v) // Format the value, force leading zeroes
} mkString("\n")
</syntaxhighlight>
</lang>
{{out}}
<pre>123
Line 3,565 ⟶ 5,814:
No middle three
No middle three
</pre>
 
=={{header|sed}}==
<syntaxhighlight lang="sed">h
s/^[-+]\{0,1\}0*\([1-9]\([0-9][0-9]\)\{1,\}\)$/\1/
t l
s/$/ -> error!/
b
:l
s/.\(.\{3,\}\)./\1/
t l
x
G
s/\n/ -> /</syntaxhighlight>
{{out}}
<pre>
$ printf "%s\n" -12345 -10001 -2002 -123 -100 -10 -1 0 1 2 100 123 2002 10001 12345 1234567 987654321 | sed -f middle_three_digits.sed
-12345 -> 234
-10001 -> 000
-2002 -> error!
-123 -> 123
-100 -> 100
-10 -> error!
-1 -> error!
0 -> error!
1 -> error!
2 -> error!
100 -> 100
123 -> 123
2002 -> error!
10001 -> 000
12345 -> 234
1234567 -> 345
987654321 -> 654
</pre>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$include "seed7_05.s7i";
 
const func string: middle3 (in integer: number) is func
Line 3,591 ⟶ 5,874:
writeln(number <& ": " <& middle3(number));
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,612 ⟶ 5,895:
-2002: error
0: error
</pre>
 
=={{header|SenseTalk}}==
As a People Oriented Programming language, SenseTalk treats values in a fluid fashion. So although the calls to the middle3Digits handler pass an integer as the parameter, the handler itself treats the value as text, looking for occurrences of the text pattern <digit> in it. Similarly, the variable 'output' is initially set to a number, then becomes a text value when the middle digits are put into it at character position 15.
<syntaxhighlight lang="sensetalk">set inputs to [123, 12345, 1234567, 987654321,
10001, -10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0]
 
repeat with each num in inputs
put num into output
put middle3digits of num into character 15 of output -- will autofill with "."s
put output
end repeat
 
to handle middle3digits of number
put every occurrence of <digit> in number into digits
if the number of items in digits is less than 3 then return "Error: too few digits"
if the number of items in digits is an even number then return "Error: even number of digits"
repeat while the number of items in digits is greater than 3
delete the first item of digits
delete the last item of digits
end repeat
return digits joined by empty
end middle3digits
</syntaxhighlight>
{{out}}
<pre>
123...........123
12345.........234
1234567.......345
987654321.....654
10001.........000
-10001........000
-123..........123
-100..........100
100...........100
-12345........234
1.............Error: too few digits
2.............Error: too few digits
-1............Error: too few digits
-10...........Error: too few digits
2002..........Error: even number of digits
-2002.........Error: even number of digits
0.............Error: too few digits
</pre>
 
=={{header|Sidef}}==
{{trans|Perl 6Raku}}
<langsyntaxhighlight lang="ruby">func middle_three(n) {
var l = n.len;
if (l < 3) {
"#{n} is too short"
Line 3,623 ⟶ 5,950:
"#{n} has an even number of digits"
} else {
"The three middle digits of #{n} are: " + n.digits.ftslice((l-3 )/ 2, l/2 + 1).first(3).flip.join
}
}
Line 3,630 ⟶ 5,957:
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0
);
nums.each { say middle_three(_) };</langsyntaxhighlight>
{{out}}
<pre>
Line 3,654 ⟶ 5,981:
 
=={{header|SQL}}==
<langsyntaxhighlight lang="sql">;WITH DATA
AS (SELECT CAST(ABS(NUMBER) AS NVARCHAR(MAX)) charNum,
NUMBER,
Line 3,665 ⟶ 5,992:
END Output,
NUMBER Input
FROM DATA </langsyntaxhighlight>
 
<pre>
Line 3,693 ⟶ 6,020:
| Error! | 0 |
</pre>
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">var num:Int = \\enter your number here
if num<0{num = -num}
var numArray:[Int]=[]
while num>0{
var temp:Int=num%10
numArray.append(temp)
num=num/10
}
var i:Int=numArray.count
if i<3||i%2==0{
print("Invalid Input")
}
else{
i=i/2
print("\(numArray[i+1]),\(numArray[i]),\(numArray[i-1])")
}</syntaxhighlight>
<pre>
123: 123
12345: 234
1234567: 345
987654321: 654
10001: 000
-10001: 000
-123: 123
-100: 100
100: 100
-12345: 234
1: Invalid Input
2: Invalid Input
-1: Invalid Input
-10: Invalid Input
2002: Invalid Input
-2002: Invalid Input
0: Invalid Input
</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc middleThree n {
if {$n < 0} {
set n [expr {-$n}]
Line 3,709 ⟶ 6,073:
set idx [expr {$idx / 2}]
string range $n $idx [expr {$idx+2}]
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">foreach n {
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0
Line 3,722 ⟶ 6,086:
puts "found for ${n}: $mid"
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,743 ⟶ 6,107:
error for 0: no middle three digits: insufficient digits
</pre>
 
=={{header|TI SR-56}}==
{| class="wikitable"
|+ Texas Instruments SR-56 Program Listing for "Middle three digits"
|-
! Display !! Key !! Display !! Key !! Display !! Key !! Display !! Key
|-
| 00 28 || <nowiki>*|x|</nowiki> || 25 54 || / || 50 || || 75 ||
|-
| 01 33 || STO || 26 02 || 2 || 51 || || 76 ||
|-
| 02 01 || 1 || 27 74 || - || 52 || || 77 ||
|-
| 03 18 || *log || 28 01 || 1 || 53 || || 78 ||
|-
| 04 29 || *Int || 29 53 || ) || 54 || || 79 ||
|-
| 05 20 || *1/x || 30 19 || *10^x || 55 || || 80 ||
|-
| 06 20 || *1/x || 31 94 || = || 56 || || 81 ||
|-
| 07 33 || STO || 32 29 || *Int || 57 || || 82 ||
|-
| 08 02 || 2 || 33 54 || / || 58 || || 83 ||
|-
| 09 54 || / || 34 01 || 1 || 59 || || 84 ||
|-
| 10 02 || 2 || 35 00 || 0 || 60 || || 85 ||
|-
| 11 94 || = || 36 00 || 0 || 61 || || 86 ||
|-
| 12 12 || INV || 37 00 || 0 || 62 || || 87 ||
|-
| 13 29 || *Int || 38 94 || = || 63 || || 88 ||
|-
| 14 74 || - || 39 12 || INV || 64 || || 89 ||
|-
| 15 92 || . || 40 29 || *Int || 65 || || 90 ||
|-
| 16 05 || 5 || 41 64 || * || 66 || || 91 ||
|-
| 17 94 || = || 42 01 || 1 || 67 || || 92 ||
|-
| 18 20 || *1/x || 43 00 || 0 || 68 || || 93 ||
|-
| 19 34 || RCL || 44 00 || 0 || 69 || || 94 ||
|-
| 20 01 || 1 || 45 00 || 0 || 70 || || 95 ||
|-
| 21 54 || / || 46 94 || = || 71 || || 96 ||
|-
| 22 52 || ( || 47 41 || R/S || 72 || || 97 ||
|-
| 23 34 || RCL || 48 || || 73 || || 98 ||
|-
| 24 02 || 2 || 49 || || 74 || || 99 ||
|}
 
Asterisk denotes 2nd function key.
 
{| class="wikitable"
|+ Register allocation
|-
| 0: Unused || 1: Number || 2: Log || 3: Unused || 4: Unused
|-
| 5: Unused || 6: Unused || 7: Unused || 8: Unused || 9: Unused
|}
 
Annotated listing:
<syntaxhighlight lang="text">
*|x| STO 1 // Number := |input|
*log *Int // #Digits - 1
*1/x *1/x // Divide by zero if 1-digit number
STO 2 // Log := #Digits - 1
/ 2 = INV *Int - . 5 = *1/x // Divide by zero if #Digits is even
RCL 1 / ( RCL 2 / 2 - 1 ) *10^x = // Shift appropriately
*Int / 1 0 0 0 = INV *Int * 1 0 0 0 = // Take the middle 3 digits
R/S // End
</syntaxhighlight>
 
'''Usage:'''
 
Enter the number and then press RST R/S. A flashing number indicates an error.
 
{{in}}
 
987654321 RST R/S
 
{{out}}
 
After about two seconds, '''654''' will appear on the screen.
 
{{in}}
 
12345 +/- RST R/S
 
{{out}}
 
After about two seconds, '''234''' will appear on the screen.
 
{{in}}
 
5 RST R/S
 
{{out}}
 
A flashing 9.999999999 99 appears on the screen indicating an error.
 
=={{header|UNIX Shell}}==
Line 3,749 ⟶ 6,220:
{{works with|Z Shell}}
 
<langsyntaxhighlight lang="bash">function middle3digits
{
typeset -i n="${1#-}"
Line 3,771 ⟶ 6,242:
printf "%10d: " $n
middle3digits "$n"
done</langsyntaxhighlight>
 
Output: <pre> 123: 123
Line 3,790 ⟶ 6,261:
-2002: -2002 has an even number of digits
0: 0 has less than 3 digits</pre>
 
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
Option Explicit
 
Sub Main_Middle_three_digits()
Dim Numbers, i&
Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _
100, -12345, 1, 2, -1, -10, 2002, -2002, 0)
For i = 0 To 16
Debug.Print Numbers(i) & " Return : " & Middle3digits(CStr(Numbers(i)))
Next
End Sub
 
Function Middle3digits(strNb As String) As String
If Left(strNb, 1) = "-" Then strNb = Right(strNb, Len(strNb) - 1)
If Len(strNb) < 3 Then
Middle3digits = "Error ! Number of digits must be >= 3"
ElseIf Len(strNb) Mod 2 = 0 Then
Middle3digits = "Error ! Number of digits must be odd"
Else
Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)
End If
End Function
</syntaxhighlight>
{{out}}
<pre>123 Return : 123
12345 Return : 234
1234567 Return : 345
987654321 Return : 654
10001 Return : 000
-10001 Return : 000
-123 Return : 123
-100 Return : 100
100 Return : 100
-12345 Return : 234
1 Return : Error ! Number of digits must be >= 3
2 Return : Error ! Number of digits must be >= 3
-1 Return : Error ! Number of digits must be >= 3
-10 Return : Error ! Number of digits must be >= 3
2002 Return : Error ! Number of digits must be odd
-2002 Return : Error ! Number of digits must be odd
0 Return : Error ! Number of digits must be >= 3</pre>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">'http://rosettacode.org/wiki/Middle_three_digits
 
Function mid3n(n)
Line 3,812 ⟶ 6,327:
WScript.StdOut.Write n & ": " & mid3n(n)
WScript.StdOut.WriteLine
Next</langsyntaxhighlight>
{{Out}}
<pre>
Line 3,835 ⟶ 6,350:
 
=={{header|Vedit macro language}}==
<langsyntaxhighlight lang="vedit">do {
#1 = Get_Num("Enter a number, or 0 to stop: ", STATLINE)
Ins_Text("Input: ") Num_Ins(#1, COUNT, 10)
Line 3,863 ⟶ 6,378:
}
Buf_Quit(OK)
Return </langsyntaxhighlight>
 
Output:
Line 3,883 ⟶ 6,398:
Input: -2002 Result: Not odd number of digits!
Input: 0 Result: Too few digits! </pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import math
 
const
(
valid = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
invalid = [1, 2, -1, -10, 2002, -2002, 0]
)
 
fn main() {
for elem in valid {println(middle(elem))}
for elem in invalid {println(middle(elem))}
}
 
 
fn middle(num int) string {
mut strip := math.abs(num).str()
if strip.len < 3 {return 'Error: $num has less than 3 digits'}
if strip.len % 2 == 0 {return 'Error: $num has an even number of digits'}
start := (strip.len / 2) - 1
return strip.substr(start, start + 3)
}
</syntaxhighlight>
 
{{out}}
<pre>
123
234
345
654
000
000
123
100
100
234
Error: 1 has less than 3 digits
Error: 2 has less than 3 digits
Error: -1 has less than 3 digits
Error: -10 has less than 3 digits
Error: 2002 has an even number of digits
Error: -2002 has an even number of digits
Error: 0 has less than 3 digits
</pre>
 
=={{header|Wart}}==
 
<langsyntaxhighlight lang="wart">def (mid3 n)
withs (digits (with outstring # itoa
(pr abs.n))
Line 3,892 ⟶ 6,452:
mid (int max/2))
if (and odd?.max (max >= 3))
(digits mid-1 mid+2)</langsyntaxhighlight>
 
'''Output'''
Line 3,931 ⟶ 6,491:
(mid3 0)
=> nil</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
 
var middle3 = Fn.new { |n|
if (n < 0) n = -n
var s = "%(n)"
var c = s.count
if (c < 3) return "Minimum is 3 digits, only has %(c)."
if (c%2 == 0) return "Number of digits must be odd, %(c) is even."
if (c == 3) return s
var d = (c - 3)/2
return s[d..d+2]
}
 
var a = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0]
 
for (e in a) {
Fmt.print("$9d -> $n", e, middle3.call(e))
}</syntaxhighlight>
 
{{out}}
<pre>
123 -> 123
12345 -> 234
1234567 -> 345
987654321 -> 654
10001 -> 000
-10001 -> 000
-123 -> 123
-100 -> 100
100 -> 100
-12345 -> 234
1 -> Minimum is 3 digits, only has 1.
2 -> Minimum is 3 digits, only has 1.
-1 -> Minimum is 3 digits, only has 1.
-10 -> Minimum is 3 digits, only has 2.
2002 -> Number of digits must be odd, 4 is even.
-2002 -> Number of digits must be odd, 4 is even.
0 -> Minimum is 3 digits, only has 1.
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\stdlib;
 
func Mid3Digits(I); \Return the middle three digits of I
Line 3,956 ⟶ 6,559:
Text(0, Mid3Digits(Passing(X))); CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 3,980 ⟶ 6,583:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn middle(ns){
ns.apply("toString").apply('-("-"))
.apply(fcn(n){nl:=n.len();
Line 3,988 ⟶ 6,591:
}
middle(T(123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345)).println()
middle(T(1, 2, -1, -10, 2002, -2002, 0)).println();</langsyntaxhighlight>
{{out}}
<pre>
Anonymous user