Greatest element of a list: Difference between revisions
→{{header|PostScript}}: Improved PostScript example. The previous code had some problems, namely being written like an imperative language and polluting the current variable dict |
m →{{header|PostScript}}: added works with |
||
Line 935: | Line 935: | ||
Ghostscript has a <code>max</code> built-in: |
Ghostscript has a <code>max</code> built-in: |
||
{{works with|Ghostscript}} |
|||
<lang postscript>/findmax { |
<lang postscript>/findmax { |
||
dup 0 get exch % put the first element underneath the array |
dup 0 get exch % put the first element underneath the array |
Revision as of 00:17, 8 March 2011
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
Create a function that returns the maximum value in a provided set of values, where the number of values isn't known until runtime.
ActionScript
<lang ActionScript>function max(... args):Number { var curMax:Number = -Infinity; for(var i:uint = 0; i < args.length; i++) curMax = Math.max(curMax, args[i]); return curMax; }</lang>
Ada
The keys for this task are initializing the compared value to the 'First value of the element type, and use of an unconstrained array type. <lang ada>with Ada.Text_Io;
procedure Max_Test is
-- substitute any array type with a scalar element type Flt_Array is array (Natural range <>) of Float; -- Create an exception for the case of an empty array Empty_Array : Exception; function Max(Item : Flt_Array) return Float is Max_Element : Float := Float'First; begin if Item'Length = 0 then raise Empty_Array; end if; for I in Item'range loop if Item(I) > Max_Element then Max_Element := Item(I); end if; end loop; return Max_Element; end Max; Buf : Flt_Array := (-275.0, -111.19, 0.0, -1234568.0, 3.14159, -3.14159);
begin
Ada.Text_IO.Put_Line(Float'Image(Max(Buf)));
end Max_Test;</lang> A generic function Max to deal with any floating-point type. <lang ada>generic
type Item is digits <>; type Items_Array is array (Positive range <>) of Item;
function Generic_Max (List : Items_Array) return Item;</lang> Implementation of: <lang ada>function Generic_Max (List : Items_Array) return Item is
Result : Item := List (List'First);
begin
for Index in List'First + 1..List'Last loop Result := Item'Max (Result, List (Index)); end loop; return Result;
end Generic_Max;</lang> When the argument array is empty, Constraint_Error exception is propagated, because array indexing is checked in Ada. Note also use of the floating-type attribute Max.
ALGOL 68
<lang algol68># substitute any array type with a scalar element # MODE FLT = REAL;
- create an exception for the case of an empty array #
PROC raise empty array = VOID:(
GO TO except empty array
);
PROC max = ([]FLT item)FLT: BEGIN
IF LWB item > UPB item THEN raise empty array; SKIP ELSE FLT max element := item[LWB item];
FOR i FROM LWB item + 1 TO UPB item DO IF item[i] > max element THEN max element := item[i] FI OD; max element FI
END # max #;
test:(
[]FLT buf = (-275.0, -111.19, 0.0, -1234568.0, pi, -pi); print((max(buf),new line)) EXIT except empty array: SKIP
)</lang> Output:
+3.14159265358979e +0
APL
<lang apl>LIST←2 4 6 3 8 ⌈/LIST</lang> Output: <lang apl>8</lang>
AppleScript
<lang AppleScript>on max(aList) set _curMax to first item of aList repeat with i in (rest of aList) if i > _curMax then set _curMax to contents of i end repeat return _curMax end max</lang>
AutoHotkey
<lang AutoHotkey>Loop Parse, list, `,
x := x < A_LoopField ? A_LoopField : x
MsgBox Max = %x%</lang>
AWK
<lang awk>$ awk 'func max(a){for(i in a)if(a[i]>r)r=a[i];return r}BEGIN{a[0]=42;a[1]=33;a[2]=21;print max(a)}' 42</lang>
Batch File
<lang dos>::max.cmd @echo off setlocal enabledelayedexpansion set a=.%~1 if "%a%" equ "." set /p a="Input stream: " call :max res %a% echo %res% endlocal goto :eof
- max
set %1=%2
- loop
shift /2 if "%2" equ "" goto :eof if %2 gtr !%1! set res=%2 goto loop</lang>
Invocation from command line or from internal prompt
<lang dos>>max "123 456 3 234243 12" 234243
>max Input stream: 5 4 3 2 67 1 67</lang>
BASIC
<lang qbasic>DECLARE SUB addVal (value AS INTEGER) DECLARE FUNCTION findMax% ()
REDIM SHARED vals(0) AS INTEGER DIM SHARED valCount AS INTEGER DIM x AS INTEGER, y AS INTEGER
valCount = -1
begin test run RANDOMIZE TIMER FOR x = 1 TO 10
y = INT(RND * 100) addVal y PRINT y; " ";
NEXT PRINT ": "; findMax end test run
SUB addVal (value AS INTEGER)
DIM tmp AS INTEGER IF valCount > -1 THEN 'this is needed for BASICs that don't support REDIM PRESERVE REDIM v2(valCount) AS INTEGER FOR tmp = 0 TO valCount v2(tmp) = vals(tmp) NEXT END IF valCount = valCount + 1 REDIM vals(valCount) IF valCount > 0 THEN 'also needed for BASICs that don't support REDIM PRESERVE FOR tmp = 0 TO valCount - 1 vals(tmp) = v2(tmp) NEXT END IF vals(valCount) = value
END SUB
FUNCTION findMax%
DIM tmp1 AS INTEGER, tmp2 AS INTEGER FOR tmp1 = 0 TO valCount IF vals(tmp1) > tmp2 THEN tmp2 = vals(tmp1) NEXT findMax = tmp2
END FUNCTION</lang>
Sample output:
8162 5139 7004 7393 5151 4476 577 4419 3333 4649 : 8162
C
This works well with floats. Replace with double, int or what-have-you before passing a different data type. <lang c>#include <assert.h>
float max(unsigned int count, float values[]) {
float themax = values[0]; assert(count > 0); for(unsigned int idx = 1; idx < count; ++idx) { themax = values[idx] > themax ? values[idx] : themax; } return themax;
}</lang>
The following macro can be used with any number and type of arguments, provided that the arguments are simple, i.e. must not contain subexpressions where commas appear (this is because of the way the arguments are counted; the macro can be modified so that it is up to the caller to count the number of arguments passed).
<lang c>#include <stdarg.h>
- define MAX(A,...) ({ inline __typeof__ (A) _max_(__typeof__ (A) a, ...) {\
va_list l; int i,c; const char *s = #__VA_ARGS__; __typeof__ (A) max = a;\ __typeof__ (A) t;\ for(c=1;*s!=0;s++) if (*s==',') c++;\ va_start(l, a);\ for(i=0;i<=c;i++) {\ if ((t=va_arg(l,__typeof__ (A))) > max) max = t;\ }\ va_end(l); return max;\
}\ _max_((A),__VA_ARGS__);\ })</lang>
C++
This will work for any type with a < operator defined. Uses the standard library function max_element(). <lang cpp>#include <algorithm>
- include <cassert>
template<typename Ty> Ty max(unsigned int count, Ty values[]) {
assert(count > 0); return *std::max_element(values, values + count);
}</lang>
C#
C# already have a "Maximum Value" function.
<lang csharp>using System.Linq;
values.Max();</lang>
Clojure
The Clojure.core function max takes the max of its arguments. <lang clojure>(max 1 2 3 4) ; evaluates to 4
- if the values are already in a collection, use apply
(apply max [1 2 3 4]) ; evaluates to 4</lang>
Common Lisp
The built-in Common Lisp function max takes the max of all its arguments. <lang lisp>(max 1 2 3 4) (reduce #'max values) ; find max of a list (loop for x in values
maximize x) ; alternative way to find max of a list</lang>
D
<lang d>import std.stdio, std.algorithm;
void main() {
auto array = [9, 4, 3, 8, 5]; auto m = reduce!max(array); writeln(m);
}</lang>
E
This function works for any value which responds to max/1
:
<lang e>pragma.enable("accumulator") # non-finalized syntax feature
def max([first] + rest) {
return accum first for x in rest { _.max(x) }
}</lang>
<lang e>? max([1, 2, 3])
- value: 3</lang>
To require only the comparison protocol, one needs to write out the algorithm a little more explicitly:
<lang e>def max([var bestSoFar] + rest) {
for x ? (x > bestSoFar) in rest { bestSoFar := x } return bestSoFar
}</lang>
<lang e>? max([1, 3, 2])
- value: 3
? max([[1].asSet(), [2].asSet(), [1, 2].asSet()])
- value: [1, 2].asSet()</lang>
Emacs Lisp
<lang lisp>(defun max (first-arg &rest more-args)
(if more-args (let ((max-rest (apply 'max more-args)))
(if (> first-arg max-rest) first-arg max-rest))
first-arg))</lang>
Example use: <lang lisp>(max 2 7 5) 7</lang>
Efene
<lang efene>list_max = fn ([Head:Rest]) {
list_max(Rest, Head)
}
list_max = fn ([], Res) {
Res
} fn ([Head:Rest], Max) when Head > Max {
list_max(Rest, Head)
} fn ([_Head:Rest], Max) {
list_max(Rest, Max)
}
list_max1 = fn ([H:T]) {
lists.foldl(fn erlang.max:2, H, T)
}
@public run = fn () {
io.format("~p~n", [list_max([9, 4, 3, 8, 5])]) io.format("~p~n", [list_max1([9, 4, 3, 8, 5])])
} </lang>
Erlang
From here <lang erlang>list_max([Head|Rest]) ->
list_max(Rest, Head).
list_max([], Res) -> Res; list_max([Head|Rest], Max) when Head > Max ->
list_max(Rest, Head);
list_max([_Head|Rest], Max) -> list_max(Rest, Max).</lang> or an alternative [shorter] version using the standard function max/2 within a fold: <lang erlang>list_max([H|T]) -> lists:foldl(fun erlang:max/2, H, T).</lang> Using it. <lang erlang>>list_max([9,4,3,8,5]). 9</lang>
Euphoria
Applying a function to each element of an array <lang Euphoria>function aeval( sequence sArr, integer id ) for i = 1 to length( sArr ) do sArr[ i ] = call_func( id, { sArr[ i ] } ) end for return sArr end function
object biggun function biggest( object elem ) if compare(elem, biggun) > 0 then biggun = elem end if return elem end function </lang> Example runs <lang Euphoria>biggun = 0 object a = aeval( {1,1234,62,234,12,34,6}, routine_id("biggest") ) printf( 1, "%d\n", biggun )
sequence s = { "antelope", "dog", "cat", "cow", "wolf", "wolverine", "aardvark"} biggun = "ant" a = aeval( s, routine_id("biggest") ) printf( 1, "%s\n", {biggun} )</lang> Output
1234 wolverine
F#
F# has a built in function for getting the max of a list:
<lang fsharp>>[2;3;4;5;36;3;2;6;7] |> List.max;; val it : int = 36</lang>
To use as a function <lang fsharp>let ListMax n = n |> List.max</lang>
Factor
The following word is in factor's standard library. <lang factor>: supremum ( seq -- elt ) [ ] [ max ] map-reduce ;</lang>
Fancy
<lang fancy>[1,-2,2,4,6,-4,-1,5] max println # => 6</lang>
Fantom
Has a built-in method to get maximum from a list.
<lang fantom> class Greatest {
public static Void main () { Int[] values := [1,2,3,4,5,6,7,8,9] Int greatest := values.max echo (greatest) }
} </lang>
Forth
<lang forth>: array-max ( addr len -- max )
dup 0= if nip exit then over @ rot cell+ rot 1- cells bounds ?do i @ max cell +loop ;
- stack-max ( n ... m count -- max ) 1 ?do max loop ;</lang>
Fortran
The intrinsic function maxval returns the maximum value of the elements in an integer or real array:
<lang fortran>program test_maxval
integer,dimension(5),parameter :: x = [10,100,7,1,2] real,dimension(5),parameter :: y = [5.0,60.0,1.0,678.0,0.0]
write(*,'(I5)') maxval(x) write(*,'(F5.1)') maxval(y)
end program test_maxval</lang>
Output:
100 678.0
The intrinsic function max accepts any number of arguments. The type of these arguments can be integer, real, character, string of characters or arrays of these. <lang fortran>program test_max
implicit none
write (*, '(i0)') & & max (1, 2, 3) write (*, '(f3.1)') & & max (1.0, 2.0, 3.0) write (*, '(a)') & & max ('a', 'b', 'c') write (*, '(a)') & & max ('abc', 'bca', 'cab') write (*, '(i0, 2 (1x, i0))') & & max ([1, 8, 6], [7, 5, 3], [4, 2, 9]) write (*, '(f3.1, 2 (1x, f3.1))') & & max ([1.0, 8.0, 6.0], [7.0, 5.0, 3.0], [4.0, 2.0, 9.0]) write (*, '(a, 2 (1x, a))') & & max (['a', 'h', 'f'], ['g', 'e', 'c'], ['d', 'b', 'i']) write (*, '(a, 2 (1x, a))') & & max (['abc', 'hig', 'fde'], ['ghi', 'efd', 'cab'], ['def', 'bca', 'igh'])
end program test_max</lang> Output:
3 3.0 c cab 7 8 9 7.0 8.0 9.0 g h i ghi hig igh
Go
<lang go>package main
import (
"fmt" "rand" "time"
)
// function, per task description func largest(a []int) (lg int) {
for _, e := range a { if e > lg { lg = e } } return
}
func main() {
// random size array rand.Seed(time.Nanoseconds()) a := make([]int, 50+rand.Intn(51)) for i := range a { a[i] = rand.Intn(101) // fill with random numbers }
fmt.Println(largest(a))
}</lang>
Groovy
<lang groovy>println ([2,4,0,3,1,2,-12].max())</lang>
Output:
4
Haskell
The built-in Haskell function maximum already does this. <lang haskell>my_max = maximum</lang> It can alternately be defined as a "fold" on the built-in two-argument max function. <lang haskell>my_max = foldl1 max</lang>
HicEst
<lang hicest>
max_value = MAX( -123, 234.56, 345.678, -456E3, -455) ! built-in function MAX(...)
! or for an array:
max_value = MAX( array_of_values )
! or to find a maximum value in a file named filename:
CHARACTER List, filename='Greatest element of a list.hic' ! filename contains this script REAL values(1) ! unknown number of values, allocate more below
OPEN(FIle=filename, BINary, LENgth=len) ALLOCATE(values, len/2) ! number of values <= half byte count of file ! read all values, returns item count in values_found: READ(FIle=filename, ItemS=values_found, CLoSe=1) values ! no Format needed for plain text numbers
max_value = MAX(values)
! write values found in filename and result to spreadsheet type dialog window: DLG(Text=values, Text=max_value, TItle=values_found)
WRITE(ClipBoard, Name) max_value, values_found, values ! pasted to line below ! max_value=345.678; values_found=30; values(1)=-123; values(2)=234.56; values(3)=345.678; values(4)=-456E3; values(5)=-455; values(6)=1; values(7)=2; values(8)=1; values(9)=0; values(10)=0; ...truncated END
</lang>
Icon and Unicon
<lang icon>procedure main()
local l l := [7,8,6,9,4,5,2,3,1] write(max(l))
end
procedure max(l)
local max max := l[1] every max <:= !l return max
end</lang>
J
Solution:<lang j> >./</lang> Example:<lang J> >./ 1 2 3 2 1 3
>./ NB. Maximum value of an empty list = identity element (or neutral) of max = -∞
__</lang>
Java
The first function works with arrays of floats. Replace with arrays of double, int, or other primitive data type. <lang java>public static float max(float[] values) throws NoSuchElementException {
if (values.length == 0) throw new NoSuchElementException(); float themax = values[0]; for (int idx = 1; idx < values.length; ++idx) { if (values[idx] < themax) themax = values[idx]; } return themax;
}</lang>
Optionally, if it is OK to rearrange the contents of the original array: <lang java>public static float max(float[] values) throws NoSuchElementException {
if (values.length == 0) throw new NoSuchElementException(); Arrays.sort(values);//sorts the values in ascending order return values[values.length-1];
}</lang>
The following functions work with Lists or arrays of reference types, respectively. Note that the type is required to implement Comparable, to ensure we can compare them. For Lists, there is a utility method Collections.max() that already does this. For arrays, we can just use the Arrays.asList() wrapper to wrap it into a list and then use the function for lists. <lang java>import java.util.List; import java.util.Collections; import java.util.Arrays;
public static <T extends Comparable<? super T>> T max(List<T> values) {
return Collections.max(values);
}
public static <T extends Comparable<? super T>> T max(T[] values) {
return Collections.max(Arrays.asList(values));
}</lang>
JavaScript
Using the built-in Math.max method
<lang javascript>function max(arr) {
return Math.max.apply(null, arr);
}
// Test it a = [0,1,2,5,4]; alert(max(a));</lang>
Liberty BASIC
<lang lb>aList$= "1 15 -5 6 39 1.5 14"
maxVal = val(word$(aList$, 1)) token$ = "?" while token$ <> ""
index = index + 1 token$ = word$(aList$, index) aVal = val(token$) if aVal > maxVal then maxVal = aVal
wend
print "maxVal = ";maxVal</lang>
Logo
If the template is, like SUM, the name of a procedure that is capable of accepting arbitrarily many inputs, it is more efficient to use APPLY instead of REDUCE. The latter is good for associative procedures that have been written to accept exactly two inputs: <lang logo>to max :a :b output ifelse :a > :b [:a] [:b] end
print reduce "max [...]</lang>
Alternatively, REDUCE can be used to write MAX as a procedure that accepts any number of inputs, as SUM does: <lang logo>to max [:inputs] 2 if emptyp :inputs ~
[(throw "error [not enough inputs to max])]
output reduce [ifelse ?1 > ?2 [?1] [?2]] :inputs end</lang>
Logtalk
<lang logtalk> max([X| Xs], Max) :-
max(Xs, X, Max).
max([], Max, Max). max([X| Xs], Aux, Max) :-
( X @> Aux -> max(Xs, X, Max) ; max(Xs, Aux, Max) ).</lang>
Lua
<lang lua> vals = io.read() + 0 val_t = {} for i = 1, vals do val_t[i] = io.read() + 0 end print(math.max(unpack(val_t))) </lang>
Mathematica
Input: <lang Mathematica>Max[1, 3, 3, 7] Max[Pi,E+2/5,17 Cos[6]/5,Sqrt[91/10]] Max[1,6,Infinity] Max[]</lang> Output <lang Mathematica> 7
17 Cos[6]/5 Infinity
-Infinity</lang> Note that Max returns minus infinity if supplied with no arguments; as it should: <lang Mathematica>Max[Max[],Max[a,b,c]] Max[Max[a],Max[b,c]] Max[Max[a,b],Max[c]] Max[Max[a,b,c],Max[]]</lang> should all give the same results, therefore max[] should give -Infinity. If it WOULD give 0 strange this can happen: <lang Mathematica>Max[Max[], Max[-4, -3]]</lang> WOULD give 0 instead of -3
MATLAB
<lang Matlab>function [maxValue] = findmax(setOfValues)
maxValue = max(setOfValues);</lang>
Modula-3
Modula-3 provides a builtin MAX
function, but it only works on two elements (or enumerations) but not arrays or sets.
We provide a generic Maximum implementation: <lang modula3>GENERIC INTERFACE Maximum(Elem);
EXCEPTION Empty;
PROCEDURE Max(READONLY a: ARRAY OF Elem.T): Elem.T RAISES {Empty};
END Maximum.</lang>
<lang modula3>GENERIC MODULE Maximum(Elem);
PROCEDURE Max(READONLY arr: ARRAY OF Elem.T): Elem.T RAISES {Empty} =
VAR max := FIRST(Elem.T); BEGIN IF NUMBER(arr) = 0 THEN RAISE Empty; END; FOR i := FIRST(arr) TO LAST(arr) DO IF arr[i] > max THEN max := arr[i]; END; END; RETURN max; END Max;
BEGIN END Maximum.</lang>
Elem
can be instantiated to any type (any type that can be compared with the '>' function). For convenience Modula-3 provides interfaces/modules for the built in types, like Integer, Real, LongReal, etc, which contain type definitions as well as properties specific to the type.
To make a generic interface/module for a specific type, you must instantiate it: <lang modula3>INTERFACE RealMax = Maximum(Real) END RealMax.</lang> <lang modula3>MODULE RealMax = Maximum(Real) END RealMax.</lang>
Now we can import RealMax
into our source and use the Max
function:
<lang modula3>MODULE Main;
IMPORT RealMax, IO, Fmt;
VAR realarr := ARRAY [1..5] OF REAL {1.1, 1.0, 0.0, 2.4, 3.3};
BEGIN
IO.Put(Fmt.Real(RealMax.Max(realarr)) & "\n");
END Main.</lang>
MAXScript
MAXScript has a built-in function called amax(), which will return the maximum of an array or the values supplied to it. The following custom function will return the maximum of the array supplied to it, or 'undefined' if an empty array is supplied. <lang MAXScript>fn MaxValue AnArray = ( if AnArray.count != 0 then ( local maxVal = 0 for i in AnArray do if i > maxVal then maxVal = i maxVal ) else undefined )</lang>
Metafont
The max
macro (in the base set of macro for Metafont) accepts any number of arguments, and accepts both numerics (numbers), pairs (bidimensional vectors), and strings (not mixed).
<lang metafont>show max(4,5,20,1); show max((12,3), (10,10), (25,5)); show max("hello", "world", "Hello World");</lang>
MUMPS
<lang MUMPS> MV(A,U)
;A is a list of values separated by the string U NEW MAX,T,I FOR I=1:1 SET T=$PIECE(A,U,I) QUIT:T="" S MAX=$SELECT(($DATA(MAX)=0):T,(MAX<T):T,(MAX>=T):MAX) QUIT MAX
</lang> Usage:
USER>SET V="," USER>SET B="-1,-1000,1000,2.3E5,8A,""A"",F" USER>W $$MV^ROSETTA(B,V) 2.3E5
Nial
The behavior of multi-dimensional arrays is like J
<lang nial>max 1 2 3 4 =4</lang>
Objective-C
This code "extends" (through Objective-C categories) the NSArray adding the method
maximumValue
; this one iterates over the objects of the collection
calling the method compare
, if it exists for the object of the
collection. Since normally comparing makes sense between numbers, the code
also check if the objects being compared are of "kind" NSNumber. If one eliminates
this check (substituting it maybe with one that checks if the two object are of
the same "kind"), the code is able to get a maximum value for any objects for
which make sense a compare method (e.g. strings), that must be implemented.
If there's no a known way of comparing two objects of the collection (or if the objects are not "NSNumber"), the the method return nil (the void object).
<lang objc>#import <Foundation/Foundation.h>
@interface NSArray (WithMaximum) - (id)maximumValue; @end
@implementation NSArray (WithMaximum) - (id)maximumValue {
if ( [self count] == 0 ) return nil; id maybeMax = [self objectAtIndex: 0]; NSEnumerator *en = [self objectEnumerator]; id el; while ( (el=[en nextObject]) != nil ) { if ( [maybeMax respondsToSelector: @selector(compare:)] &&
[el respondsToSelector: @selector(compare:)] && [el isKindOfClass: [NSNumber class]] && [maybeMax isKindOfClass: [NSNumber class]] ) {
if ( [maybeMax compare: el] == NSOrderedAscending )
maybeMax = el;
} else { return nil; } } return maybeMax;
} @end</lang>
This example mixes integers with a double value, just to show that everything is fine until they are NSNumber.
<lang objc>int main() {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSArray *collection = [NSArray arrayWithObjects:
[NSNumber numberWithInt: 1], [NSNumber numberWithInt: 2], [NSNumber numberWithInt: 10], [NSNumber numberWithInt: 5], [NSNumber numberWithDouble: 10.5], nil];
NSLog(@"%@", [collection maximumValue]); [pool release]; return 0;
}</lang>
Objeck
The language has a "Max" method for vectors. <lang objeck> values := IntVector->New([4, 1, 42, 5]); values->Max()->PrintLine(); </lang>
OCaml
<lang ocaml>let my_max = function
[] -> invalid_arg "empty list" | x::xs -> List.fold_left max x xs</lang>
# my_max [4;3;5;9;2;3] ;; - : int = 9
Octave
Octave's max
accepts a vector (and can return also the index of the maximum value in the vector)
<lang octave>m = max( [1,2,3,20,10,9,8] ); % m = 20 [m, im] = max( [1,2,3,20,10,9,8] ); % im = 4</lang>
Oz
<lang oz>declare
fun {Maximum X|Xr} %% pattern-match on argument to make sure the list is not empty {FoldL Xr Value.max X} %% fold the binary function Value.max over the list end
in
{Show {Maximum [1 2 3 4 3]}}</lang>
PARI/GP
<lang>vecmax(v)</lang>
Perl
<lang perl>sub max {
my @list = @_; my $themax = $list[0]; foreach ( @list ) { $themax = $_ > $themax ? $_ : $themax; } return $themax;
}</lang>
It is already implemented in the module List::Util's max() function: <lang perl>use List::Util qw(max);
max(@values);</lang>
Perl 6
There's a built-in infix operator max
; combining this with the reduction metaoperator (square brackets) yields the list operator we want:
<lang perl6>say [max] 17, 13, 50, 56, 28, 63, 62, 66, 74, 54;</lang> Note that this works over any type for which comparison is defined: <lang perl6>say [max] 'my', 'dog', 'has', 'fleas';</lang>
We could implement a list operator without using max
by calling the generic reduce function with a lambda:
<lang perl6>sub max2 (*@a) { reduce -> $x, $y { $y after $x ?? $y !! $x }, @a } say max2 17, 13, 50, 56, 28, 63, 62, 66, 74, 54;</lang> Since we've used the generic 'after' function, this can also be used on any type that defines cmp.
PHP
The built-in PHP function max() already does this. <lang php>max($values)</lang>
PicoLisp
<lang PicoLisp>: (max 2 4 1 3) # Return the maximal argument -> 4
- (apply max (2 4 1 3)) # Apply to a list
-> 4
- (maxi abs (2 -4 -1 3)) # Maximum according to given function
-> -4</lang>
PL/I
<lang PL/I> maximum = A(lbound(A,1)); do i = lbound(A,1) to hbound(A,1);
if maximum < A(i) then maximum = A(i);
end; </lang>
PostScript
Ghostscript has a max
built-in:
<lang postscript>/findmax {
dup 0 get exch % put the first element underneath the array {max} forall % replace it by the respective larger value if necessary
} def</lang>
If not using Ghostscript this gets a bit longer:
<lang postscript>/findmax {
dup 0 get exch % put the first element underneath the array { dup % duplicate the current item 2 index % duplicate the current maximum value gt % if the current item is larger {exch} if % swap the two items so the previous maximum is now the top of the stack pop % remove it } forall
} def</lang>
PowerBASIC
<lang powerbasic>FUNCTION PBMAIN()
DIM x AS LONG, y AS LONG, z AS LONG RANDOMIZE TIMER
FOR x = 1 TO 10 y = INT(RND * 10000) z = MAX(y, z) NEXT
? STR$(z) & " was the highest value"
END FUNCTION</lang>
Sample output:
8104 was the highest value
PowerShell
The Measure-Object
cmdlet in PowerShell already has this capability:
<lang powershell>function Get-Maximum ($a) {
return ($a | Measure-Object -Maximum).Maximum
}</lang>
Prolog
SWI-Prolog already knows max_list. <lang Prolog> ?- max_list([1, 2, 10, 3, 0, 7, 9, 5], M). M = 10.</lang>
can be implemented like this:
<lang Prolog> max_list([H|T], Max) :- max_list(T, H, Max).
max_list([], Max, Max).
max_list([H|T], Max0, Max) :- H > Max0, !, max_list(T, H, Max).
max_list([_|T], Max0, Max) :- max_list(T, Max0, Max).
</lang>
PureBasic
<lang PureBasic>Procedure.f Max (Array a.f(1))
Protected last, i, ret.f
ret = a(0) last = ArraySize(a()) For i = 1 To last If ret < a(i) ret = a(i) EndIf Next ProcedureReturn ret
EndProcedure</lang>
Python
The built-in Python function max() already does this. <lang python>max(values)</lang>
Of course this assumes we have a list or tuple (or other sequence like object). (One can even find the max() or min() character of a string since that's treated as a sequence of characters and there are "less than" and "greater than" operations (object methods) associate with those characters).
If we truly were receiving a stream of data then in Python, such streams are usually iterable, meaning they have a way of generating one item at a time from the stream.
max(), (and min()), can take iterables and a key argument which takes a function that can transform each item into a type that we can compare, for example, if the stream were returning string representations of integers, one to a line, you could do <lang python>>>> floatstrings = ['1\n', ' 2.3\n', '4.5e-1\n', '0.01e4\n', '-1.2'] >>> max(floatstrings, key = float) '0.01e4\n' >>></lang> Normally we would want the converted form as the maximum and we could just as easily write: <lang python>>>> max(float(x) for x in floatstrings) 100.0 >>></lang>
R
<lang R>v <- c(1, 2, 100, 50, 0) print(max(v)) # 100</lang>
REBOL
<lang REBOL>REBOL [
Title: "Maximum Value" Date: 2009-12-15 Author: oofoe URL: http://rosettacode.org/wiki/Maximum_Value
]
max: func [ "Find maximum value in a list." values [series!] "List of values." ] [ first maximum-of values ]
print ["Max of" mold d: [5 4 3 2 1] "is" max d] print ["Max of" mold d: [-5 -4 -3 -2 -1] "is" max d]</lang>
Output:
Max of [5 4 3 2 1] is 5 Max of [-5 -4 -3 -2 -1] is -1
REXX
If the list is a string that contains a list of numbers:
<lang rexx>
/*list of first twenty reversed primes.*/
y='2 3 5 7 11 31 71 91 32 92 13 73 14 34 74 35 95 16 76 17'
big=word(y,1)
do j=2 to words(y) big=max(big,word(y,j)) end
say 'biggest value in list of' words(y) "numbers is" big </lang> Output:
biggest value in list of 20 numbers is 95
If the list is an array of numbers:
<lang rexx> y.1 = 2; y.2 = 3; y.3 = 5; y.4 = 7; y.5 =11 y.6 =31; y.7 =71; y.8 =91; y.9 =32; y.10=92 y.11=13; y.12=73; y.13=14; y.14=34; y.15=74 y.16=35; y.17=95; y.18=16; y.19=76; y.20=17
big=y.1 items=20
do j=2 to items big=max(big,y.j) end
say 'biggest value in an arrow of' items "elements is" big </lang> Output:
biggest value in an arrow of 20 elements is 95
Ruby
max is a method of all Enumerables <lang ruby>values.max</lang>
Scala
max is a method in Int (e.g. 3 max 5 == 5) <lang scala>List(1,2,3,4) reduceLeft { _ max _ }</lang> With Scala2.8 a build-in function could also be used. <lang scala>List(1,2,3,4).max</lang>
Scheme
The built-in Scheme function max takes the max of all its arguments. <lang scheme>(max 1 2 3 4) (apply max values) ; find max of a list</lang>
Slate
<lang slate>#(1 2 3 4 20 10 9 8) reduce: [| :a :b | a max: b]</lang>
Smalltalk
Using fold it is very simple to find the maximum value among a collection.
<lang smalltalk>Smalltalk at: #maximum put: nil. maximum := [ :c | c fold: [:a :b | a max: b] ]. maximum value: #(1 2 3 4 20 10 9 8). "returns 20"</lang>
SNOBOL4
<lang snobol4>while a = trim(input) :f(stop)
max = gt(a,max) a :(while)
stop output = max end</lang>
Standard ML
Comparisons are specific for each type. Here is a max function for a list of ints: <lang sml>fun max_of_ints [] = raise Empty
| max_of_ints (x::xs) = foldl Int.max x xs</lang>
- max_of_ints [4,3,5,9,2,3]; val it = 9 : int
Tcl
Use the {*}
expansion operator to substitute the list value with its constituent elements
<lang tcl>package require Tcl 8.5
set values {4 3 2 7 8 9}
- tcl::mathfunc::max {*}$values ;# ==> 9</lang>
TI-89 BASIC
The builtin max
function can be applied to lists. max({1, 3, 2})
= 3.
Trith
<lang trith>[1 -2 3.1415 0 42 7] [max] foldl1</lang>
UNIX Shell
<lang bash>max() {
local m= while [ -n "$1" ] do [ -z "$m" ] && m=$1 [ $m -lt $1 ] && m=$1 shift done echo $m
}
max 10 9 11 57 1 12</lang>
Ursala
The built-in $^
operator takes a binary predicate of any type to a
function extracting the maximum value from a non-empty list of that type. In this
case it is used with fleq
, the partial order relation on floating point
numbers.
<lang Ursala>#import flo
- cast %e
example = fleq$^ <-1.,-2.,0.,5.,4.,6.,1.,-5.></lang> output:
6.000000e+00
V
Assuming it is a list of positive numbers <lang v>[4 3 2 7 8 9] 0 [max] fold =9</lang>
If it is not <lang v>[4 3 2 7 8 9] dup first [max] fold</lang>
=9
Yorick
The built-in function max does this. Interactive example:
> foo = [4, 3, 2, 7, 8, 9] > max(foo) 9
- Programming Tasks
- Arithmetic operations
- ActionScript
- Ada
- ALGOL 68
- APL
- AppleScript
- AutoHotkey
- AWK
- Batch File
- BASIC
- C
- C++
- C sharp
- Clojure
- Common Lisp
- D
- E
- Emacs Lisp
- Efene
- Erlang
- Euphoria
- F Sharp
- Factor
- Fancy
- Fantom
- Forth
- Fortran
- Go
- Groovy
- Haskell
- HicEst
- Icon
- Unicon
- J
- Java
- JavaScript
- Liberty BASIC
- Logo
- Logtalk
- Lua
- Mathematica
- MATLAB
- Modula-3
- MAXScript
- Metafont
- MUMPS
- Nial
- Objective-C
- Objeck
- OCaml
- Octave
- Oz
- PARI/GP
- Perl
- Perl 6
- PHP
- PicoLisp
- PL/I
- PostScript
- PowerBASIC
- PowerShell
- Prolog
- PureBasic
- Python
- R
- REBOL
- REXX
- Ruby
- Scala
- Scheme
- Slate
- Smalltalk
- SNOBOL4
- Standard ML
- Tcl
- TI-89 BASIC
- Trith
- UNIX Shell
- Ursala
- V
- Yorick