더 큰 영광을 향하여 앞뒤로!


15

이 도전이 95 세의 나이로 세상을 떠난 스탠 리에게 또 하나의 찬사로 쓰길 바랍니다.

Stan Lee는 우리에게 귀중한 유산과 독특한 캐치 단어 Excelsior를 남겼습니다 . 여기에 그가 의미 하는 바에 근거한 작은 도전 이 있습니다 .

마지막으로“엑셀 시어”는 무엇을 의미합니까? “위로 향하여 더 큰 영광을!”그것이 트윗을 마칠 때마다 당신이 원하는 것입니다! 대팻밥!

도전

음수가 아닌 일련의 정수가 주어지면 Excelsior!정수가 이전 정수보다 클 때마다 행을 출력하십시오 .

규칙

  • 입력은 음이 아닌 정수의 배열입니다.
  • 출력은 단어 가 더 큰 줄 Excelsior(대소 문자는 중요 함) !과 현재 더 큰 숫자의 현재 런 길이 만큼 줄로 구성됩니다 . 문자열 배열을 반환 할 수도 있습니다.
  • 입력 및 출력 형식은 사이트 규칙에 따라 유연하므로 언어 ​​형식에 맞게 자유롭게 조정하십시오. 줄 끝에 공백을 추가하거나 필요한 경우 텍스트 뒤 또는 앞에 줄을 추가 할 수도 있습니다.

Input             Output
-----------------------------------
[3,2,1,0,5]       Excelsior!      // Excelsior because 5 > 0

[1,2,3,4,5]       Excelsior!      // Excelsior because 2 > 1
                  Excelsior!!     // Excelsior because 3 > 2 (run length: 2)
                  Excelsior!!!    // Excelsior because 4 > 3 (run length: 3)
                  Excelsior!!!!   // Excelsior because 5 > 4 (run length: 4)

[]                <Nothing>

[42]              <Nothing>

[1,2,1,3,4,1,5]   Excelsior!      // Excelsior because 2 > 1
                  Excelsior!      // Excelsior because 3 > 1
                  Excelsior!!     // Excelsior because 4 > 3 (run length: 2)
                  Excelsior!      // Excelsior because 5 > 1

[3,3,3,3,4,3]     Excelsior!      // Excelsior because 4 > 3

이것은 이므로 각 언어마다 가장 짧은 코드가 이길 수 있습니다!


ouflak은 정수가 1 자리라고 가정합니다. 괜찮습니다
ASCII 전용

1
@ASCII 전용은 아닙니다. LUA에 제한이 있는지 모르겠지만, 그렇지 않은 경우 ouflak은 길이의 정수를 구문 분석해야합니다.
Charlie

@Charlie Lua는 모르지만 장황하지만 예를 들어 공백으로 구분 된 입력을 취하고 이와 같이 나눌 있습니다.
케빈 크루이 ssen

보고 있어요 트릭은 두 시나리오를 모두 처리 할 수있는 것입니다.
ouflak

C 또는 Javascript와 같은 FWIW 언어는 어쨌든 정밀도 (9/16 자리) 내의 정수만 처리합니다.
user202729

답변:


9

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

a=>a.map(c=>a<(a=c)?`Excelsior${s+='!'}
`:s='').join``

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

댓글

a =>                           // a[] = input array, also used to store the previous value
  a.map(c =>                   // for each value c in a[]:
    a <                        //   compare the previous value
    (a = c)                    //   with the current one; update a to c
                               //   this test is always falsy on the 1st iteration
    ?                          //   if a is less than c:
      `Excelsior${s += '!'}\n` //     add a '!' to s and yield 'Excelsior' + s + linefeed
    :                          //   else:
      s = ''                   //     reset s to an empty string and yield an empty string
  ).join``                     // end of map(); join everything

이전 값을 저장하기 위해 a []를 재사용하는 것이 안전한 이유

