Range, Reverse, Sum!

21

1

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.

Comrade SparklePony

Posted 2017-07-31T23:17:43.860

Reputation: 5 784

More test case results (not numbered, sorry, but you can parse through and get their line number if you want): Try it online!

– Stephen – 2017-07-31T23:49:30.930

@StepHen >:D Charcoal is faster

– ASCII-only – 2017-08-01T00:36:49.143

Numbered – ASCII-only – 2017-08-01T00:38:48.603

1Relevant – Silvio Mayolo – 2017-08-01T01:12:09.937

1OEIS A062918 – Leaky Nun – 2017-08-01T06:37:31.173

4-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 – 2017-08-21T08:23:19.577

Answers

16

05AB1E, 3 bytes

Code

LíO

Uses the 05AB1E encoding. Try it online!

Explanation

L       # Range
 í      # Reverse
  O     # Sum

Adnan

Posted 2017-07-31T23:17:43.860

Reputation: 41 965

20dat explanation tho – ETHproductions – 2017-08-01T00:41:31.057

1@ETHproductions well Reverse should be Reverse each actually... – Erik the Outgolfer – 2017-08-01T08:31:11.883

@EriktheOutgolfer It's not vectorized? – ASCII-only – 2017-08-01T10:40:18.497

@ASCII-only 05AB1E vectorization is really 1 level deep, not ∞. Also just "reverse" is R, while í is "reverse each". – Erik the Outgolfer – 2017-08-01T10:43:22.930

12

Bash + GNU utils, 24

seq $1|rev|paste -sd+|bc

Try it online.

Explanation

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

Digital Trauma

Posted 2017-07-31T23:17:43.860

Reputation: 64 644

8

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
}

Brad Gilbert b2gills

Posted 2017-07-31T23:17:43.860

Reputation: 12 713

Is the 'possibly in parallel' required? Seems like you could get rid of a byte or two by omitting it. – Fund Monica's Lawsuit – 2017-08-02T16:17:23.900

@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 – 2017-08-05T15:49:04.763

Oh, so the key part is "each", not "(possibly in parallel)". Might be worth splitting them out, then. – Fund Monica's Lawsuit – 2017-08-05T22:28:32.630

@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 – 2017-08-06T14:59:50.933

8

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)

ETHproductions

Posted 2017-07-31T23:17:43.860

Reputation: 47 880

7

Retina, 41 36 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.

Neil

Posted 2017-07-31T23:17:43.860

Reputation: 95 035

@FryAmTheEggman Bah, I keep forgetting about that. – Neil – 2017-08-01T07:54:19.250

You don't need the in the .+¶ The match will match across lines – PunPun1000 – 2017-08-01T16:35:43.920

@PunPun1000 I did need it before FryAmTheEggman's fix! – Neil – 2017-08-01T17:31:00.880

