# Range, Reverse, Sum!

Given a positive integer n as input, output the reversed range sum of n.

A reversed range sum is created by making an inclusive range up to n, starting with 1 and including n, reversing each of the numbers inside, and summing it.

Example:

Here is what would happen for an input of 10:

Range: [1,2,3,4,5,6,7,8,9,10]

Reverse: [1,2,3,4,5,6,7,8,9,01] (1-char numbers reversed are themselves, 10 reversed is 01 or 1)

Sum: 46

Numbers with 3+ digits are reversed the same way numbers with 2 digits are. For example, 1234 would become 4321.

Test cases:

Input -> Output

10 -> 46
5 -> 15
21 -> 519
58 -> 2350
75 -> 3147
999 -> 454545

Complete text cases to input of 999 can be found here, thanks very much to @fireflame241.

• More test case results (not numbered, sorry, but you can parse through and get their line number if you want): Try it online! – Stephen Jul 31 '17 at 23:49
• @StepHen >:D Charcoal is faster – ASCII-only Aug 1 '17 at 0:36
• Relevant – Silvio Mayolo Aug 1 '17 at 1:12
• OEIS A062918 – Leaky Nun Aug 1 '17 at 6:37
• -1 because this is uninteresting. It seems like most, if not all, of the submissions are using the same approach. This challenge seems like a bunch of problems that have already been asked, just piped together with no obvious shortcuts. – Esolanging Fruit Aug 21 '17 at 8:23

# 05AB1E, 3 bytes

### Code

LíO

Uses the 05AB1E encoding. Try it online!

### Explanation

L       # Range
í      # Reverse
O     # Sum
• dat explanation tho – ETHproductions Aug 1 '17 at 0:41
• @ETHproductions well Reverse should be Reverse each actually... – Erik the Outgolfer Aug 1 '17 at 8:31
• @EriktheOutgolfer It's not vectorized? – ASCII-only Aug 1 '17 at 10:40
• @ASCII-only 05AB1E vectorization is really 1 level deep, not ∞. Also just "reverse" is R, while í is "reverse each". – Erik the Outgolfer Aug 1 '17 at 10:43

# Bash + GNU utils, 24

seq $1|rev|paste -sd+|bc ### Explanation seq$1                    # range
|rev                # reverse (each line)
|paste -sd+|bc  # sum

## JavaScript (ES6), 42 bytes

f=n=>n&&+[...n+""].reverse().join+f(n-1)

My favorite doubly-recursive solution is unfortunately 3 bytes longer:

f=n=>n&&+(g=x=>x?x%10+g(x/10|0):"")(n)+f(n-1)

# Perl 6, 20 bytes

{(1..$_)».flip.sum} Test it ## Expanded: { ( 1 ..$_ )\  # Range
».flip        # flip each value in the Range (possibly in parallel)
.sum          # sum up the list
}
• Is the 'possibly in parallel' required? Seems like you could get rid of a byte or two by omitting it. – Fund Monica's Lawsuit Aug 2 '17 at 16:17
• @QPaysTaxes No. The ».flip calls the .flip method on each of the values in the Range. The next shortest way to do this is .map(*.flip) which is 5 bytes more. – Brad Gilbert b2gills Aug 5 '17 at 15:49
• Oh, so the key part is "each", not "(possibly in parallel)". Might be worth splitting them out, then. – Fund Monica's Lawsuit Aug 5 '17 at 22:28
• @QPaysTaxes I'm not sure I know what you mean ».flip is a hyper method call. While I can split up the » and .flip by using an unspace \ like I did before it; that would make it harder to understand, as it would look like the end of a qqww/ / construct (« a b "c d" »). – Brad Gilbert b2gills Aug 6 '17 at 14:59

# Retina, 4136 35 bytes

.+
$* 1 1$¶
1+
$.& %O^$.

.+
$* 1 Try it online! Link includes test cases. Edit: Saved 5 bytes thanks to @FryAmTheEggman. Saved 1 byte thanks to @PunPun1000. Explanation: .+$*

Convert to unary.

1
1$¶ Create a range from 1 to n. 1+$.&

Convert back to decimal.

