숫자를 확장


11

숫자를 확장

다음과 같은 방법으로 0보다 큰 정수를 확장해야합니다.

숫자를 10 진수로 나누고 각 숫자에 대해 다음 규칙에 따라 목록을 생성하십시오.

  • 숫자가 홀수 인 경우 목록은 숫자로 시작하여 1로 내려갑니다.
  • 숫자가 짝수이면 목록은 숫자로 시작하여 9까지 올라갑니다.
  • 숫자가 0이면 목록이 비어 있습니다.

숫자 아래의 홀수 목록과 짝수의 홀수 목록을 기록하십시오. 그런 다음 열을 상단 정렬하고 각 행의 숫자를 수집하여 정수를 만듭니다. 마지막 단계로 숫자를 더하여 숫자의 확장을 찾으십시오.

34607에 적용된 위 규칙의 예는 다음과 같습니다.

 9          
 8          
 79         
 68         
 57         
346 7 ->  399 7 -> 3997 -> 9418
2   6     288 6    2886
1   5     177 5    1775
    4      66 4     664
    3      5  3      53
    2      4  2      42 
    1         1       1

테스트 사례는 다음과 같습니다.

1: 1
2: 44
3: 6
44: 429
217: 1270
911: 947
2345: 26114
20067: 3450
34875632: 70664504
9348765347634763: 18406119382875401

이것은 이므로 각 언어에서 가장 짧은 바이트 단위의 대답이 이깁니다.


1
입력을 문자열로 할 수 있습니까? 아니면 숫자의 배열로?
Arnauld

@Arnauld 정수 여야하며 프로그램 / 기능을 사용하여 숫자로 나누려면
Galen Ivanov

@GalenIvanov 그러나 입력이 stdin에서 나온다면 괜찮습니다 (기술적으로 문자열이더라도).
Adám

@ Adám 예, 기술적으로는 문자열이므로 괜찮습니다.
Galen Ivanov

그리고 나는 이것이 이와 같은 확장이라고 생각했습니다 .
엔지니어 토스트

답변:


8

젤리 , 13 바이트

Dḟ0RrḂ?€9UZḌS

양의 정수를 가져오고 리턴하는 모나드 링크.

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

어떻게?

Dḟ0RrḂ?€9UZḌS - Link: positive integer           e.g. 702
D             - cast to a decimal list                [7,0,2]
  0           - literal zero                          0
 ḟ            - filter discard                        [7,2]
        9     - literal nine
       €      - for each:
      ?       -   if:
     Ḃ        -   ...condition: bit (modulo by 2)      1              ,0
   R          -   ...then: range ([1,...n])            [1,2,3,4,5,6,7],n/a
    r         -   ...else: inclusive range ([n,...9])  n/a            ,[2,3,4,5,6,7,8,9]
         U    - upend                                 [[7,6,5,4,3,2,1],[9,8,7,6,5,4,3,2]]
          Z   - transpose                             [[7,9],[6,8],[5,7],[4,6],[3,5],[2,4],[1,3],2]
           Ḍ  - cast from decimal lists               [79,68,57,46,35,24,13,2]
            S - sum                                   324

4

펄 6 ,  68  66 바이트

{sum roundrobin(.comb».&{$_%2??($_...1)!!(9...+$_) if +$_})».join}

시도 해봐

{sum roundrobin(.comb».&{[R,] $_%2??1..$_!!$_..9 if +$_})».join}

시도 해봐

넓히는:

{  # bare block lambda with implicit parameter 「$_」

  sum

    roundrobin( # grab from the sub lists in a round robin fashion

      .comb\             # split the input into digits
      ».&{               # for each digit do this

        [R,]             # reduce with reversed &infix:«,» (shorter than reverse)

              $_ % 2     # is the digit not divisible by 2?
          ??  1  .. $_   # from 1 to the digit
          !!  $_ ..  9   # from the digit to 9

        if +$_           # only do the above if the current digit isn't 0
                         # (has the effect of removing 0 from the list)
     }

    )».join     # join each of the sub-lists from roundrobin
}

3

APL (Dyalog) , 39 바이트

