RTA(Reverse-Then-Add)数値のルート


22

逆引き加算(RTA)シーケンスは、その逆に数値を追加し、その結果に対してプロセスを繰り返すことによって取得されるシーケンスです。たとえば、

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

したがって、5のRTAシーケンスには、10、11、22、44、88、176などが含まれます。

数値のRTAルートは、RTAシーケンスでに等しいか、またはを上げる最小の数値です。n nnnn

たとえば、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

Perl 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の省略記号の構文は、出くわすたびに魔法のようになります。そのラムダベースのシーケンス仕様は、とてもきちんとしたアイデアです!
スンダ

@sundar、その構文は実際に私がPerl 6に来た主な理由の1つです(そして、しばらくして、それが私の最も好きな言語になった理由)
Ramillies

7

Brachylog24 22バイト

{~{ℕ≤.&≜↔;?+}{|↰₁}|}ᶠ⌋
  • 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
{|↰₁}そこの使用はシンプルですが素晴らしいです。よくできました!
スンダ

5

Haskell59 57バイト

user1472751のおかげで2バイト(untillist-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れます。

また別には、このすべてをラッピングuntilしてオフに開始する1として1加える(+1)最初のRTAルートを見つけます。

の適切なRTAルートが存在しない場合、n最終的に関数が適用されないn場所に到達しuntilますn<=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ますか?編集:ああ、私£ソースコードで何かを見ます。どこで使用されますか?
ケビンクルーッセン

1
@KevinCruijssenはい、これらは再帰的環境で使用されるフラグです。j基本的に、入力値がシーケンス内にあるかどうかを確認します。シーケンスの£最初のn個の値を返すようにします(と同じλ<...>}¹£)。
アドナン

3

ゼリー12 11バイト

ṚḌ+ƊС€œi¹Ḣ

9991111

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操作で生成できない数に到達するまでRTA操作を繰り返し「元に戻す」再帰関数。その後、最小値を返します。

filter長いを使用する代わりにmap、1から数値までの範囲を単純に超えます。この範囲の各mについて、m + rev(m)が数値の場合、mに対して関数を再帰的に呼び出します。そうでない場合は、nを返します。これにより、aが不要にfilterなり、f(n)= nの基本ケースが無料で提供されます。

ハイライトには、次を使用したバイトの保存が含まれますInteger#digits

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

最後のものは1バイト短くなりますが、悲しいことに、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

JavaScript(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

05AB1E21 16 15 バイト

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

@Emignaのおかげで-1バイト。

オンラインでお試しください。

説明:

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

暗黙的な印刷のため、印刷は必要ありません。
エミグナ

1

、33バイト

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

オンラインでお試しください!リンクは、コードの詳細バージョンです。説明:

Nθ

q

≔⊗θη

2qh

W›ηθ«

h>q

≔L⊞Oυωη

uh

W‹ηθ

h<q

≧⁺I⮌Iηη

hh

»ILυ

u


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) しました。オンラインで試してみてください。
スンダ

1

Java 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;}

オンラインでお試しください!

入力が与えられるとiiを含むシーケンスのために0から0 までの整数をすべてチェックしますi

  • i 入力値です
  • o 出力値(これまでに見つかった最小ルート)
  • a チェックされている現在の整数
  • baはのシーケンスの現在の要素です
  • cそしてその逆dに追加するbために使用されます

でコンパイルする-DL=forと、2バイト節約できます。

スクラッチ; 数学を間違えています。

ただし、をi=o;使用すると、出力値を返すことができ-O0、5バイト節約できます。

1

Japt16 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?


弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.