[Question]
  [
Your task is to generate the nth term of the RATS sequence, where n is the input. The RATS sequence is also known as the Reverse Add Then Sort sequence. This sequence can also be found here: <http://oeis.org/A004000>.
test cases:
```
0 > 1
1 > 2
2 > 4
3 > 8
4 > 16
5 > 77
6 > 145
7 > 668
```
For example, the output for 5 is 77 because 16 + 61 = 77. After this the 77 is sorted.
Shortest submission wins. This is my first challenge so i hope this is not a duplicate or something.
  
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 11 ~~12~~ bytes
```
1i"tVPU+VSU
```
Input is a *string* (with single quotes) representing an integer in *unary*. String input is allowed by the challenge, and unary [is a valid format](https://codegolf.meta.stackexchange.com/a/5344/36398).
[**Try it online!**](http://matl.tryitonline.net/#code=MWkidFZQVStWU1U&input=JzExMTExMTEn)
### Explanation
```
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    
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
Code:
```
$FDR+{
```
Explanation:
```
$       # 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
```
This also works with a **0 byte** program.
[Answer]
## Pyth, ~~17~~ ~~13~~ 12 bytes
```
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
```
[Try it on the online interpreter](https://pyth.herokuapp.com/?code=uS%60%2BvGv_GQ%5C1&input=7&debug=0).
[Answer]
## CJam, 15 bytes
```
1ri{_sW%i+s$i}*
```
[Test it here.](http://cjam.aditsu.net/#code=1ri%7B_sW%25i%2Bs%24i%7D*&input=10)
### Explanation
```
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.
}*
```
[Answer]
# Python 2, 72
```
f=lambda x,n=1:x and f(x-1,int(''.join(sorted(`n+int(`n`[::-1])`))))or n
```
Recursive function, makes use of the Python 2 shorthand for `__repr__`, which will break once the function reaches very large values (an `L` will be appended to the number's string), I'm not certain from the spec if there is a place where we can stop, but if not changing to `str()` only adds 6 bytes, but then it becomes slightly shorter to output as a string, at 75 bytes:
```
f=lambda x,n='1':x and f(x-1,''.join(sorted(str(int(n)+int(n[::-1])))))or n
```
1 byte saved thanks to trichoplax on this version
[Answer]
# JavaScript ES6, 70 bytes
*Saved 1 byte thanks to @user81655*
```
f=n=>n?+[...+[...''+(b=f(n-1))].reverse().join``+b+''].sort().join``:1
```
*sigh* JavaScript is really verbose. A **lot** (> 50%) of the code is just case to string + array function + join + cast to int. I've tried reduce, eval, and all sorts of stuff but this seems to be the shortest.
[Try it online](http://vihanserver.tk/p/esfiddle/?code=f%3Dn%3D%3En%3F%2B%5B...''%2B((b%3Df(n-1))%2B%20%2B%5B...''%2Bb%5D.reverse().join%60%60)%5D.sort().join%60%60%3A1%0A%0Af(7)) (All browsers work)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 19 bytes
```
0,1 .|-1=:0&Rr+R=o.
```
### Explanation
```
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.
```
[Answer]
## Haskell, 67 bytes
```
import Data.List
g i=i:g(sort$show$read i+read(reverse i))
(g"1"!!)
```
Usage example: `(g"1"!!) 7`-> `"668"`.
It's a direct implementation of the definition: starting with `"1"`, repeatedly append the reverse-add-sort result of the current element. The main function `(g"1"!!)` picks the `i`th element.
[Answer]
# Julia, 77 bytes
```
n->(x=1;for _=1:n x=(p=parse)(join(sort(["$(x+p(reverse("$x")))"...])))end;x)
```
This is a lambda function that accepts an integer and returns an integer. To call it, assign it to a variable.
Ungolfed:
```
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
```
[Answer]
# Jelly, ~~13~~ 12 bytes
I'm sure this can probably be golfed, as this is my first answer in Jelly/in a tacit language.
```
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
```
EDIT: Saved 1 byte, thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)
[Answer]
# [Perl 6](http://perl6.org), 40 bytes
```
{(1,{[~] ($_+.flip).comb.sort}...*)[$_]} # 40
```
( If you want it to return an Int put a `+` right before `[~]` )
### Usage:
```
# 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)
```
[Answer]
## Java 1.8, 251 bytes
```
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);}}
```
### Expanded
```
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);
}
}
```
[Answer]
## Seriously, 17 bytes
```
1,`;$R≈+$S≈`n
```
[Try it online!](http://seriously.tryitonline.net/#code=MSxgOyRS4omIKyRT4omIYG4&input=NQ)
Explanation:
```
1,`;$R≈+$S≈`n
1              push 1
 ,`       `n   do the following n times:
   ;$R≈        reverse
       +       add
        $S≈    sort
    