가능한 세 가지 경우가 있습니다.

  • 경우 a[ ] 비어의 콜백 함수는 .map()전혀 호출되지 않고, 우리는 단지 빈 문자열을 산출, 빈 상태 (empty)의 배열이.
  • 경우 a[ ] 정확히 하나의 원소를 포함 x , 이는 제 (독특한) 시험 중 해당 요소에 강제된다 a < (a = c). 그래서 우리는 x<x 테스트하고 있습니다. 빈 문자열을 포함하는 배열을 가져 와서 빈 문자열을 다시 생성합니다.
  • 경우 [는 ] 여러 요소를 포함하는, 그것은로 강제되어 제 시험 중에 . 따라서 결과는 거짓이며 실행되는 것은 s 를 빈 문자열로 초기화 하는 것입니다. 우리가 원하는 것입니다. 첫 번째 의미있는 비교는 두 번째 반복에서 발생합니다.a[ ]NaNa < (a = c)s


5

05AB1E , 26 24 23 바이트

ü‹γvyOE.•1Š¥èò²•™N'!׫,

@Kroppeb 덕분에 -2 바이트 .

온라인으로 시도 하거나 모든 테스트 사례를 확인하십시오 .

설명:

ü                        # Loop over the (implicit) input as pairs
                        #  And check for each pair [a,b] if a<b is truthy
                         #   i.e. [1,2,1,3,4,1,5,7,20,25,3,17]
                         #   → [1,0,1,1,0,1,1,1,1,0,1]
  γ                      # Split it into chunks of equal elements
                         #  i.e. [1,0,1,1,0,1,1,1,1,0,1]
                         #   → [[1],[0],[1,1],[0],[1,1,1,1],[0],[1]]
   vy                    # Foreach `y` over them
     O                   #  Take the sum of that inner list
                         #   i.e. [1,1,1,1] → 4
                         #   i.e. [0] → 0
      E                  #  Inner loop `N` in the range [1, length]:
       .•1Š¥èò²•         #   Push string "excelsior"
                        #   Titlecase it: "Excelsior"
                 N'!׫  '#   Append `N` amount of "!"
                         #    i.e. N=3 → "Excelsior!!!"
                      ,  #   Output with a trailing newline

이 05AB1E 광산의 팁을 참조하십시오 (섹션 압축 문자열 사전의 일부에 어떻게? ) 이유를 이해하는 .•1Š¥èò²•것입니다 "excelsior".


2
정말 05AB1E 모르지만 당신은이 교환 수 0KgO?
Kroppeb

@ Kroppeb Ah, 완전히 그것을 놓쳤다. 그러나 그렇다, 나는 정말로 할 수있다. 감사! :)
Kevin Cruijssen 10


4

자바 8 118 113 바이트

n->{String e="";for(int i=0;i<n.length-1;)System.out.print(""==(n[i+1]>n[i++]?e+="!":(e=""))?e:"Excelsior"+e+"\n");}

읽기 쉬운 :

private static void lee(int num[]) {
    String exclamation = "";
    for (int i = 0; i < num.length - 1;) {
        exclamation = num[i + 1] > num[i++] ? exclamation += "!" : "";
        System.out.print("".equals(exclamation) ? "" : "Excelsior" + exclamation + "\n");
    }
}

2
다음은 10 바이트를 절약 할 수있는 골프 n->{var e="";for(int i=0;i<n.length-1;System.out.print(""==e?e:"Excelsior"+e+"\n"))e=n[i++]<n[i]?e+="!":"";}입니다. 온라인으로 시도하십시오 ( 108 바이트 ). (자바 10+)
Kevin Cruijssen

@KevinCruijssen 감사합니다!
CoderCroc

2
n->{for(int e=0,i=0;i<n.length-1;)if(n[i++]<n[i])System.out.println("Excelsior"+"!".repeat(e++));else e=0;}( 107 bytes )
Olivier Grégoire

내 문제 해결 : 인쇄 할 것이 하나 이상 있도록하는 ++e대신 . e++!
Olivier Grégoire

1
@KevinCruijssen 골프에 작은 오타가있어 1 바이트를 얻는 e=...?e+"!":대신 : 대신 e=...?e+="!":.
Olivier Grégoire


4