전체 프로그램 본문. STDIN에서 입력하라는 메시지를 표시합니다. 결과를 STDOUT에 인쇄합니다.

+/10⊥¨0~⍨¨↓⍉↑{2|⍵:⌽⍳⍵⋄×⍵:⌽⍵,⍵↓⍳9⋄⍬}¨⍎¨⍞

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

올바르게 마지막 테스트 케이스를 표시 ⎕FR( F loating 점 R의 epresentation)를 128 비트 십진수로 설정되었다 ⎕PP( P RINT P 34 자리 recision)이었다 세트.

 STDIN에서 텍스트 입력을위한 프롬프트

⍎¨ 각 실행 (각 숫자를 숫자로 표시)

{ 각 요소에 대해 인수가 표시되는 다음 함수를 적용하십시오 .

2|⍵: 홀수 인 경우 (2로 나눈 나머지 "if"나누기) :

   역

  1에서 until까지  의 ntnters

   논쟁 거리

 그밖에

×⍵: 인수가 긍정 인 경우 (lit. "if"signum) :

   역

   논쟁 거리

  , 뒤에

   논의

   요소에서 떨어졌다

  ⍳91에서 9까지  의 nt ntegers

 그밖에

   빈 목록

 이 목록을 단일 행렬로 혼합 (결합)하여 오른쪽에 0을 채 웁니다.

 바꾸어 놓다

 이 행렬을 목록의 목록으로 나누십시오

0~⍨¨ 각 목록에서 0을 모두 제거하십시오.

10⊥¨ 각각 10 진수를 일반 숫자로 변환합니다 (숫자 수집)

+/ 숫자를 합하다


2
설명해 주셔서 감사합니다. APL 코드 골프 비디오에서 당신을 본 후 코드 골프를 발견했다는 것을 알려드립니다.
Galen Ivanov

3

자바 스크립트 (ES6), 88 83 82 바이트

f=(n,k=0)=>k<9&&+[...n+''].map(x=>+x&&(x=x&1?x:9-k<x||9)>k?x-k:'').join``+f(n,k+1)

노트

9 - k < x || 9바이트를 저장 9 - k >= x && 9하지만 불평등이 확인되면 1대신 생성 됩니다 0. 1 > k외부 삼항에서 잘못된 경로를 유발하여 문제가 발생했을 수 있습니다. 그러나 그 의미 k = 0하기 때문에 9 - k = 9우리는 아마도 가질 수 있도록 9 - k < x같은 시간에.

테스트 사례

NB : JS 숫자 정밀도를 초과하는 마지막 테스트 사례를 제거했습니다.



3

자바 11 210 209 191 181 바이트

n->{long r=0;var a="0".repeat(9).split("");for(int d:(n+"").getBytes())for(int k=0,x=d-48,y=9;x>0&(k<1||(d%2<1?y-->x:x-->1));a[k++]+=d%2<1?y:x);for(var q:a)r+=new Long(q);return r;}

좋아, 이것은 꽤 오래 걸렸습니다 (주로 처음에 실수를했기 때문에 내가 잘못한 것을 더 잘 이해하기 위해 각 단계를 작성해야했습니다). 골프를 더 많이 할 수 있습니다.

@ceilingcat 덕분에 -18 바이트 .

설명:

여기에서 시도하십시오.

n->{                             // Method with long as both parameter and return-type
  long r=0;                      //  Result-long `r`, starting at 0
  var a="0".repeat(9).split(""); //  String array `a`, filled with nine String zeroes
  for(int d:(n+"").getBytes())   //  Cast the input to a String,
                                 //   and loop over its codepoints as integers:
    for(int k=0,                 //   Row-index `k`, starting at
        x=d-48,                  //   Temp integer `x`, set to the current digit
        y=9                      //   Temp integer `y`, set to 9
        ;                        //   Inner loop, if:
         x>0                     //     The current digit is not a 0,
          &(k<1                  //     and if this is the first iteration,
             ||(d%2<1?           //     or if the digit is even:
                 y-->x           //      And `y` is larger than the digit
                                 //      (and afterwards decrease `y` by 1 with `y--`)
                :                //     or if the digit is odd:
                 x-->1));        //      And `x` is larger than 1
                                 //      (and afterwards decrease `x` by 1 with `x--`)
      a[k++]+=                   //    Append the current row with:
                                 //    (and afterwards increase `k` by 1 with `k++`)
       d%2<1?                    //     If the digit is even:
        y                        //      Append the row with `y`
       :                         //     Else (the digit is odd):
        x);                      //      Append the row with `x`
  for(var q:a)                   //  Loop over the String rows in the array:
    r+=new Long(q);              //   Convert it to a long, and add it to the result-sum
  return r;}                     //  Return the result

2

, 28 바이트

J_MS(RV{a?a%2?\,aa,tl}Ma)ZDx

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

설명

                      Ma      Map this function to the digits of the 1st cmdline arg:
        a?                     If digit != 0:
          a%2?                  If digit is odd:
              \,a                Inclusive-range(digit)
                 a,t            Else (digit is even), range from digit to 10 (exclusive)
                    l          Else (digit is 0), empty list
     RV{             }         Apply reverse to the result before returning it
                              This gives us a list of lists like [9 8 7 6] or [3 2 1]
    (                   )ZDx  Zip, with a default value of empty string
J_MS                          Use map-sum to join each sublist and sum the results
                              Autoprint (implicit)

단계 34607가 인수로 진행되는 방법 :

34607
[[1 2 3] [4 5 6 7 8 9] [6 7 8 9] [] [1 2 3 4 5 6 7]]
[[3 2 1] [9 8 7 6 5 4] [9 8 7 6] [] [7 6 5 4 3 2 1]]
[[3 9 9 "" 7] [2 8 8 "" 6] [1 7 7 "" 5] ["" 6 6 "" 4] ["" 5 "" "" 3] ["" 4 "" "" 2] ["" "" "" "" 1]]
[3997 2886 1775 664 53 42 1]
9418



2

R , 153146 바이트

function(n,m=n%/%10^(nchar(n):0)%%10)sum(strtoi(apply(sapply(m[m>0],function(x)c(r<-"if"(x%%2,x:1,9:x),rep("",9-sum(r|1)))),1,paste,collapse="")))

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

때로는 골프 를 타다 가 쓰레기인지 R이 ... .

당신은 대체 할 수 strtoias.double취득하는 18406718084351604(잘못이다) 마지막 테스트 케이스에 대한; R에는 32 비트 정수만 있습니다.


n을 정수로 사용하고 트릭 중 하나를 사용하여 숫자로 변환하면 비트를 절약 할 수 있습니다! 146 바이트
user2390246

@ user2390246 당신이 알고, 내가 그 시도,하지만 난에 대한 암시 적 변환 사용에 대한 집착이라고 생각 character->int내가 전화했을 때를 :다음 사용 strtoi어쨌든!
주세페



1

05AB1E , 16 바이트

0KεDÈi9ŸëL]íõζJO

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

또는 대안으로 :

0KεDÈ8*>Ÿ{R}õζJO
0Kε9Ÿ¬L‚yèR}õζJO

설명:

0K        # Remove all 0s from the (implicit) input-integer
  ε       #  Map each digit to:
   D      #   Duplicate the digit
    Èi    #   If it's even:
      9Ÿ  #    Pop and push a list in the range [digit, 9]
     ë    #   Else (the digit is odd):
      L   #    Pop and push a list in the range [1, digit]
  ]       # Close both the if-else statement and map
   í      # Reverse each inner ranged list
     ζ    # Zip/transpose, swapping rows and columns,
    õ     # with an empty string as filler
      J   # Join each inner list together
       O  # And sum that list
          # (after which the result is output implicitly)

1

해 학적 인 , 39 바이트

riXX:nz{J2dv{{9r@}{ro}}che!<-}m[tp)im++

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

ri      #Read as int
XX      #Return list of digits
:nz     #Filter for non-zero
{
 J2dv   #Divisible by 2?
 {
  {9r@} #Range a, 9
  {ro}  #Range 1, a
 }che!  #Run based on if divisible
 <-     #Reverse the range
}m[     #Apply to each digit
tp      #Transpose digits
)im     #Join each list into single int
++      #Sum each int
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.