```
[Answer]
# Lua, ~~179~~ 156 Bytes
~~I can't see how I could golf it more, but I'm sure there's a way.~~ Thanks to @LeakyNun I took the time to come down on this and golf it the proper way, I could maybe still win some bytes by using another approach.
```
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)
```
### Ungolfed and explanations
```
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)
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) 2, 11 bytes, language postdates challenge
```
;1{↔;?+o}ⁱ⁽
```
[Try it online!](https://tio.run/nexus/brachylog2#@29tWP2obYq1vXZ@7aPGjY8a9/7/b/4/CgA "Brachylog – TIO Nexus")
## Explanation
```
;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
```
I'm not quite clear on what this does with zero digits, but the question doesn't state any particular handling, and they probably don't appear in the sequence anyway.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
!¡ödOdS+↔1
```
[Try it online!](https://tio.run/##yygtzv7/X/HQwsPbUvxTgrUftU0x/P//vwUA "Husk – Try It Online")
1-indexed.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~70~~ 66 bytes
```
f=lambda n,a=1:n<1or int(''.join(sorted(`f(n-1)+f(n-1,-1)`))[::a])
```
[Try it online!](https://tio.run/##HYxBDoIwEEX3nmLChplYiGXZiBcxJIyBQolMSe3GEM5eqqv/Fu/97RtnL01Ktn3z@hoYRHGrjdy1D@AkYlnWi3eCHx/iOGBvUSpN1/@oTD3R0xjuKNlfkRsILNOI@kbmAlvIJ1DsB1QP2I@iztbKEZ0Ci44onQ "Python 2 – Try It Online")
[Answer]
## ES6, 79 bytes
```
n=>eval("r=1;while(n--)r=+[...+[...r+''].reverse().join``+r+''].sort().join``")
```
82 bytes without `eval`:
```
n=>[...Array(n)].reduce(r=>+[...+[...r+''].reverse().join``+r+''].sort().join``,1)
```
All those conversions are painful.
@edc65 I actually saved 4 bytes by switching from `map` to `reduce` this time... no doubt you'll prove me wrong again though.
[Answer]
## Python 2, 91 Bytes
Input as Integer, result is printed to the screen.
```
def f(n):
 t=1
 for i in range(n):t=int("".join(sorted(str(int(str(t)[::-1])+t))))
 print t
```
This could be a lot shorter with some recursion magic I guess, but I cant wrap my head around it yet. Gonna have a fresh look later and hopefully improve this one.
[Answer]
## Python 2, 83 bytes
```
def f(n):
 v='1'
 for _ in v*n:v=''.join(sorted(str(int(v)+int(v[::-1]))))
 print v
```
[Answer]
# Mathematica 10.3, ~~66~~ 61 bytes
```
Nest[FromDigits@Sort@IntegerDigits[#+IntegerReverse@#]&,1,#]&
```
Quite simple.
[Answer]
# PHP, 102 Bytes
```
$r=[1];$i++<$argn;sort($v),$r[]=join($v))$v=str_split(bcadd(strrev($e=end($r)),$e));echo$r[$argn];
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/3ce999f7aa824bbe12ccfe4421222922a3f64698)
## PHP, 95 Bytes
n <= 39
```
for($r=[1];$i++<$argn;sort($v),$r[]=join($v))$v=str_split(strrev($e=end($r))+$e);echo$r[$argn];
```
[Answer]
# [Java](http://openjdk.java.net/), ~~171~~ ~~167~~ ~~163~~ 160 bytes
```
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;}
```
[Try it online!](https://tio.run/nexus/java-openjdk#JZDPioMwEMbP61OEQiHZGFdPBdPYJ9hTj5LDGLUEbBSN2yzis7uT7WU@mG/@/GamtRmsIWaAZSHfYN12WOdJT2N0bIsCylX5radOFKzM06CKPG1qrVz3IujXQadGQdqqXPbjTKWpcmm@VGCtaj8DN@fwnweuWgnoQfSaGs5Bc/5ugWuQRmGOcy0EbjPYKASUhsm58@vsSGQwZSH3Y3ozLx48ys9oW/JEcnr3s3WPWsP8WNiWfMTJkd8imL2qi7ScM3L/XXz3zMbVZxPW@8FRy0@kIiceD4o/oCzDBzAmkz3Zjz8 "Java (OpenJDK 8) – TIO Nexus")
Not the longest entry! \o/
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 20 bytes
```
{x{.o@<o:$x+.|$x}/1}
```
[Try it online!](https://tio.run/##y9bNz/7/P82quqJaL9/BJt9KpUJbr0alolbfsPZ/mrqixX8A "K (oK) – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 56 bytes
```
Stream.iterate("1"){p=>p.toInt+p.reverse.toInt+""sorted}
```
[Try it online!](https://tio.run/##LcwxCsMgFAbgPaf4cVIKkhzAQMcOnXoCa57Ukj5FHyEQcnbboeO3fC341ff8fFMQ3H1i0C7ES8O1FBwDsPkVEQ79IZX8xyah6oW0mpQ5ipuLlXxjuRRbaaPa6G@lWq5Cy9kBPUIyptHYmH9JeGmGm1FqYllZR83GmOHsXw "Scala – Try It Online")
An infinite stream.
[Answer]
# [cQuents](https://github.com/stestoltz/cQuents), 9 bytes
```
=1:sZ+\rZ
```
[Try it online!](https://tio.run/##Sy4sTc0rKf7/39bQqjhKO6Yo6v9/AA "cQuents – Try It Online")
1-indexed.
## Explanation
```
=1            first term is 1
  :           sequence mode
              each term equals
   s                           sort(                                   )
    Z                                previous
     +                                        plus
      \r                                           reverse(          )
        Z                                                   previous
```
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, 51 bytes
```
$.=join'',sort(($.+reverse$.)=~/./g)while$_--;say$.
```
[Try it online!](https://tio.run/##K0gtyjH9/19FzzYrPzNPXV2nOL@oRENDRU@7KLUstag4VUVP07ZOX08/XbM8IzMnVSVeV9e6OLFSRe//f/N/@QUlmfl5xf91fU31DAwN/usm5gAA "Perl 5 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~7~~ 5 bytes
```
1?(ms
```
[Try it Online!](http://lyxal.pythonanywhere.com?s=?flags=&code=1?(ms&inputs=7&header=&footer=)
## Explained
```
1?(ms
1?          # Push 1 followed by the input
  (         # for n in range(0, input):
    m       #   push tos + tos[::-1] (palindromize on integers doesn't make it a palindrome)
     +s     #   add and sort the result
```
It's a shame how in order to remain competitive, one has to port other answers. Why do I say this? Because I have a nifty 21 byte function that accomplishes the same task:
```
@f:1|0=[1|n⨪@f;:ŉ+]s;
```
Example usage:
```
6 @f; , # Single number
0 11 r °f; z # Provide a test case unit kinda display
```
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~91~~ ~~89~~ ~~87~~ 76 bytes
```
$ofs=''
for($c="1";$args[0]--){$c="$("$(+$c+"$($c[20..0])")"|% t*y|sort)"}$c
```
[Try it online!](https://tio.run/##JcvNCoMwEATgu08hYVtNJRK1f1LyJOKhLIk9CCkboRT12VO7wvANDMzbfyyFlx1HhZ5sBGfmCN4Fk2WJ85QDGlGJBzxpCJ3ulZLzf4J8SwFYbAXY1bosdS@FFMshnU7fJXiapFgB45ocwaWardiabdgze2Gv7I29s@3@2s9NG38 "PowerShell Core – Try It Online")
PowerShell converts strings to `long` by default. The maximum length would always be 19 chars.
Cool challenge!
-2 bytes thanks to Mazzy!
[Answer]
# Axiom, 146 bytes
```
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)))
```
test and results [RATS sequence]
```
(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]]
```
]