목록의 두 번째 최대 실행


20

정수 목록이 주어지면 작업은 2와 입력 목록의 길이 사이의 각 k 에 대해 첫 번째 k 요소 에서 두 번째로 큰 값을 출력하는 것 입니다.

즉, 입력의 각 접두사에 대해 두 번째로 큰 값을 출력하십시오.

첫 번째 요소 (여기서 k = 1)에 대한 임의의 값을 출력 하거나 1 개의 요소 목록에 대해 두 번째 최대 값이 없으므로 간단히이 값을 생략 할 수 있습니다. 입력에 2 개 이상의 요소가 있다고 가정 할 수 있습니다.

가장 짧은 코드가 승리합니다.

Input:
1 5 2 3 5 9 5 8
Output:
  1 2 3 5 5 5 8
Input:
1 1 2 2 3 3 4
Output:
  1 1 2 2 3 3
Input:
2 1 0 -1 0 1 2
Output:
  1 1 1 1 1 2

내 영어가 최고가 아닌데 어떻게 k결정 되나요?
LiefdeWen

@LiefdeWen 각 k에 대한 답이 포함 된 목록을 출력합니다.
jimmy23013

2
1엄밀히 말하면 (두 번째 예) 의 두 번째로 큰 값1,1내림차순으로 정렬 할 때 두 번째 값입니다.
Jonathan Allan

어쩌면 나는 어리석은 일이지만 (주말을 정말로 시작할 수 있다고 생각하지만) 어떻게 작동하는지 잘 모르겠습니다. 누군가 ELI5가 마지막 테스트 케이스 일 수 있습니까? 처음 두 테스트 사례는 목록을 반복하여 목록의 현재 최소값을 결정한 다음 해당 항목을 제거하거나 더 쉬운 방법으로 목록을 정렬하고 마지막 항목을 제거하여 해결할 수 있습니다. 그것은 처음 두 테스트 사례에 대한 올바른 결과를 제공하지만 분명히 잘못되었습니다 (그리고 -1, 0, 0, 1, 1, 2마지막 테스트 사례를 제공 할 것 입니다)
Kevin Cruijssen

1
@KevinCruijssen 당신이 본 가장 큰 두 숫자를 기억하십시오. 마지막으로, 2가 가장 큰 것으로 시작 하여이 시점에서 의미가 없으므로 아무것도 출력하지 않습니다. 그런 다음 다음 반복에서 1과 2로 변경하여 1을 출력합니다. 이것은 마지막에 2에 도달 할 때까지 동일하게 유지되며 2와 2는 가장 크고 두 번째로 큽니다.
FryAmTheEggman

답변:


6

05AB1E , 5 바이트

ηεà\à

온라인으로 사용해보십시오!

[]먼저 (임의 값)을 반환합니다 .