I notice that O^$s`. to reverse the whole string also works. – Neil – 2017-11-25T17:20:45.697

6

Jelly, 4 bytes

Ṛ€ḌS

Try it online!

How?

Ṛ€ḌS - Link: n
Ṛ€   - reverse for €ach (in implicit range)
  Ḍ  - convert from decimal list (vectorises)
   S - sum

Jonathan Allan

Posted 2017-07-31T23:17:43.860

Reputation: 67 804

I KNEW there had to be a way to use Range implicitly, +1 – nmjcman101 – 2017-08-01T11:19:16.047

6

Haskell, 34 bytes

\n->sum$read.reverse.show<$>[1..n]

Simple and straightforward.

Silvio Mayolo

Posted 2017-07-31T23:17:43.860

Reputation: 1 817

6

C (gcc), 63 bytes

f(n){int t=0,c=n;for(;c;c/=10)t=t*10+c%10;return n?t+f(n-1):0;}

Try it online!

Leaky Nun

Posted 2017-07-31T23:17:43.860

Reputation: 45 011

5

cQuents, 4 bytes

;\r$

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)

Stephen

Posted 2017-07-31T23:17:43.860

Reputation: 12 293

5

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!

Adnan

Posted 2017-07-31T23:17:43.860

Reputation: 41 965

You can use import sys and sys.setrecursionlimit() if you want to handle larger numbers, in the tio header. – Mr. Xcoder – 2017-08-01T06:01:02.557

5

Brachylog, 4 bytes

⟦↔ᵐ+

Try it online!

Explanation

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

DanTheMan

Posted 2017-07-31T23:17:43.860

Reputation: 3 140

5

Röda, 56 41 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

user41805

Posted 2017-07-31T23:17:43.860

Reputation: 16 320

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 – 2017-08-02T07:31:25.503

@fergusq Thanks for the tips, my Röda has gone a bit rusty :) – user41805 – 2017-08-02T09:16:38.853

4

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

Kamil Drakari

Posted 2017-07-31T23:17:43.860

Reputation: 3 461

You don't need the trailing semi colon. I think using new int[r] and .Select((_,n)=>...) will save you bytes. – TheLethalCoder – 2017-08-01T08:15:24.693

@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 – 2017-08-01T12:19:30.420

4

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.

akostadinov

Posted 2017-07-31T23:17:43.860

Reputation: 211

1->n{ works as well. – Value Ink – 2017-08-15T18:27:03.750

1

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: https://codegolf.stackexchange.com/a/150636/21830

– Unihedron – 2017-12-14T17:50:38.707

@Unihedron, haha, I didn't know Ruby is so crazy to allow string ranges. Thanks. – akostadinov – 2017-12-14T18:53:25.030

Yes, ruby also has nifty features like ?a..?z and ?a1..?h8 (although you better be careful with the 2nd format :D) – Unihedron – 2017-12-14T19:19:20.233

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 – 2017-12-14T19:39:29.667

3

Mathematica, 47 bytes

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

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

J42161217

Posted 2017-07-31T23:17:43.860

Reputation: 15 931

Tr@*IntegerReverse@*Range – ngenisis – 2017-08-21T22:20:15.657

3

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!

notjagan

Posted 2017-07-31T23:17:43.860

Reputation: 4 011

since it's python 2, `` instead of str saves 3 bytes. – officialaimm – 2017-08-01T04:53:17.703

3

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

Justin Mariner

Posted 2017-07-31T23:17:43.860

Reputation: 4 746

1You know z2 on a flat array is the same as w, righ... uhm... excuse my inadequacy at Japt... – ETHproductions – 2017-08-01T00:43:39.343

6 bytes: õ_swÃx thanks to the new addition of N.s(f).

– Shaggy – 2017-08-15T16:00:33.320

Or even just õs xw for 5 bytes.

– Shaggy – 2017-08-15T16:04:22.200

@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 – 2017-08-15T16:15:06.187

@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 – 2017-08-15T16:29:22.513

3

Charcoal, 14 13 bytes

-1 byte thanks to Carlos Alejo

I∕…·⁰N«⁺ιI⮌Iκ

Try it online! Link is to verbose version.

Explanation

I                  Cast
  ∕     «           Reduce
   …·⁰N            Inclusive range from 0 to input as number
         ⁺          Plus
          ι         i
           I⮌Iκ   Cast(Reverse(Cast(k)))

ASCII-only

Posted 2017-07-31T23:17:43.860

Reputation: 4 687

You can save a byte by dropping the last ». By the way, where in the Charcoal wiki is the Reduce operator documented? – Charlie – 2017-08-01T06:04:48.630

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 – 2017-08-01T07:07:47.700

Also yeah I forgot why leaving out ending braces works lol – ASCII-only – 2017-08-01T07:08:31.483

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 – 2017-08-01T07:38:06.020

So why do you need the «? You don't need it for Map... – Neil – 2017-08-01T08:03:28.497

@Neil Because otherwise it's treated as normal divide since it's then a valid expression. Should I have another custom operator instead (btw this is the same for any () and all () even though they're not overloads :| sorry i'll change them if you think it's going to have a big effect) – ASCII-only – 2017-08-01T10:37:03.210

1@CarlosAlejo I've had a bit of free time so I've started documenting stuff, hope you like it! – Neil – 2017-08-03T13:31:45.633

@CarlosAlejo it's python style modulo so the format is exactly the same as with Python, also sent invite to what I think it's your GitHub – ASCII-only – 2017-08-03T14:01:22.833

@ASCII-only Wait until I start reporting bugs... – Neil – 2017-08-03T15:55:38.957

Well that's good as well isn't it, it means Charcoal will be less buggy – ASCII-only – 2017-08-03T17:38:13.783

@CarlosAlejo pls accept github invite tyvm – ASCII-only – 2017-08-08T01:18:16.337

@ASCII-only I didn't receive any invitation. My Github account is charliealejo. – Charlie – 2017-08-08T12:42:28.737

@CarlosAlejo done (also i invited "Carlos Alejo" who joined 13 days ago, I thought it was you) – ASCII-only – 2017-08-08T12:43:36.700

3

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

HatsuPointerKun

Posted 2017-07-31T23:17:43.860

Reputation: 1 891

Good job! You can spare some bytes by removing the header and putting "using namespace std" (check here https://tio.run/#cpp-gcc). I also think you could replace "auto t" with just "t" (?)

– koita_pisw_sou – 2017-08-01T06:33:59.683

Yeah, koita_pisw_sou is right about the first part. But you need the auto. – Zacharý – 2017-08-01T12:24:31.003

@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 – 2017-08-01T13:43:59.347

Yes, check the link I sent – koita_pisw_sou – 2017-08-01T13:44:43.687

(Whoops, I am not sure about the removing the header!) But I was referring to using namespace std; saving bytes. – Zacharý – 2017-08-01T15:00:37.837

You can use #import<string> to save a byte, but the bytes for the header still count. – Karl Napf – 2017-09-04T20:24:13.720

@KarlNapf From what i read, the import statement is non standard and doesn't work the same way between GCC and VC++ – HatsuPointerKun – 2017-09-04T21:59:37.227

Regarding code golfing, you're free to chose a specific compiler/interpreter and/or a specific implementation of a given language. Writing standard code shouldn't be a concern, only the bytecount should. :-) – scottinet – 2017-09-05T15:36:21.487

3

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

ბიმო

Posted 2017-07-31T23:17:43.860

Reputation: 15 345

3

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

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

Try it online!

Xcali

Posted 2017-07-31T23:17:43.860

Reputation: 7 671

26 bytes: map$r+=reverse,1..<>;say$r. – Denis Ibaev – 2017-12-29T09:35:32.237

Got it down even further using -p – Xcali – 2017-12-30T06:44:38.603

3

Magneson, 102 bytes

Source

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

Display Purposes Only

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

Isaac

Posted 2017-07-31T23:17:43.860

Reputation: 61

3

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

user41805

Posted 2017-07-31T23:17:43.860

Reputation: 16 320

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ý – 2017-08-01T14:57:24.353

7 bytes: +/⍎⌽⍕⍳⎕

– Adám – 2017-08-02T09:27:38.187

@Adám Thanks for the tip. Removing the ¨ was clever :) – user41805 – 2017-08-02T09:40:16.657

3

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

Erik the Outgolfer

Posted 2017-07-31T23:17:43.860

Reputation: 38 134

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ý – 2017-08-01T15:18:55.643

@Zacharý done... – Erik the Outgolfer – 2017-08-01T15:23:25.687

You don't need the , – Business Cat – 2017-08-01T17:36:09.390

@BusinessCat Ohhh used too much to GolfScript apparently... – Erik the Outgolfer – 2017-08-01T17:36:42.413

3

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

CoderCroc

Posted 2017-07-31T23:17:43.860

Reputation: 337

1Integer.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 – 2017-08-03T13:01:58.503

@KevinCruijssen Thank you for your valuable inputs. I'll update my answer. Thanks. :) – CoderCroc – 2017-08-03T13:22:43.613

2

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!

ATaco

Posted 2017-07-31T23:17:43.860

Reputation: 7 898

2

Pyth, 8 6 bytes

-2 bytes thanks to FryAmTheEggman!

sms_`h

