Middle three digits: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|J}}) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 17:
{{trans|Python}}
<
V s = String(abs(i))
assert(s.len >= 3 & s.len % 2 == 1, ‘Need odd and >= 3 digits’)
Line 29:
print(‘middle_three_digits(#.) returned: #.’.format(x, answer))
X.catch AssertionError error
print(‘middle_three_digits(#.) returned error: ’.format(x)‘’String(error))</
{{out}}
Line 55:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<
INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit
Line 99:
Test("2002") Test("-2002")
Test("0")
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Middle_three_digits.png Screenshot from Atari 8-bit computer]
Line 124:
=={{header|Ada}}==
<
procedure Middle_Three_Digits is
Line 166:
end loop;
end Middle_Three_Digits;</
{{out}}
Line 188:
=={{header|Aime}}==
<
m3(integer i)
{
Line 228:
return 0;
}</
{{out}}
<pre> 123: 123
Line 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 312:
print( ( newline ) )
OD
)</
{{out}}
<pre>
Line 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 382:
end for_n
end.</
{{out}}
<pre>
Line 408:
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.
<
try
n as number -- Errors if n isn't a number or coercible thereto.
Line 442:
set output to output as text
set AppleScript's text item delimiters to astid
return output</
{{output}}
<
The middle three digits of 12345 are 234.
The middle three digits of 1234567 are 345.
Line 462:
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."</
===Functional===
<
-- mid3digits :: Int -> Either String String
Line 755:
end tell
end if
end zipWith</
{{Out}}
<pre>Mid three digits:
Line 778:
=={{header|Arturo}}==
<
n: to :string abs num
if 3 > size n -> return "Number must have at least three digits"
Line 794:
loop samples 's [
print [pad to :string s 10 ":" middleThree s]
]</
{{out}}
Line 817:
=={{header|ATS}}==
<syntaxhighlight lang="ats">
(* ****** ****** *)
//
Line 938:
(* ****** ****** *)
</syntaxhighlight>
{{out}}
<pre>Middle-three-digits(123): 123
Line 959:
=={{header|AutoHotkey}}==
<
Loop, parse, Numbers, `,
{
Line 971:
log := log . A_LoopField . "`t: " . SubStr(n,((d-3)//2)+1,3) . "`n"
}
MsgBox % log</
{{out}}
<pre>123 : 123
Line 992:
=={{header|AWK}}==
<
# use as: awk -f middle_three_digits.awk
Line 1,020:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,044:
=={{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 1,066:
300 DATA123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345
310 DATA1,2,-1,-10,2002,-2002,0
</syntaxhighlight>
{{out}}
<pre>
Line 1,089:
==={{header|BBC BASIC}}===
<
FOR i% = 1 TO 17
READ test%
Line 1,109:
OTHERWISE
= MID$(n$, LEN n$ / 2, 3)
ENDCASE</
{{out}}
<pre> 123 -> 123
Line 1,130:
==={{header|FBSL}}===
<
DIM numbers AS STRING = "123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0"
Line 1,174:
RETURN m
END IF
END FUNCTION</
Output
<pre> 123 --> 123
Line 1,197:
==={{header|IS-BASIC}}===
<
120 PRINT MIDDLE$(N)
130 DEF MIDDLE$(N)
Line 1,205:
170 LET P=(LEN(N$)-3)/2
180 LET MIDDLE$=N$(P+1:P+3)
190 END DEF</
==={{header|PureBasic}}===
<
Protected x$, digitCount
Line 1,236:
Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Sample output:
<pre> 123 : 123
Line 1,257:
==={{header|Run BASIC}}===
<
while word$(x$,i+1,",") <> ""
Line 1,269:
end if
wend
end</
<pre>123 123
234 12345
Line 1,289:
=={{header|Batch File}}==
<
setlocal enabledelayedexpansion
Line 1,334:
)
goto :EOF
%==/The Procedure ==%</
{{Out}}
<pre>123: 123
Line 1,359:
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 1,366:
2^,+55_,#!>#:<
>/>\#<$#-:#1_v
>_@#<,+55,,,$<</
{{out}} (multiple runs)
Line 1,405:
=={{header|Bracmat}}==
<
= x p
. @(!arg:? [?p:? [(1/2*!p+-3/2) %?x [(1/2*!p+3/2) ?)
Line 1,420:
&
);
</syntaxhighlight>
Output:
<pre>123
Line 1,442:
=={{header|Burlesque}}==
<
blsq ) {123 12345 1234567 987654321 -10001 -123}{XX{~-}{L[3.>}w!m]\[}m[uN
123
Line 1,450:
000
123
</syntaxhighlight>
<tt>m]\[</tt> and <tt>uN</tt> are just for displaying it nicely.
Line 1,456:
=={{header|C}}==
This code is followed by its output.
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
Line 1,488:
}
return 0;
}</
<pre>
Line 1,512:
===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,568:
}
}</
{{out}}
Line 1,595:
=={{header|C++}}==
<
std::string middleThreeDigits(int n)
Line 1,622:
}
}
</syntaxhighlight>
{{out}}
<pre>middleThreeDigits(123): 123
Line 1,643:
=={{header|C_sharp|C#}}==
<
namespace RosettaCode
Line 1,655:
}
}
}</
{{out}}
<pre>123:123
Line 1,678:
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(defn middle3 [v]
(let [no (Math/abs v)
Line 1,695:
(def fails '(1 2 -1 -10 2002 -2002 0))
</syntaxhighlight>
{{out}}
Line 1,706:
=={{header|CLU}}==
<
signals (too_small, even_length)
s: string := int$unparse(int$abs(n))
Line 1,729:
end
end
end start_up</
{{out}}
<pre> 123: 123
Line 1,750:
=={{header|COBOL}}==
<
program-id. middle3.
environment division.
Line 1,840:
add 1 to digit-counter
end-perform.
exit paragraph.</
Output
<pre> 123 --> 123
Line 1,860:
0 --> Number too small</pre>
Optimised version
<
program-id. middle3.
environment division.
Line 1,932:
end-if.
</syntaxhighlight>
Output
<pre> 123 --> 123
Line 1,954:
=={{header|Common Lisp}}==
<
(defun mid3 (n)
(let ((a (abs n))
Line 1,967:
((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,997:
=={{header|D}}==
<
string middleThreeDigits(T)(in T n) pure nothrow if (isIntegral!T) {
Line 2,017:
foreach (immutable n; failing)
writefln("middleThreeDigits(%s): %s", n, middleThreeDigits(n));
}</
{{out}}
<pre>middleThreeDigits(123): 123
Line 2,043:
===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 2,129:
writefln("middleThreeDigits(cast(short)%d): %s", n, mtd);
}
}</
{{out}}
<pre>middleThreeDigits(123): 123
Line 2,180:
=={{header|Dart}}==
<syntaxhighlight lang="text">
import'dart:math';
int length(int x)
Line 2,227:
}
}
</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 2,244:
$ endif
$ i = i + 1
$ goto loop</
{{out}}
<pre>$ @middle_three_digits
Line 2,269:
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 2,331:
end
</syntaxhighlight>
{{out}}
<pre>
Line 2,356:
=={{header|Elena}}==
ELENA 5.0 :
<
import extensions;
Line 2,384:
console.printLine("middleThreeDigits(",n,"):",middleThreeDigits(n) | on:(e => e.Message))
}
}</
{{out}}
<pre>
Line 2,407:
=={{header|Elixir}}==
<
def three(num) do
n = num |> abs |> to_string
Line 2,436:
e -> IO.puts e.message
end
end)</
{{out}}
Line 2,460:
=={{header|Erlang}}==
<
-module(middle_three_digits).
-export([main/0]).
Line 2,499:
loop(X,N) when X>0 ->
loop(X-1, N div 10).
</syntaxhighlight>
{{out}}
<pre>123
Line 2,522:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM MIDDLE
Line 2,567:
END FOR
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 2,590:
=={{header|Factor}}==
<syntaxhighlight lang="text">USING: combinators formatting io kernel math math.parser
sequences ;
IN: rosetta-code.middle-three-digits
Line 2,618:
test-values [ dup "%9d : " printf middle-three ] each ;
MAIN: main</
{{out}}
<pre>
Line 2,642:
=={{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,723:
end program MiddleMuddle
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
Function middleThreeDigits (n As Integer) As String
Line 2,757:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 2,784:
=={{header|FutureBasic}}==
<
local fn MiddleThreeDigits( n as NSInteger ) as CFStringRef
CFStringRef testStr, resultStr
Line 2,818:
HandleEvents
</syntaxhighlight>
{{output}}
<pre style="font-size: 13px">
Line 2,848:
=={{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,871:
Next
End</
Output:
<pre>
Line 2,896:
File m3.go:
<
import (
Line 2,921:
m := len(s) / 2
return s[m-1 : m+2], nil
}</
File m3_test.go:
<
import (
Line 2,981:
t.Logf("d(%d) returns %q", tc.i, err)
}
}</
{{out}}
Output of go test is normally terse:
Line 3,014:
=={{header|Gosu}}==
<
valid.each(\ num ->print(middleThree(num)))
Line 3,026:
var start = (s.length / 2) - 1
return s.substring(start, start + 3)
}</
{{Output}}
Line 3,049:
=={{header|Groovy}}==
<
def text = Math.abs(number) as String
assert text.size() >= 3 : "'$number' must be more than 3 numeric digits"
Line 3,056:
int start = text.size() / 2 - 1
text[start..(start+2)]
}</
Test Code:
<
def text = (number as String).padLeft(10)
try {
Line 3,065:
println "$text cannot be converted: $error.message"
}
}</
Output:
<pre> 123: 123
Line 3,086:
=={{header|Haskell}}==
<
mid3 n
| m < 100 = Left "is too small"
Line 3,126:
where
justifyRight :: Int -> Char -> String -> String
justifyRight n c s = drop (length s) (replicate n c ++ s)</
Output:
<pre> 123 -> 123
Line 3,150:
The following solution works in both languages.
<
every n := !a do write(right(n,15)," -> ",midM(n))
end
Line 3,161:
else "wrong number of digits"
else "too short"
end</
with output:
Line 3,187:
=={{header|J}}==
'''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 3,210:
err
err
err</
Or, expressed more concisely:<
123
234
Line 3,229:
err
err
err</
=={{header|Java}}==
<
public static void main(String[] args) {
Line 3,258:
return s.substring(mid - 1, mid + 2);
}
}</
<pre>middleThreeDigits(123): 123
middleThreeDigits(12345): 234
Line 3,282:
=={{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 3,291:
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 3,314:
Or, using an option type, composing a solution from existing generic primitives, and formatting the output a little:
{{Trans|Python}}
<
'use strict';
Line 3,439:
// MAIN ---
return main();
})();</
{{Out}}
<pre>
Line 3,461:
=={{header|jq}}==
<
if . < 0 then -. else . end
| tostring as $s
Line 3,470:
(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0)
| "\(.) => \( .|middle3 )"</
Typescript:<
123 => 123
12345 => 234
Line 3,488:
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 3,506:
-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 3,528:
=={{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 3,562:
=={{header|Klingphix}}==
<
( 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0 )
Line 3,576:
" " input
</syntaxhighlight>
{{out}}
<pre>123 : 123
Line 3,597:
=={{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 3,620:
println(middleThree(123))// 123
println(middleThree(123555)) //null
}</
=={{header|Lambdatalk}}==
<
{def S 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0}
Line 3,665:
-2002: has an even number of digits
0: has not enough digits
</syntaxhighlight>
=={{header|Lasso}}==
<
local(
pos_value = math_abs(#value),
Line 3,689:
'<br />'
^}
'</pre>'</
'''Output'''
<pre> 123: 123
Line 3,710:
=={{header|Logo}}==
<
if [less? :n 0] [make "n minus :n]
local "len make "len count :n
Line 3,728:
]
bye</
{{Output}}
Line 3,750:
=={{header|Lua}}==
<
if n < 0 then
n = -n
Line 3,775:
print(n, middle_three(n))
end
end</
{{out}}
Line 3,797:
=={{header|Maple}}==
<
local nList, start;
nList := [seq(parse(i), i in convert (abs(n), string))];
Line 3,815:
middleDigits(i);
printf("\n");
end do;</
{{out}}
<pre>
Line 3,838:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Block[{digits = IntegerDigits[n], len},
len = Length[digits];
Line 3,848:
100, -12345, 1, 2, -1, -10, 2002, -2002, 0};
Column[middleThree /@ testData]</
{{out}}<pre>123
234
Line 3,868:
=={{header|MATLAB}} / {{header|Octave}}==
<
% http://rosettacode.org/wiki/Middle_three_digits
Line 3,882:
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,908:
=={{header|MiniScript}}==
<
if num < 0 then num = -num
s = str(num)
Line 3,920:
100, -12345, 1, 2, -1, -10, 2002, -2002, 0]
print test + " --> " + middle3(test)
end for</
{{out}}
<pre>123 --> 123
Line 3,941:
=={{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,950:
=={{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,975:
;
map (println o middleThreeDigits) test_array;</
Output:
<pre>123 --> 123
Line 3,997:
=={{header|MUMPS}}==
This sample shows the MUMPS code required to pass the specification.
<
MID3(N) ;
N LEN,N2
Line 4,007:
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 4,031:
=={{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 4,077:
end
return text
</syntaxhighlight>
'''Output:'''
<pre>
Line 4,107:
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">
(define (middle3 x)
(if (even? (length x))
Line 4,119:
(map middle3 lst)
</syntaxhighlight>
'''Output:'''
<pre>
Line 4,142:
=={{header|Nim}}==
<
var s = $abs(i)
if s.len < 3 or s.len mod 2 == 0:
Line 4,155:
var answer = try: middleThreeDigits(i)
except ValueError: getCurrentExceptionMsg()
echo "middleThreeDigits(", i, ") returned: ", answer</
{{out}}
Line 4,177:
=={{header|Objeck}}==
<
class Test {
function : Main(args : String[]) ~ Nil {
Line 4,190:
}
}</
<pre>
Line 4,214:
=={{header|OCaml}}==
<
let middle_three_digits x =
Line 4,238:
print_endline "Should fail:";
List.iter print failing;
;;</
{{out}}
Line 4,266:
=={{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 4,290:
=={{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 4,341:
writeln(n:9,': ',GetMid3dig(Test[i]));
end;
end.</
{{out}}
<pre> 123: 123
Line 4,363:
=={{header|Perl}}==
<
use strict ;
use warnings ;
Line 4,388:
1, 2, -1, -10, 2002, -2002, 0 ) ;
map { middlethree( $_ ) } @numbers ;
</syntaxhighlight>
{{out}}
<pre>Middle 3 digits of 123 : 123 !
Line 4,410:
=={{header|Phix}}==
<!--<
<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>
Line 4,422:
<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>
<!--</
{{out}}
<pre>
Line 4,445:
=={{header|PHP}}==
<
// 64-bit builds of PHP: Integers can be from -9223372036854775808 to 9223372036854775807
Line 4,483:
{
echo $nums.' : '.middlethree($nums). '<br>';
}</
Output:
<pre>123 : 123
Line 4,506:
===Prolog-style===
{{trans|Prolog}}
<
append(Pre,[X,Y,Z],Post,Str),
length(Pre) = length(Post).</
===List slice===
<
Mid = 1 + Str.len div 2.</
===Test===
<
Success = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345],
Fail = [1, 2, -1, -10, 2002, -2002, 0],
Line 4,540:
if Len mod 2 = 0 then throw $not_odd_length(N)
elseif Len < 3 then throw $number_too_small(N)
end.</
{{out}}
Line 4,562:
=={{header|PicoLisp}}==
<
(let (Lst (chop (abs N)) Len (length Lst))
(tab (10 -2 -30)
Line 4,571:
((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 4,598:
{{trans|PHP}}
<
i = abs(i);
int length = sizeof((string)i);
Line 4,623:
}
return 0;
}</
{{out}}
<pre>123 : 123
Line 4,644:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
middle: procedure options (main); /* 29 October 2013 */
declare n fixed (15);
Line 4,669:
end middle;
</syntaxhighlight>
Output:
<pre>
Line 4,691:
=={{header|Plain English}}==
<
Start up.
Test 123.
Line 4,727:
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.</
{{out}}
<pre>
Line 4,750:
=={{header|PowerShell}}==
<
$str = [Math]::abs($inp)
Line 4,773:
$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 4,796:
{{works with|SWI-Prolog|6}}
<
middle_3_digits(Number, [D1,D2,D3]) :-
verify_middle_3_able(Number, Digits),
Line 4,811:
; true
).
</syntaxhighlight>
Test code:
<
test_correct :-
TestCases = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345],
Line 4,823:
format('Middle 3 digits of ~w ~30|: ~w~n', [TestCase, Result])
).
</syntaxhighlight>
Line 4,863:
=={{header|Python}}==
===Procedural===
<
s = str(abs(i))
length = len(s)
Line 4,897:
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,986:
if __name__ == '__main__':
main()</
{{Out}}
<pre>Middle three digits, where defined:
Line 5,011:
=={{header|Quackery}}==
<
[ over size -
Line 5,038:
[ dup number$ 9 justify echo$
say " --> "
middle3 echo$ cr ]</
{{out}}
Line 5,061:
=={{header|Racket}}==
<
(define (middle x)
(cond
Line 5,074:
(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"
given $n.abs {
when .chars < 3 { "$n is too short" }
Line 5,093:
123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
1 2 -1 -10 2002 -2002 0
>;</
{{out}}
<pre>The three middle digits of 123 are: 123
Line 5,114:
It is also possible to write a regular expression with a code assertion:
<syntaxhighlight lang="raku"
{{out}}
<pre>01234 => 123
Line 5,122:
=={{header|REXX}}==
===version 1===
<
* 03.02.2013 Walter Pachl
* 19.04.2013 mid 3 is now a function returning the middle 3 digits
Line 5,149:
End
End
Return res</
Output:
<pre>
Line 5,178:
<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 5,193:
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 5,223:
=={{header|Ring}}==
<
n = 1234567
middle(n)
Line 5,234:
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|Ruby}}==
<
# minus sign doesn't factor into digit count,
# and calling #abs acts as a duck-type assertion
Line 5,251:
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 5,268:
puts e
end
end</
{{out}}
<pre>
Line 5,291:
=={{header|Rust}}==
<
let s: String = x.abs().to_string();
let len = s.len();
Line 5,320:
print_result(*i);
}
}</
{{Out}}
Line 5,356:
course just list the numbers backwards.
</pre>
<
define m3(i)
{
Line 5,386:
#endif
1, 2, -1, -10, 2002, -2002, 0 } );
</syntaxhighlight>
{{out}}<pre>
" 123: 123"
Line 5,410:
=={{header|Scala}}==
<
* Optionally return the middle three digits of an integer.
*
Line 5,431:
case Some(v) => "%03d".format(v) // Format the value, force leading zeroes
} mkString("\n")
</syntaxhighlight>
{{out}}
<pre>123
Line 5,453:
=={{header|Seed7}}==
<
const func string: middle3 (in integer: number) is func
Line 5,476:
writeln(number <& ": " <& middle3(number));
end for;
end func;</
{{out}}
Line 5,501:
=={{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.
<
10001, -10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0]
Line 5,521:
return digits joined by empty
end middle3digits
</syntaxhighlight>
{{out}}
<pre>
Line 5,545:
=={{header|Sidef}}==
{{trans|Raku}}
<
var l = n.len;
if (l < 3) {
Line 5,560:
1 2 -1 -10 2002 -2002 0
);
nums.each { say middle_three(_) };</
{{out}}
<pre>
Line 5,583:
=={{header|SQL}}==
<
AS (SELECT CAST(ABS(NUMBER) AS NVARCHAR(MAX)) charNum,
NUMBER,
Line 5,594:
END Output,
NUMBER Input
FROM DATA </
<pre>
Line 5,625:
=={{header|Swift}}==
<
if num<0{num = -num}
var numArray:[Int]=[]
Line 5,640:
i=i/2
print("\(numArray[i+1]),\(numArray[i]),\(numArray[i-1])")
}</
<pre>
123: 123
Line 5,662:
=={{header|Tcl}}==
<
if {$n < 0} {
set n [expr {-$n}]
Line 5,675:
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 5,688:
puts "found for ${n}: $mid"
}
}</
{{out}}
<pre>
Line 5,715:
{{works with|Z Shell}}
<
{
typeset -i n="${1#-}"
Line 5,737:
printf "%10d: " $n
middle3digits "$n"
done</
Output: <pre> 123: 123
Line 5,759:
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 5,781:
End If
End Function
</syntaxhighlight>
{{out}}
<pre>123 Return : 123
Line 5,802:
=={{header|VBScript}}==
<
Function mid3n(n)
Line 5,822:
WScript.StdOut.Write n & ": " & mid3n(n)
WScript.StdOut.WriteLine
Next</
{{Out}}
<pre>
Line 5,845:
=={{header|Vedit macro language}}==
<
#1 = Get_Num("Enter a number, or 0 to stop: ", STATLINE)
Ins_Text("Input: ") Num_Ins(#1, COUNT, 10)
Line 5,873:
}
Buf_Quit(OK)
Return </
Output:
Line 5,896:
=={{header|Wart}}==
<
withs (digits (with outstring # itoa
(pr abs.n))
Line 5,902:
mid (int max/2))
if (and odd?.max (max >= 3))
(digits mid-1 mid+2)</
'''Output'''
Line 5,944:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<
var middle3 = Fn.new { |n|
Line 5,962:
for (e in a) {
System.print("%(Fmt.s(9, e)) -> %(middle3.call(e))")
}</
{{out}}
Line 5,986:
=={{header|XPL0}}==
<
func Mid3Digits(I); \Return the middle three digits of I
Line 6,009:
Text(0, Mid3Digits(Passing(X))); CrLf(0);
];
]</
{{out}}
Line 6,033:
=={{header|zkl}}==
<
ns.apply("toString").apply('-("-"))
.apply(fcn(n){nl:=n.len();
Line 6,041:
}
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>
|