숫자의 RTA (Reverse-Then-Add) 근


22

RTA (reverse-then-add) 시퀀스는 숫자를 역방향에 추가하고 결과에 대해 프로세스를 반복하여 얻은 시퀀스입니다. 예를 들어

5+5=1010+01=1111+11=2222+22=44 ...

따라서, 5의 RTA 서열은 10, 11, 22, 44, 88, 176 등을 포함한다.

RTA 루트 다수의 하나 같다 최소 개수 N 이상으로 인상을 준다 N 의 RTA 시퀀스이다.nnn

예를 들어 44는 5, 10, 11, 13, 22, 31 등의 RTA 시퀀스에서 발견됩니다.이 중 5는 가장 작으므로 RTAroot (44) = 5입니다.

72는 숫자의 RTA 시퀀스의 일부가 아니므로 자체 RTA 루트로 간주됩니다.

입력 은 언어가 자연스럽게 처리 할 수있는 범위의 양의 정수입니다.

출력 은 위에서 정의한대로 주어진 숫자의 RTA 루트입니다.

테스트 사례

Input
Output

44
5

72
72

132
3

143
49

1111
1

999
999

관련 OEIS : A067031 . 출력은이 시퀀스의 숫자입니다.

답변:


13

펄 6 , 45 44 바이트

->\a{first {a∈($_,{$_+.flip}...*>a)},1..a}

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

설명:

->\a{                                    }  # Anonymous code block
->\a     # That takes a number a
     first  # Find the first element
                                     1..a  # In the range 1 to a
           {                       },    # Where
            a       # a is an element of
              (             ...   )  # A sequence defined by
               $_,  # The first element is the number we're checking
                  {$_+.flip}  # Each element is the previous element plus its reverse
                               *>$a  # The last element is larger than a

5
Perl 6 줄임표 구문은 내가 올 때마다 더 마술 적입니다. 람다 기반 시퀀스 사양은 정말 깔끔한 아이디어입니다!
모니카

나는 펄 6. (왜, 잠시 후, 그것은되었다 내 가장 좋아하는 언어)에 온 이유 @sundar, 그 구문은 실제로 주된 이유 중 하나였다
Ramillies

7

Brachylog , 24 22 바이트

{~{ℕ≤.&≜↔;?+}{|↰₁}|}ᶠ⌋
  • 내가 가지고 있음을 인식하는 sundar 덕분에 2 바이트 {{}}

