在不使用内置函数的情况下查找数组中的最小和最大整数


15

挑战

给定一个从stdin,函数参数,程序参数或其他方法接收的整数数组:

输出在阵列中的最小和最大数目,通过一个返回值,标准输出,或其它拟合方法。

会话示例

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

参考实施

// C++14

void minmax(std::vector<int> v) {
    int min = v[0]; int max = v[0];
    for(auto it : v) {
        if (*it < min)
            min = *it;
        if (*it > max)
            max = *it;
    }
    std::cout << min << ' ' << max << std::endl;
}

规则

  • 您可能无法使用内置函数来计算值。
  • 不允许出现标准漏洞。
  • 鼓励创造性的实施。
  • 这是,最短的答案将获胜,但不会被选中。

澄清说明

  • 如果数组包含1个元素,则需要输出两次。
  • 如果最小值和最大值相同,则需要将它们两者都输出。

12
这是没有Y挑战do X,这并不是特别有趣。
Mego

5
@DmitryKudriavtsev下次尝试使用沙箱
Mego

5
认真地使用Sandbox。您对挑战所做的更改已使每个答案无效。
Mego

1
我鼓励采用创造性的方法,不,您通过标记解决方案来鼓励短期解决方案code golf
Luis Mendo

1
正如Luis Mendo所说,是的,每个人都只是在用不同的语言发布“我使用内置函数对数组进行排序并采用第一个和最后一个”:x
Walfrat,2016年

Answers:


29

果冻,3个字节

Ṣ.ị

在线尝试!

对数组进行排序,然后采用第0.5个元素。

果冻使用1索引,而浮点索引则占用其底线和ceil。

因此,第0.5个元素将为您提供第0个元素和第一个元素。

第0个元素是最后一个元素。


2
很聪明,我在等...果冻!
Rohan Jhunjhunwala

哦,这样将使发现中位数变得微不足道。
2013年

1
@KonradRudolph 这个
Leaky Nun

1
您不想要第一个最后一个元素,而不是前两个元素吗?还是我误解了您的解释?
Toby Speight,

1
@TobySpeight在基于1的索引中,第0个元素是最后一个元素。
Leaky Nun

12

Python,61 49 37 36 34 31字节

lambda s:s.sort()or[s[0],s[-1]]

-12字节感谢RootTwo

感谢chepner,另外-12个字节

-2个字节,感谢johnLate

-3个字节,感谢johnLate


1
我将标题更改为Python,因为它也适用于Python 3。
Leaky Nun

1
您可以打出12个字节:[::(len(s)-1)or 1]用于第一个下标。第二项可以简化为s[:len(s)<2]
RootTwo 2016年

只需对列表进行两次排序,您就可以节省另外12个字节:lambda s:sorted(s)[:1]+sorted(s)[-1:]
chepner '16

通过lambda s:sorted(s)[::len(s)-1]
Aaron

当前版本(lambda s:sorted(s)[::len(s)-1])不适用于具有一个元素(ValueError: slice step cannot be zero)的数组。可能的解决办法是lambda s:sorted(s*2)[::len(s*2)-1](34个字节)。
johnLate

8

脑高射炮 220个 218字节

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

在线试用!

说明

首先,它使最高值加倍(强制转换列表只有一个长)

(({}))

然后使用我的气泡排序算法:

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

然后,它获取堆栈的最高值(即最小值)

({}<...>)

然后弹出,直到堆栈的高度为一:

((())){{}{}([][()])}{}

8

JavaScript(ES6),34个字节

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

sort就地排序,因此我可以只引用[0]索引来获取pop数组中的最小值和最大值,但是默认情况下它会进行字符串排序,因此我必须通过一个比较器。


我认为您不需要此(x,y)=>x-y部分,除非使用sort()默认算法作为内置函数。
斯科特

1
@Scott但是我不希望使用词汇排序...
Neil

是的...我没有用大于10或小于0的数字进行测试。我不知道sort()内部将所有内容都视为字符串-抱歉!
斯科特

5

Mathematica,18个字节

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

对数组排序并提取第一个和最后一个值。


5

R,31个字节

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

不是那个原始的,但是嘿!


5

ARM机器码,26个字节

十六进制转储(小端):

6810 4601 f852 cb04 4560 bfc8 4660 4561 bfb8 4661 3b01 d8f5 4770

这是一个函数,没有系统调用或库依赖性。编码为Thumb-2,这是用于32位ARM的变量(2或4字节)编码。可以想象,没有简单的方法可以对此处的第一个和最后一个元素进行排序和选择。总的来说,这里没有什么花哨的事情,它与参考实现大致相同。

非高尔夫装配(GNU语法):