05AB1E , 20 19 바이트

ü‹0¡€ƶ˜ε'!×”¸Îsiorÿ

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

설명

ü‹                    # pair-wise comparison, less-than
  0¡                  # split at zeroes
    €ƶ                # lift each, multiplying by its 1-based index
      ˜               # flatten
       ε              # apply to each
        '!×           # repeat "!" that many times
                  ÿ   # and interpolate it at the end of
           ”¸Îsior    # the compressed word "Excel" followed by the string "sior"

4

C (gcc / clang), 106 99 97 바이트

f(a,n)int*a;{int r=0,s[n];for(memset(s,33,n);n-->1;)r*=*a<*++a&&printf("Excelsior%.*s\n",++r,s);}

골프 2 바이트 용 gastropner 덕분 입니다.

여기에서 온라인으로 사용해보십시오 .

언 골프 드 :

f(a, n) // function taking a pointer to the first integer and the length of the array
  int *a; { // a is of type pointer to int, n is of type int

    int r = 0, // length of the current run
        i = 0, // loop variable
        s[n];  // buffer for exclamation marks; we will never need more than n-1 of those (we are declaring an array of int, but really we will treat it as an array of char)

    for(memset(s, 33, n); // fill the buffer with n exclamation marks (ASCII code 33)
        n -- > 1; ) // loop over the array

        r *= *a < *(++ a) // if the current element is less than the next:
             && printf("Excelsior%.*s\n", // print (on their own line) "Excelsior", followed by ...
                       ++ r, // ... r (incremented) of the ...
                       s) // ... n exclamation marks in the buffer s
             ; // else r is reset to 0

}

나는 해결책을 만들기 시작했지만 결국 당신과 너무 가까워서 별도의 답변으로 내 것을 게시하는 것은 약간 어리석은 느낌이었습니다. 여전히 몇 가지 차이점이 있으므로 몇 바이트를 절약 할
gastropner

@gastropner 버전을 공유해 주셔서 감사합니다. 나는 당신의 개선 사항을 통합하고 99 바이트까지 골프를 쳤다. 빈 배열을 처리 할 필요가없는 경우에만 루프 스타일을 사용하여 97 바이트가 됩니다.
OOBalance

4

apt -R, 25 22 바이트

ò¨ ËÅ£`Ex­lÐâ`ú'!Y+A
c

시도 해봐

Kamil 덕분에 3 바이트 절약

ò¨                      :Partition at items that are greater than or equal to the previous item
   Ë                    :Map
    Å                   :  Slice off the first element
     £                  :  Map each element at 0-based index Y
      `Ex­lÐâ`           :    Compressed string "Excelsior"
             ú'!        :    Right pad with exclamation marks
                Y+A     :     To length Y+10
c                       :Flatten
                        :Implicitly join with newlines & output


-R플래그가 실제로 필요하지 않습니다, 도전은 출력을 문자열 배열을 할 수 말한다.
카밀 드라 카리

감사합니다, @KamilDrakari. slice첫 번째 패스를 사용하여 솔루션을 시도했지만 너무 오래 작동하면 해산했습니다. 지금 다시 돌아와서, 당신의 프롬프트와 함께, 나는 그것을 22로 낮추었 기 때문에 그것에 붙어 있어야한다고 생각합니다.
Shaggy


3

자바 8, 106 바이트

n->{String s="",z=s;for(int i=0;i<n.length-1;)z+=n[i++]<n[i]?"Excelsior"+(s+="!")+"\n":(s="")+s;return z;}

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

( s... 이의 재 할당 )


당신은 대체하여 골프 두 개 더 바이트 수 (s="")+s=>(s="")
OOBalance

1
n->{String s="",z=s;for(int i=0;i<n.length-1;)z+=n[i++]>=n[i]?s="":"Excelsior"+(s+="!")+"\n";return z;}( 103 바이트 ) s=""를 여분의 바이트로 이동하십시오 .
Olivier Grégoire



3

젤리 , 16 바이트

<Ɲṣ0ÄẎ”!ẋ“Ø6ḥ»;Ɱ

