RATSシーケンス


30

あなたの仕事は、RATSシーケンスのn番目の項を生成することです。ここで、nは入力です。RATSシーケンスは、Reverse Add Then Sortシーケンスとも呼ばれます。このシーケンスは、http//oeis.org/A004000にもあります。

テストケース:

0 > 1
1 > 2
2 > 4
3 > 8
4 > 16
5 > 77
6 > 145
7 > 668

たとえば、16 + 61 = 77であるため、5の出力は77です。この後、77がソートされます。

最短の提出が勝ちです。これは私の最初の挑戦ですので、これが重複や何かではないことを願っています。


入力は整数である必要がありますか、それとも文字列である可能性がありますか?
デンカー

@DenkerAffeは、文字列形式の数字ですか?
justaprogrammer

@justaprogrammerそうだから、整数として123ではなく「123」を取得できます。いくつかのバイトを節約するかもしれません。
デンカー

2
77 + 77 = 154ではありませんか?または私は何かを見逃しましたか?編集:ああ、はい、ソートするのを忘れました。
デンハムクート

6
私はあなたが意味するものだと思う@DenhamCoote「ラットああS、私はソートするために忘れてしまいました!」
マーティンエンダー

回答:


11

MATL、11 12バイト

1i"tVPU+VSU

入力は、単項の整数を表す文字列(単一引用符付き)です。文字列の入力はチャレンジで許可されており、単項は有効な形式です

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

説明

1      % push number 1 to the stack
i      % input. Will be a string of "n" ones 
"      % for loop: repeat n times (consumes string)
  t    %   duplicate
  V    %   convert to string
  P    %   reverse
  U    %   convert to number
  +    %   add
  V    %   convert to string
  S    %   sort
  U    %   convert to number
       % loop is implicitly ended
       % stack content is implicitly displayed    

4
MATLとJellyのどちらがおびえているのかわかりません... +1
Downgoat

9

05AB1E、6バイト

コード:

$FDR+{

説明:

$       # Push 1 and input
 F      # For N in range(0, input)
  D     # Duplicate top of the stack
   R    # Reverse top of the stack
    +   # Add top two items
     {  # Sort top of the stack
        # Implicitly print top of the stack

これは、0バイトのプログラムでも機能します


@Adnan 3日前、実際に。それでも、よく遊んだ...
ドアノブ

@Doorknobジャストインタイムハハ
アドナン

19
ソースコードを削除することで、6バイトを節約できます。
デニス

2
あなたも短縮することができます05AB1E最初の先行ゼロを排除して、省略することにより1として、1E==E。次に、ちょうど5ABE-2バイトを取得します。
フレイ

1
@デニスの素晴らしい観察
アドナン

8

CJam、15バイト

1ri{_sW%i+s$i}*

ここでテストしてください。

説明

1     e# Push 1 as the start of the sequence.
ri    e# Read input and convert to integer N.
{     e# Run this block N times...
  _s  e#   Duplicate and convert to string.
  W%  e#   Reverse string.
  i+  e#   Convert back to integer and add to previous value.
  s$  e#   Convert to string and sort.
  i   e#   Convert back to integer for the next iteration.
}*

3
これらすべての言語をどのように短くすることができますか
ジャスタプログラマー

2
@justaprogrammer組み込み関数の単一文字の名前が役立ちます。;)CJam、Pyth、およびBrachylogはすべて、特にゴルフを念頭に置いて設計されたゴルフ言語です。(en.wikipedia.org/wiki/Code_golf#Dedicated_golfing_languagesを参照してください)それから、APLやJのような言語もあります。これらの言語はまったくゴルフ言語ではありませんが、同様に簡潔です。
マーティンエンダー

このようなチャレンジに勝つために、どれを最もお勧めしますか?
-justaprogrammer

3
@justaprogrammer私はこれらの挑戦に勝っている人に基づいて1つを選びません(それはおそらくPythまたはJellyでしょう)。「通常の」言語でゴルフをするのも同じように楽しいことがあります(特に、その言語でより多くの競争がある可能性があるため)。ゴルフ言語では、おそらくそれを楽しんで使用することがより重要です。CJamは非常に楽しいです-それはあなたが他の言語よりも少しあなたの心を曲げさせるスタックベースであり、同時にそれは非常に強力な言語であり、私はゴルフ以外の単純な使い捨てスクリプトに使用し始めました私の生産性を大きく後押しします。
マーティンエンダー

これらの言語は非常に面白そうで、自分で学ぶのが待ち遠しいです。ゼリーとは何ですか?それはある種のゼラチンか何かですか?
-justaprogrammer

8

Pyth、17 13 12バイト

uS`+vGv_GQ\1
u        Q\1    reduce range(input()) on base case of "1" (string)
   +vG          eval the string (to get a number), and add...
      v_G       the same number, reversed first and then eval'd
 S`             convert back to string and sort

オンライン通訳で試してみてください


4
この魔法とは何ですか?これはどのように作動しますか?
-justaprogrammer

1
@justaprogrammer説明を追加しました。:)
ドアノブ

えー、でもどうやって。このコードをどのようにテストしますか?
-justaprogrammer

1
@justaprogrammerコードを実行できるオンラインインタープリターへのリンクを追加しました。
ドアノブ

これは、まだとても美しい、とても短いです、素晴らしいです
justaprogrammer

5

Python 2、72

f=lambda x,n=1:x and f(x-1,int(''.join(sorted(`n+int(`n`[::-1])`))))or n

再帰関数は、Python 2の略記を使用します__repr__。これは、関数が非常に大きな値に達すると壊れます(L数値の文字列に追加されます)、停止できる場所があるかどうかは仕様からわかりません、ただし、変更しstr()ない場合は6バイトしか追加されませんが、文字列として出力するには75バイトでわずかに短くなります。

f=lambda x,n='1':x and f(x-1,''.join(sorted(str(int(n)+int(n[::-1])))))or n

このバージョンのtrichoplaxのおかげで1バイト節約


それはor2番目のコードブロックの前の余剰スペースですか?
-trichoplax

1
@trichoplaxキャッチに感謝します:)
FryAmTheEggman

5

JavaScript ES6、70バイト

@ user81655のおかげで1バイト節約

f=n=>n?+[...+[...''+(b=f(n-1))].reverse().join``+b+''].sort().join``:1

ため息 JavaScriptは本当に冗長です。コードの多く(> 50%)は、文字列+配列関数+結合+ intにキャストするだけです。削減、評価、あらゆる種類のものを試しましたが、これは最短のようです。

オンラインで試す(すべてのブラウザーが機能します)


2
私と同じですが、より良い(そして以前に投稿されました)。ああ!
edc65

文字列操作はJSはとても長いです、あなたは私の哀
dolの

@ user81655かっこいい、ありがとう!私はそのように再注文することを決して考えなかったでしょう
-Downgoat

f=n=>n?[...+[...b=f(n-1)].reverse().join``+b+''].sort().join``:'1'文字列を返すことが許可されている場合
-l4m2

4

Brachylog、19バイト

0,1 .|-1=:0&Rr+R=o.

説明

0,1 .               § If Input is 0, unify the Output with 1
     |              § Else
      -1=:0&R       § unify R with the output of this main predicate, with input = Input - 1
             r+R=o. § Reverse R, add it to itself and order it, then unify with the Output.

3

Haskell、67バイト

import Data.List
g i=i:g(sort$show$read i+read(reverse i))
(g"1"!!)

使用例:(g"1"!!) 7-> "668"

これは、定義の直接の実装です。で始まり"1"、現在の要素のreverse-add-sort結果を繰り返し追加します。メイン関数(g"1"!!)ith要素を選択します。


これは、70バイト未満の最も読みやすいプログラムです!
ガウラヴアガルワル

3

ジュリア、77バイト

