組み込み関数を使用せずに、配列内の最小および最大整数を見つけます


15

チャレンジ

stdinから受け取った整数の配列、関数の引数、プログラムの引数、またはその他のメソッドを指定します。

出力のみ戻り値、STDOUT、または他のフィッティング方法を介して、アレイ内の最小値および最大値、。

セッション例

> 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つの要素が含まれる場合、2回出力する必要があります。
  • 最小値と最大値が同じ場合、両方を出力する必要があります。

12
これは、Yのないdo Xチャレンジであり、特に興味深いものではありません。
Mego

5
@DmitryKudriavtsev 次回はサンドボックスをお試しください。
メゴ

5
真剣に、サンドボックスを使用してください。チャレンジへの変更により、すべての回答が無効になりました。
メゴ

1
私は創造的な方法を奨励しましたいいえ、あなたはそれをタグ付けすることによって、短い解決策を奨励しましたcode golf
ルイス・メンドー

1
X:としては、ルイス・Mendoはい、誰もがちょうど、異なる言語で、本当に創造的でない「ビルトインし、最初と最後のテイクを使用して私は、ソートあなたの配列を」投稿された
Walfrat

回答:


29

ゼリー、3バイト

Ṣ.ị

オンラインでお試しください!

配列を並べ替えてから、0.5番目の要素を取得します。

Jellyは1-indexingを使用し、浮動小数点のindexing手段は床と天井を取得します。

したがって、0.5番目の要素は0番目の要素と1番目の要素になります。

0番目の要素は最後の要素です。


2
かなり賢い私はそれを待っています....ゼリー!
ローハンジュンジュンワラ

ああ、そうすると中央値を見つけるのは簡単になります。
アダム

1
@KonradRudolph これ
リーキー修道女

1
最初の2つの要素ではなく、最初最後の要素が必要ではありませんか?または、私はあなたの説明を誤解しましたか?
トビーSpeight

1
@TobySpeight 1ベースのインデックス付けでは、0番目の要素が最後の要素です。
リーキー修道女

12

Python、61 49 37 36 34 31バイト

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

RootTwoのおかげで-12バイト

chepnerのおかげでさらに-12バイト

johnLateのおかげで-2バイト

johnLateのおかげで-3バイト


1
Python 3でも機能するため、見出しをPythonに変更しました。
リーキー修道女

1
数十バイトのゴルフをすることができます:[::(len(s)-1)or 1]最初の添え字に使用します。そして、2番目の用語はに短縮できますs[:len(s)<2]
RootTwo

リストを2回ソートすることで、さらに12バイト削ることができますlambda s:sorted(s)[:1]+sorted(s)[-1:]
-chepner

6バイトを節約lambda s:sorted(s)[::len(s)-1]
アーロン

現在のバージョン(lambda s:sorted(s)[::len(s)-1])は、要素が1つの配列()では機能しませんValueError: slice step cannot be zero。可能な修正はlambda s:sorted(s*2)[::len(s*2)-1](34バイト)です。
johnLate

8

Brain-Flak 220 218バイト

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

オンラインでお試しください!

説明

最初に最上位の値を2倍にします(キャストではリストは1つだけの長さです)

(({}))

次に、バブルソートアルゴリズムを使用します。

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

次に、スタックの一番上の値(つまり、min)を取得します

({}<...>)

次に、スタックの高さが1になるまでポップします。

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

8

JavaScript(ES6)、34バイト

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

sortインプレースでソートするためpop、配列の最低値と最高値の[0]インデックスを参照できますが、デフォルトでは文字列ソートを行うため、コンパレーターを渡す必要があります。


デフォルトのアルゴリズムでビルトインとしてカウントし(x,y)=>x-yない限り、この部品は必要ないと思いますsort()
スコット

1
@スコットしかし、私は字句の並べ替えをしたくない...-
ニール

正しい... 10以上または0以下の数値ではテストしませんでした。sort()内部的にすべてを文字列として扱うことを知りませんでした-ごめんなさい!
スコット



5

ARMマシンコード、26バイト

16進ダンプ(リトルエンディアン):

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では、minおよびmax二つの引数のではなく、リストの最小値と最大値を与えます。私は(代わりにだけと思われ、これは禁止されているかどうかを言うことができなかったminimumし、maximumそう、彼らはあるなら、私に知らせてください禁止されるだろう)と私は、速やかにこの回答を削除します。


@nimi FGITW効果、悲しげに...
ThreeFx

3

オクターブ、20バイト

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

これにより、入力ベクトルが並べ替えられ、最初と最後の値が出力されます。






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

gcc、置き換えることができる*a>M?M=*a:0*a<M?:M=*a
ceilingcat



2

CJam、10 9バイト

q~$_(p;W>

オンラインでお試しください。

私は本当にCJamが得意ではありません。

q~          e# eval input
  $         e# sort
   _        e# duplicate
    (       e# pop first
     p      e# print
      ;     e# remove array
       W>   e# get last element

リストの最初の要素を取得する通常の方法は次のとおりです0=(ただし、残念ながらバイトを節約できません)。他の2つの9バイトソリューション:0W]q~$f=pまたは名前のないブロック{$2*_,(%}
マーティンエンダー

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

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

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

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.

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.