Find the largest and the smallest number in an array

29

3

The Task

The task is very simple. Given an array containing only integers and strings, output the largest number and the smallest number.

Test Cases

Input: [1, 2, 3, 4, 5, 6, 7, 8]
Output: 1, 8

Input: [5, 4, 2, 9, 1, 10, 5]
Output: 1, 10

Input: [7, 8, 10, "Hello", 5, 5]
Output: 5, 10

Numbers in strings are not considered integers:

Input: [1, 2, 3, 4, "5"]
Output: 1, 4

If there is only one integer, it is both the largest and smallest integer:

Input: [1]
Output: 1, 1

Input: ["1", "2", "3", "4", 5]
Output: 5, 5

Rules

  • You can assume that an array will always contains at least one integer.
  • All integers are positive (greater than 0)
  • The order of the output doesn't matter.
  • This is , so the submission with the least amount of bytes wins!
  • Strings can contain all printable ASCII characters (32 - 126) and are non-empty.

Adnan

Posted 2016-02-05T10:47:43.120

Reputation: 41 965

How are strings that contain quote marks represented in the input? – feersum – 2016-02-05T11:23:20.327

@feersum Wouldn't that depend on your language? – Martin Ender – 2016-02-05T11:25:34.590

@feersum With escape characters probably, but if the language doesn't handle that, that's okay. – Adnan – 2016-02-05T11:25:35.520

@MartinBüttner If input is taken from stdin, it should not depend on what language is used. – feersum – 2016-02-05T13:31:03.147

3@feersum That's new to me. Even from STDIN [1, 2, 3] 1 2 3 and {1; 2; 3} are all valid input formats, so I don't see why it should be any different for string literals received from STDIN. – Martin Ender – 2016-02-05T13:33:17.933

Answers

9

Seriously, 9 6 bytes

,ì;M@m

Try It Online

How it works

,                              Read list input
 ì                             Remove everything but numbers from it
  ;                            Make a copy
   m                           Extract its min value
    @M                         Extract the other one's max value
                               Implicit output (max then min)

quintopia

Posted 2016-02-05T10:47:43.120

Reputation: 3 899

Ah, yes, I was looking for such a command. But the docs are not easy to search. – quintopia – 2016-02-06T05:03:59.260

I agree. The docs are my next big goal. – Mego – 2016-02-06T06:32:25.080

11

JavaScript (ES6), 54 56

Edit 2 bytes saved thx @Neil

Note: x===+x is true if and only if x is a number

a=>[Math.max(...a=a.filter(x=>x===+x)),Math.min(...a)]

edc65

Posted 2016-02-05T10:47:43.120

Reputation: 31 086

3Why the outer ()s? – Neil – 2016-02-05T12:41:38.087

@Neil what outer ()? Why on earth should I have outer ()s? – edc65 – 2016-02-05T14:27:57.140

This returns a function, you still need to call it. (or just remove a=>) – Michael Theriot – 2016-02-05T16:18:14.787

2Yes it's an anonymous function. It's quite a common way to post an answer in JavaScript @MichaelTheriot – edc65 – 2016-02-05T16:29:21.237

@MichaelTheriot By default, we allow submissions to be standalone functions rather than always requiring full programs.

– Alex A. – 2016-02-05T18:39:49.913

Yeah, I've missed that case... :( – Andreas – 2016-02-06T10:59:34.317

8

Pyth, 14 11 10 bytes

hM_BS^I#1Q

Try it online. Test suite.

Explanation

  • Q: evaluated input
  • #: filter that on:
    • I: the value being the same after:
      • ^…1 raising it to power 1
  • S: sort that
  • _B: create array [previous, reversed(previous)]
  • hM: take first item of each item of that

