# 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

# Excel VBA, 80 78 49 Bytes

Anonymous VBE Immediate Window function that takes input expected type Integer from range [A1] determines all of the values that fall within the range 1:[A1], and outputs the sum of the reversed values to the VBE immediate window

For i=1To[A1]:s=s+Val(StrReverse(Str(i))):Next:?s


## TXR Lisp: 62 56 bytes:

(opip(range 1)(mapcar[chain tostring reverse toint])sum)


Interactive:

1> (opip(range 1)(mapcar[chain tostring reverse toint])sum)
#<intrinsic fun: 0 param + variadic>
2> [*1 10]
46
3> [*1 999]
454545


The following 44 byte expression, inspired by the Pari/GP solution, is possible; however, it requires the sum macro to be defined:

1> (defmacro sum (var from to expr)
(with-gensyms (accum)
^(for ((,var ,from) (,accum 0))
((<= ,var ,to) ,accum)
((inc ,accum ,expr) (inc ,var)))))
sum
2> (do sum x 1 @1 (toint(reverse(tostring x))))
#<interpreted fun: lambda (#:arg-01-0171 . #:rest-0170)>
3> [*2 10]
46
4> [*2 999]
454545


# Gaia, 7 bytes

@…)¦v¦Σ


Try it online!

Range, Reverse, and sum!

@             # push an input. stack: n
…            # generate range. stack: [0...n-1]
)¦          # map over the list with increment. stack: [1...n]
v¦        # map over the list with reverse. stack: [1...n], but all digitally reversed
Σ       # sum the list; output TOS.


# Ruby, 38 35 bytes

Similar to the previous Ruby solution, but a full program and also shorter (for less than an hour)!

p (?1..gets).sum{|x|x.reverse.to_i}


Shortened by 3 bytes thanks to user akostadinov

Try it online!

## Explanation

p             # Inspect and print. Written as infix notation to avoid using ()
(?1..gets)    # All strings from "1" to "input", based on successive string format
.sum{|x|    # Enumerable -> Map to value -> Sum by value
x.reverse.to_i
}

• you can do (?1..gets).sum{...}) – akostadinov Dec 14 '17 at 18:54

# Gol><>, 26 bytes

&IFLPWaSD$|~rlMFa*+|&+&|&h  Try it online! ## Explanation &I &h < register init, read "n"; print register (h = n;) FLP | < For loop, do "n" times for each x in [1] to [n] WaSD$|                < modpow "x" to digits: [123] [3 12] [3 2 1] [3 2 1 0]
~rlMFa*+|       < Ditch zero, reverse stack, build the number back
&+&    < register += final x


# Pyke, 7 bytes

SF_b)s


Try it online!

S       -   range(1, input)
F   )  -  for i in ^:
-     str(i)
_    -    reversed(^)
b   -   int(^)
s  - sum(^)


# MATL, 5 bytes

:VPUs


Try it online!

# Python 3, 50 bytes

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


Quite close to idiomatic Python code, and honestly I don't really see much room for improvement.

# Pyth - 7 bytes

sms_dS


Explanation

sms_dSQ  Q added implicitly
s         Sum of
m        map
s_d    integer representation of reversal of string representation
to
SQ  Range from 1 to input


# Pyt, 3 bytes

ř₫Ʃ


Try it online!

The characters perform the following operations: range, reverse, sum.

• Dammit. You beat me to it. +1 – mudkip201 Feb 22 '18 at 3:55
• @mudkip201 Yeah I feel like its almost a race to see who can get the most trivial arithmetic challenges answered – FantaC Feb 22 '18 at 14:56

# Jelly, 5 bytes

RDUḌS


Try it online!

R      ' [R]ange
D     ' Integer -> [D]ecimal
U    ' [U]pend (vectorized reverse?)
Ḍ   ' [Ḍ]ecimal -> Integer
S  ' [S]um

• Shouldn't you make it [U]pend for completion's sake? – Zacharý Aug 1 '17 at 0:00
• You right, all better. Thanks! – nmjcman101 Aug 1 '17 at 0:01

# Ly, 31 bytes

ns[l1-s]pr[s>lSrJs>l<p<p]>>r&+u


Try it online!

# Pari/GP, 43 bytes

n->sum(i=1,n,fromdigits(Vecrev(digits(i))))


Try it online!

# QBIC, 19 bytes

[:|_F!a$|p=p+!A!}?p  ## Explanation [:| FOR a = 1 to n (read from cmd line) _F | FLIP and assign to A$
!a$a string cast of our loop counter p=p+!A! increment p with A$ cast back to number
}           NEXT
?p         Print the result


# LOGO, 33 bytes

[reduce "+ map "reverse iseq 1 ?]


There is no "Try it online!" link because all online LOGO interpreter does not support template-list.

That is a template-list (equivalent of lambda function in other languages).

Usage:

pr invoke [reduce[?+reverse ?2]iseq 1 ?] 10


(invoke calls the function, pr prints the result)

prints 46.

Explanation:

LOGO stores numbers as words, therefore apply reverse on a number reverse the digits in that number.

reduce "f [a b c d e] (where [a b c d e] is a list) will calculate f(a, f(b, f(c, f(d, e)))). So reduce "+ list will calculate sum of values of list.

Swift 3, 98 bytes

func f(a:Int)->Int{return (0...a).map{Int(String(String($0).characters.reversed()))!}.reduce(0,+)}  • – Mr. Xcoder Aug 12 '17 at 17:33 • Also String($0) can be "\($0)" to save a couple of bytes too. – Mr. Xcoder Aug 12 '17 at 17:37 # PowerShell, 53 bytes (1.."$args"|%{-join"$_"["$_".length..0]})-join'+'|iex


