Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Challenge

Given an array of integers, received from stdin, function arguments, program arguments, or some other method:

Output only the minimum and maximum numbers in the array, through a return value, stdout, or other fitting methods.

Example session

> minmax( {0, 15, 2, 3, 7, 18, -2, 9, 6, -5, 3, 8, 9, -14} )
-14 18

Reference implementation

// C++

void minmax(std::vector<int> v) {
    int min = v[0]; int max = v[0];
    for(std::vector<int>::iterator it = v.begin(); it != v.end(); it++) {
        if (*it < min)
            min = *it;
        if (*it > max)
            max = *it;
    }
    std::cout << min << ' ' << max << std::endl;
}

Rules

  • You may not use a built-in function to calculate the values.
  • Standard loopholes disallowed.
  • Creative implementations encouraged.
  • This is , shortest answer wins but will not be selected.

Clarifications

  • If the array contains 1 element you need to output it twice.
  • If the minimum and maximum values are the same, you need to output them both.
share|improve this question
    
Anti-Dupe Information: Built ins are explicitly disallowed, and there are no strings in the array – Dmitry Kudriavtsev 2 days ago
    
Is it allowed to output a single value if min and max are the same or do we have to output the same value twice? – Martin Ender 2 days ago
10  
This is a do X without Y challenge, which aren't particularly interesting. – Mego 2 days ago
5  
@DmitryKudriavtsev Try the sandbox next time. – Mego 2 days ago
3  
Seriously, use the Sandbox. Your changes to the challenge have invalidated every single answer. – Mego yesterday

35 Answers 35

Jelly, 3 bytes

Ṣ.ị

Try it online!

Sort the array, and then takes the 0.5-th element.

Jelly uses 1-indexing, and floating points indexing means take its floor and its ceil.

So the 0.5-th element would give you the 0th element and the 1st element.

The 0th element is the last element.

share|improve this answer
1  
Pretty Clever I'm wait for it.... Jelly! – Rohan Jhunjhunwala yesterday
    
Oh, so that would make finding the median trivial. – Adám yesterday
    
In which encoding is that three bytes? – Konrad Rudolph yesterday
1  
@KonradRudolph This. – Leaky Nun yesterday
1  
Don't you want the first and last elements, rather than the first two elements? Or have I misunderstood your explanation? – Toby Speight yesterday

Python, 61 49 37 36 bytes

S=sorted;lambda s:S(s)[:1]+S(s)[-1:]

-12 bytes thanks to RootTwo

Another -12 bytes thanks to chepner

share|improve this answer
1  
I changed the heading to Python because it works in Python 3 also. – Leaky Nun 2 days ago
1  
You can golf off a dozen bytes: use [::(len(s)-1)or 1] for the first subscript. And the second term can be shortened to s[:len(s)<2]. – RootTwo yesterday
    
At the cost of sorting the list twice, you can shave off another 12 bytes: lambda s:sorted(s)[:1]+sorted(s)[-1:]. – chepner 18 hours ago

Brain-Flak 220 218 bytes

(({}))([]){({}[()]<(([])<{({}[()]<([([({}<(({})<>)<>>)<><({}<>)>]{}<(())>)](<>)){({}())<>}{}({}<><{}{}>){{}<>(<({}<({}<>)<>>)<>({}<>)>)}{}({}<>)<>>)}{}<>{}>[()]){({}[()]<({}<>)<>>)}{}<>>)}{}({}<((())){{}{}([][()])}{}>)

Try It Online!

Explanation

First it doubles the top value (in cast the list is only one long)

(({}))

Then it uses my bubble sort algorithm:

([]){({}[()]<(([])<{({}[()]<([([({}<(({})<>)<>>)<><({}<>)>]{}<(())>)](<>)){({}())<>}{}({}<><{}{}>){{}<>(<({}<({}<>)<>>)<>({}<>)>)}{}({}<>)<>>)}{}<>{}>[()]){({}[()]<({}<>)<>>)}{}<>>)}{}

Then it picks up the top value of the stack (i.e. the min)

({}<...>)

Then it pops until the height of the stack is one:

((())){{}{}([][()])}{}
share|improve this answer

R, 31 bytes

l=sort(scan());l[c(1,sum(l|1))]

Not that original, but hey !

share|improve this answer

Mathematica, 18 bytes