설명

                --  f(n):
                --      g(x):
 {              --          h(y):
  ~             --              get z where k(z) = y
   {            --              k(z):
    ℕ≤.         --                  z>=0 and z<=k(z) (constrain so it doesn't keep looking)
    &≜          --                  label input (avoiding infinite stuff)
      ↔;?+      --                  return z+reverse(z)
   }            --
    {           --                  
     |↰₁        --              return z and h(z) (as in returning either)
    }           --                  
  |             --          return h(x) or x (as in returning either)
 }              --
ᶠ               --      get all possible answers for g(n)
  ⌋             --      return smallest of them

기발한 설명에 대해 죄송합니다. 이것은 내가 생각해 낼 수있는 최선입니다.

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


1
의 사용 {|↰₁}이 간단하지만 훌륭합니다. 잘 했어!
sundar-복원 모니카

5

하스켈 , 59 57 바이트

-2 덕분 바이트 user1472751을 (제를 사용until list-comprehension & 대신 사용 head)!

f n=until((n==).until(>=n)((+)<*>read.reverse.show))(+1)1

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

설명

이것은 평가할 것이다 True 모든 RTA 루트 대해 .

(n==) . until (n<=) ((+)<*>read.reverse.show)

용어 (+)<*>read.reverse.show 는 골프 버전입니다

\r-> r + read (reverse $ show r)

역수를 추가합니다.

이 기능은 until반복적으로 적용됩니다(+)<*>read.reverse.show목표를 초과 할 때까지 .

이 모든 것을 또 다른 것으로 감싸고 1 until부터 시작 1하여(+1) 하면 첫 번째 RTA 루트가 발견됩니다.

의 적절한 RTA- 루트가 없으면 n결국 부터 함수를 적용하지 않는 n위치에 도달합니다 .untiln<=n


1
until외부 루프에도 사용하여 2 바이트를 절약 할 수 있습니다 . TIO
user1472751

5

05AB1E , 7 바이트

새 버전의 05AB1E 사용 (Elixir로 다시 작성)

암호

L.ΔλjÂ+

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

설명

L           # Create the list [1, ..., input]
 .Δ         # Iterate over each value and return the first value that returns a truthy value for:
   λ        #   Where the base case is the current value, compute the following sequence:
     Â+     #   Pop a(n - 1) and bifurcate (duplicate and reverse duplicate) and sum them up.
            #   This gives us: a(0) = value, a(n) = a(n - 1) + reversed(a(n - 1))
    j       #   A λ-generator with the 'j' flag, which pops a value (in this case the input)
            #   and check whether the value exists in the sequence. Since these sequences will be 
            #   infinitely long, this will only work strictly non-decreasing lists.

잠깐만 .. j재귀 환경에서 특별한 의미가 있습니까? 나는 재귀 환경 내에서 의 통과 와 그 λ자체 에 대해서만 알았습니다 . 그 밖에 더 j있나요? 편집 : 아, 나는 소스 코드£ 에서도 뭔가를 본다 . 어디에 사용됩니까?
Kevin Cruijssen

1
@KevinCruijssen 예, 재귀 환경에서 사용되는 플래그입니다. j기본적으로 입력 값이 순서에 있는지 확인합니다. 시퀀스 £의 처음 n 값을 반환하는지 확인하십시오 (와 동일 λ<...>}¹£).
Adnan

3

젤리 , 12 11 바이트

ṚḌ+ƊС€œi¹Ḣ

9991111 이 TIO에서 시간 종료되었습니다.

1 바이트를 골프로 해준 @JonathanAllan에게 감사합니다!

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

작동 원리

ṚḌ+ƊС€œi¹Ḣ  Main link. Argument: n

      €      Map the link to the left over [1, ..., n].
    С         For each k, call the link to the left n times. Return the array of k
               and the link's n return values.
   Ɗ           Combine the three links to the left into a monadic link. Argument: j
Ṛ                Promote j to its digit array and reverse it.
 Ḍ               Undecimal; convert the resulting digit array to integer.
  +              Add the result to j.
       œi¹   Find the first multindimensional index of n.
          Ḣ  Head; extract the first coordinate.

3

루비, 66 57 바이트

f=->n{(1..n).map{|m|m+(m.digits*'').to_i==n ?f[m]:n}.min}

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

생성 할 수없는 수에 도달 할 때까지 RTA 작업을 반복적으로 "실행 취소"하는 재귀 함수는 최소값을 반환합니다.

filter긴 을 사용 하는 대신 간단히 map1에서 숫자까지의 범위를 넘어서는 것입니다. 이 범위의 각 m 에 대해 m + rev (m) 이 숫자이면 m에서 재귀 적으로 함수를 호출합니다 . 그렇지 않으면 n 을 반환합니다 . 이것은 a의 필요성을 제거하고 f (n) = nfilter 의 기본 사례를 제공합니다. 무료 를 제공합니다.

하이라이트는 다음을 사용하여 바이트 저장을 포함합니다 Integer#digits.

m.to_s.reverse.to_i
(m.digits*'').to_i
eval(m.digits*'')

마지막은 바이트가 짧지 만 안타깝게도 Ruby는 08 진수로 시작하는 숫자를 구문 분석합니다 .



2

Pyth , 12 바이트