Try it online!

notjagan

Posted 2017-07-31T23:17:43.860

Reputation: 4 011

1 byte longer version, sms_`dS, that does not abuse implicit U at the end. – Mr. Xcoder – 2017-08-01T06:44:16.077

2

Tcl, 66 bytes

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

Try it online!

sergiol

Posted 2017-07-31T23:17:43.860

Reputation: 3 055

2

Neim, 4 bytes

Δ)

Try it online!

Explanation

Δ )              for each element 1 to n (outputs list)
                reverse 
                sum 

space junk

Posted 2017-07-31T23:17:43.860

Reputation: 305

2Alternative solution: Ψ (create inclusive range, reverse each element, sum) – Okx – 2017-08-01T11:31:29.867

@Okx didn't know that the Ψ token existed! would have definitely used that in hindsight. real nice – space junk – 2017-08-01T12:01:46.423

2

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

Taylor Scott

Posted 2017-07-31T23:17:43.860

Reputation: 6 709

2

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!

Giacomo Garabello

Posted 2017-07-31T23:17:43.860

Reputation: 1 419

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 – 2017-09-05T15:47:29.277

2

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

Kaz

Posted 2017-07-31T23:17:43.860

Reputation: 372

2

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
  }

Unihedron

Posted 2017-07-31T23:17:43.860

Reputation: 1 115

1you can do (?1..gets).sum{...}) – akostadinov – 2017-12-14T18:54:41.500

2

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.

Giuseppe

Posted 2017-07-31T23:17:43.860

Reputation: 21 077

2

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

Unihedron

Posted 2017-07-31T23:17:43.860

Reputation: 1 115

1

Pyke, 7 bytes

SF`_b)s

Try it online!

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

Blue

Posted 2017-07-31T23:17:43.860

Reputation: 26 661

1

MATL, 5 bytes

:VPUs

Try it online!

Cinaski

Posted 2017-07-31T23:17:43.860

Reputation: 1 588

1

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.

Łukasz Rogalski

Posted 2017-07-31T23:17:43.860

Reputation: 131

1

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

Tornado547

Posted 2017-07-31T23:17:43.860

Reputation: 389

1

Pyt, 3 bytes

ř₫Ʃ

Try it online!

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

FantaC

Posted 2017-07-31T23:17:43.860

