나의 Ada 어레이 골프


10

배경

에이다 (Ada) 는 간결한 것으로 잘 알려져 있지 않은 프로그래밍 언어입니다.

그러나 배열 리터럴 구문은 이론적으로 상당히 간결한 배열 스펙을 허용 할 수 있습니다. 다음은 배열 리터럴 구문에 대한 간단한 EBNF 설명입니다 ( bottlecaps.de로 전달 가능) .

array ::= positional_array | named_array
positional_array ::= expression ',' expression (',' expression)*
                   | expression (',' expression)* ',' 'others' '=>' expression
named_array ::= component_association (',' component_association)*
component_association ::= discrete_choice_list '=>' expression
discrete_choice_list ::= discrete_choice ('|' discrete_choice)*
discrete_choice ::= expression ('..' expression)? | 'others'

단순성을 위해 정수의 1 차원 배열로 제한합니다. 이는 표현식 값에 정수만 사용한다는 것을 의미합니다. 아마도 미래의 도전에서 우리는 변수와 다차원 배열 선언과 같은 더 진보 된 것을 시도 할 수있을 것입니다. 정수 리터럴을 사용할 필요가 없습니다 .

다음은 Ada 배열 리터럴의 예와 명확성을 위해 파이썬과 동등한 표현입니다.

(1, 2, 3) = [1, 2, 3]
(1, others => 2) = [1, 2, 2, ..., 2]
(others => 1) = [1, 1, ..., 1]
(1 => 1, 2 => 3) = [1, 3]
(1|2 => 1, 3 => 2) = [1, 1, 2]
(1 => 1, 3 => 2, others => 3) = [1, 3, 2, 3, 3, ..., 3]

도전

이 과제의 목표는 주어진 입력 배열에 대해 가장 짧은 바이트 수의 Ada 배열 리터럴을 출력하는 것입니다. Ada 배열은 원하는 인덱스에서 시작할 수 있으므로 각 값이 순차적 인 한 시작 인덱스를 원하는 것을 선택할 수 있습니다. 이 예에서 나는 1에서 시작하기로 선택했는데, 이것은 Ada에 대한 관용적이지만 다른 정수에서 시작하도록 선택할 수 있습니다.

입력

입력은 편리한 형태의 정수 목록으로 구성됩니다.

산출

출력은 입력 정수 목록을 나타내는 가장 짧은 유효한 Ada 배열 리터럴을 나타내는 텍스트 문자열입니다. 이 배열에서 원하는 시작 색인을 사용할 수 있지만, 선택에 상관없이 선택 사항을 지정해야합니다 (시작 색인은 동적 일 수도 있음).

정수는 예제와 같이 부호있는 10 진수로 표시됩니다. 이 과제는 정수 값의 골프를 다루지 않습니다.

여기 몇 가지 예가 있어요.

Simple: [1, 2, 3] -> (1,2,3)
Range: [1, 1, 1, 1, 1, 1, 1,] -> (1..7=>1)
Others: [1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1] -> (6=>2,others=>1)
Multiple Ranges: [1,1,1,1,1,2,2,2,2,2,1,1,1,1,1,2,2,2,2,2,1,1,1,1,1] -> (6..10|16..20=>2,others=>1)
Tiny Ranges: [1,1,2,2,1,1,1,1,1] -> (3|4=>2,others=>1)
Far Range: [[1]*5, [2]*100, [3]*5] -> (1..5=>1,6..105=>2,others=>3)
Alternation: [1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2] -> (1|3|5|7|9|11|13|15|17=>1,others=>2)
Big Number: [1234567890,1,1234567890] -> (2=>1,1|3=>1234567890)
Big-ish Number: [1234567,1,1234567] -> (1234567,1,1234567)
Solo: [-1] -> (1=>-1)
Huge Input: [[0],[1]*1000000000] -> (0,others=>1)
Positional Others: [1, 2, 3, 3, 3, 3, 3, 3] -> (1,2,others=>3)
Range and Choice, no Others: [1,1,1,12,12,3,3,3,3,3,3,3,3,3,3,4] -> (1..3=>1,4|5=>12,6..15=>3,16=>4)