%O^$. Reverse each number. .+$*

Convert back to unary.

1

Sum and convert back to decimal.

• @FryAmTheEggman Bah, I keep forgetting about that. – Neil Aug 1 '17 at 7:54
• You don't need the in the .+¶ The match will match across lines – PunPun1000 Aug 1 '17 at 16:35
• @PunPun1000 I did need it before FryAmTheEggman's fix! – Neil Aug 1 '17 at 17:31

Try it online!

## Explanation

Implicit input n.
;      Series mode. Outputs the sum of the sequence from 1 to n.
\r$Each item in the sequence equals: \r String reverse of$                     current index (1-based)

# Python 2, 38 bytes

Can't compute higher terms than the recursion limit:

f=lambda x:x and int(x[::-1])+f(x-1)

Try it online!

• You can use import sys and sys.setrecursionlimit() if you want to handle larger numbers, in the tio header. – Mr. Xcoder Aug 1 '17 at 6:01

# Brachylog, 4 bytes

⟦↔ᵐ+

Try it online!

### Explanation

⟦↔ᵐ+
⟦        range from 0 to input
↔ᵐ      map reverse
+     sum

# Röda, 5641 36 bytes

15 bytes saved thanks to @fergusq

{seq 1,_|parseInteger$_[::-1]|sum} Try it online! This is an anonymous function that takes an integer from the input stream and outputs an integer to the output stream. ### Explanation {seq 1,_|parseInteger$_[::-1]|sum} Anonymous function
seq 1,_                             Create a sequence 1 2 3 .. input and push each value to the stream
|                            For each value in the stream:
$_ Cast it into a string [::-1] And reverse it parseInteger And parse the resulting string as an integer, while pushing the value to the stream |sum Sum all the values in the stream • You can save a lot of bytes by using [::-1] instead of reverse. Also $_  is shorter than _.."" and parentheses after parseInteger are not needed. – fergusq Aug 2 '17 at 7:31
• @fergusq Thanks for the tips, my Röda has gone a bit rusty :) – Kritixi Lithos Aug 2 '17 at 9:16

# C# (.NET Core), 103 97 bytes

using System.Linq;r=>new int[r+1].Select((_,n)=>int.Parse(string.Concat((n+"").Reverse()))).Sum()

Try it online!

TIO link outputs all the results from 1 to 999, so feel free to check my work.

I expected this to be a bit shorter, but it turns out Reverse() returns an IEnumerable<char> instead of another string so I had to add some extra to turn it back into a string so I could parse it to an int. Maybe there's a shorter way to go from IEnumerable<char> to int correctly.

Of minor note, this also uses the functions Range() Reverse() and Sum() all in order.

-6 bytes thanks to TheLethalCoder

• You don't need the trailing semi colon. I think using new int[r] and .Select((_,n)=>...) will save you bytes. – TheLethalCoder Aug 1 '17 at 8:15
• @TheLethalCoder It takes new int[r+1] to get the right output since the index starts at 0, but it does still save a few bytes. RIP Range() though – Kamil Drakari Aug 1 '17 at 12:19

# Ruby, 56, 52, 41, 39 bytes

->n{(1..n).sum{|i|i.to_s.reverse.to_i}}

# Ruby, 34 bytes (if lambda param is a string)

->n{(1..n).sum{|i|i.reverse.to_i}}

Thanks to @Unihedron for the second solution.