fqQ.W<HQ+s_`

테스트 스위트를 확인하십시오!

놀랍도록 빠르고 효율적입니다. 모든 테스트 사례는 한 번에 2 초 미만으로 실행되었습니다.

작동 원리

fqQ.W<HQ+s_` – Full program. Q is the variable that represents the input.
f            – Find the first positive integer T that satisfies a function.
   .W        – Functional while. This is an operator that takes two functions A(H)
               and B(Z) and while A(H) is truthy, H = B(Z). Initial value T.
     <HQ     – First function, A(H) – Condition: H is strictly less than Q.
        +s_` – Second function, B(Z) – Modifier.
         s_` – Reverse the string representation of Z and treat it as an integer.
        +    – Add it to Z.
             – It should be noted that .W, functional while, returns the ending
               value only. In other words ".W<HQ+s_`" can be interpreted as
               "Starting with T, while the current value is less than Q, add it
               to its reverse, and yield the final value after the loop ends".
 qQ          – Check if the result equals Q.

2

05AB1E , 13 바이트

LʒIFDÂ+})Iå}н

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

설명

L               # push range [1 ... input]
 ʒ         }    # filter, keep elements that are true under:
  IF   }        # input times do:
    D           # duplicate
     Â+         # add current number and its reverse
        )       # wrap in a list
         Iå     # check if input is in the list
            н   # get the first (smallest) one

똑똑한! 21 바이트 버전이 이미 너무 길다는 것을 알고 있습니다 (동일한 접근 방식으로 16으로 골프를 쳤습니다).하지만 실제로 더 짧은 방법을 알아낼 수 없었습니다. 나는 필터 후 머리를 사용하는 방법에 대해 생각하지 않은 믿을 수 없어 .. 나는 루프 인덱스 + 1, 또는 사용하려고 보관 global_counter. ...>>
케빈 Cruijssen

2

자바 스크립트 (ES6), 61 바이트

n=>(g=k=>k-n?g(k>n?++x:+[...k+''].reverse().join``+k):x)(x=1)

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

댓글

n =>                        // n = input
  (g = k =>                 // g() = recursive function taking k = current value
    k - n ?                 //   if k is not equal to n:
      g(                    //     do a recursive call:
        k > n ?             //       if k is greater than n:
          ++x               //         increment the RTA root x and restart from there
        :                   //       else (k is less than n):
          +[...k + '']      //         split k into a list of digit characters
          .reverse().join`` //         reverse, join and coerce it back to an integer
          + k               //         add k
      )                     //     end of recursive call
    :                       //   else (k = n):
      x                     //     success: return the RTA root
  )(x = 1)                  // initial call to g() with k = x = 1

2

05AB1E , 21 16 15 바이트

G¼N¹FÂ+йQi¾q]¹

덕분에 -1 바이트 @Emigna .

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

설명:

G               # Loop `N` in the range [1, input):
 ¼              #  Increase the global_counter by 1 first every iteration (0 by default)
 N              #  Push `N` to the stack as starting value for the inner-loop
  ¹F            #  Inner loop an input amount of times
    Â           #   Bifurcate (short for Duplicate & Reverse) the current value
                #    i.e. 10 → 10 and '01'
     +          #   Add them together
                #    i.e. 10 and '01' → 11
      Ð         #   Triplicate that value
                #   (one for the check below; one for the next iteration)
       ¹Qi      #   If it's equal to the input:
          ¾     #    Push the global_counter
           q    #    And terminate the program
                #    (after which the global_counter is implicitly printed to STDOUT)
]               # After all loops, if nothing was output yet:
 ¹              # Output the input

암시 적 인쇄로 인해 인쇄가 필요하지 않습니다.
Emigna

1

, 33 바이트

Nθ≔⊗θηW›ηθ«≔L⊞OυωηW‹ηθ≧⁺I⮌Iηη»ILυ

온라인으로 사용해보십시오! 링크는 자세한 버전의 코드입니다. 설명:

Nθ

입력 .

≔⊗θη

양수인 2h 루프가 시작되도록

W›ηθ«

동안 반복 h>:

≔L⊞Oυωη

더미 null 문자열을 따라서 길이를 늘리고 결과 길이를 h;

