The RATS sequence

30

1

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.

justaprogrammer

Posted 2016-01-31T15:27:49.633

Reputation: 301

Does the input have to be an Integer or could it also be a string? – Denker – 2016-01-31T15:36:26.607

@DenkerAffe do you mean a number in the form of a string? – justaprogrammer – 2016-01-31T15:37:18.823

@justaprogrammer Yea, so I can get "123" instead of 123 as Integer. Would mayve save some bytes. – Denker – 2016-01-31T15:40:19.597

@DenkerAffe sure, if that works best – justaprogrammer – 2016-01-31T15:41:10.957

2isn't 77+77=154? Or have I missed something? EDIT: Oh, yes, I forgot to sort. – Denham Coote – 2016-02-01T10:48:00.113

6@DenhamCoote I think you meant "oh rat*s*, I forgot to sort!" – Martin Ender – 2016-02-02T10:49:26.700

Answers

11

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.

Try it online!

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    

Luis Mendo

Posted 2016-01-31T15:27:49.633

Reputation: 87 464

4I don't know which scares/perplexes me more, MATL or Jelly... +1 – Downgoat – 2016-01-31T19:00:13.970

9

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.

Adnan

Posted 2016-01-31T15:27:49.633

Reputation: 41 965

@Adnan Three days ago, actually. Still, well played...

– Doorknob – 2016-01-31T19:23:41.283

@Doorknob Just in time haha – Adnan – 2016-01-31T19:28:18.743

19You can save 6 bytes by eliminating your source code. – Dennis – 2016-01-31T21:00:55.620

2You can also shorten 05AB1E by first eliminating the leading zero, and then omitting the 1, as 1E==E. Then you get just 5ABE, -2 bytes. – flawr – 2016-01-31T23:49:11.377

1@Dennis great observation – Adnan – 2016-02-01T20:48:58.997

Does this language do the problem by default or something? – djechlin – 2016-02-01T23:39:02.830

@djechlin yes. This language can, without any code, solve this exact problem.. >.> (line 2059: https://github.com/Adriandmen/05AB1E/commit/1c339310d567fce64b307344cf08d396ac71b4ae)

– d0nut – 2016-02-02T01:22:11.953

is @justaprogrammer actually Adnan in disguise? – Denham Coote – 2016-02-02T10:44:33.937

I think he saw that in the sandbox and added the thing – Oliver Ni – 2017-08-11T01:22:00.073

8

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.

Doorknob

Posted 2016-01-31T15:27:49.633

Reputation: 68 138

4What is this magic? How does this work? – justaprogrammer – 2016-01-31T15:42:48.013

1@justaprogrammer I've added an explanation. :) – Doorknob – 2016-01-31T16:00:04.570

Huh, but how. How do you test this code? – justaprogrammer – 2016-01-31T16:02:51.210

1@justaprogrammer I've added a link to an online interpreter that you can run the code on. – Doorknob – 2016-01-31T16:06:45.993

This is awesome, it is so short, yet so beautiful – justaprogrammer – 2016-01-31T16:11:33.293

8

CJam, 15 bytes

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

Test it here.

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.
}*

Martin Ender

Posted 2016-01-31T15:27:49.633

Reputation: 184 808

3how can all these languages be so short – justaprogrammer – 2016-01-31T15:52:05.723

2

@justaprogrammer Single-character names for built-in functions help. ;) CJam, Pyth and Brachylog are all golfing languages, specifically designed with code golf in mind. (See https://en.wikipedia.org/wiki/Code_golf#Dedicated_golfing_languages.) Then there's also languages like APL and J that aren't golfing languages at all but are similarly terse, because the designers thought it would be a good idea.

– Martin Ender – 2016-01-31T15:54:31.000

Which one do you recommend the most for winning challenges like these? – justaprogrammer – 2016-01-31T16:03:35.100

3@justaprogrammer I wouldn't pick one based on which one is winning these challenges (that would likely be Pyth or Jelly). It can be just as fun to golf in a "normal" language (especially because there might be more competition within that language). For a golfing language, it's probably more important that you enjoy using it. CJam is quite fun - it's a stack-based which makes you bend your mind a bit more than other languages, and at the same time it's quite a powerful language, that I've started to use for simple throwaway scripts outside of golf, which is a good boost to my productivity. – Martin Ender – 2016-01-31T16:07:06.477

These languages look very interesting and I can't wait to learn one myself. I don't know what jelly is? Is that some kind of gelatine or something? – justaprogrammer – 2016-01-31T16:23:37.387

@justaprogrammer Jelly is Dennis's language: https://github.com/DennisMitchell/Jelly ... I think documentation is still pretty sparse for it though (and the language is under active development).

– Martin Ender – 2016-01-31T16:35:07.643

5

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 (All browsers work)

Downgoat

Posted 2016-01-31T15:27:49.633

Reputation: 27 116

2Just like mine, but better (and posted earlier). Bah! – edc65 – 2016-01-31T16:04:49.377

String Manipulation is JS is so long, you have my condolences – MayorMonty – 2016-01-31T18:24:31.717

@user81655 cool, thanks! I would of never thought to re-order that way – Downgoat – 2016-02-01T03:17:07.820

f=n=>n?[...+[...b=f(n-1)].reverse().join``+b+''].sort().join``:'1' if returning string allowed – l4m2 – 2018-04-26T03:47:23.697

5

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

FryAmTheEggman

Posted 2016-01-31T15:27:49.633

Reputation: 16 206

Is that a surplus space before the or in the second code block? – trichoplax – 2016-02-01T02:09:41.290

1@trichoplax thanks for the catch :) – FryAmTheEggman – 2016-02-01T02:21:11.797