문자 목록을 생성하는 모나 딕 링크.

온라인으로 사용해보십시오!(바닥 글은 줄 바꿈과 결합합니다)

어떻게?

<Ɲṣ0ÄẎ”!ẋ“Ø6ḥ»;Ɱ - Link: list of integers     e.g. [1,1,4,2,1,1,3,4]
 Ɲ               - for each pair of integers:      [1,1] [1,4] [4,2] [2,1] [1,1] [1,3] [3,4]
<                -   less than?                    [  0,    1,    0,    0,    0,    1,    1]
  ṣ0             - split at zeros                  [[],    [1],     [],   [],      [1,    1]]
    Ä            - cumulative sums                 [[],    [1],     [],   [],      [1,    2]]
     Ẏ           - tighten                         [1,1,2]
      ”!         - literal '!' character           '!'
        ẋ        - repeat (vectorises)             [['!'],['!'],['!','!']]
         “Ø6ḥ»   - dictionary lookup               ['E','x','c','e','l','s','i','o','r']
               Ɱ - map with:
              ;  -   concatenate                   [['E','x','c','e','l','s','i','o','r','!'],['E','x','c','e','l','s','i','o','r','!'],['E','x','c','e','l','s','i','o','r','!','!']]


3

apt , 22 바이트

ò¨ ®£`Ex­lÐâ`+'!pYÃÅÃc

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

간단한 예와 함께 설명 :

ò¨                       :Split whenever the sequence does not increase
                           e.g. [2,1,1,3] -> [[2],[1],[1,3]]
   ®               Ã     :For each sub-array:
    £            Ã       :  For each item in that sub-array:
     `Ex­lÐâ`             :    Compressed "Excelsior"
            +            :    Concat with
             '!pY        :    a number of "!" equal to the index
                               e.g. [1,3] -> ["Excelsior","Excelsior!"]
                  Å      :  Remove the first item of each sub-array
                            e.g. [[Excelsior],[Excelsior],[Excelsior,Excelsior!]]->[[],[],[Excelsior!]]
                    c    :Flatten
                           e.g. [[],[],[Excelsior!]] -> [Excelsior!]

3

파워 쉘, 69 바이트

$args|%{if($o-ne$e-and$_-gt$o){'Excelsior'+'!'*++$c}else{$c=0}$o=$_}

덜 골프 테스트 스크립트 :

$f = {

$args|%{
    if($old-ne$empty-and$_-gt$old){
        'Excelsior'+'!'*++$c
    }else{
        $c=0
    }
    $old=$_
}

}

@(
    ,( (3,2,1,0,5),  'Excelsior!')      # Excelsior because 5 > 0

    ,( (1,2,3,4,5),  'Excelsior!',      # Excelsior because 2 > 1
                    'Excelsior!!',     # Excelsior because 3 > 2 (run length: 2)
                    'Excelsior!!!',    # Excelsior because 4 > 3 (run length: 3)
                    'Excelsior!!!!')   # Excelsior because 5 > 4 (run length: 4)

    ,( $null,         '')                # <Nothing>

    ,( (42),          '')                # <Nothing>

    ,( (1,2,1,3,4,1,5), 'Excelsior!',      # Excelsior because 2 > 1
                        'Excelsior!',      # Excelsior because 3 > 1
                        'Excelsior!!',     # Excelsior because 4 > 3 (run length: 2)
                        'Excelsior!')      # Excelsior because 5 > 1

    ,( (3,3,3,3,4,3),   'Excelsior!')      # Excelsior because 4 > 3
) | % {
    $a,$expected = $_
    $result = &$f @a
    "$result"-eq"$expected"
    $result
}

산출:

True
Excelsior!
True
Excelsior!
Excelsior!!
Excelsior!!!
Excelsior!!!!
True
True
True
Excelsior!
Excelsior!
Excelsior!!
Excelsior!
True
Excelsior!

1
거기에, 나는 지연 포인터를 작동 시키려고했지만 어떻게 생각하지 못했습니다.
Veskah

3

PowerShell , 87 85 바이트

