21
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ More test case results (not numbered, sorry, but you can parse through and get their line number if you want): Try it online! \$\endgroup\$ – Stephen Jul 31 '17 at 23:49
  • \$\begingroup\$ @StepHen >:D Charcoal is faster \$\endgroup\$ – ASCII-only Aug 1 '17 at 0:36
  • 1
    \$\begingroup\$ Relevant \$\endgroup\$ – Silvio Mayolo Aug 1 '17 at 1:12
  • 1
    \$\begingroup\$ OEIS A062918 \$\endgroup\$ – Leaky Nun Aug 1 '17 at 6:37
  • 4
    \$\begingroup\$ -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. \$\endgroup\$ – Esolanging Fruit Aug 21 '17 at 8:23

61 Answers 61

2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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.
\$\endgroup\$
2
\$\begingroup\$

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
  }
\$\endgroup\$
  • 1
    \$\begingroup\$ you can do (?1..gets).sum{...}) \$\endgroup\$ – akostadinov Dec 14 '17 at 18:54
2
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Pyke, 7 bytes

SF`_b)s

Try it online!

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

MATL, 5 bytes

:VPUs

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Pyt, 3 bytes

ř₫Ʃ

Try it online!

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

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

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
\$\endgroup\$
  • 1
    \$\begingroup\$ Shouldn't you make it [U]pend for completion's sake? \$\endgroup\$ – Zacharý Aug 1 '17 at 0:00
  • \$\begingroup\$ You right, all better. Thanks! \$\endgroup\$ – nmjcman101 Aug 1 '17 at 0:01
0
\$\begingroup\$

Ly, 31 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Pari/GP, 43 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

Swift 3, 98 bytes

func f(a:Int)->Int{return (0...a).map{Int(String(String($0).characters.reversed()))!}.reduce(0,+)}
\$\endgroup\$
0
\$\begingroup\$

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).

\$\endgroup\$
0
\$\begingroup\$

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
            +    Add
              * Reduce
\$\endgroup\$
0
\$\begingroup\$

PHP, 39+1 bytes

while($i++<$argn)$s+=strrev($i);echo$s;

Run as pipe with -nR.

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ I know it's an old one but what about this for 82 bytes? \$\endgroup\$ – JayCe Jun 1 '18 at 17:53
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

Common Lisp, 62 bytes

(loop as i to(read)sum(parse-integer(reverse(format()"~d"i))))

Try it online!

\$\endgroup\$
0
\$\begingroup\$

REXX, 46 bytes

arg n
s=0
do i=1 to n
  s=s+reverse(i)
  end
say s
\$\endgroup\$
0
\$\begingroup\$

Javascript,89 77 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.

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Justin Mariner Aug 1 '17 at 1:26
  • \$\begingroup\$ 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``). \$\endgroup\$ – Neil Aug 2 '17 at 8:59
  • 1
    \$\begingroup\$ @Neil doesn't work for 999(produces 4153), probably because of octal literals getting added \$\endgroup\$ – SuperStormer Aug 2 '17 at 10:19
  • \$\begingroup\$ Bah, stupid octal literals. Best I can do in that case is n=>-eval(`-'${[...[...Array(n+1).keys()].join`'-'`].reverse().join``}'`). \$\endgroup\$ – Neil Aug 2 '17 at 11:35
0
\$\begingroup\$

Swift 4, 63 61 bytes

{v in(1...v).reduce(0,{$0+Int(String("\($1)".reversed()))!})}

Try it online!


Explanation

  • {v in} - Creates an anonymous (lambda-like) function with a parameter v.

  • (1...v) - Inclusive range from 1 to v (although it kind of breaks the rules of logic).

  • Int(String("\($1)".reversed())) - Reverses the Number by converting it to a String, returning ReverseCollection<String>. That cannot be casted directly to an integer (Swift borked types!), so we have to cast it to String again, before making the conversion to an Integer.

  • reduce(0,{$0+...}) - Sums the mapped range.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ You do not need to include let f= in the byte count. That saves 6 bytes. \$\endgroup\$ – Mr. Xcoder Aug 12 '17 at 17:38
  • \$\begingroup\$ You also do not need Array(1...n). It can be n in(1...n).reduce... \$\endgroup\$ – Mr. Xcoder Aug 12 '17 at 17:39
  • \$\begingroup\$ So an anonymous function is good enough for golf? \$\endgroup\$ – idrougge Aug 14 '17 at 13:42
  • \$\begingroup\$ 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 \$\endgroup\$ – Mr. Xcoder Aug 14 '17 at 13:43
0
\$\begingroup\$

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!

\$\endgroup\$
  • 1
    \$\begingroup\$ >_> unimplemented codepage \$\endgroup\$ – ASCII-only Aug 1 '17 at 0:19
  • 1
    \$\begingroup\$ ...I just have to ask, why did you rearrange ASCII for your codepage? :P \$\endgroup\$ – ETHproductions Aug 1 '17 at 0:57
  • \$\begingroup\$ 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. \$\endgroup\$ – Zacharý Aug 1 '17 at 2:16
  • \$\begingroup\$ Also, what do you expect from a language that has 12- result in 1 rather than -1? \$\endgroup\$ – Zacharý Aug 1 '17 at 13:17
  • \$\begingroup\$ MY's codepage is now implemented, and MY is finally on TIO! \$\endgroup\$ – Zacharý Aug 21 '17 at 17:23
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

Recursiva, 10 bytes

smBa"I_Va"

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.