최소한의 필요 조건

  • 최소 100 개의 숫자와 최소 256 개의 숫자를 지원합니다.

  • 이러한 모든 입력에 대해 올바른 결과를 생성하십시오

    • 마지막에 '다른 사람들'을 두는 것을 포함
    • 단일 항목 배열에 대한 인덱스를 포함
  • 1 분 안에 위의 각 입력에 대해 종료하십시오 (TIO에서 선호).

바이트 단위의 최단 솔루션이 승리합니다!

참조 구현

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

이 구현은 입력을 배열로 사용하며 각 문자는 숫자입니다. 대문자는 큰 값을 나타내는 특수 상수입니다. 프로그램 인수는 사용할 '시작 색인'입니다.

TIO 링크의 "코드"섹션은 문제에 대한 올바른 솔루션이며 "헤더"및 "풋터"는 테스트 구조를 구현합니다.


3
"Far Range"사례는 단순히 우리 일반 배열뿐만 아니라 해당 입력 형식을 처리 할 수 ​​있어야 한다는 것을 선택 하거나 강조 표시 할 때 해당 형식으로 입력을받을 수 있음을 나타 내기 위해 존재 합니까? 또한 마지막 테스트 사례가 출력되지 않아야 합니까? (-1)
얽히고 설킨 Shaggy

3
"Far Range"의 경우 공간을 절약하기 위해 작성되었으며 실제 입력은 110 개의 정수로 구성된 평면 배열이지만 출력은 정확합니다. 이 키워드의 목적은 'others'키워드가 더 긴 표현의 짧은 범위에 있어야하는 경우를 보여주기위한 것입니다. ( 106..110=>3,others=>2문법이 허용하지 않는 한, 마지막 경우는 인덱스를 가질 필요가 더 이상 것) 단일 요소의 위치 배열 ( positional_array ::= expression ',' expression (',' expression)*)
LambdaBeta

1
1(1=>1,others=>1)(1..100000000=>1)

2
(1|3=>1234567,2=>1)대한 또 다른 유효한 출력인지 확인 [1234567,1,1234567]하시겠습니까?
Arnauld

1
Ada를 선택한 언어로 사용할 수 있습니까?
Benjamin Urquhart

답변:


5

자바 스크립트 (ES6),  (307)  304 바이트

@KevinCruijssen 덕분에 2 바이트 절약

이것은 당황스럽게 길다 ...

a=>[b=([...a,m=''].map(o=(v,i)=>(i?p==v?!++n:m=o[(o[p]=[o[p]&&o[p]+'|']+(n?i-n+(n>1?'..':'|')+i:i))[m.length]?(x=i-n,j=p):j]:1)&&(p=v,M=n=0)),Object.keys(o).map(k=>j-k|!m[6]?o[k]+'=>'+k:O,O='others=>'+j).sort()),1/a[1]?[...a]:b,j-a.pop()?b:a.slice(0,x-1)+[,O]].map(a=>M=M[(s=`(${a})`).length]||!M?s:M)&&M

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


복제 된에 대한 변수를 작성하여 305 바이트 (-2)'others=>' .
케빈 Cruijssen

@KevinCruijssen 감사합니다! (NB : 버전에서는 t정의되기 전에 사용됩니다. 충돌하지 않는 이유는 처음 두 테스트 사례가 전혀 사용하지 않기 때문에 비용없이 쉽게 수정할 수 있습니다.)
Arnauld

그래. 나는 어디에서 무엇이 사용되었는지 알기 위해 당신의 대답을 풀지 않았습니다. 나는 단순히 'others'두 번이나 출력을 변경하지 않고 변수를 만들려고 한다는 것을 알았습니다 . ;) 그래도 설명해 주셔서 감사합니다 [,O]. 를 사용하여 쉼표의 멋진 골프입니다 . :)
Kevin Cruijssen '

2

05AB1E , 136 (134) 132 바이트

"',ý'(ì')«ˆ"©.V"θ…ˆ†=>쪮.V"Uγ¨D€gPi˜IX.V}\ÙεQƶ0KDāαγ€g£}D2Fε¾iεнyg≠iyθyg<i'|ë„..}ý}}ë˜}'|ý„=>«Iyнн<è«}Ю.VgFDN._ć'>¡X.V}\¼}¯éIgi¦}н