n->(x=1;for _=1:n x=(p=parse)(join(sort(["$(x+p(reverse("$x")))"...])))end;x)

これは、整数を受け入れて整数を返すラムダ関数です。呼び出すには、変数に割り当てます。

ゴルフをしていない:

function f(n::Int)
    # Begin x at 1
    x = 1

    # Repeat this process n times
    for _ = 1:n
        # Add x to itself with reversed digits
        s = x + parse(reverse("$x"))

        # Refine x as this number with the digits sorted
        x = parse(join(sort(["$s"...])))
    end

    # Return x after the process (will be 1 if n was 0)
    return x
end

3

ゼリー、13 12バイト

これは、おそらくゼリー/暗黙の言語での私の最初の回答であるため、おそらくゴルフができると確信しています。

DUḌ+ðDṢḌ Performs RATS
1Ç¡      Loops

D        Converts integer to decimal
 U       Reverses
  Ḍ      Converts back to integer
   +     Adds original and reversed
    ð    Starts new chain
     D   Converts back to decimal
      Ṣ  Sorts
       Ḍ Back to integer again

1        Uses 1 instead of input
 Ḍ       Uses line above
  ¡      For loop

編集:デニスのおかげで1バイトを保存しました


2

Java 1.8、251バイト

interface R{static void main(String[]a){int i,r,n=1,c=0,t=Byte.valueOf(a[0]);while(++c<=t){i=n;for(r=0;i!=0;i/=10){r=r*10+i%10;}n+=r;a[0]=n+"";char[]f=a[0].toCharArray();java.util.Arrays.sort(f);n=Integer.valueOf(new String(f));}System.out.print(n);}}

拡大

interface R{
static void main(String[]args){
    int input,reversed,nextValue=1,count=0,target=Byte.valueOf(args[0]);
    while(++count<=target){
        input=nextValue;
        for(reversed=0;input!=0;input/=10){reversed=reversed*10+input%10;}
        nextValue+=reversed;
        args[0]=nextValue+"";
        char[]sortMe=args[0].toCharArray();
        java.util.Arrays.sort(sortMe);
        nextValue=Integer.valueOf(new String(sortMe));
    }
    System.out.print(nextValue);
}
}

なぜ4バイト短いinterfaceRではなくR を使用するのclassですか?
ウィルシャーウッド

1
@WillSherwoodは、main()のpublic修飾子を省略して全体を短くできるためです:)
Denham Coote


2

Lua、179 156バイト

もっとゴルフできる方法はわかりませんが、方法はあると確信しています。@LeakyNunのおかげで、私はこれに時間をかけて適切な方法でゴルフをしましたが、別のアプローチを使用することで、まだいくつかのバイトを獲得できました。