• ->n{ works as well. – Value Ink Aug 15 '17 at 18:27
• I have crafted a shorter program in the same tool (Ruby) that is different enough (it deals with input and output) to be its own submission, you can find it here: codegolf.stackexchange.com/a/150636/21830 – Unihedron Dec 14 '17 at 17:50
• @Unihedron, haha, I didn't know Ruby is so crazy to allow string ranges. Thanks. – akostadinov Dec 14 '17 at 18:53
• Yes, ruby also has nifty features like ?a..?z and ?a1..?h8 (although you better be careful with the 2nd format :D) – Unihedron Dec 14 '17 at 19:19
• Ranges has to either 1. (for start value) implement succ and 2. (if either start or end value does not implement succ) be numeric, so int..string will get rejected as "Bad value for range". The inverse is true (but alas there's no downto range), or (?1..n) can be used instead – Unihedron Dec 14 '17 at 19:39

# Mathematica, 47 bytes

Tr[FromDigits@*Reverse/@IntegerDigits@Range@#]&

Try it online! (in order to work on mathics we need to replace "Tr" with "Total")

• Tr@*IntegerReverse@*Range – ngenisis Aug 21 '17 at 22:20

# Charcoal, 14 13 bytes

-1 byte thanks to Carlos Alejo

Ｉ∕…·⁰Ｎ«⁺ιＩ⮌Ｉκ

Try it online! Link is to verbose version.

## Explanation

Ｉ                  Cast
∕     «           Reduce
…·⁰Ｎ            Inclusive range from 0 to input as number
⁺          Plus
ι         i
Ｉ⮌Ｉκ   Cast(Reverse(Cast(k)))
• You can save a byte by dropping the last ». By the way, where in the Charcoal wiki is the Reduce operator documented? – Charlie Aug 1 '17 at 6:04
• Nowhere, it's an overload of the division one :| I can give you edit access if you want (sorry I'm too lazy to do it myself) – ASCII-only Aug 1 '17 at 7:07
• Also yeah I forgot why leaving out ending braces works lol – ASCII-only Aug 1 '17 at 7:08
• I would really like the Charcoal wiki to be a bit more documented, as there are still some working but hidden features. If you grant me edit access I'll do my best to document them. Example: how can the Modulo operator be used to format strings in Charcoal? – Charlie Aug 1 '17 at 7:38
• @CarlosAlejo I've had a bit of free time so I've started documenting stuff, hope you like it! – Neil Aug 3 '17 at 13:31

## Magneson, 102 bytes

That's not very visible, so here's a scaled up version (Note: Won't actually run, and still isn't very pretty)

Magneson operates by parsing an image and evaluating commands from the colours of the pixels it reads. So stepping through the image for this challenge, we have:

• R: 0, G: 1, B: 1 is an integer assignment command, which takes a string for the variable name and the value to assign. We'll use this to store the sum total.
• R: 0, G: 1, B: 0 is a prebuilt string with the value VAR_1 (Note: This is only while we're asking for a string; the colour code has a separate function when used elsewhere).
• R: 3, G: 0, B: 0 is a raw number. Magneson handles standard numbers by requiring the Red component to be exactly 3, and then forms a number by using the blue value directly plus the green value multiplied by 256. In this case, we're just getting the number 0.
• R: 0, G: 1, B: 1 is another integer assignment command. This time, we're storing an iteration variable, to keep track of which number we're on
• R: 0, G: 1, B: 1 is a prebuilt string with the value VAR_2 (Once more, only when we need a string)
• R: 3, G: 0, B: 0 is the number 0, once more. Onto the interesting bits now.
• R: 1, G: 0, B: 0 indicates the start of a loop. This takes a number and loops the following snippet of code that many times.
• R: 2, G: 0, B: 0 is the STDIN function, or at least it is when we need a number. This reads a line of input from the console and turns it into a number, since we asked for a number.
• R: 0, G: 8, B: 0 starts off our looping code, and it is an additive command. This adds a number to an integer variable, and so takes a string for the variable name, and the number to add.
• R: 0, G: 1, B: 1 is the prebuilt string for VAR_2, which is our iteration variable.
• R: 3, G: 0, B: 1 is a raw number, but this time it's the number 1.
• R: 0, G: 8, B: 0 is another addition command.
• R: 0, G: 1, B: 0 is the string for VAR_1, which is our sum total.
• R: 0, G: 3, B: 0 is a function that reverses a string. In the context of asking for a number, it then converts the reversed string to a number.
• R: 0, G: 2, B: 1 is an integer retrieval command, and will retrieve the number stored in a provided variable. In the context of asking for a string (such as from the reverse command), it converts the number to a string.
• R: 0, G: 1, B: 1 is the name VAR_2; our iteration variable.
• R: 1, G: 0, B: 1 is the marker to end the loop, and go back to the start of the loop if the criteria isn't met (so if we need to keep looping). Otherwise, proceed onwards.
• R: 0, G: 0, B: 1 is a very simple println command, and takes a string.
• R: 0, G: 2, B: 1 retrieves an integer from a variable
• R: 0, G: 1, B: 0 is the name of our sum total variable, VAR_1

All in all, the program:

• Assigns the value 0 to VAR_1 and VAR_2
• Loops from 0 to a number provided in STDIN
• Adds one to VAR_2
• Adds the integer value of reversing VAR_2 to VAR_1
• Prints the contents of VAR_1

# Python 2, 50 47 bytes

-3 bytes thanks to officialaimm!

lambda n:sum(int(i+1[::-1])for i in range(n))

Try it online!

• since it's python 2,  instead of str saves 3 bytes. – officialaimm Aug 1 '17 at 4:53

# CJam, 12 bytes

ri){sW%i}%:+

Try it online!

-1 thanks to Business Cat.

Explanation:

ri){sW%i}%:+
r            Get token
i           To integer
)          Increment
{sW%i}    Push {sW%i}
s         To string
W        Push -1
%       Step
i      To integer
%   Map
:+ Map/reduce by Add
• Could you add an explanation? I don't understand CJam (nor GolfScript). But MY beat two (albeit ancient in terms of golf-langs) golfing languages! – Zacharý Aug 1 '17 at 15:18
• @Zacharý done... – Erik the Outgolfer Aug 1 '17 at 15:23
• You don't need the , – Business Cat Aug 1 '17 at 17:36
• @BusinessCat Ohhh used too much to GolfScript apparently... – Erik the Outgolfer Aug 1 '17 at 17:36