The hardest part is to golf the removal of strings, which currently takes 4 bytes. The current approach works due to ^<str>1 taking the first Cartesian power of the sequence (basically, the list of the string's characters), but ^<int>1 is just the identity function.

PurkkaKoodari

Posted 2016-02-05T10:47:43.120

Reputation: 16 699

Hrm, you could also use *#_1Q to remove the strings, which would be shorter if a variable was initialized to negative one... – FryAmTheEggman – 2016-02-05T14:07:16.843

7

Python 2, 42 bytes

In Python 2, integers are always less than strings during comparisons, so a simple min(s) will find the smallest integer. When finding the maximum though, we must filter out strings first. The anonymous function accepts a sequence and returns a tuple with the minimum and maximum.

lambda s:(min(s),max(x for x in s if''>x))

Example:

[1,'77', 6, '', 4] -> (1, 6)

Logic Knight

Posted 2016-02-05T10:47:43.120

Reputation: 6 622

3You need a lambda a: stuck before that. – Doorknob – 2016-02-05T12:29:37.520

if x>0 or if''>x save one byte. – grc – 2016-02-05T12:39:39.830

@Doorknob, now lambda as suggested. – Logic Knight – 2016-02-05T14:00:47.877

@grc, thanks for the tip. Saved a byte. – Logic Knight – 2016-02-05T14:01:25.760

1@Dennis, I did not know this. I have edited the solution to make clear the comparison only works in Python 2. – Logic Knight – 2016-02-05T23:17:11.603

1Building up: lambda s:(min(s),-min(-1*_ for _ in s)) (39 bytes) – Fran Borcic – 2016-02-08T09:10:49.523

Wow. That is some very nice work with the -min() trick. It took me a few minutes to figure out how it works. You should post that answer yourself. You will certainly have a +1 from me. – Logic Knight – 2016-02-08T10:39:57.283

7

Jelly, 8 bytes

|f¹Ṣ0,1ị

Try it online!

Background

In a perfect world, it would suffice to intersect the list with a flattened version of itself. Strings are simply lists of characters in Jelly, so while the original list would contain integers and strings, the flattened version would contain integers and characters, leaving only the integers in the intersection.

In the real world, both the parsers of both input and string literals yield characters instead of strings of length 1. The only way to pass a singleton string to a function would be to encode it "manually" as, e.g., [”a], which is a character wrapped in an array.

This would save a byte, for a total of 7 bytes (Try it online!).

fFṢ0,1ị

Since that's probably not acceptable, we also need a way to differentiate characters from integers.

Jelly's bitwise atoms desperately try to convert their arguments to integers. They start by vectorizing until they encounter types of depth 0 (numbers or characters), then attempt to convert them to integers. For a character that represents an integer, this will be successful. For others, a dyadic, bitwise atom will simply give up and return 0.

For example, bitwise ORing the list [1, "2", "34", "-5", "a", "bc"] with itself will yield

[1, 2, [3, 4], [0, 5], 0, [0, 0]]

By intersecting the result with the original list, we get rid of the arrays and the integers that weren't present in the original list.

How it works

|f¹Ṣ0,1ị  Main link. Input: A (list)

|         Bitwise OR the list A with itself.
 f¹       Filter the result by presence in A.
   Ṣ      Sort the resulting list of integers.
    0,1ị  Retrieve the elements at those indexes.
          Indices are 1-based and modular in Jelly, so 0 is the last (maximum),
          and 1 is the first (minimum).

Dennis

Posted 2016-02-05T10:47:43.120

Reputation: 196 637

6

Ruby, 57 36 29 bytes

Newbie here, so I don't know if there is any standard or universally accepted place/way to calculate bytes used, any help would be very appreciated!

Edited as per manatwork & Doorknob's comment!

->n{(n.map(&:to_i)&n).minmax}

Test

2.3.0 :076 > f=->n{[(n.map(&:to_i) & n).min, (n.map(&:to_i) & n).max]}
 => #<Proc:0x007ff7650ee868@(irb):76 (lambda)>
2.3.0 :077 > f[[7, 8, 10, "Hello", 5, 5]]
 => [5, 10]

Nirajan Pokharel

Posted 2016-02-05T10:47:43.120

Reputation: 159

136 characters: ->n{[(x=n.map(&:to_i)&n).min,x.max]} – manatwork – 2016-02-05T11:44:22.033

229 bytes, using minmax: ->a{(a.map(&:to_i)&a).minmax} – Doorknob – 2016-02-05T12:03:15.853

6

Mathematica, 20 bytes

MinMax@*Select[#>0&]

Test cases

MinMax@*Select[#>0&]@{1,2,3,4,"5"}
(* {1,4} *)

njpipeorgan

Posted 2016-02-05T10:47:43.120

Reputation: 2 992

1Why is there the * there? It seems like you can get to 19 just by cutting it. – A Simmons – 2016-02-05T12:07:29.473

1@ASimmons It is necessary. MinMax@Select[#>0&] is not a valid pure function. – njpipeorgan – 2016-02-05T12:10:03.130

1@ASimmons @* is function composition, whereas @ is function application. – Martin Ender – 2016-02-05T12:11:45.893

1MinMax@Select[# > 0 &][{1, 2, 3, 4, "Hello", 5}] yields a correct response – A Simmons – 2016-02-05T12:13:46.300

1@ASimmons Try assign MinMax@Select[# > 0 &] to a symbol, or just evaluate it. – njpipeorgan – 2016-02-05T12:16:50.540

1@njpipeorgan I appreciate that it isn't a valid pure function, but I don't see why it needs to be one in order to be a valid solution to the challenge? – A Simmons – 2016-02-05T12:17:51.257

1@ASimmons That one works because precendence in your case is MinMax@(Select[# > 0 &][{1, 2, 3, 4, "Hello", 5}]) – Martin Ender – 2016-02-05T12:18:00.790

1

@ASimmons It needs to be a valid function expression because that's our consensus. Otherwise, the submission would be classified as a "snippet" instead which is not valid by default.

– Martin Ender – 2016-02-05T12:19:02.037

1@MartinBüttner I see, I'll try to conform to that. – A Simmons – 2016-02-05T12:21:33.200

5

CJam, 15 13 bytes

{_:z&$2*_,(%}

An unnamed block (function) which expects the input array on the stack and leaves the output array in its place.

Run all test cases.

Explanation

_     e# Duplicate.
:z    e# Map over list: a) take abs() of integer elements (a no-op) or b) wrap strings
      e# in an array.
&     e# Set intersection: only the integers will appear in both arrays.
$     e# Sort.
2*    e# Repeat array twice (to make the code work with single-integer input).
_,    e# Duplicate, get length N.
(%    e# Decrement, get every (N-1)th element, i.e. the first and the last.

Martin Ender

Posted 2016-02-05T10:47:43.120

Reputation: 184 808

I sugeested e) and e( to aditsu. He hasn't accepted that – username.ak – 2016-02-05T21:15:12.313

@username.ak I don't think those are really useful. Adding a two-char operator that only saves a single byte over the current solution isn't something aditsu is likely to implement, and I also think there must be more useful features to use those for. – Martin Ender – 2016-02-05T21:27:26.570

it will save 3 bytes: q~_e(ae)a+ – username.ak – 2016-02-06T10:50:18.040

@username.ak Well that's assuming that e( and e) would ignore strings or something, which seems inconsistent. And if it did involve comparison with strings it would probably fail the same way that $ and e> can't compare integers with strings. – Martin Ender – 2016-02-06T11:04:35.783

5

jq, 21 characters

[.[]|numbers]|min,max

Sample run:

bash-4.3$ bin/jq '[.[]|numbers]|min,max' <<< '[7, 8, 10, "Hello", 5, 5]'
5
10

On-line test:

manatwork

Posted 2016-02-05T10:47:43.120

Reputation: 17 865

5

Haskell, 41 39 bytes

f x=[minimum,maximum]<*>[[i|Left i<-x]]

In Haskell all elements of a list have to be of the same type, so I cannot mix Integer and String. However, there's the Either type for combining two types into a single one. The input list is therefore of type Either Integer String1. f filters the Integers, removes the Either wrapper, puts the list as the single element in a new list (e.g. [[1,2,3]]), so that <*> can apply the functions given in the first argument to it.

Usage example: f [Left 1, Left 3, Right "Hello", Left 2] -> [1,3].

Edit: @xnor brought <*> into play and saved 2 bytes. Thanks!


1 actually it's fully polymorphic in the second type as the String property is never used.

nimi

Posted 2016-02-05T10:47:43.120

Reputation: 34 639

Nice idea with the pattern match. You can save two chars with a reversed map: f x=[minimum,maximum]<*>[[i|Left i<-x]] – xnor – 2016-02-07T09:23:52.363

@xnor: very nice. Thanks a lot! – nimi – 2016-02-07T10:01:43.500

4

Mathematica, 28 bytes

MinMax[#/._String->Nothing]&

A Simmons

Posted 2016-02-05T10:47:43.120

Reputation: 4 005

I still don't understand your obsession with Nothing... It doesn't mean anything special... Also, for 23 bytes: MinMax@*Select[NumberQ] – LegionMammal978 – 2016-02-05T11:48:40.433

@LegionMammal978 Make use of "all integers are positive"! See my answer. – njpipeorgan – 2016-02-05T11:56:59.290

1Nice solutions guys, I should have thought of doing it that way!

@LegionMammal978, Nothing does have a special meaning. Since Mathematica 10.2, it gets automatically removed from Lists. – A Simmons – 2016-02-05T12:05:27.447

@LegionMammal978 Nothing is a documented function in the latest versions.

– Mr.Wizard – 2016-02-08T03:00:59.693

4

PHP, 50 48 bytes

<?=min($a=array_filter($a,is_int)).', '.max($a);

PaulSkinner

Posted 2016-02-05T10:47:43.120

Reputation: 141

1Beat me by 2 minutes :). – TMH – 2016-02-05T12:03:28.850

2

It's generally forbidden to suppose that the input is already in a variable. By the way, you can save two bytes by removing the ' around is_int.

– Blackhole – 2016-02-05T16:23:29.690

@Blackhole Thanks. Didn't realise. I've utilised your quote removal :) – PaulSkinner – 2016-02-05T16:45:59.873

4

Retina, 71

Thanks (as always) to @MartinBüttner for the golfing help.

Not competitive golf-wise, but its interesting to implement integer bubble sorting in Retina.

Assumes all strings in the input are " double-quoted and don't contain any escaped double quotes \".

A`"
¶

\d+
$&$*a $&$*a
+`\b(a+) +\1(a+)\b
$1$2 $1
 +[a ]+ +

(a)+
$#1

Input is newline-separated.

Try it online.

Digital Trauma

Posted 2016-02-05T10:47:43.120

Reputation: 64 644

I think you can use <space>.*<space> in the second to last stage because of greed. – FryAmTheEggman – 2016-02-12T18:18:01.587

4

Mathematica, 14

#&@@@MinMax@#&

Example:

tests = {
   {1, 2, 3, 4, 5, 6, 7, 8},
   {5, 4, 2, 9, 1, 10, 5},
   {7, 8, 10, "Hello", 5, 5},
   {1, 2, 3, 4, "5"},
   {1},
   {"1", "2", "3", "4", 5}
 };

# & @@@ MinMax@# & /@ tests
{{1, 8}, {1, 10}, {5, 10}, {1, 4}, {1, 1}, {5, 5}}

Explanation:

When MinMax gets non-numeric input it reduces the problem as far as it can, then leaves terms wrapped in Min and Max:

MinMax @ {7, 8, 10, "Hello", 5, 5}
{Min[5, "Hello"], Max[10, "Hello"]}

Due to the automatic ordering that takes place strings follow integers.

Apply at levelspec {1}, shorthand @@@, is then used to pull the first argument of non-atomic elements. Note that 5 is untouched here:

foo @@@ {5, Max[10, "Hello"]}
{5, foo[10, "Hello"]}

Mr.Wizard

Posted 2016-02-05T10:47:43.120

Reputation: 2 481

3

MATL, 23 bytes

"@Y:tX%1)2\?x]N$htX<wX>

Try it online!

"       % implicitly input cell array. For loop that iterates on each cell
  @     %   push each cell
  Y:    %   cell's contents (either a number or a string)
  tX%   %   duplicate and push class. This will produce 'char'  or 'double'
  1)    %   get first letter: either 'c' or 'd'
  2\    %   is its ASCII code odd?
  ?     %   if so...
    x   %     delete (it's a string)
  ]     %   end if
  N$h   %   concatenate all stack into an array. This array will contain up to
        %   three numbers: minimum up to now, maximum up to now, new value (if any)
  tX<   %   duplicate. Push minimum
  wX>   %   swap. Push maximum.
        % implicitly end for
        % implicitly display stack contents

Luis Mendo

Posted 2016-02-05T10:47:43.120

Reputation: 87 464

Oh, my bad :p. Nice answer though :) – Adnan – 2016-02-05T12:36:06.797

@Adnan Thanks! A little too long :-) – Luis Mendo – 2016-02-05T12:36:35.337

3

Oracle SQL 11.2, 189 bytes

SELECT MIN(TO_NUMBER(i)),MAX(TO_NUMBER(i))FROM(SELECT REGEXP_SUBSTR(:1,'[^,]+',1,LEVEL)i FROM DUAL CONNECT BY LEVEL<REGEXP_COUNT(:1,',')+2)WHERE TRIM(TRANSLATE(i,' 0123456789',' '))IS NULL;

Un-golfed

SELECT MIN(TO_NUMBER(i)),MAX(TO_NUMBER(i)) 
FROM  (
        SELECT REGEXP_SUBSTR(:1,'[^,]+',1,LEVEL)i 
        FROM   DUAL 
        CONNECT BY LEVEL<REGEXP_COUNT(:1,',')+2
      )
WHERE TRIM(TRANSLATE(i,' 0123456789',' '))IS NULL;

The sub-query parse the array and split it to populate a view with one element per row. Then the non numeric elements are filtered out.

I wish I could have found a way to do it with LEAST and GREATEST, but no luck with how to handle the array as a parameter.

Jeto

Posted 2016-02-05T10:47:43.120

Reputation: 1 601

You're leaving the [] in the array so you're not selecting the max or min if they're the first or last elements of the array. You also don't need your WHERE clause, you're already selecting aggregates so you don't need to filter. Search for numeric characters in your regexes and push the number conversion down to the sub-query (very little danger of pushed predicates) and it becomes 126 bytes: select min(i),max(i)from(select to_number(regexp_substr(&1,'\d+',1,level))i from dual connect by level<=regexp_count(&1,'\d')) – Ben – 2016-02-07T18:57:21.673

There's no need for a + in the second regex here as it doesn't matter if you generate a few extra rows (saves a byte). It's also worth noting though that if you have a string made up solely of numbers you won't ignore it here; that needs overloaded functions in the same package, so is not at all pretty. – Ben – 2016-02-07T19:00:48.010

3

Perl 44 39 + 3 = 41 bytes

@a=sort{$a-$b}grep!/"/,@F;$_="@a[0,-1]"

Requires -pa flags:

$ perl -pae'@a=sort{$a-$b}grep!/"/,@F;$_="@a[0,-1]"' <<< '1 2 3 5 4'
1 5
$ perl -pae'@a=sort{$a-$b}grep!/"/,@F;$_="@a[0,-1]"' <<< '1 2 3 4 "5"'
1 4

Thanks to @manatwork for shaving off a few bytes

andlrc

Posted 2016-02-05T10:47:43.120

Reputation: 1 613

Which Perl version? For your second example I get different result: http://pastebin.com/judJys5g

– manatwork – 2016-02-05T12:33:28.087

@manatwork You are correct, Figure I cannot remove sort{$a-$b}grep... – andlrc – 2016-02-05T12:36:01.267

The requirement doesn't state that the output has to be formatted exactly as in the examples and in this task clearly not the formatting is the point. So many of us just used what is handier in our language of choice. In Perl I would do it like this: $_="@a[0,-1]". – manatwork – 2016-02-05T13:22:24.023

One character shorter filtering: grep!/"/. – manatwork – 2016-02-05T13:27:52.867

It says the array will be numbers and strings. All the examples in the question are with double-quoted strings, but I don't see anything saying they can't be single-quoted. I think !/\D/ is necessary instead of !/"/, for one more byte. – msh210 – 2016-02-07T03:45:48.563

3

vimscript, 25 bytes

g/"/d
sort n
t.
t.
2,$-1d

Yep, that's right, vimscript.

Expects input in the form

1
2
3
4
"5"

And outputs in the form

1
4

Explanation:

g/"/d    delete all lines that contain quotes
sort n   sort numerically
t.       duplicate the first line
t.       duplicate it again
2,$-1d   delete from line 2 to line (END-1)

The first line needs to be duplicated twice to handle the edge case of an input of a single number. This is because the last command will complain if there are only two lines when it is reached, since it ends up being 2,1d which is a backwards range.

Doorknob

Posted 2016-02-05T10:47:43.120

Reputation: 68 138

3

Bash, 40 31 30 bytes

sort -n|sed /\"/d|sed '1p;$p;d'

Requires a line separated list:

$ echo $'5\n4\n2\n9\n1\n"10"\n5' | sort -n|sed /\"/d|sed '1p;$p;d'
1
9

Thanks to @manatwork to shave off a few bytes

andlrc

Posted 2016-02-05T10:47:43.120

Reputation: 1 613

sed '1p;$p;d' saves a byte. – Dennis – 2016-02-07T03:58:41.977

3

PowerShell, 53 36 bytes

@($args[0]|?{$_-is[int]}|sort)[0,-1]

Saved 17 bytes thanks to @goric

OOOF ... PowerShell usually plays pretty fast and loose with casting, which is normally a good thing for golfing, but hurts it here.

Takes our input $args[0] and pipes it into a Where-Object statement (the ?) that will only select integers and passes them along the pipeline, discarding anything else. Since dynamic re-casting happens on-the-fly in the background for you (e.g., 1+"5" returning 6 is perfectly valid PowerShell), we need to use the -is operator in order to differentiate between the data types.

From there, we pipe that collection into Sort-Object, which will sort the integers from smallest to largest. The outer () is necessary so we can reference the first and last elements with [0,-1] (i.e., the smallest and the largest), but note we also need the outer @ to force casting the output of sort as an array if there's only one object (as the result of the ?, or only one object was input).

AdmBorkBork

Posted 2016-02-05T10:47:43.120

Reputation: 41 581

1

Take a look at the -is type operator here. I think you could replace .GetType().Name-eq"Int32" with -is[int] to save 17 bytes

– goric – 2016-02-08T20:53:16.653

@goric Super awesome! Thanks for the massive golf! – AdmBorkBork – 2016-02-08T21:37:23.703

3

Julia, 35 bytes

x->extrema(filter(i->isa(i,Int),x))

This is a lambda function that accepts an array and returns a tuple of integers. To call it, assign it to a variable.

Julia has a built-in function extrema for getting the minimum and maximum elements of an array as a tuple. However, since the array can also have strings in it, we first have to filter those out. We can do that by testing whether each element is an integer using isa.

Alex A.

Posted 2016-02-05T10:47:43.120

Reputation: 23 761

3

Japt, 23 bytes

[V=Uf_bZÃn@X-Y})g Vw g]

Test it online!

How it works

[V=Uf_  bZÃ n@  X-Y})g Vw g]
[V=UfZ{ZbZ} nXY{X-Y})g Vw g]

UfZ{ZbZ}   // Filter out the items Z in U where Z.b(Z) is falsy.
           // For numbers, this the original number, which is always non-0 (non-falsy).
           // For strings, this returns Z.indexOf(Z), which is always 0 (falsy).
nXY{X-Y}   // Sort by subtraction. Small items move to the front, large to the back.
V=         // Set variable V to the resulting array.
)g Vw g    // Take the first item in V, and the first in V.reverse().
[       ]  // Wrap them in an array so both are sent to output.