η¦ε{¨θ6 바이트 작동
Adnan

@Adnan 물론> _ <는 어쨌든 더 나은 방법을 찾았습니다 ...
Erik the Outgolfer

흥미 Z©KZ®‚¹sÃ롭다 .. 내가 생각했던 것이었고, à심지어 일인지 도 몰랐다 !
매직 문어 Urn

다른 5 바이트 대안을 찾았습니다 . Áθ대신에 사용 했습니다.
Mr. Xcoder

5

껍질 , 9 7 바이트

@Zgarb 덕분에 한두 바이트 절약

mȯ→hOtḣ

0첫 번째 "두 번째 최대 값"을 반환 합니다.

설명

         -- implicit input, e.g          [1,5,3,6]
      ḣ  -- prefixes                     [[],[1],[1,5],[1,5,3],[1,5,3,6]]
     t   -- remove the first element     [[1],[1,5],[1,5,3],[1,5,3,6]]
mȯ       -- map the composition of 3 functions
    O    --   sort                       [[1],[1,5],[1,3,5],[1,3,5,6]]
   h     --   drop the last element      [[],[1],[1,3],[1,3,5]
  →      --   return the last element    [0,1,3,5]
         -- implicit output

온라인으로 사용해보십시오!


1
→hO대신 매핑 하고 바이트를 저장할 수 있습니다 .
Zgarb


3

자바 스크립트 (ES6), 58 51 50 바이트

@Neil 덕분에 1 바이트 절약

k = 1에 추가 undefined합니다 .

a=>a.map(e=>(b=[e,...b]).sort((a,b)=>b-a)[1],b=[])

테스트 사례

NB :이 스 니펫은 JSON.stringify()가독성을 위해 사용 되며 부작용으로로 변환 undefined됩니다 null.


1
나는 a=>a.map(e=>(b=[e,...b]).sort((a,b)=>b-a)[1],b=[])단지 50 이라고 생각합니다.
Neil

@ 닐 니스. :-)
Arnauld

2

Pyth , 8 바이트

m@Sd_2._

온라인으로 사용해보십시오! 또는 테스트 스위트를 사용해보십시오!


방법?

스펙에 따라 목록의 첫 번째 요소를 목록의 첫 번째 값으로 출력합니다 . 첫 번째 요소에 대한 임의의 값을 출력 할 수 있습니다 .

m@Sd_2._-암시 적 입력의 전체 프로그램.

m ._Q-변수 d를 사용하여 입력 접두사를 매핑합니다.
  Sd-현재 접두사를 정렬합니다.
 @-요소를 가져옵니다 ...
    _2-색인에서-2 (두 번째로 높음).
           -암시 적으로 인쇄합니다.

2

젤리 , 8 바이트

ḣJṢ€Ṗ€Ṫ€

온라인으로 사용해보십시오!

첫 번째 값은 항상 0이며 다음 숫자는 각 접두사의 두 번째 최대 값입니다.

설명

ḣJṢ€Ṗ€Ṫ€  Input: array A
 J        Enumerate indices, [1, 2, ..., len(A)]
ḣ         Head, get that many values from the start for each, forms the prefixes
  Ṣ€      Sort each
    Ṗ€    Pop each, removes the maximum
      Ṫ€  Tail each

@ Challenger5 나는 그것이 작동한다고 믿지 않는다
마일

@ Challenger5 작동하지 않습니다 ...
Outgolfer Erik

@EriktheOutgolfer 오, 알겠습니다.
Esolanging 과일


2

파이썬 2 , 45 바이트

f=lambda l:l[1:]and f(l[:-1])+[sorted(l)[-2]]

온라인으로 사용해보십시오!

코드의 오른쪽은 자명하다. 그러나 왼쪽에 무엇을 넣을 and까요? 리스트의 일부를 재귀 적으로 연결하기 때문에 l2 개 이상의 요소가 있으면 왼쪽이 사실이어야 하고 그렇지 않으면 비어있는리스트가 필요합니다. l[1:]이 기준을 훌륭하게 만족시킵니다.




1

배치, 123 바이트

@set/af=s=%1
@for %%n in (%*)do @call:c %%n
@exit/b
:c
@if %1 gtr %s% set s=%1
@if %1 gtr %f% set/as=f,f=%1
@echo %s%


1

05AB1E , 5 바이트

Erik의 솔루션 과는 매우 다른 또 다른 5 바이트를 발견했습니다 . 임의의 값은 목록의 첫 번째 요소입니다.

ηε{Áθ

온라인으로 사용해보십시오!


설명

ηε{Áθ  - Full program that reads implicitly from STDIN and outputs to STDOUT.

η      - Push the Prefixes of the list.
 ε     - Apply to each element (each prefix):
  {      - Sort the prefix list.
   Á     - Shift the list to the right by 1, such that the first element goes to the 
           beginning  and the second largest one becomes the last.
    θ    - Get the last element (i.e. the second largest)
         - Print implicitly.

이해하기 쉽도록 예를 들어 봅시다.

  • 먼저 암시 적 입력을 얻습니다 [1, 5, 2, 3, 5, 9, 5, 8].

  • 그런 다음 η-를 사용하여 접두사를 푸시합니다 [[1], [1, 5], [1, 5, 2], [1, 5, 2, 3], [1, 5, 2, 3, 5], [1, 5, 2, 3, 5, 9], [1, 5, 2, 3, 5, 9, 5], [1, 5, 2, 3, 5, 9, 5, 8]].

  • 이제 코드가 목록을 매핑하고 {-를 사용하여 각 접두사를 정렬합니다 [[1], [1, 5], [1, 2, 5], [1, 2, 3, 5], [1, 2, 3, 5, 5], [1, 2, 3, 5, 5, 9], [1, 2, 3, 5, 5, 5, 9], [1, 2, 3, 5, 5, 5, 8, 9]].

  • 그런 다음 가장 마지막 요소를 가져 와서 시작 부분으로 옮깁니다 [[1], [5, 1], [5, 1, 2], [5, 1, 2, 3], [5, 1, 2, 3, 5], [9, 1, 2, 3, 5, 5], [9, 1, 2, 3, 5, 5, 5], [9, 1, 2, 3, 5, 5, 5, 8]].

  • 물론, 이제 코드는 θ-를 사용하여 각 하위 목록의 마지막 요소를 가져옵니다 [1, 1, 2, 3, 5, 5, 5, 8](첫 번째 요소 는 임의의 값임).




1

Japt , 12 10 바이트

출력 배열은 입력 배열의 첫 번째 요소와 원하는 순서로 구성됩니다.

£¯YÄ n< g1

그것을 테스트


설명

배열의 암시 적 입력 U.

£

지도 위에 U, Y현재 색인은 어디에 있습니까 ?

¯YÄ

U에서 0까지 슬라이스 합니다 Y+1.

n<

내림차순으로 정렬합니다.

g1

두 번째 요소를 가져옵니다.

결과 배열을 내재적으로 출력합니다.


1

MATL , 19 10 바이트

9 바이트를 줄여준 Luis Mendo에게 감사드립니다!

"GX@:)SP2)

여기서 사용해보십시오 .

설명

"GX@:)SP2)
"                  for all the values in the input
 G                 get input
  X@:)             get values up to the iteration
      SP           sort it in descending order
        2)         get the second value
                   implicit end of loop and output

@LuisMendo 와우! MATL에 대해 얼마나 알고 있는지 보여줍니다. 도와 주셔서 감사합니다!
DanTheMan





0

Swift 3, 67 bytes

func g(l:[Int]){print((1..<l.count).map{l[0...$0].sorted()[$0-1]})}

Test Suite.

Swift 3, 65 bytes

{l in(1..<l.count).map{l[0...$0].sorted()[$0-1]}}as([Int])->[Int]

Test Suite.


How to run these?

The first one is a complete function that takes the input as a function parameter and prints the result. You can use them exactly as shown in the testing link. I decided to add instructions though, because the second type of function is used very rarely and most people don't even know of its existence. Usage:

g(l: [1, 1, 2, 2, 3, 3, 4] )

The second one is an anonymous function, like lambdas. You can use it exactly as you'd do it Python, declaring a variable f and calling it:

var f = {l in(1..<l.count).map{l[0...$0].sorted()[$0-1]}}as([Int])->[Int]

print(f([1, 1, 2, 2, 3, 3, 4]))

or wrap it between brackets and call it directly ((...)(ArrayGoesHere)):

print(({l in(1..<l.count).map{l[0...$0].sorted()[$0-1]}}as([Int])->[Int])([1, 1, 2, 2, 3, 3, 4]))

0

PHP, 53 bytes

for(;a&$n=$argv[++$i];rsort($a),print$a[1]._)$a[]=$n;

takes input from command line arguments. Output delimited, lead and trailed by semicola.
Run with -nr or try it online.

Yields a warning in PHP 7.1; replace a& with ""< to fix.
Or use for(;++$i<$argc;rsort($a),print$a[1]._)$a[]=$argv[$i]; (54 bytes)


0

Mathematica 42 Bytes

Independently arrived at a answer very similar to @Jenny_mathy but 3 bytes shorter

Sort[#[[;;i]]][[-2]]~Table~{i,2,Length@#}&

Realized that the 1st running max takes only 15 bytes and two function calls!:

Max~FoldList~#&

This can be done so concisely because Max has the attributes Flat and OneIdentity but that's not true for RankedMax which would be the logical replacement. Unfortunately defining attributes or modifying them on existing functions takes up way too many bytes, so the flattening must be done by other means.

All of the nth running maxes can be found in 48 bytes:

PadLeft[Sort/@Flatten/@FoldList[{##}&,{},#&@#]]&


0

k, 13 bytes

{x(>x)1}'1_,\

Try it online!

           ,\ /sublists of increasing lengths (scan concat)
         1_   /remove the first sublist
{      }'     /for each sublist:
  (>x)        /    indices to permute sublist into largest to smallest
      1       /    get second index
 x            /    get sublist[that index]

0

Octave, 51 bytes

@(a){[~,I]=cummax(a);a(I(2:end))=-inf;cummax(a)}{3}

- An arbitrary value returned for the first element.

Try it online!


0

JavaScript (ES6), 43 51 bytes

Edit: Added 8 bytes since numerical sorting is desired. :(

a=>a.map((_,b)=>a.slice(0,b+1).sort((a,b)=>b-a)[1])

Keeping this one here, though, as it is shorter providing one wants lexicographical ordering:

a=>a.map((_,b)=>a.slice(0,b+1).sort()[b-1])

Both expressions produce undefined for the first element.

Test code


Note that I would have preferred to simply comment on the existing JS post if it were not for the reputation system.
Aaron Hill

Welcome to PPCG! I don't like the 50-rep comment threshold either, but I guess they need it to keep spammers from commenting. Anyway, I think this will fail if the input contains a double digit number such as 10, as .sort() sorts lexicographically by default (i.e. 1,10,100,11,12,13,...,2,20,21,...). You'd need to include (a,b)=>a-b or similar to get it to sort by number.
ETHproductions

Thanks, @ETHproductions. I've updated for numerical ordering, which means this is no longer good enough. Oh, well.
Aaron Hill

0

Clojure, 56 bytes

#(for[i(drop 2(reductions conj[]%))](nth(sort-by - i)1))

Maybe there is a better way to generate those prefixes.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.