4

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.

Fatalize

Posted 2016-01-31T15:27:49.633

Reputation: 32 976

3

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 ith element.

nimi

Posted 2016-01-31T15:27:49.633

Reputation: 34 639

This is the most readable program under 70 bytes! – Gaurav Agarwal – 2016-02-01T23:54:20.943

3

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

Alex A.

Posted 2016-01-31T15:27:49.633

Reputation: 23 761

3

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

ASCII-only

Posted 2016-01-31T15:27:49.633

Reputation: 4 687

2

Brachylog 2, 11 bytes, language postdates challenge

;1{↔;?+o}ⁱ⁽

Try it online!

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.

user62131

Posted 2016-01-31T15:27:49.633

Reputation:

2

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)

Katenkyo

Posted 2016-01-31T15:27:49.633

Reputation: 2 857

Well it looks like you aren't here anymore... but maybe you can refer to my java answer. – Leaky Nun – 2017-05-02T11:10:25.637

@LeakyNun Well, I'm not participating a lot this times but still peaking at challenges from time to times, I'll try to take a look at your answer, but even without that I see some thing that can be golfed pretty easily (a=a<1 and 1or for instance). – Katenkyo – 2017-05-03T20:07:07.617

we would be glad – I would be glad – to have you back. – Leaky Nun – 2017-05-04T01:54:44.997

2

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

Denham Coote

Posted 2016-01-31T15:27:49.633

Reputation: 1 397

Why do you use interface R instead of class R which is 4 bytes shorter? – Will Sherwood – 2016-02-02T05:04:36.883

1@WillSherwood because you can then omit the public modifier on main(), making it shorter overall :) – Denham Coote – 2016-02-02T08:08:53.833

2

Seriously, 17 bytes

1,`;$R≈+$S≈`n

Try it online!

Explanation:

1,`;$R≈+$S≈`n
1              push 1
 ,`       `n   do the following n times:
   ;$R≈        reverse
       +       add
        $S≈    sort

Mego

Posted 2016-01-31T15:27:49.633

Reputation: 32 998

1

Java, 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!

Not the longest entry! \o/

Leaky Nun

Posted 2016-01-31T15:27:49.633

Reputation: 45 011

@Katenkyo see this

– Leaky Nun – 2017-05-07T14:46:37.743

It is ok f(1)...f(20) But from f(21) result seems wrong... – RosLuP – 2017-05-07T18:42:42.257

Loss of precision I suppose. – Leaky Nun – 2017-05-07T18:43:08.103

1

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

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];

Jörg Hülsermann

Posted 2016-01-31T15:27:49.633

Reputation: 13 026

1

Python 2, 70 bytes

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

Try it online!

ovs

Posted 2016-01-31T15:27:49.633

Reputation: 21 408

1

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.

Neil

Posted 2016-01-31T15:27:49.633

Reputation: 95 035

for is shorter: n=>eval("for(r=1;n--)r=+[...+[...r+''].reverse().join\`+r+''].sort().join``")` – Downgoat – 2016-01-31T16:01:07.800

@Doᴡɴɢᴏᴀᴛ Doesn't work for n=0, even after I've fixed the syntax errors. – Neil – 2016-01-31T16:03:36.530

1

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.

Denker

Posted 2016-01-31T15:27:49.633

Reputation: 6 639

1

Python 2, 83 bytes

def f(n):
 v='1'
 for _ in v*n:v=''.join(sorted(str(int(v)+int(v[::-1]))))
 print v

jatinderjit

Posted 2016-01-31T15:27:49.633

Reputation: 111

1

Perl 6, 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)

Brad Gilbert b2gills

Posted 2016-01-31T15:27:49.633

Reputation: 12 713

1

Mathematica 10.3, 66 61 bytes

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

Quite simple.

LegionMammal978

Posted 2016-01-31T15:27:49.633

Reputation: 15 731

0

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]]

RosLuP

Posted 2016-01-31T15:27:49.633

Reputation: 3 036

0

Tcl, 91 bytes

proc R n {join [lsort [split [expr {$n?[set v [R [expr $n-1]]]+[string rev $v]:1}] ""]] ""}

Try it online!

sergiol

Posted 2016-01-31T15:27:49.633

Reputation: 3 055