Try it online!

Literal translation of the specification. Creates a range with .., reverses each by using string manipulation and -joining them back into a single number, then -joins each number together with a + and piping that to iex (short for Invoke-Expression and similar to eval).

# GolfScript, 15 bytes

~),{-1%~}%{+}*


Try it online!

Explanation:

~),{-1%~}%{+}* Input all at once
~               Eval
)              Increment
,             Exclusive range
{     }      Push block
Repr
-1          -1
%         Every xth element
~        Eval
%     Map
{ }  Push block
* Reduce


# PHP, 39+1 bytes

while($i++<$argn)$s+=strrev($i);echo$s;  Run as pipe with -nR. # R, 89 bytes sum(strtoi(sapply(strsplit(paste(1:scan()),''),function(x)paste(rev(x),collapse='')),10))  Reads from stdin; returns the value. sum( #compute the sum strtoi( #convert string to int sapply( #iterate over strsplit( #this where each element is the list of characters in the number paste(1:scan()), #convert range to character ""), #split on each character function(x)paste(rev(x), collapse="")), #reverse the list and concatenate digits 10)) #as base 10  Try it online! • I know it's an old one but what about this for 82 bytes? – JayCe Jun 1 '18 at 17:53 # Rust, 110 bytes |x:i64|(1..x+1).map(|v|format!("{}",v).chars().rev().collect::<String>().parse::<i64>().unwrap()).sum::<i64>()  Try it online! I like Rust, but it is not a very efficient language for golfing! # Common Lisp, 62 bytes (loop as i to(read)sum(parse-integer(reverse(format()"~d"i))))  Try it online! ## REXX, 46 bytes arg n s=0 do i=1 to n s=s+reverse(i) end say s  # Javascript,8977 72 bytes saved 12 bytes thanks to @Justin Mariner saved 5 bytes thanks to @Neil n=>-eval(-'${[...[...Array(n+1).keys()].join'-'].reverse().join}')


### Explanation:

[...Array(n+1).keys()] creates an array from 0 to n.

.reverse(‌).join reverses every value.

.join'-' and eval(-'{stuff}') subtracts the values in order, producing the negative of the answer. - negates the negative to a positive.

• You can use [...Array(n)] to avoid fill() and can combine both maps: n=>eval([...Array(n)].map((_,a)=>+(++a+"").split.reverse().join).join+). Be careful coping that since SE adds unprintable chars to break code lines. – Justin Mariner Aug 1 '17 at 1:26
• It's quicker to join the array first, then reverse it, as that saves you from converting the numbers to strings: n=>eval([...[...Array(n+1).keys()].join+].reverse().join). – Neil Aug 2 '17 at 8:59
• @Neil doesn't work for 999(produces 4153), probably because of octal literals getting added – SuperStormer Aug 2 '17 at 10:19

• reduce(0,{$0+...}) - Sums the mapped range. # k, 13 bytes +/.:'|:'$1+!:


Try it online!

         1+!: /create list 1 2 3 ... x
$/turn each number into a string |:' /reverse each string .:' /eval each string +/ /sum  ## Swift 3, 83 68 characters let f={n in Array(1...n).reduce(0){$0+Int(String("($1)".characters.reversed()))!}} {(1...$0).reduce(0){$0+Int(String("\($1)".characters.reversed()))!}}


This would probably be shortened by Swift 4's new String and Character handling.

• You do not need to include let f= in the byte count. That saves 6 bytes. – Mr. Xcoder Aug 12 '17 at 17:38
• You also do not need Array(1...n). It can be n in(1...n).reduce... – Mr. Xcoder Aug 12 '17 at 17:39
• So an anonymous function is good enough for golf? – idrougge Aug 14 '17 at 13:42
• Of course. The same applies to a lambda in Python, and that's because it's valid even without the declaration, since you can call it like ({n in Array(1...n).reduce(0){$0+Int(String("\($1)".characters.reversed()))!}})(someValue) anyway – Mr. Xcoder Aug 14 '17 at 13:43

# MY, 11 bytes

𝕫iC4ǵ'ƒ⇹(Σ↵


Try it online!

## How?

• 𝕫 input as integer
• i [1 ... pop()] inclusive
• C4ǵ' push the string '\x4C' (The reverse command (⌽), which works on numbers)
• ƒ as a function
• ⇹ mapped over the argument (pushes a function)
• ( apply the function
• Σ sum
• ↵ output with a new line

MY is capable of something, woohoo!

• >_> unimplemented codepage – ASCII-only Aug 1 '17 at 0:19
• ...I just have to ask, why did you rearrange ASCII for your codepage? :P – ETHproductions Aug 1 '17 at 0:57
• I started with the functions, rather than the codepage, and I want the cp to be organized as heck (Nilads, Monads, Dyads, Triads). The unimplemented codepage is there so even readable at all. – Zacharý Aug 1 '17 at 2:16
• Also, what do you expect from a language that has 12- result in 1 rather than -1? – Zacharý Aug 1 '17 at 13:17
• MY's codepage is now implemented, and MY is finally on TIO! – Zacharý Aug 21 '17 at 17:23

# Java 8, 84 bytes

Lambda from int to long (e.g. IntToLongFunction). Adaptation of coder-croc's solution.

n->{long s=0;while(n>0)s+=new Long(new StringBuffer(""+n--).reverse()+"");return s;}


Try It Online

# Recursiva, 10 bytes

smBa"I_Va"


Try it online!