# APL (Dyalog), 10 7 bytes

3 bytes golfed thanks to @Adám by converting to a tradfn from a train

+/⍎⌽⍕⍳⎕

Try it online!

⎕          Input (example input: 10)
⍳          Range; 1 2 3 4 5 6 7 8 9 10
⍕          Stringify; '1 2 3 4 5 6 7 8 9 10'
⌽          Reverse; '01 9 8 7 6 5 4 3 2 1'
⍎          Evaluate; 1 9 8 7 6 5 4 3 2 1
+/         Sum; 46
• To @Uriel & Cows quack about the chat question: Well, I did the Mathematics portion, in addition to that, I've been suspended from chat, hence my not responding in there. – Zacharý Aug 1 '17 at 14:57
• 7 bytes: +/⍎⌽⍕⍳⎕ – Adám Aug 2 '17 at 9:27
• @Adám Thanks for the tip. Removing the ¨ was clever :) – Kritixi Lithos Aug 2 '17 at 9:40

# Java 8, 97 bytes

IntStream.range(1,n+1).map(i->Integer.valueOf(new StringBuffer(""+i).reverse().toString())).sum()

EDIT

As per the comment of Kevin Cruijssen, I would like to improve my answer.

# Java 8, 103 bytes

n->java.util.stream.LongStream.range(1,n+1).map(i->new Long(new StringBuffer(""+i).reverse()+"")).sum()
• Integer.valueOf can be golfed to new Integer, and .reverse().toString() can be golfed to .reverse()+"". Also, you must include the required imports and lambda parameters, like java.util.stream.IntStream and n-> before it. And you can also golf IntStream & Integer to LongStream and Long. The final answer will be n->java.util.stream.LongStream.range(1,n+1).map(i->new Long(new StringBuffer(""+i).reverse()+"")).sum() (103 bytes - Your current answer with added import and lambda parameter would be 117 bytes.) Still +1, nice answer! – Kevin Cruijssen Aug 3 '17 at 13:01
• @KevinCruijssen Thank you for your valuable inputs. I'll update my answer. Thanks. :) – CoderCroc Aug 3 '17 at 13:22

# Japt, 7 5 bytes

-2 bytes thanks to @Shaggy.

õs xw

Try it online!

## Explanation

õs xw  Implicit input of integer U
õs     Create range [1,U] and map to strings
w  Reverse each string
x   Sum the array, implicitly converting to numbers.

# Old solution, 7 bytes

Keeping this since it's a really cool use of z2.

õs z2 x

Try it online!

## Explanation