k=0z=table
for i=0,io.read()do
t={}(""..k+(""..k):reverse()):gsub("%d",function(d)t[#t+1]=d
end)z.sort(t)k=k<1 and 1or tonumber(z.concat(t,""))
end
print(k)

非ゴルフと説明

k=0                                  
z=table                              -- z is a pointer on the table named table
                                     -- it allows me to use its functions
                                     -- while saving 4 bytes/use

for i=0,io.read()                    -- Iterate n times for the nth element
do
  t={}
  (""..a+(""..a):reverse())          -- we add k with its "reversed" value
                                     -- and convert the whole thing to a string
    :gsub(".",function(d)            -- for each character in it, use an anonymous fucntion
       t[#t+1]=d end)                -- which insert them in the array t
  z.sort(t)                          
  a=a<1 and 1 or                     -- if i==0, k=1
     tonumber(z.concat(t,""))        -- else we concat t in a string and convert it to number
end
print(k)

さて、あなたはもうここにいないようです...
リーキー修道女

@LeakyNunさて、私は今回はあまり参加していませんが、それでも時々チャレンジにピークがあります、あなたの答えを見てみますが、それなしでもかなり簡単にゴルフできるものがあります(a=a<1 and 1or例えば)。
-Katenkyo

私たちはあなたが戻ってきてくれてうれしいです-私はうれしいです。
リーキー修道女

2

Brachylog 2、11バイト、言語のポストデートチャレンジ

;1{↔;?+o}ⁱ⁽

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

説明

;1{↔;?+o}ⁱ⁽
  {     }ⁱ  Repeatedly apply the following,
 1            starting at 1,
;         ⁽   a number of times equal to the input:
   ↔            reverse,
    ;?+         add the original input,
       o        then sort the resulting number

私はこれがゼロ桁で何をするのかはっきりしていませんが、質問には特定の処理は記載されておらず、おそらくそれらはシーケンスに表示されません。


1

ES6、79バイト

n=>eval("r=1;while(n--)r=+[...+[...r+''].reverse().join``+r+''].sort().join``")

82バイトなしeval

n=>[...Array(n)].reduce(r=>+[...+[...r+''].reverse().join``+r+''].sort().join``,1)

これらの変換はすべて苦痛です。

@ edc65私は実際mapreduceこの時間に切り替えて4バイトを節約しました。


for短い:n=>eval("for(r=1;n--)r=+[...+[...r+''].reverse().join``+r+''].sort().join``")
Downgoat

@Doᴡɴɢᴏᴀᴛはn=0、構文エラーを修正した後でも動作しません。
ニール

1

Python 2、91バイト

整数として入力すると、結果が画面に出力されます。

def f(n):
 t=1
 for i in range(n):t=int("".join(sorted(str(int(str(t)[::-1])+t))))
 print t

再帰の魔法を使えば、これはもっと短くなるかもしれませんが、まだ頭を包むことはできません。後で見直して、これを改善することを願っています。



1

Perl 6、40バイト

{(1,{[~] ($_+.flip).comb.sort}...*)[$_]} # 40

(Intを返したい場合は、+直前に[~]

使用法:

# give it a lexical name
my &RATS = {…}

say RATS 5; # 77

# This implementation also accepts a list of indexes

# the first 10 of the sequence
say RATS ^10; # (1 2 4 8 16 77 145 668 1345 6677)

1

Mathematicaの10.3、66の 61バイト

Nest[FromDigits@Sort@IntegerDigits[#+IntegerReverse@#]&,1,#]&

とても簡単です。


1

PHP、102バイト

$r=[1];$i++<$argn;sort($v),$r[]=join($v))$v=str_split(bcadd(strrev($e=end($r)),$e));echo$r[$argn];

オンライン版

PHP、95バイト

n <= 39

for($r=[1];$i++<$argn;sort($v),$r[]=join($v))$v=str_split(strrev($e=end($r))+$e);echo$r[$argn];

1

ジャワ171の 167 163 160バイト

int f(int n){int a=n>0?f(n-1):0,x=10,b[]=new int[x],c=a,d=0;for(;c>0;c/=x)d=d*x+c%x;for(a+=d;a>0;a/=x)b[a%x]++;for(;a<x;c=b[a++]-->0?c*x+--a:c);return n>0?c:1;}

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

最長のエントリーではありません!\ o /



それは大丈夫ですf(1)... f(20)しかし、f(21)からは結果が間違っているようです
...-RosLuP

精度の低下だと思います。
リーキー修道女


0

公理、146バイト

c(r:String):NNI==reduce(+,[(ord(r.i)-48)*10^(#r-i) for i in 1..#r]);f(n:INT):NNI==(n<1=>1;v:=f(n-1);v:=v+c(reverse(v::String));c(sort(v::String)))

テストと結果[RATSシーケンス]

(3) -> [[i, f(i)] for i in 0..20]
   (3)
   [[0,1], [1,2], [2,4], [3,8], [4,16], [5,77], [6,145], [7,668], [8,1345],
    [9,6677], [10,13444], [11,55778], [12,133345], [13,666677], [14,1333444],
    [15,5567777], [16,12333445], [17,66666677], [18,133333444], [19,556667777],
    [20,1233334444]]

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