param($n)for(;++$i-lt$n.count){if($n[$i]-gt$n[$i-1]){"Excelsior"+"!"*++$c}else{$c=0}}

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

아마도 그 안에는 구조 조정이 숨어있을 것입니다. 인덱스와을 만드는 데 ol ' "인스턴스화되지 않은 변수 기본값은 0"트릭을 사용합니다 !.


2

망막 , 55 바이트

\d+
*
L$rv`(_*,(?<!(?(1)\1|\2,)))+(_+)\b
Excelsior$#1*!

온라인으로 사용해보십시오! 링크에는 테스트 사례가 포함됩니다. 설명:

\d+
*

단항으로 변환합니다.

rv`(_*,(?<!(?(1)\1|\2,)))+(_+)\b

일치하는 항목은 왼쪽에서 오른쪽으로 나열 되더라도 겹치는 일치 항목은 오른쪽에서 왼쪽으로 처리하십시오. 즉, 런의 모든 숫자를 일치시킬 수 있으며 일치는 런의 시작으로 확장됩니다. 각 일치는 추가 일치 숫자가 이전에 일치 한 추가 숫자보다 작아야하거나 추가 숫자가 아직 일치하지 않으면 첫 번째 숫자보다 작아야합니다.

L$...
Excelsior$#1*!

각 경기에 대해 Excelsior원하는만큼 런에 추가 숫자의 수를 출력 합니다.


2

Pyth, 32 바이트

j+L"Excelsior"*L\!fT.u*hN<0Y.+Q0

여기 에서 온라인으로 시도 하거나 모든 테스트 사례를 한 번에 확인 하십시오 .

j+L"Excelsior"*L\!fT.u*hN<0Y.+Q0   Implicit: Q=eval(input())
                            .+Q    Get forward difference between consecutive elements of Q
                    .u         0   Reduce the above, returning all steps, with current value N starting at 0, next element as Y, using:
                       hN            N+1
                      *              Multiplied by
                         <0Y         1 if 0<Y, 0 otherwise
                  fT               Filter to remove 0s
              *L\!                 Repeat "!" each element number of times
 +L"Excelsior"                     Prepend "Excelsior" to each
j                                  Join on newlines, implicit print


2

루아 , 88 87 83 82 96 95 113 바이트

원래 질문의 정신을 고수하는 업데이트에 대해 @Kevin Cruijssen에게 감사드립니다.

s=io.read()n=9 e="Excelsior!"f=e
for c in s.gmatch(s,"%S+")do if n<c+0then print(e)e=e..'!'else e=f end n=c+0 end

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


1
죄송하지만 규칙에 따라 느낌표를 인쇄해야합니다 (현재 숫자가 증가하는 현재 길이의 길이 당 하나의 느낌표).
Charlie

문제 없어요. 다른 사람이 무언가를 보지 않으면 내가 할 수있는 한 많이했다고 생각하십시오.
ouflak

1
Lua를 잘 모르지만 다음은 코드에 대한 수정 사항이므로 모든 테스트 사례를 올바르게 실행합니다. 현재 "!" 숫자가 이전 숫자보다 높을 때마다 더 많지만 그렇지 않은 경우 다시 1로 재설정하지 않습니다. 더 많은 골프를 쳤을 수도 있지만, 루아에서 골프를 본 적이 없기 때문에 마이너 골프만으로 골프를 고치는 데 집중했습니다. 추신 : 아니 입력을 가정하는 것은 항상 한 자리가 있는지 경우 .. 올
케빈 Cruijssen

2
@Charlie는 챌린지 설명 아래의 주석에서 여러 자리 숫자를 입력으로 사용할 수 있어야한다고 언급 했으므로 공백으로 구분 된 입력을 사용하여 분할하여 가능한 수정 사항 입니다.
케빈 크루이 ssen

Kevin Cruijssen 수정 사항이 OP의 기대치와 더 일치한다고 결정했습니다. 감사!
ouflak

2

C ++ 14 (g ++), 123118 바이트