W‹ηθ

반복 h<:

≧⁺I⮌Iηη

의 반대를 추가 hh.

»ILυ

최종 길이 인쇄 이것은 원하는 루트입니다.


1

MATL , 17 바이트

`@G:"ttVPU+]vG-}@

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

설명

`         % Do...while loop
  @       %   Push iteration index, k (starting at 1)
  G:"     %   Do as many times as the input
    tt    %     Duplicate twice
    VPU   %     To string, reverse, to number
    +     %     Add
  ]       %   End
  v       %   Concatenate all stack into a column vector. This vector contains
          %   a sufficient number of terms of k's RTA sequence
  G-      %   Subtract input. This is used as loop condition, which is falsy
          %   if some entry is zero, indicating that we have found the input
          %   in k's RTA sequence
}         % Finally (execute on loop exit)
  @       %   Push current k
          % End (implicit). Display (implicit)

1
참고로,이 31 바이트 버전을 사용하여 MATL을 사용하여 테스트 케이스 출력을 생성 :!`tG=~yV2&PU*+tG>~*tXzG=A~]f1) 했습니다. 온라인으로 사용해보십시오!
sundar-복 직원 모니카

1

자바 8, 103 바이트

n->{for(int i=0,j;;)for(j=++i;j<=n;j+=n.valueOf(new StringBuffer(j+"").reverse()+""))if(n==j)return i;}

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

설명:

n->{                // Method with Integer as both parameter and return-type
  for(int i=0,j;;)  //  Infinite loop `i`, starting at 0
    for(j=++i;      //  Increase `i` by 1 first, and then set `j` to this new `i`
        j<=n        //  Inner loop as long as `j` is smaller than or equal to the input
        ;           //    After every iteration:
         j+=        //     Increase `j` by:
            n.valueOf(new StringBuffer(j+"").reverse()+""))
                    //     `j` reversed
     if(n==j)       //   If the input and `j` are equal:
       return i;}   //    Return `i` as result

산술적으로 정수를 뒤집는 것은 1 바이트 더 길다 ( 104 바이트 ) :

n->{for(int i=0,j,t,r;;)for(j=++i;j<=n;){for(t=j,r=0;t>0;t/=10)r=r*10+t%10;if((j+=r)==n|i==n)return i;}}

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


1

C (GCC) , 120 (100) 99 바이트

f(i,o,a,b,c,d){for(a=o=i;b=a;o=i/b?a:o,a--)for(;b<i;b+=c)for(c=0,d=b;d;d/=10)c=c*10+d%10;return o;}

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

입력이 주어지면 i, 모든 정수에서 i0까지의 시퀀스를 점검합니다 i.

  • i 입력 값입니다
  • o 출력 값입니다 (지금까지 찾은 최소 루트)
  • a 검사중인 현재 정수입니다.
  • ba의 시퀀스 의 현재 요소입니다
  • c그리고 d추가하는 데 사용되는 b그 역에

컴파일 -DL=for하면 2 바이트를 절약 할 수 있습니다.

흠집; 수학을 잘못하고 있습니다.

그러나 i=o;를 사용하면 출력 값을 반환하여 -O05 바이트를 절약 할 수 있습니다.

1

Japt , 16 15 11 바이트

@ÇX±swÃøU}a

시도 해봐

@ÇX±swÃøU}a     :Implicit input of integer U
@        }a     :Loop over the positive integers as X & output the first that returns true
 Ç              :  Map the range [0,U)
  X±            :    Increment X by
    sw          :    Its reverse
      Ã         :  End map
       øU       :  Contains U?


0

C (gcc) , 89 바이트

일치 할 때까지 [1, n )의 각 시퀀스를 실행합니다 . 0은 종료되지 않기 때문에 특별한 경우입니다.

j,k,l,m;r(i){for(j=k=0;k-i&&++j<i;)for(k=j;k<i;k+=m)for(l=k,m=0;l;l/=10)m=m*10+l%10;j=j;}

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

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