õs z2 x  Implicit input of integer U
õs       Create range [1,U] and map to strings
z2    Rotate the array 180°, reversing strings
x  Sum the array, implicitly converting back to integers
• You know z2 on a flat array is the same as w, righ... uhm... excuse my inadequacy at Japt... – ETHproductions Aug 1 '17 at 0:43
• 6 bytes: õ_swÃx thanks to the new addition of N.s(f). – Shaggy Aug 15 '17 at 16:00
• Or even just õs xw for 5 bytes. – Shaggy Aug 15 '17 at 16:04
• @Shaggy I can't believe nobody mentioned that 5-byte solution until now... will edit in a bit. As for the 6-byte one, if that was added after this challenge was posted, I think that'd be non-competing. – Justin Mariner Aug 15 '17 at 16:15
• @JustinMariner, neither can I! :D Although, it seems a shame to ditch that z2 trick; that was pretty damn genius. Note that non-competing is no longer a thing. – Shaggy Aug 15 '17 at 16:29

## C++, 146 bytes

#include<string>
using namespace std;int r(int i){int v=0,j=0;for(;j<=i;++j){auto t=to_string(j);reverse(t.begin(),t.end());v+=stoi(t);}return v;}
• Good job! You can spare some bytes by removing the header and putting "using namespace std" (check here tio.run/#cpp-gcc). I also think you could replace "auto t" with just "t" (?) – koita_pisw_sou Aug 1 '17 at 6:33
• Yeah, koita_pisw_sou is right about the first part. But you need the auto. – Zacharý Aug 1 '17 at 12:24
• @koita_pisw_sou Do you mean that i can exclude the header directive from the byte count ? Same for the namespace ? auto keyword is needed – HatsuPointerKun Aug 1 '17 at 13:43
• Yes, check the link I sent – koita_pisw_sou Aug 1 '17 at 13:44
• (Whoops, I am not sure about the removing the header!) But I was referring to using namespace std; saving bytes. – Zacharý Aug 1 '17 at 15:00

# Husk, 7 6 3 bytes

ṁ↔ḣ

Try it online!

### Ungolfed/Explanation

ḣ  -- With the list [1..N] ..
ṁ    -- .. do the following with each element and sum the values:
↔   --    reverse it

# Perl 5, 29 27 22 + 1 (-p) = 23 bytes

map$\+=reverse,1..$_}{

Try it online!

• 26 bytes: map$r+=reverse,1..<>;say$r. – Denis Ibaev Dec 29 '17 at 9:35
• Got it down even further using -p – Xcali Dec 30 '17 at 6:44

# RProgN 2, 8 bytes

{Ø.in}S+

## Explained

{Ø.in}S+
{    }S # Create a stack in range 0 through the implicit input, using the function defined
Ø.     # Append nothing, stringifying the number
i    # Reverse the string
n   # Convert back to a number
+# Get the sum of the stack, and output implicitly.

Try it online!

# Pyth, 8 6 bytes

-2 bytes thanks to FryAmTheEggman!

sms_h

Try it online!

• 1 byte longer version, sms_`dS, that does not abuse implicit U at the end. – Mr. Xcoder Aug 1 '17 at 6:44

# Tcl, 66 bytes

time {incr s [regsub ^0+ [string rev $n] ""];incr n -1}$n
puts \$s

Try it online!

Δ𝐫)𝐬

Try it online!

# Explanation

Δ )              for each element 1 to n (outputs list)
𝐫               reverse
𝐬             sum
• Alternative solution: 𝐈Ψ𝐫𝐬 (create inclusive range, reverse each element, sum) – Okx Aug 1 '17 at 11:31
• @Okx didn't know that the Ψ token existed! would have definitely used that in hindsight. real nice – space junk Aug 1 '17 at 12:01

# C (gcc), 71 bytes

q(n,x,p){p=n?q(n/10,x*10+n%10):x;}f(w,a,e){for(a=0;w;)a+=q(w--,0);e=a;}

Try it online!

• Wait... what? How f() returns its result without any return statement? Does the e=a instruction manipulates the registers in such a way that the result is stored in the same register than the one used by returned values? – scottinet Sep 5 '17 at 15:47