Reputation: 1 425

Dammit. You beat me to it. +1 – mudkip201 – 2018-02-22T03:55:33.120

@mudkip201 Yeah I feel like its almost a race to see who can get the most trivial arithmetic challenges answered – FantaC – 2018-02-22T14:56:19.487

0

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

nmjcman101

Posted 2017-07-31T23:17:43.860

Reputation: 3 274

1Shouldn't you make it [U]pend for completion's sake? – Zacharý – 2017-08-01T00:00:42.190

You right, all better. Thanks! – nmjcman101 – 2017-08-01T00:01:14.267

0

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!

Zacharý

Posted 2017-07-31T23:17:43.860

Reputation: 5 710

1ockquote>

_> unimplemented codepage

– ASCII-only – 2017-08-01T00:19:53.893

1...I just have to ask, why did you rearrange ASCII for your codepage? :P – ETHproductions – 2017-08-01T00:57:21.513

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ý – 2017-08-01T02:16:54.077

Also, what do you expect from a language that has 12- result in 1 rather than -1? – Zacharý – 2017-08-01T13:17:06.933

MY's codepage is now implemented, and MY is finally on TIO! – Zacharý – 2017-08-21T17:23:14.247

0

Ly, 31 bytes

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

Try it online!

LyricLy

Posted 2017-07-31T23:17:43.860

Reputation: 3 313

0

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.

SuperStormer

Posted 2017-07-31T23:17:43.860

Reputation: 927

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 – 2017-08-01T01:26:49.820

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 – 2017-08-02T08:59:14.607

1@Neil doesn't work for 999(produces 4153), probably because of octal literals getting added – SuperStormer – 2017-08-02T10:19:10.733

Bah, stupid octal literals. Best I can do in that case is n=>-eval(`-'${[...[...Array(n+1).keys()].join`'-'`].reverse().join``}'`). – Neil – 2017-08-02T11:35:21.660

0

Pari/GP, 43 bytes

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

Try it online!

alephalpha

Posted 2017-07-31T23:17:43.860

Reputation: 23 988

0

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

steenbergh

Posted 2017-07-31T23:17:43.860

Reputation: 7 772

0

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.

Mr. Xcoder

Posted 2017-07-31T23:17:43.860

Reputation: 39 774

0

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.

user202729

Posted 2017-07-31T23:17:43.860

Reputation: 14 620

0

Swift 3, 98 bytes

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

Sergii Martynenko Jr

Posted 2017-07-31T23:17:43.860

Reputation: 213

1Also String($0) can be "\($0)" to save a couple of bytes too. – Mr. Xcoder – 2017-08-12T17:37:55.377

0

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

AdmBorkBork

Posted 2017-07-31T23:17:43.860

Reputation: 41 581

0

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

Erik the Outgolfer

Posted 2017-07-31T23:17:43.860

Reputation: 38 134

0

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!

Giuseppe

Posted 2017-07-31T23:17:43.860

Reputation: 21 077

I know it's an old one but what about this for 82 bytes?

– JayCe – 2018-06-01T17:53:06.913

0

PHP, 39+1 bytes

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

Run as pipe with -nR.

Titus

Posted 2017-07-31T23:17:43.860

Reputation: 13 814

0

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!

jferard

Posted 2017-07-31T23:17:43.860

Reputation: 1 764

0

Common Lisp, 62 bytes

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

Try it online!

Renzo

Posted 2017-07-31T23:17:43.860

Reputation: 2 260

0

REXX, 46 bytes

arg n
s=0
do i=1 to n
  s=s+reverse(i)
  end
say s

idrougge

Posted 2017-07-31T23:17:43.860

Reputation: 641

0

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.

idrougge

Posted 2017-07-31T23:17:43.860

Reputation: 641

You do not need to include let f= in the byte count. That saves 6 bytes. – Mr. Xcoder – 2017-08-12T17:38:53.803

You also do not need Array(1...n). It can be n in(1...n).reduce... – Mr. Xcoder – 2017-08-12T17:39:27.477

So an anonymous function is good enough for golf? – idrougge – 2017-08-14T13:42:42.050

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 – 2017-08-14T13:43:24.027

0

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

zgrep

Posted 2017-07-31T23:17:43.860

Reputation: 1 291

0

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

Jakob

Posted 2017-07-31T23:17:43.860

Reputation: 2 428

0

Recursiva, 10 bytes

smBa"I_Va"

Try it online!

officialaimm

Posted 2017-07-31T23:17:43.860

Reputation: 2 739

0

J, 18 Bytes

+/(".@|.@":)"0>:i.

Explanation:

+/                 | Sum of
  (".@|.@":)       | Reverse
            "0     | Each member of
              >:i. | Integers from 1 to n inclusive

Bolce Bussiere

Posted 2017-07-31T23:17:43.860

Reputation: 970