ETHproductions

Posted 2016-02-05T10:47:43.120

Reputation: 47 880

2

APL (Dyalog), 13 bytes

(⌊/,⌈/)⎕AV~⍨∊

Try it online!

 enlist (flatten – this makes all the strings into characters in the big list)

⎕AV~⍨ remove all characters in the Atomic Vector (the character set – leaves numbers)

() apply the following tacit function:

⌊/ the minimum across

, appended to

⌈/ the maximus across

Adám

Posted 2016-02-05T10:47:43.120

Reputation: 37 779

2

JavaScript (ES5), 105 bytes

function a(b){m=Math;b=b.filter(function(c){return c===+c});alert(m.min.apply(m,b)+','+m.max.apply(m,b))}

Usage: a([1,2,3,'4'])

Just trying :)

"Ungolfed":

function a(b){
  m=Math;
  b=b.filter(function(c){
    return c===+c
  });
  alert(m.min.apply(m,b) + ',' + m.max.apply(m,b))
}

Alex

Posted 2016-02-05T10:47:43.120

Reputation: 141

2

Pyth, 11 bytes

hJSf!>TkQeJ

Explanation:

   f    Q   - filter([V for T in >], Q)
    !>Tk    - not(T>"")
  S         - sorted(^)
hJ       eJ - print first and last element