.syntax unified
.text
.global minmax
.thumb_func
minmax:
    @Input: @r0 and r1 are dummy parameters (they don't do anything)
    @r2 - Pointer to list of integers (int*)
    @r3 - Number of integers to sort (size_t)
    @Output:
    @Minimum of the list in r0 (int)
    @Maximum in r1 (int)
    ldr r0,[r2] @min=r2[0]
    mov r1,r0 @max=min
    loop:
        @ip is intra-procedure call register, a.k.a. r12
        ldr ip,[r2],#4 @ip=*r2++
        cmp r0,ip
        it gt @if (r0>ip)
        movgt r0,ip @r0=ip
        cmp r1,ip
        it lt @if (r1<ip)
        movlt r1,ip @r1=ip
        subs r3,r3,#1
        bhi loop @while (--r3>0)
    bx lr @Return

在Raspberry Pi 3上测试;这是测试脚本(C99,通过argv输入):

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
//First 2 arguments are dummies.
uint64_t minmax(int,int,int* array,size_t size);

int main(int argc,char** argv) {
    int i;
    int array[argc-1];
    for (i=1;i<argc;i++) {
        array[i-1]=atoi(argv[i]);
    }
    uint64_t result = minmax(0,0,array,argc-1);
    printf("Minimum is %d, maximum is %d.\n",(unsigned)result,(unsigned)(result>>32));
}

4

Haskell,27个字节

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

在Haskell,minmax给予最小和最大的两个参数不是列表。我无法告诉您这是否被禁止(似乎只是minimum并且maximum将被禁止),所以请让我知道是否是这样,我将立即删除此答案。


@nimi FGITW效果,可悲的是……
ThreeFx

3

八度,20字节

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

这将对输入向量进行排序,并输出第一个和最后一个值。




3

MATL,4个字节

S5L)

在线尝试!

说明

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


3

C,83 81 79字节

m,M;f(a,s)int*a;{for(m=M=*a;s--;++a)*a<m?m=*a:*a>M?M=*a:0;pr‌​intf("%i %i",m,M);}

1
该声明可以变成...f(a,s)int*a{...

1
您可以结合三元表达式来获得另外2个字节:m,M;f(a,s)int*a;{for(m=M=*a;s--;++a)*a<m?m=*a:*a>M?M=*a:0;printf("%i %i",m,M);}
gastropner

In gcc you can replace *a>M?M=*a:0 with *a<M?:M=*a
ceilingcat



2

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

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

8 bytes: q~$(p)p;. You can use ) to get the last element like you use ( to get the first.
Business Cat

@BusinessCat That's what I originally had, but it fails for single-element input.
PurkkaKoodari

@Pietu1998: Oh, you're right. I didn't notice that.
Business Cat

2

Python 2, 34 bytes

x=sorted(input());print x[0],x[-1]

2

PHP, 44 bytes

function a($a){sort($a);echo $a[0].end($a);}

2

Processing, 59 52 bytes

void m(int[]x){x=sort(x);print(x[0],x[x.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).


You can save bytes by removing spaces after int[]
Kritixi Lithos

1

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)

Darn, you beat me there!
bb94

1

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;};


1

Octave, 35 bytes

@(x)[x(all(t=x<=x')) x(sum(t)==1)]

This is an anoynymous function. Try it at ideone.

The code avoids using sorting. Namely, it does all pairwise "less than or equal" comparisons between elements of the input. The minimum is the element for which all comparisons are true. The maximum is that for which only one comparison is true.


1

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.


1
Though not the shortest answer in Python, this is very creative! +1
mbomb007

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

@mbomb007 - fine, golfed. This is now tied for the shortest Python implementation, and as a bonus it works in both 2 and 3.
TLW

1

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

1

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


1

Bash + coreutils, 30 bytes

tr \  \\n|sort -n|sed '$p;1!d'

The sed script prints, after the input is sorted, the first and last integers.


1

dc, 110 bytes

?ddsMsmzdsAsa[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!

Thanks to @seshoumara for finding that bug!

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

?dd 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

I didn't record how to invoke this, and now I can't remember. Whatever I'm doing now, I'm doing it wrong, because this is always returning 0 as the smallest element.
Joe

1
Pfew! It took some starring at it, but found the bug in your code. It's the first character (0) which you duplicate and initialize registers M and m. But if in the input list no number is smaller than m=0, or no number is greater than M=0, then you get an incorrect result, because you artificially added 0 to the sample numbers. The solution is to replace that first 0 with ?d, which reads the numbers and initializes M and m with the last number, thus making it a part of the sample. Then run the code like this: echo "8 _2 5"|dc -e "?ddsMsm....".
seshoumara

Wow, thanks, @seshoumara! I never would have noticed that! (I'd forgotten all about this question, too :P)
Joe

1

Java, 115 bytes

String f(int[]i){int t=i[0],a=t,b=t;for(int c=0;c<i.length;c++){a=i[c]<a?i[c]:a;b=i[c]>b?i[c]:b;}return""+a+" "+b;}

Ungolfed:

String f(int[] i) {
    int t=i[0], a=t, b=t; // assigns a and b to i[0]
    for (int c=0; c < i.length; c++) { // loop through the array
        a=(i[c]<a) ? i[c] : a;
        b=(i[c]>b) ? i[c] : b; // assignment with ternary operator
    }
    return ""+a+" "+b; // returns a string
}

My first ever code "golf" solution.

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.