Sort[#][[{1,-1}]]&

Sorts the array and extracts the first and last values.

share|improve this answer

Octave, 20 bytes

@(n)sort(n)([1,end])

This sorts the input vector and outputs the first and last value.

share|improve this answer

Actually, 5 bytes

S;F@N

Try it online!

Explanation:

S;F@N
S      sort
 ;     dupe
  F    first element
   @N  and last element
share|improve this answer

JavaScript (ES6), 34 bytes

a=>[a.sort((x,y)=>x-y)[0],a.pop()]

sort sorts in-place, so I can just refer to the [0] index for the lowest value and pop the highest value from the array, however it does a string sort by default so I have to pass a comparator.

share|improve this answer
    
I don't think you need the (x,y)=>x-y part, unless using sort() with the default algorithm counts as a builtin. – Scott yesterday
    
@Scott But I don't want a lexical sort... – Neil yesterday
    
Right... I didn't test it with numbers > 10 or < 0. I didn't know sort() internally treats everything as strings - sorry! – Scott yesterday

Brachylog, 9 bytes

oOtT,Oh:T

Try it online!

share|improve this answer

V, 12 bytes

:sor
ò2Gjkd

Try it online!

Credit to DJMcMayhem for this.

share|improve this answer
1  
\o/ Yay, I'm no longer the only person to have ever used this language! – DJMcMayhem yesterday
1  
If the input is a single number, that number still has to be output twice – Luis Mendo yesterday
    
@LuisMendo hm, will work on that. – Easterly Irk yesterday

05AB1E, 6 4 bytes

{Âø¬

Explanation

{     # sort list
 Â    # bifurcate
  ø   # zip
   ¬  # head

Try it online

share|improve this answer

CJam, 10 9 bytes

q~$_(p;W>

Try it online.

I'm really not good at CJam.

q~          e# eval input
  $         e# sort
   _        e# duplicate
    (       e# pop first
     p      e# print
      ;     e# remove array
       W>   e# get last element
share|improve this answer
    
The usual way to get the first element of a list is 0= (but that unfortunately that doesn't save any bytes). Two other 9-byte solutions: 0W]q~$f=p or the unnamed block {$2*_,(%}. – Martin Ender yesterday
    
8 bytes: q~$(p)p;. You can use ) to get the last element like you use ( to get the first. – Business Cat yesterday
    
@BusinessCat That's what I originally had, but it fails for single-element input. – Pietu1998 yesterday
    
@Pietu1998: Oh, you're right. I didn't notice that. – Business Cat yesterday

Haskell, 27 bytes

f x=(`foldl1`x)<$>[min,max]

In Haskell, min and max give minimum and maximum of two arguments, not of a list. I couldn't tell whether this is disallowed (it seems that instead only minimum and maximum would be disallowed) so please let me know if they are and I'll promptly delete this answer.

share|improve this answer
    
I had the same idea and asked if it's allowed in the comments of the challenge. Memo to myself: post first, ask later. – nimi yesterday
    
@nimi FGITW effect, sadly... – ThreeFx 16 hours ago

MATL, 4 bytes

S5L)

Try it online!

Explanation

S    % Implicitly input the array. Sort
5L   % Push [1 0]. When used as a (modular, 1-based) index, this means "first and last"
)    % Apply as an indexing vector into the sorted array. Implicitly display
share|improve this answer

Python 2, 34 bytes

x=sorted(input());print x[0],x[-1]
share|improve this answer

C#, 60 bytes

n=>{System.Array.Sort(n);return new[]{n[0],n[n.Length-1]};};

A naïve method at 93 bytes:

n=>{var r=new[]{n[0],n[0]};foreach(int i in n){if(i<r[0])r[0]=i;if(i>r[1])r[1]=i;}return r;};
share|improve this answer

Haskell, 36 bytes

(\l->(head l,last l)).Data.List.sort

Would love to use &&& here but imports are so costly...

share|improve this answer

Retina, 17 bytes

O#`
$
¶$`
Ss`¶.+¶

Input and output are linefeed-separated.

Try it online!

Explanation

O#`

Sort lines by numerical value.

$
¶$`

Duplicate the entire input to make sure that the first and last element are distinct.

Ss`¶.+¶

Remove all intermediate lines, leaving only the minimum and maximum.

share|improve this answer

Ruby, 38 23 bytes

def m(v) puts v.sort![0];$><<v[-1];end

->v{[v.sort![0],v[-1]]}

Thanks @Jordan!

share|improve this answer
1  
You don't need the space after def m(v). Regardless, you can save 15 bytes by using a lambda and just returning an array: ->v{[v.sort![0],v[-1]]}. – Jordan 2 days ago

Perl 6 13 bytes

*.sort[0,*-1]

Test:

my &min-max = *.sort[0,*-1];

say min-max 1;
# (1 1)
say min-max (0, 15, 2, 3, 7, 18, -2, 9, 6, -5, 3, 8, 9, -14)
# (-14 18)
share|improve this answer
    
Darn, you beat me there! – bb94 20 hours ago

Pyke, 5 bytes

ShQSe

Try it here!

share|improve this answer

Dyalog APL, 11 bytes

(⊃,⊃∘⌽)⍋⊃¨⊂

(

first

, followed by

⊃∘⌽ first of the reversed (i.e. the last)

) of

the indices of the elements in ascending order

⊃¨ each picks from

the entire argument

TryAPL online!


For reference, using built-ins:

⌊/,⌈/

⌊/ minimum across

, followed by

⌈/ maximum across

share|improve this answer

Python, 35 34 bytes

lambda s:sorted(s+s[:1])[::len(s)]

Alternative version:

lambda s:sorted(s+s)[::len(s)*2-1]

Old version, 35 bytes.

lambda s:sorted(s+[s[0]])[::len(s)]

Fairly simple: take the input list, append the first element, sort it, then take the first and (length)th element of the resulting list. As the length of the input after appending an element is length + 1, this ends up taking the first and last element of said list, which are the minimum and maximum elements.

share|improve this answer
1  
Though not the shortest answer in Python, this is very creative! +1 – mbomb007 yesterday
    
The 34-byte one doesn't work in Python 3; this works in both 2 and 3. Also, it was posted after this one. – TLW 20 hours ago
    
@mbomb007 - fine, golfed. This is now tied for the shortest Python implementation, and as a bonus it works in both 2 and 3. – TLW 20 hours ago

zsh, 22 bytes

(){echo $1 $_} ${(n)@}

defines a lambda function that prints its first arg ($1) and the last argument to the previous command ($_), and passes it $@ after sorting it so the previous command becomes the invocation of that lambda


zsh, 21 bytes

this only works fine if there's more than 1 argument :(

<<<"${${(n)@}/ * / }"

sorts $@, makes it a string and replaces everything from the first space to the last one with a single space, then passes it as input to cat with <<<


usage:

$ ./minmax 23 342 21 10
10 342
share|improve this answer

Scala, 55 bytes

val s=args.map(_.toInt).sorted
print(s.head+" "+s.last)

To execute:

$ scala minmax.scala 1 2 3 4 5 6 7 8 9

share|improve this answer

dc, 109 bytes

0dsMsmzdsAsa[z1-:az0<S]dsSx[>R]s?[la;asM]sR[lM]sQ[lQxla1-dsa;al?xla0<N]dsNxlAsa[<R]s?[la;asm]sR[lm]sQlNxlmlMf

Help me, dcers! You are my only hope!

I'll add an explanation later. Here it is broken up a bit:

0d sM sm
zd sA sa
[z 1- :a z0<S]dsSx
 [>R]s?
 [la;asM]sR
 [lM]sQ
[lQx la 1- dsa ;a l?x la0<N]dsNx
lA sa
 [<R]s?
 [la;a sm]sR
 [lm]sQ
lNx
lm lM f
share|improve this answer

BASH 38

grep -o '[^ ]*'|sort -g|sed -n '1p;$p'
share|improve this answer

Processing, 59 bytes

void m(int[] x){int[] y=sort(x);print(y[0],y[y.length-1]);}

Processing doesn't actually let me read from stdin that I've been able to find, and I don't know if its internal Java compiler supports lambdas (and its been so long since I've had to write serious Java that I don't remember how).

share|improve this answer

Factor, 38 bytes

[ natural-sort [ first ] [ last ] bi ]

Sort the sequence and get its first and last elements.

share|improve this answer

dc, 45 bytes

[dsa]dsAx[dsz]dsZx[dla>Adlz<Zs.z0<f]dsfxlzlaf

This is a fairly straightforward equivalent of the C++ reference code:

#Test data
0 15 2 3 7 18 _2 9 6 _5 3 8 9 _14

# Uses two variables: a for min, and z for max

# Functions A and Z simply store a copy to a and z respectively.  Call
# them both, to initialize the variables.
[dsa]dsAx
[dsz]dsZx

# Function f is the main work - define and call it
[
    dla>A                       # copy into a if lower
    dlz<Z                       # copy into z if higher
    s.                          # discard value
    z0<f                        # recurse until end of input
]dsfx

# print the result
lzlaf
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.