Try it here!

Blue

Posted 2016-02-05T10:47:43.120

Reputation: 26 661

2

Perl 6, 25 bytes

The obvious answer would be this WhateverCode lambda

*.grep(Int).minmax.bounds

If it has to be a full program

put get.words».&val.grep(Int).minmax.bounds

The input to this full program is a space separated list of values


Usage

# give it a lexical name
my &code = *.grep(Int).minmax.bounds;

say code [1, 2, 3, 4, 5, 6, 7, 8];  # (1 8)
say code [5, 4, 2, 9, 1, 10, 5];    # (1 10)
say code [7, 8, 10, "Hello", 5, 5]; # (5 10)
say code [1, 2, 3, 4, "5"];         # (1 4)
say code [1];                       # (1 1)
say code ["1", "2", "3", "4", 5];   # (5 5)

say code []; # (Inf -Inf)

Brad Gilbert b2gills

Posted 2016-02-05T10:47:43.120

Reputation: 12 713

2

, 16 chars / 20 bytes

[МƲ(ï⇔⒡≔=+$⸩,МƵï

Try it here (Firefox only).

Not bad, not bad...

Explanation

This outputs an array containing both the maximum and minimum. (ï⇔⒡≔=+$⸩, basically filters out all strings in the input, МƲ gets the maximum in the input, and МƵ gets the minimum.

Just a note: this is the first challenge where I get to use , which basically turns ï⇔ into ï=ï.

Mama Fun Roll

Posted 2016-02-05T10:47:43.120

Reputation: 7 234

2

Python 3, 56 bytes

lambda x:[m(t for t in x if str(t)!=t)for m in(min,max)]

Try it online on Ideone.

Dennis

Posted 2016-02-05T10:47:43.120

Reputation: 196 637

2

Java (OpenJDK 8), 124 bytes

a->{int s[]={0,0},t;for(Object i:a)try{t=(int)i;s[0]=s[0]<1|t<s[0]?t:s[0];s[1]=s[1]<t?t:s[1];}catch(Exception e){}return s;}

Try it online!

Java 8 lambda function, takes array as input and gives out array {min, max}. Non competing, because the input has to be an integer array.

Fixed and -1 byte thanks to Kevin Cruijssen

HyperNeutrino

Posted 2016-02-05T10:47:43.120

Reputation: 26 575

You could make this competing by taking a list of Objects and checking if an item is an integer or String. – Kevin Cruijssen – 2018-05-07T14:19:01.857

@KevinCruijssen done, thanks – HyperNeutrino – 2018-05-08T12:00:54.870

<i now gives an error without integer-cast. Also, your initial code (and this one as well) doesn't work for min, since it will always output 0 for min. Here is a possible fix. EDIT: Try-catch seems to be 1 byte shorter than the if(i instanceof Integer). – Kevin Cruijssen – 2018-05-08T12:11:15.483

@KevinCruijssen oh didn't notice that, thanks! – HyperNeutrino – 2018-05-09T12:09:19.177

1

Jolf, 20 bytes

I can probably golf this... I need to implement type-checking shorter solutions.

γ fxd='nF~tH0ͺZkγZKγ
 _fx                 filter the input
    d='nF~tH0        checking for number type
γ                    call that "γ"
             ͺ       pair
              ZkγZKγ  the min and max of the array

Conor O'Brien

Posted 2016-02-05T10:47:43.120

Reputation: 36 228

1

Python 3, 65 bytes

Here's the obligatory example of how Python 3 is worse (for golfing) than Python 2, because it got rid of weird behaviours, like "you can compare ints and strings, and all ints are less than all strings".

def m(a):b=sorted(n for n in a if type(n)==int);return b[0],b[-1]

Tim Pederick

Posted 2016-02-05T10:47:43.120

Reputation: 1 411

1

C#, 71 bytes

(object[]z)=>{var a=z.OfType<int>();return new int[]{a.Max(),a.Min()};};

Simple lambda which returns the min and max as an int array.

Olivia Trewin

Posted 2016-02-05T10:47:43.120

Reputation: 351

1

PARI/GP, 52 bytes

This is terrible -- there has to be a better way to check if something is a number than type. polcoeff(eval(x),0) is even worse, despite (ab)using the requirement that numbers are positive. iferr(O(x);1,E,0) is clever but a byte longer: E is required for some reason, and p-adic numbers like O(3) are falsy (i.e., O(3)==0) so the ;1 is needed.

v->v=[x|x<-v,type(x)=="t_INT"];[vecmin(v),vecmax(v)]

An alternate approach is just as long:

v->[f([x|x<-v,type(x)=="t_INT"])|f<-[vecmin,vecmax]]

Charles

Posted 2016-02-05T10:47:43.120

Reputation: 2 435

1

Hoon, 90 84 bytes

|*
*
=+
(sort (skip ((list @) +<) (curr test 0)) lte)
[(snag 0 -) (snag 0 (flop -))]

This uses a couple fun features of Hoon:

  • I'm returning a wet gate instead of a dry one to prevent having to specify the type. This makes the caller typecheck the function instead of definition, which is perfectly fine.

  • The function argument for |= is an unnamed arm, which is placed in the subject at +<. Specifying a/* and using a as the input is longer than just leaving it unnamed and using +< directly

  • The same thing applies for =+ - it places the variable at the top of the subject at -, so I save the sorted list as an intermediate and can reference it the three times needed cheaply

  • The input specifies "All integers are positive (greater than 0)", which along with the fact the string will never be empty helps immensely. I can then slam the input through the type verifier gate (list @), which converts all entries in the list that aren't a number into 0 and then get rid of all zeros.

Example of use:

> %.  (limo ~[1 2 "hello" 9 17])
      |*
      *
      =+
      (sort (skip ((list @) +<) (curr test 0)) lte)
      [(snag 0 -) (snag 0 (flop -))]
[1 17]

RenderSettings

Posted 2016-02-05T10:47:43.120

Reputation: 620