Middle three digits: Difference between revisions
Content deleted Content added
No edit summary |
Added Uiua solution |
||
(65 intermediate revisions by 37 users not shown) | |||
Line 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}}==
<
procedure Middle_Three_Digits is
Line 58 ⟶ 166:
end loop;
end Middle_Three_Digits;</
{{out}}
Line 80 ⟶ 188:
=={{header|Aime}}==
<
m3(integer i)
{
Line 120 ⟶ 228:
return 0;
}</
{{out}}
<pre> 123: 123
Line 142 ⟶ 250:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.6.win32}}
<
# return either an integer on success or a error message if #
# the middle 3 digits couldn't be extracted #
Line 204 ⟶ 312:
print( ( newline ) )
OD
)</
{{out}}
<pre>
Line 227 ⟶ 335:
=={{header|ALGOL W}}==
<
% 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 %
Line 274 ⟶ 382:
end for_n
end.</
{{out}}
<pre>
Line 295 ⟶ 403:
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">
(* ****** ****** *)
//
Line 418 ⟶ 1,088:
(* ****** ****** *)
</syntaxhighlight>
{{out}}
<pre>Middle-three-digits(123): 123
Line 439 ⟶ 1,109:
=={{header|AutoHotkey}}==
<
Loop, parse, Numbers, `,
{
Line 451 ⟶ 1,121:
log := log . A_LoopField . "`t: " . SubStr(n,((d-3)//2)+1,3) . "`n"
}
MsgBox % log</
{{out}}
<pre>123 : 123
Line 472 ⟶ 1,142:
=={{header|AWK}}==
<
# use as: awk -f middle_three_digits.awk
Line 500 ⟶ 1,170:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 524 ⟶ 1,194:
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<
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 546 ⟶ 1,216:
300 DATA123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345
310 DATA1,2,-1,-10,2002,-2002,0
</syntaxhighlight>
{{out}}
<pre>
Line 567 ⟶ 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}}===
<
FOR i% = 1 TO 17
READ test%
Line 589 ⟶ 1,286:
OTHERWISE
= MID$(n$, LEN n$ / 2, 3)
ENDCASE</
{{out}}
<pre> 123 -> 123
Line 610 ⟶ 1,307:
==={{header|FBSL}}===
<
DIM numbers AS STRING = "123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0"
Line 654 ⟶ 1,351:
RETURN m
END IF
END FUNCTION</
Output
<pre> 123 --> 123
Line 677 ⟶ 1,374:
==={{header|IS-BASIC}}===
<
120 PRINT MIDDLE$(N)
130 DEF MIDDLE$(N)
Line 685 ⟶ 1,382:
170 LET P=(LEN(N$)-3)/2
180 LET MIDDLE$=N$(P+1:P+3)
190 END DEF</
==={{header|PureBasic}}===
<
Protected x$, digitCount
Line 716 ⟶ 1,413:
Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Sample output:
<pre> 123 : 123
Line 737 ⟶ 1,434:
==={{header|Run BASIC}}===
<
while word$(x$,i+1,",") <> ""
Line 749 ⟶ 1,446:
end if
wend
end</
<pre>123 123
234 12345
Line 767 ⟶ 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}}==
<
setlocal enabledelayedexpansion
Line 814 ⟶ 1,544:
)
goto :EOF
%==/The Procedure ==%</
{{Out}}
<pre>123: 123
Line 835 ⟶ 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.
<
v+*86%+55:p00<
>\55+/:00g1+\|
Line 847 ⟶ 1,576:
2^,+55_,#!>#:<
>/>\#<$#-:#1_v
>_@#<,+55,,,$<</
{{out}} (multiple runs)
Line 886 ⟶ 1,615:
=={{header|Bracmat}}==
<
= x p
. @(!arg:? [?p:? [(1/2*!p+-3/2) %?x [(1/2*!p+3/2) ?)
Line 901 ⟶ 1,630:
&
);
</syntaxhighlight>
Output:
<pre>123
Line 923 ⟶ 1,652:
=={{header|Burlesque}}==
<
blsq ) {123 12345 1234567 987654321 -10001 -123}{XX{~-}{L[3.>}w!m]\[}m[uN
123
Line 931 ⟶ 1,660:
000
123
</syntaxhighlight>
<tt>m]\[</tt> and <tt>uN</tt> are just for displaying it nicely.
Line 937 ⟶ 1,666:
=={{header|C}}==
This code is followed by its output.
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
Line 969 ⟶ 1,698:
}
return 0;
}</
<pre>
Line 993 ⟶ 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">
#include <stdio.h>
#include <stdlib.h>
Line 1,049 ⟶ 1,778:
}
}</
{{out}}
Line 1,073 ⟶ 1,802:
Error, 0 is too short.
The middle three digits of 1234567890 are 456.
</pre>
=={{header|C++}}==
<
std::string middleThreeDigits(int n)
Line 1,138 ⟶ 1,832:
}
}
</syntaxhighlight>
{{out}}
<pre>middleThreeDigits(123): 123
Line 1,157 ⟶ 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
(let [
(cond
(< len 3) :
(even? len) :
:else (let [
(subs digit-str (- half
(clojure.pprint/print-table
(for [i [123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0]]
{:i i :middle-3 (middle3 i)}))
</syntaxhighlight>
{{out}}
<pre>
| :i | :middle-3 |
|-----------+-------------------|
| 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 | :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}}==
<
program-id. middle3.
environment division.
Line 1,277 ⟶ 2,062:
add 1 to digit-counter
end-perform.
exit paragraph.</
Output
<pre> 123 --> 123
Line 1,297 ⟶ 2,082:
0 --> Number too small</pre>
Optimised version
<
program-id. middle3.
environment division.
Line 1,369 ⟶ 2,154:
end-if.
</syntaxhighlight>
Output
<pre> 123 --> 123
Line 1,391 ⟶ 2,176:
=={{header|Common Lisp}}==
===Solution #1===
<syntaxhighlight lang="lisp">
(defun mid3 (n)
(let ((a (abs n))
Line 1,404 ⟶ 2,190:
((evenp hmd) (need "odd number of"))
(t (nbr (mod (truncate a (expt 10 (/ (- hmd 3) 2))) 1000)))))))
</syntaxhighlight>
Test code:
<
(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>
{{out}}
<pre>123: 123
Line 1,432 ⟶ 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}}==
<
string middleThreeDigits(T)(in T n) pure nothrow if (isIntegral!T) {
Line 1,454 ⟶ 2,317:
foreach (immutable n; failing)
writefln("middleThreeDigits(%s): %s", n, middleThreeDigits(n));
}</
{{out}}
<pre>middleThreeDigits(123): 123
Line 1,480 ⟶ 2,343:
===Alternative Version===
This longer version gives a stronger typed output, and it tries to be faster avoiding conversions to string.
<
/// Returns a string with the error, or the three digits.
Line 1,566 ⟶ 2,429:
writefln("middleThreeDigits(cast(short)%d): %s", n, mtd);
}
}</
{{out}}
<pre>middleThreeDigits(123): 123
Line 1,617 ⟶ 2,480:
=={{header|Dart}}==
<syntaxhighlight lang="text">
import'dart:math';
int length(int x)
Line 1,664 ⟶ 2,527:
}
}
</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,680 ⟶ 2,544:
$ endif
$ i = i + 1
$ goto loop</
{{out}}
<pre>$ @middle_three_digits
Line 1,700 ⟶ 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">
class
APPLICATION
Line 1,764 ⟶ 2,668:
end
</syntaxhighlight>
{{out}}
<pre>
Line 1,786 ⟶ 2,690:
</pre>
=={{header|Elena}}==
ELENA
<
import extensions;
Line 1,797 ⟶ 2,702:
if(len<3)
{
InvalidArgumentException.new
}
else if(len.isEven())
{
InvalidArgumentException.new
};
Line 1,812 ⟶ 2,717:
{
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)
}
}</
{{out}}
<pre>
Line 1,839 ⟶ 2,744:
=={{header|Elixir}}==
<
def three(num) do
n = num |> abs |> to_string
Line 1,868 ⟶ 2,773:
e -> IO.puts e.message
end
end)</
{{out}}
Line 1,892 ⟶ 2,797:
=={{header|Erlang}}==
<
-module(middle_three_digits).
-export([main/0]).
Line 1,931 ⟶ 2,836:
loop(X,N) when X>0 ->
loop(X-1, N div 10).
</syntaxhighlight>
{{out}}
<pre>123
Line 1,954 ⟶ 2,859:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM MIDDLE
Line 1,999 ⟶ 2,904:
END FOR
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 2,022 ⟶ 2,927:
=={{header|Factor}}==
<syntaxhighlight lang="text">USING: combinators formatting io kernel math math.parser
sequences ;
IN: rosetta-code.middle-three-digits
CONSTANT: test-values {
-123 -100 100 -12345 1 2 -1 -10 2002 -2002 0
}
: (middle-three) ( str -- str' )
[ midpoint@ [ 1 - ] [ 2 + ] bi ]
: too-short ( -- )
"Number must have at least three digits." print ;
: number-even ( -- )
"Number must have an odd number of digits." print ;
:
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</
{{out}}
<pre>
Line 2,071 ⟶ 2,979:
=={{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.
<
abs s>d <# #s #> dup 2/ 0<> over 1 and 0<> and
if 2/ 1- chars + 3 else drop 0 then
;</
=={{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">
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sat Jun 1 14:48:41
Line 2,151 ⟶ 3,060:
end program MiddleMuddle
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
Function middleThreeDigits (n As Integer) As String
Line 2,185 ⟶ 3,094:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 2,208 ⟶ 3,117:
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]'''
<
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
Line 2,234 ⟶ 3,208:
Next
End</
Output:
<pre>
Line 2,259 ⟶ 3,233:
File m3.go:
<
import (
Line 2,284 ⟶ 3,258:
m := len(s) / 2
return s[m-1 : m+2], nil
}</
File m3_test.go:
<
import (
Line 2,344 ⟶ 3,318:
t.Logf("d(%d) returns %q", tc.i, err)
}
}</
{{out}}
Output of go test is normally terse:
Line 2,377 ⟶ 3,351:
=={{header|Gosu}}==
<
valid.each(\ num ->print(middleThree(num)))
Line 2,389 ⟶ 3,363:
var start = (s.length / 2) - 1
return s.substring(start, start + 3)
}</
{{Output}}
Line 2,412 ⟶ 3,386:
=={{header|Groovy}}==
<
def text = Math.abs(number) as String
assert text.size() >= 3 : "'$number' must be more than 3 numeric digits"
Line 2,419 ⟶ 3,393:
int start = text.size() / 2 - 1
text[start..(start+2)]
}</
Test Code:
<
def text = (number as String).padLeft(10)
try {
Line 2,428 ⟶ 3,402:
println "$text cannot be converted: $error.message"
}
}</
Output:
<pre> 123: 123
Line 2,449 ⟶ 3,423:
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">------------------- MIDDLE THREE DIGITS ------------------
mid3 :: Int -> Either String String
mid3 n
| m < 100 = Left "
| even lng = Left "
| otherwise = Right . take 3 $ drop ((lng - 3) `div` 2) s
where
Line 2,459 ⟶ 3,435:
lng = length s
main :: IO ()
main = do
Line 2,481 ⟶ 3,457:
, 0
]
w = maximum $
(putStrLn . unlines) $
(\n ->
xs
Output:
<pre> 123 -> 123
Line 2,501 ⟶ 3,477:
100 -> 100
-12345 -> 234
1 -> (
2 -> (
-1 -> (
-10 -> (
2002 -> (
-2002 -> (
0 -> (
=={{header|Icon}} and {{header|Unicon}}==
Line 2,513 ⟶ 3,489:
The following solution works in both languages.
<
every n := !a do write(right(n,15)," -> ",midM(n))
end
Line 2,524 ⟶ 3,500:
else "wrong number of digits"
else "too short"
end</
with output:
Line 2,549 ⟶ 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:'''
<
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@:|</
'''Example:'''
<
getMiddle3 vals
123
Line 2,573 ⟶ 3,552:
err
err
err</
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}}==
<
public static void main(String[] args) {
Line 2,602 ⟶ 3,600:
return s.substring(mid - 1, mid + 2);
}
}</
<pre>middleThreeDigits(123): 123
middleThreeDigits(12345): 234
Line 2,626 ⟶ 3,624:
=={{header|JavaScript}}==
<
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,635 ⟶ 3,633:
1, 2, -1, -10, 2002, -2002, 0].forEach(function(n){
try{console.log(n,middleThree(n))}catch(e){console.error(e.message)}
});</
<pre>123 "123"
Line 2,658 ⟶ 3,656:
Or, using an option type, composing a solution from existing generic primitives, and formatting the output a little:
{{Trans|Python}}
<
'use strict';
Line 2,783 ⟶ 3,781:
// MAIN ---
return main();
})();</
{{Out}}
<pre>
Line 2,805 ⟶ 3,803:
=={{header|jq}}==
<
if . < 0 then -. else . end
| tostring as $s
Line 2,814 ⟶ 3,812:
(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0)
| "\(.) => \( .|middle3 )"</
Typescript:<
123 => 123
12345 => 234
Line 2,832 ⟶ 3,830:
2002 => invalid length: 4
-2002 => invalid length: 4
0 => invalid length: 1 </
=={{header|Julia}}==
{{works with|Julia|1.0.3}}
<
function middle3(n::Integer)
Line 2,849 ⟶ 3,848:
-100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0]
@printf("%10d -> %s\n", n, try middle3(n) catch e e.msg end)
end</
{{out}}
Line 2,871 ⟶ 3,870:
=={{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}}
Line 2,903 ⟶ 3,902:
"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}}==
<
mid3::{[d k];:[3>k::#$#x;"small":|0=k!2;"even";(-d)_(d::_(k%2)-1)_$#x]}
.p(mid3'items)</
Output:
<pre>[123 234 345 654 000 000 123 100 100 234 small small small small even even small]</pre>
=={{header|Kotlin}}==
<
val s = Math.abs(x).toString()
return when {
Line 2,928 ⟶ 3,962:
println(middleThree(123))// 123
println(middleThree(123555)) //null
}</
=={{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}}==
<
local(
pos_value = math_abs(#value),
Line 2,952 ⟶ 4,031:
'<br />'
^}
'</pre>'</
'''Output'''
<pre> 123: 123
Line 2,973 ⟶ 4,052:
=={{header|Logo}}==
<
if [less? :n 0] [make "n minus :n]
local "len make "len count :n
Line 2,991 ⟶ 4,070:
]
bye</
{{Output}}
Line 3,013 ⟶ 4,092:
=={{header|Lua}}==
<
if n < 0 then
n = -n
Line 3,038 ⟶ 4,117:
print(n, middle_three(n))
end
end</
{{out}}
Line 3,060 ⟶ 4,139:
=={{header|Maple}}==
<
local nList, start;
nList := [seq(parse(i), i in convert (abs(n), string))];
Line 3,078 ⟶ 4,157:
middleDigits(i);
printf("\n");
end do;</
{{out}}
<pre>
Line 3,100 ⟶ 4,179:
</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Block[{digits = IntegerDigits[n], len},
len = Length[digits];
Line 3,111 ⟶ 4,190:
100, -12345, 1, 2, -1, -10, 2002, -2002, 0};
Column[middleThree /@ testData]</
{{out}}<pre>123
234
345
Line 3,129 ⟶ 4,207:
err: even number of digits
err: even number of digits
err: n too small</pre>
=={{header|MATLAB}} / {{header|Octave}}==
<
% http://rosettacode.org/wiki/Middle_three_digits
Line 3,147 ⟶ 4,224:
end;
s = s((length(s)+1)/2+[-1:1]);</
Test with
<
for k=1:length(x); fprintf(1,'%9i:%s\n',x(k),middle_three_digits(x(k)));end;</
Result
<pre>
Line 3,173 ⟶ 4,250:
=={{header|MiniScript}}==
<
if s.len < 3 then return "Input too short"
if s.len %
mid = (s.len + 1) / 2 - 1
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(
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
/</
''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 3,237 ⟶ 4,292:
=={{header|ML}}==
==={{header|mLite}}===
<
val test_array = ["123","12345","1234567","987654321","10001","~10001","~123","~100","100","~12345","1","2","~1","~10","2002","~2002","0"];
Line 3,262 ⟶ 4,317:
;
map (println o middleThreeDigits) test_array;</
Output:
<pre>123 --> 123
Line 3,284 ⟶ 4,339:
=={{header|MUMPS}}==
This sample shows the MUMPS code required to pass the specification.
<
MID3(N) ;
N LEN,N2
Line 3,294 ⟶ 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>
'''Output:'''
<pre>
Line 3,318 ⟶ 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.
<
options replace format comments java crossref symbols nobinary
Line 3,364 ⟶ 4,419:
end
return text
</syntaxhighlight>
'''Output:'''
<pre>
Line 3,394 ⟶ 4,449:
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">
(define (middle3 x)
(if (even? (length x))
Line 3,406 ⟶ 4,461:
(map middle3 lst)
</syntaxhighlight>
'''Output:'''
<pre>
Line 3,429 ⟶ 4,484:
=={{header|Nim}}==
<syntaxhighlight lang="nim">proc middleThreeDigits(i: int): string =
var s = $abs(i)
if s.len < 3 or s.len mod 2 == 0:
Line 3,437 ⟶ 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</
{{out}}
<pre>middleThreeDigits(123) returned: 123
middleThreeDigits(12345) returned: 234
Line 3,465 ⟶ 4,519:
=={{header|Objeck}}==
<
class Test {
function : Main(args : String[]) ~ Nil {
Line 3,478 ⟶ 4,532:
}
}</
<pre>
Line 3,502 ⟶ 4,556:
=={{header|OCaml}}==
<
let middle_three_digits x =
Line 3,526 ⟶ 4,580:
print_endline "Should fail:";
List.iter print failing;
;;</
{{out}}
Line 3,554 ⟶ 4,608:
=={{header|Oforth}}==
<
| 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 ;</
{{out}}
Line 3,578 ⟶ 4,632:
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.6.0}}
<
apply(middle,[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0])</
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
<
For earlier versions <code>digits</code> can be defined as
<
or more efficiently as
<
=={{header|Pascal}}==
{{works with|Free Pascal}}
<
{$IFDEF FPC}
{$MODE Delphi} //result /integer => Int32 aka longInt etc..
Line 3,628 ⟶ 4,683:
writeln(n:9,': ',GetMid3dig(Test[i]));
end;
end.</
{{out}}
<pre> 123: 123
Line 3,648 ⟶ 4,703:
0: got too few digits
</pre>
=={{header|Perl}}==
<
use strict ;
use warnings ;
Line 3,674 ⟶ 4,730:
1, 2, -1, -10, 2002, -2002, 0 ) ;
map { middlethree( $_ ) } @numbers ;
</syntaxhighlight>
{{out}}
<pre>Middle 3 digits of 123 : 123 !
Line 3,694 ⟶ 4,750:
Middle 3 digits can't be shown : 0 too short!
</pre>
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 3,768 ⟶ 4,787:
=={{header|PHP}}==
<
// 64-bit builds of PHP: Integers can be from -9223372036854775808 to 9223372036854775807
Line 3,806 ⟶ 4,825:
{
echo $nums.' : '.middlethree($nums). '<br>';
}</
Output:
<pre>123 : 123
Line 3,825 ⟶ 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}}==
<
(let (Lst (chop (abs N)) Len (length Lst))
(tab (10 -2 -30)
Line 3,836 ⟶ 4,913:
((bit? 1 Len)
(head 3 (nth Lst (/ Len 2))) )
(T "even number of digits") ) ) ) )</
Test:
<
(123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0 ) )</
Output:
<pre> 123: 123
Line 3,859 ⟶ 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">
middle: procedure options (main); /* 29 October 2013 */
declare n fixed (15);
Line 3,886 ⟶ 5,011:
end middle;
</syntaxhighlight>
Output:
<pre>
Line 3,905 ⟶ 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}}==
<
$str = [Math]::abs($inp)
Line 3,931 ⟶ 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}</
{{Out}}
<pre>123: 123
Line 3,950 ⟶ 5,134:
-2002: [ERROR] even number of digits.
0: [ERROR] too short.</pre>
=={{header|Prolog}}==
{{works with|SWI-Prolog|6}}
<
middle_3_digits(Number, [D1,D2,D3]) :-
verify_middle_3_able(Number, Digits),
Line 3,970 ⟶ 5,153:
; true
).
</syntaxhighlight>
Test code:
<
test_correct :-
TestCases = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345],
Line 3,982 ⟶ 5,165:
format('Middle 3 digits of ~w ~30|: ~w~n', [TestCase, Result])
).
</syntaxhighlight>
Line 4,022 ⟶ 5,205:
=={{header|Python}}==
===Procedural===
<
s = str(abs(i))
length = len(s)
Line 4,056 ⟶ 5,239:
middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)
>>> </
===Composition of pure functions===
Using a composable option type as an alternative to error handling:
{{Trans|Haskell}}
<
Line 4,145 ⟶ 5,328:
if __name__ == '__main__':
main()</
{{Out}}
<pre>Middle three digits, where defined:
Line 4,166 ⟶ 5,349:
-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}}==
<
(define (middle x)
(cond
Line 4,181 ⟶ 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))</
The output:
<
'("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")</
=={{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===
<
* 03.02.2013 Walter Pachl
* 19.04.2013 mid 3 is now a function returning the middle 3 digits
Line 4,216 ⟶ 5,491:
End
End
Return res</
Output:
<pre>
Line 4,245 ⟶ 5,520:
<br><br>This REXX version is limited to numbers whose length is <big>≤</big> 100,000 decimal digits.
<br>(The decimal digits limit is defined via the '''numeric digits''' statement in the first line of the subroutine/procedure.)
<
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 4,260 ⟶ 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)</
'''output'''
<pre>
Line 4,290 ⟶ 5,565:
=={{header|Ring}}==
<
n = 1234567
middle(n)
Line 4,301 ⟶ 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>
=={{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}}==
<
# minus sign doesn't factor into digit count,
# and calling #abs acts as a duck-type assertion
Line 4,318 ⟶ 5,615:
return str[length/2 - 1, 3].to_i
end</
Testing program:
<
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0
Line 4,335 ⟶ 5,632:
puts e
end
end</
{{out}}
<pre>
Line 4,358 ⟶ 5,655:
=={{header|Rust}}==
<
let s: String = x.abs().to_string();
let len = s.len();
Line 4,387 ⟶ 5,684:
print_result(*i);
}
}</
{{Out}}
Line 4,423 ⟶ 5,720:
course just list the numbers backwards.
</pre>
<
define m3(i)
{
Line 4,453 ⟶ 5,750:
#endif
1, 2, -1, -10, 2002, -2002, 0 } );
</syntaxhighlight>
{{out}}<pre>
" 123: 123"
Line 4,477 ⟶ 5,774:
=={{header|Scala}}==
<
* Optionally return the middle three digits of an integer.
*
Line 4,498 ⟶ 5,795:
case Some(v) => "%03d".format(v) // Format the value, force leading zeroes
} mkString("\n")
</syntaxhighlight>
{{out}}
<pre>123
Line 4,517 ⟶ 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}}==
<
const func string: middle3 (in integer: number) is func
Line 4,543 ⟶ 5,874:
writeln(number <& ": " <& middle3(number));
end for;
end func;</
{{out}}
Line 4,564 ⟶ 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|
<
var l = n.len
if (l < 3) {
"#{n} is too short"
Line 4,575 ⟶ 5,950:
"#{n} has an even number of digits"
} else {
"The three middle digits of #{n} are: " + n.digits.
}
}
Line 4,582 ⟶ 5,957:
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0
)
nums.each { say middle_three(_) }
{{out}}
<pre>
Line 4,606 ⟶ 5,981:
=={{header|SQL}}==
<
AS (SELECT CAST(ABS(NUMBER) AS NVARCHAR(MAX)) charNum,
NUMBER,
Line 4,617 ⟶ 5,992:
END Output,
NUMBER Input
FROM DATA </
<pre>
Line 4,646 ⟶ 6,021:
</pre>
=={{header|Swift}}==
<
if num<0{num = -num}
var numArray:[Int]=[]
Line 4,662 ⟶ 6,038:
i=i/2
print("\(numArray[i+1]),\(numArray[i]),\(numArray[i-1])")
}</
<pre>
123: 123
Line 4,682 ⟶ 6,058:
0: Invalid Input
</pre>
=={{header|Tcl}}==
<
if {$n < 0} {
set n [expr {-$n}]
Line 4,698 ⟶ 6,073:
set idx [expr {$idx / 2}]
string range $n $idx [expr {$idx+2}]
}</
Demonstrating:
<
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0
Line 4,711 ⟶ 6,086:
puts "found for ${n}: $mid"
}
}</
{{out}}
<pre>
Line 4,733 ⟶ 6,108:
</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|Uiua}}==
{{Works with |Uiua|0.12.0-dev.1}}
Uses `assert` and `try` to handle the exceptions.
<syntaxhighlight lang="uiua">
[123 12345 1234567 987654321 10001 ¯10001 ¯123 ¯100 100 ¯12345
1 2 ¯1 ¯10 2002 ¯2002 0]
Mid ← (
⍤("too short")≥3.⧻.°□°⋕⌵
⍤("even length")≠0◿2.
↘¯⟜↘⌊÷2-3
)
⍉⊟⟜≡⍚⍣(Mid|⊂"Error: "◌) # Convert each
≡(&p$"_\t->\t_"°⊟) # Display
</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 short
2 -> Error: too short
-1 -> Error: too short
-10 -> Error: too short
2002 -> Error: even length
-2002 -> Error: even length
0 -> Error: too short
</pre>
=={{header|UNIX Shell}}==
{{works with|Bourne Again Shell}}
Line 4,738 ⟶ 6,254:
{{works with|Z Shell}}
<
{
typeset -i n="${1#-}"
Line 4,760 ⟶ 6,276:
printf "%10d: " $n
middle3digits "$n"
done</
Output: <pre> 123: 123
Line 4,782 ⟶ 6,298:
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 4,804 ⟶ 6,320:
End If
End Function
</syntaxhighlight>
{{out}}
<pre>123 Return : 123
Line 4,825 ⟶ 6,341:
=={{header|VBScript}}==
<
Function mid3n(n)
Line 4,845 ⟶ 6,361:
WScript.StdOut.Write n & ": " & mid3n(n)
WScript.StdOut.WriteLine
Next</
{{Out}}
<pre>
Line 4,868 ⟶ 6,384:
=={{header|Vedit macro language}}==
<
#1 = Get_Num("Enter a number, or 0 to stop: ", STATLINE)
Ins_Text("Input: ") Num_Ins(#1, COUNT, 10)
Line 4,896 ⟶ 6,412:
}
Buf_Quit(OK)
Return </
Output:
Line 4,916 ⟶ 6,432:
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}}==
<
withs (digits (with outstring # itoa
(pr abs.n))
Line 4,925 ⟶ 6,486:
mid (int max/2))
if (and odd?.max (max >= 3))
(digits mid-1 mid+2)</
'''Output'''
Line 4,964 ⟶ 6,525:
(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}}==
<
func Mid3Digits(I); \Return the middle three digits of I
Line 4,989 ⟶ 6,593:
Text(0, Mid3Digits(Passing(X))); CrLf(0);
];
]</
{{out}}
Line 5,013 ⟶ 6,617:
=={{header|zkl}}==
<
ns.apply("toString").apply('-("-"))
.apply(fcn(n){nl:=n.len();
Line 5,021 ⟶ 6,625:
}
middle(T(123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345)).println()
middle(T(1, 2, -1, -10, 2002, -2002, 0)).println();</
{{out}}
<pre>
|