Middle three digits: Difference between revisions
Added Uiua solution
(Added Uiua solution) |
|||
(95 intermediate revisions by 43 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 675 ⟶ 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}}===
<
Protected x$, digitCount
Line 704 ⟶ 1,413:
Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Sample output:
<pre> 123 : 123
Line 725 ⟶ 1,434:
==={{header|Run BASIC}}===
<
while word$(x$,i+1,",") <> ""
Line 737 ⟶ 1,446:
end if
wend
end</
<pre>123 123
234 12345
Line 755 ⟶ 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 802 ⟶ 1,544:
)
goto :EOF
%==/The Procedure ==%</
{{Out}}
<pre>123: 123
Line 823 ⟶ 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 835 ⟶ 1,576:
2^,+55_,#!>#:<
>/>\#<$#-:#1_v
>_@#<,+55,,,$<</
{{out}} (multiple runs)
Line 874 ⟶ 1,615:
=={{header|Bracmat}}==
<
= x p
. @(!arg:? [?p:? [(1/2*!p+-3/2) %?x [(1/2*!p+3/2) ?)
Line 889 ⟶ 1,630:
&
);
</syntaxhighlight>
Output:
<pre>123
Line 911 ⟶ 1,652:
=={{header|Burlesque}}==
<
blsq ) {123 12345 1234567 987654321 -10001 -123}{XX{~-}{L[3.>}w!m]\[}m[uN
123
Line 919 ⟶ 1,660:
000
123
</syntaxhighlight>
<tt>m]\[</tt> and <tt>uN</tt> are just for displaying it nicely.
Line 925 ⟶ 1,666:
=={{header|C}}==
This code is followed by its output.
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
Line 957 ⟶ 1,698:
}
return 0;
}</
<pre>
Line 981 ⟶ 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,037 ⟶ 1,778:
}
}</
{{out}}
Line 1,061 ⟶ 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,126 ⟶ 1,832:
}
}
</syntaxhighlight>
{{out}}
<pre>middleThreeDigits(123): 123
Line 1,145 ⟶ 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,265 ⟶ 2,062:
add 1 to digit-counter
end-perform.
exit paragraph.</
Output
<pre> 123 --> 123
Line 1,285 ⟶ 2,082:
0 --> Number too small</pre>
Optimised version
<
program-id. middle3.
environment division.
Line 1,357 ⟶ 2,154:
end-if.
</syntaxhighlight>
Output
<pre> 123 --> 123
Line 1,379 ⟶ 2,176:
=={{header|Common Lisp}}==
===Solution #1===
<syntaxhighlight lang="lisp">
(defun mid3 (n)
(let ((a (abs n))
Line 1,392 ⟶ 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,420 ⟶ 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,442 ⟶ 2,317:
foreach (immutable n; failing)
writefln("middleThreeDigits(%s): %s", n, middleThreeDigits(n));
}</
{{out}}
<pre>middleThreeDigits(123): 123
Line 1,468 ⟶ 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,554 ⟶ 2,429:
writefln("middleThreeDigits(cast(short)%d): %s", n, mtd);
}
}</
{{out}}
<pre>middleThreeDigits(123): 123
Line 1,605 ⟶ 2,480:
=={{header|Dart}}==
<syntaxhighlight lang="text">
import'dart:math';
int length(int x)
Line 1,652 ⟶ 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,668 ⟶ 2,544:
$ endif
$ i = i + 1
$ goto loop</
{{out}}
<pre>$ @middle_three_digits
Line 1,688 ⟶ 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,752 ⟶ 2,668:
end
</syntaxhighlight>
{{out}}
<pre>
Line 1,774 ⟶ 2,690:
</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
else if(len
InvalidArgumentException
int mid := len / 2
^ s
}
public program()
{
.forEach
}</syntaxhighlight>
{{out}}
<pre>
Line 1,827 ⟶ 2,744:
=={{header|Elixir}}==
<
def three(num) do
n = num |> abs |> to_string
Line 1,856 ⟶ 2,773:
e -> IO.puts e.message
end
end)</
{{out}}
Line 1,880 ⟶ 2,797:
=={{header|Erlang}}==
<
-module(middle_three_digits).
-export([main/0]).
Line 1,919 ⟶ 2,836:
loop(X,N) when X>0 ->
loop(X-1, N div 10).
</syntaxhighlight>
{{out}}
<pre>123
Line 1,942 ⟶ 2,859:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM MIDDLE
Line 1,987 ⟶ 2,904:
END FOR
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 2,010 ⟶ 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,059 ⟶ 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,139 ⟶ 3,060:
end program MiddleMuddle
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
Function middleThreeDigits (n As Integer) As String
Line 2,173 ⟶ 3,094:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 2,196 ⟶ 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,222 ⟶ 3,208:
Next
End</
Output:
<pre>
Line 2,247 ⟶ 3,233:
File m3.go:
<
import (
Line 2,272 ⟶ 3,258:
m := len(s) / 2
return s[m-1 : m+2], nil
}</
File m3_test.go:
<
import (
Line 2,332 ⟶ 3,318:
t.Logf("d(%d) returns %q", tc.i, err)
}
}</
{{out}}
Output of go test is normally terse:
Line 2,365 ⟶ 3,351:
=={{header|Gosu}}==
<
valid.each(\ num ->print(middleThree(num)))
Line 2,377 ⟶ 3,363:
var start = (s.length / 2) - 1
return s.substring(start, start + 3)
}</
{{Output}}
Line 2,400 ⟶ 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,407 ⟶ 3,393:
int start = text.size() / 2 - 1
text[start..(start+2)]
}</
Test Code:
<
def text = (number as String).padLeft(10)
try {
Line 2,416 ⟶ 3,402:
println "$text cannot be converted: $error.message"
}
}</
Output:
<pre> 123: 123
Line 2,437 ⟶ 3,423:
=={{header|Haskell}}==
<syntaxhighlight lang="haskell">------------------- MIDDLE THREE DIGITS ------------------
mid3 :: Int -> Either String String
mid3 n
| m < 100 = Left "
| even
| otherwise = Right . take 3 $ drop ((
where
m = abs n
s = show m
--------------------------- TEST -------------------------
main :: IO ()
main = do
let xs =
[ 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
12345
1234567
987654321
10001
-10001
-123
-100
100
-12345
1
2
-1
-10
-2002
0
=={{header|Icon}} and {{header|Unicon}}==
Line 2,495 ⟶ 3,489:
The following solution works in both languages.
<
every n := !a do write(right(n,15)," -> ",midM(n))
end
Line 2,506 ⟶ 3,500:
else "wrong number of digits"
else "too short"
end</
with output:
Line 2,531 ⟶ 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,555 ⟶ 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,584 ⟶ 3,600:
return s.substring(mid - 1, mid + 2);
}
}</
<pre>middleThreeDigits(123): 123
middleThreeDigits(12345): 234
Line 2,608 ⟶ 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,617 ⟶ 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,636 ⟶ 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}}==
<
if . < 0 then -. else . end
| tostring as $s
Line 2,647 ⟶ 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,665 ⟶ 3,830:
2002 => invalid length: 4
-2002 => invalid length: 4
0 => invalid length: 1 </
=={{header|Julia}}==
{{works with|Julia|1.0.
<syntaxhighlight lang="julia">using Printf
function middle3(n::Integer)
iseven(l) &&
l < 3 && error("n must have 3 digits or more")
mid = (l + 1) ÷ 2
end
Line 2,684 ⟶ 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,704 ⟶ 3,868:
-2002 -> n must have an odd number of digits
0 -> n must have 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}}==
<
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}}==
<syntaxhighlight lang="scala">fun middleThree(x: Int): Int? {
val s = Math.abs(x).toString()
return when {
Line 2,730 ⟶ 3,962:
println(middleThree(123))// 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}}==
<
local(
pos_value = math_abs(#value),
Line 2,755 ⟶ 4,031:
'<br />'
^}
'</pre>'</
'''Output'''
<pre> 123: 123
Line 2,776 ⟶ 4,052:
=={{header|Logo}}==
<
if [less? :n 0] [make "n minus :n]
local "len make "len count :n
Line 2,794 ⟶ 4,070:
]
bye</
{{Output}}
Line 2,816 ⟶ 4,092:
=={{header|Lua}}==
<
if n < 0 then
n = -n
Line 2,841 ⟶ 4,117:
print(n, middle_three(n))
end
end</
{{out}}
Line 2,863 ⟶ 4,139:
=={{header|Maple}}==
<
local nList, start;
nList := [seq(parse(i), i in convert (abs(n), string))];
Line 2,881 ⟶ 4,157:
middleDigits(i);
printf("\n");
end do;</
{{out}}
<pre>
Line 2,903 ⟶ 4,179:
</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Block[{digits = IntegerDigits[n], len},
len = Length[digits];
Line 2,914 ⟶ 4,190:
100, -12345, 1, 2, -1, -10, 2002, -2002, 0};
Column[middleThree /@ testData]</
{{out}}<pre>123
234
345
Line 2,932 ⟶ 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 2,950 ⟶ 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 2,974 ⟶ 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
/</
''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,985 ⟶ 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,010 ⟶ 4,317:
;
map (println o middleThreeDigits) test_array;</
Output:
<pre>123 --> 123
Line 3,032 ⟶ 4,339:
=={{header|MUMPS}}==
This sample shows the MUMPS code required to pass the specification.
<
MID3(N) ;
N LEN,N2
Line 3,042 ⟶ 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,066 ⟶ 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,112 ⟶ 4,419:
end
return text
</syntaxhighlight>
'''Output:'''
<pre>
Line 3,142 ⟶ 4,449:
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">
(define (middle3 x)
(if (even? (length x))
Line 3,154 ⟶ 4,461:
(map middle3 lst)
</syntaxhighlight>
'''Output:'''
<pre>
Line 3,177 ⟶ 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,185 ⟶ 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,213 ⟶ 4,519:
=={{header|Objeck}}==
<
class Test {
function : Main(args : String[]) ~ Nil {
Line 3,226 ⟶ 4,532:
}
}</
<pre>
Line 3,250 ⟶ 4,556:
=={{header|OCaml}}==
<
let middle_three_digits x =
Line 3,274 ⟶ 4,580:
print_endline "Should fail:";
List.iter print failing;
;;</
{{out}}
Line 3,302 ⟶ 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,326 ⟶ 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,376 ⟶ 4,683:
writeln(n:9,': ',GetMid3dig(Test[i]));
end;
end.</
{{out}}
<pre> 123: 123
Line 3,396 ⟶ 4,703:
0: got too few digits
</pre>
=={{header|Perl}}==
<
use strict ;
use warnings ;
Line 3,422 ⟶ 4,730:
1, 2, -1, -10, 2002, -2002, 0 ) ;
map { middlethree( $_ ) } @numbers ;
</syntaxhighlight>
{{out}}
<pre>Middle 3 digits of 123 : 123 !
Line 3,442 ⟶ 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,516 ⟶ 4,787:
=={{header|PHP}}==
<
// 64-bit builds of PHP: Integers can be from -9223372036854775808 to 9223372036854775807
Line 3,554 ⟶ 4,825:
{
echo $nums.' : '.middlethree($nums). '<br>';
}</
Output:
<pre>123 : 123
Line 3,573 ⟶ 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,584 ⟶ 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,607 ⟶ 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,634 ⟶ 5,011:
end middle;
</syntaxhighlight>
Output:
<pre>
Line 3,653 ⟶ 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,679 ⟶ 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,698 ⟶ 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,718 ⟶ 5,153:
; true
).
</syntaxhighlight>
Test code:
<
test_correct :-
TestCases = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345],
Line 3,730 ⟶ 5,165:
format('Middle 3 digits of ~w ~30|: ~w~n', [TestCase, Result])
).
</syntaxhighlight>
Line 3,769 ⟶ 5,204:
=={{header|Python}}==
===Procedural===
<syntaxhighlight lang="python">>>> def middle_three_digits(i):
s = str(abs(i))
length = len(s)
Line 3,803 ⟶ 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}}
<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}}==
<
(define (middle x)
(cond
Line 3,819 ⟶ 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 3,854 ⟶ 5,491:
End
End
Return res</
Output:
<pre>
Line 3,882 ⟶ 5,519:
<br>So is the value of a '''googol''' and a '''googolplex'''.
<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
<
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,898 ⟶ 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 3,928 ⟶ 5,565:
=={{header|Ring}}==
<
n = 1234567
middle(n)
Line 3,939 ⟶ 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 3,956 ⟶ 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 3,973 ⟶ 5,632:
puts e
end
end</
{{out}}
<pre>
Line 3,996 ⟶ 5,655:
=={{header|Rust}}==
<
let s: String = x.abs().to_string();
let len = s.len();
Line 4,025 ⟶ 5,684:
print_result(*i);
}
}</
{{Out}}
Line 4,061 ⟶ 5,720:
course just list the numbers backwards.
</pre>
<
define m3(i)
{
Line 4,091 ⟶ 5,750:
#endif
1, 2, -1, -10, 2002, -2002, 0 } );
</syntaxhighlight>
{{out}}<pre>
" 123: 123"
Line 4,115 ⟶ 5,774:
=={{header|Scala}}==
<
* Optionally return the middle three digits of an integer.
*
Line 4,136 ⟶ 5,795:
case Some(v) => "%03d".format(v) // Format the value, force leading zeroes
} mkString("\n")
</syntaxhighlight>
{{out}}
<pre>123
Line 4,155 ⟶ 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,181 ⟶ 5,874:
writeln(number <& ": " <& middle3(number));
end for;
end func;</
{{out}}
Line 4,202 ⟶ 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,213 ⟶ 5,950:
"#{n} has an even number of digits"
} else {
"The three middle digits of #{n} are: " + n.digits.
}
}
Line 4,220 ⟶ 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,244 ⟶ 5,981:
=={{header|SQL}}==
<
AS (SELECT CAST(ABS(NUMBER) AS NVARCHAR(MAX)) charNum,
NUMBER,
Line 4,255 ⟶ 5,992:
END Output,
NUMBER Input
FROM DATA </
<pre>
Line 4,284 ⟶ 6,021:
</pre>
=={{header|Swift}}==
<
if num<0{num = -num}
var numArray:[Int]=[]
Line 4,300 ⟶ 6,038:
i=i/2
print("\(numArray[i+1]),\(numArray[i]),\(numArray[i-1])")
}</
<pre>
123: 123
Line 4,320 ⟶ 6,058:
0: Invalid Input
</pre>
=={{header|Tcl}}==
<
if {$n < 0} {
set n [expr {-$n}]
Line 4,336 ⟶ 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,349 ⟶ 6,086:
puts "found for ${n}: $mid"
}
}</
{{out}}
<pre>
Line 4,371 ⟶ 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,376 ⟶ 6,254:
{{works with|Z Shell}}
<
{
typeset -i n="${1#-}"
Line 4,398 ⟶ 6,276:
printf "%10d: " $n
middle3digits "$n"
done</
Output: <pre> 123: 123
Line 4,420 ⟶ 6,298:
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 4,442 ⟶ 6,320:
End If
End Function
</syntaxhighlight>
{{out}}
<pre>123 Return : 123
Line 4,463 ⟶ 6,341:
=={{header|VBScript}}==
<
Function mid3n(n)
Line 4,483 ⟶ 6,361:
WScript.StdOut.Write n & ": " & mid3n(n)
WScript.StdOut.WriteLine
Next</
{{Out}}
<pre>
Line 4,506 ⟶ 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,534 ⟶ 6,412:
}
Buf_Quit(OK)
Return </
Output:
Line 4,554 ⟶ 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,563 ⟶ 6,486:
mid (int max/2))
if (and odd?.max (max >= 3))
(digits mid-1 mid+2)</
'''Output'''
Line 4,602 ⟶ 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,627 ⟶ 6,593:
Text(0, Mid3Digits(Passing(X))); CrLf(0);
];
]</
{{out}}
Line 4,651 ⟶ 6,617:
=={{header|zkl}}==
<
ns.apply("toString").apply('-("-"))
.apply(fcn(n){nl:=n.len();
Line 4,659 ⟶ 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>
|