편집 : 모든 테스트 사례에 대해 수정되었습니다.

온라인으로 시도 하거나 모든 테스트 사례를 확인하십시오 (너무 큰 'Huge Input'제외).

설명:

"',ý'(ì')«ˆ"       # Push this string (function 1), which does:
 ',ý              '#  Join a list by ","
    '(ì           '#  Prepend a "("
       ')«        '#  Append a ")"
          ˆ        #  Pop and add it to the global array
            ©      # Store this string in the register (without popping)
             .V    # And execute it as 05AB1E code on the (implicit) input-list
"θ…ˆ†=>쪮.V"      # Push this string (function 2), which does:
 θ                 #  Pop and push the last element of the list
  …ˆ†=>ì           #  Prepend dictionary string "others=>"
        ª          #  Append that to the list which is at the top of the stack
         ®.V       #  And execute function 1 from the register     
             U     # Pop and store this string in variable `X`
γ                  # Get the chunks of equal elements in the (implicit) input-list
 ¨                 # Remove the last chunk
  D                # Duplicate the list of remaining chunks
   g              # Get the length of each
     Pi     }      # If all chunk-lengths are 1:
       ˜           #  Flatten the list of remaining chunks
        I          #  Push the input-list
         X.V       #  Execute function 2 from variable `X`
             \     # Discard the top of the stack (in case we didn't enter the if-statement)
Ù                  # Uniquify the (implicit) input-list
 ε                 # Map each unique value `y` to:
  Q                #  Check for each value in the (implicit) input-list if it's equal to `y`
                   #  (1 if truthy; 0 if falsey)
   ƶ               #  Multiply each by its 1-based index
    0K             #  Remove all 0s
      D            #  Duplicate it
       ā           #  Push a list [1, length] without popping the list itself
        α          #  Get the absolute difference at the same indices
         γ         #  Split it into chunks of the same values
          g       #  Get the length of each
            £      #  And split the duplicated indices-list into those parts
                   # (this map basically groups 1-based indices per value.
                   #  i.e. input [1,1,2,1,1,2,2,1,1] becomes [[[1,2],[4,5],[8,9]],[[3],[6,7]]])
 }D                # After the map: duplicate the mapped 3D list
   2F              # Loop 2 times:
     ε             #  Map the 3D list of indices to:
      ¾i           #   If the counter_variable is 1:
        ε          #    Map each list `y` in the 2D inner list to:
         н         #     Leave the first value
         ygi      #     And if there is more than one index:
             yθ    #      Push the last value as well
             yg<i  #      If there are exactly two indices:
              '|  '#       Push string "|"
             ë     #      Else (there are more than two indices)
              „..  #       Push string ".."
                 #      And join the first and last value by this string
        }}         #    Close the if-statement and map
      ë            #   Else:
       ˜           #    Flatten the 2D list
      }'|ý        '#   After the if-else: join by "|"
          „=>«     #   Append "=>"
       yнн         #   Get the very first index of this 2D list
          <        #   Decrease it by 1 to make it 0-based
      I    è       #   And index it into the input-list to get its value again
            «      #   Which is also appended after the "=>"
                 #  After the map: triplicate the result
       ®.V         #  Execute function 1 from the register
       g           #  Get the amount of items in the triplicated list
        F          #  Loop that many times:
         D         #   Duplicate the list
          N._      #   Rotate it the index amount of times
          ć        #   Extract the head; pop and push remainder and head
           '>¡    '#   Split this head by ">"
              X.V  #   And then function 2 is executed again from variable `X`
        }\         #  After the loop: discard the list that is still on the stack
          ¼        #  And increase the counter_variable by 1
                 # After looping twice: push the global array
     é             # Sort it by length
      Igi }        # If the input only contained a single item:
         ¦         #  Remove the very first item
           н       # And then only leave the first item
                   # (which is output implicitly as result)

이 05AB1E 광산의 팁을 참조하십시오 (섹션 압축 문자열 사전의 일부에 어떻게? ) 이유를 이해하는 …ˆ†=>것입니다 "others=>".

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