[](auto a){for(int n=0,i=0;++i<a.size();)a[i]>a[i-1]?puts(&("Excelsior"+std::string(++n,33))[0]):n=0;}

다행히도 std::string를 반복하는 생성자가 char있습니다. 여기에서 온라인으로 사용해보십시오 .

5 바이트를 절약 한 gastropner 덕분 입니다.

언 골프 드 :

[] (auto a) { // void lambda taking a std::array of integer

    for(int n = 0, // length of the current run
        i = 0; // loop variable
        ++ i < a.size(); ) // start with the second element and loop to the last
        a[i] > a[i - 1] // if the current element is greater than the previous ...
        ? puts( // ... print a new line:
               &("Excelsior" + // "Excelsior, followed by ...
                std::string(++ n, 33)) // ... the appropriate number of exclamation marks (33 is ASCII code for '!'); increment the run length
               [0]) // puts() takes a C string
        : n = 0; // else reset run length

}


2

C # (.NET 코어) , 115 (107) 105 바이트

a=>{var b="";for(int i=0;++i<a.Length;)if(a[i]>a[i-1])Console.WriteLine("Excelsior"+(b+="!"));else b="";}

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

-8 바이트 : b int 카운터에서 "!"를 포함하는 문자열로 변경되었습니다 .
-2 바이트 : 인라인 함수로 설정 b+="!" ( Zac Faragher 덕분에 )

액션 델리게이트 를 사용 하여 입력을 가져오고 리턴 할 필요가 없습니다.

언 골프 드 :

a => {
    var b = "";                         // initialize the '!' string (b)
    for(int i = 0; ++i < a.Length;)     // from index 1 until the end of a
        if(a[i] > a[i - 1])                 // if the current index is greater than the previous index
            Console.WriteLine("Excelsior" +     // on a new line, print "Excelsior"
                                    (b += "!"));    // add a "!" to b, and print the string
        else                                // if the current index is not greater than the previous index
            b = "";                             // reset b
}

1
b+="!"Excelsior를 사용 하여 인라인을 만들어 2 바이트를 절약 할 수 if(a[i]>a[i-1])Console.WriteLine("Excelsior"+(b+="!")); 있습니다. 온라인에서 사용해보십시오!
Zac Faragher



1

자바, 113 바이트

String i="";for(int a=0;a<s.length-1;a++){if(s[a+1]>s[a]){i+="!";System.out.println("Excelsior"+i);}else{i="";}}

1

VBA, 114 바이트

For i=0 To UBound(a)-LBound(a)-1 If a(i+1)>a(i)Then s=s&"!" Debug.Print("Excelsior"&s&"") Else s="" End If Next i

불행히도이 변수는 명시 적으로 정의 된 변수가 있어야하므로 올바른 솔루션이 아닙니다 a. 즉, 함수를 subroutine입력을 예상 유형 배열의 변형으로 사용하는 함수로 정의하면 접근 방식을 유효한 솔루션으로 바꿀 수 있습니다. 같을 것이다 그 접근 방식의 Golfed 버전 sub f(x) For i=0To UBound(x)-1 If x(i+1)>x(i)Then s=s+"!":Debug.?"Excelsior"s:Else s="" Next End Sub코드 블록 사이의 휴식은 새로운 라인을 대표
테일러 스콧

1

파이썬 3, 87 바이트

c='!'
for i in range(1,len(n)):
    if n[i]>n[i-1]:print('Excelsior'+c);c+='!'
    else:c='!'

또는 다음과 같은 경우 97

c='!';n=input()
for i in range(1,len(n)):
    if n[i]>n[i-1]:print('Excelsior'+c);c+='!'
    else:c='!'

이것은 입력이 다음과 같은 형식으로 가정합니다.

32105
12345
<null input>
1
1213415
333343

1
첫 번째 프로그램은 사전 정의 된 변수를 통해 입력되므로 유효하지 않습니다. 두 번째 숫자는 여러 자릿수를 가진 숫자를 구별 할 수 없으므로 평가됩니다. 왜 파이썬 2를 사용 하거나 대신 함수로 바꾸지 않습니까?
조 왕

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