Adding up the digits and the digits reversed

26

1

Given a number > 0, output the sum with all digits (1 .. n) concatenated and reversed and add them up. For example, with n = 6:

The numbers 1 to 6 concatenated:

123456

Reversed:

654321

Adding them up together will result in: 777777. Another example is n = 11:

1 2 3 4 5 6 7 8 9 10 11 > 1234567891011

and

11 10 9 8 7 6 5 4 3 2 1 > 1110987654321

Adding them up together will result in 2345555545332. This is also known as A078262.

Shortest code wins!

Lamaro

Posted 2016-02-22T21:11:02.640

Reputation: 781

Related. – Zgarb – 2016-02-22T21:21:19.597

Is there a bound to n, or do we have to support arbitrarily large integers? – LegionMammal978 – 2016-02-22T22:16:53.057

I think the default is "bounded by max(256,yourlanguagesdefaultintegertypelimit)". But it should be specified. – CalculatorFeline – 2016-02-22T22:20:34.833

@LegionMammal978 As high as your language supports. – Lamaro – 2016-02-22T22:43:33.957

Important test case: 10, which should give 23333333231. – Adnan – 2016-02-22T23:04:36.960

Answers

9

05AB1E, 7 bytes

LDRJsJ+

Try it online.

Explanation

LDRJsJ+

L        range from 1 .. input
 D       duplicate
  R      reverse
   JsJ   convert both arrays to strings
      +  add (coerces both strings to ints)

a spaghetto

Posted 2016-02-22T21:11:02.640

Reputation: 10 647

I feel very confused by the design choice that lead to + on lists doing a nested addition, while for strings it converts to ints and then adds. But I guess it worked out here! :P – FryAmTheEggman – 2016-02-22T21:35:19.213

@FryAmTheEggman I'm going to remove nested addition though. It has never been useful since the moment I've implemented it... – Adnan – 2016-02-22T21:41:34.910

3Sheesh, I leave PPCG for two hours and you rename yourself Aqua Tart while I'm gone... Oh, the life of a PPCG user. – ETHproductions – 2016-02-22T23:55:28.787

6

Jelly, 9 bytes

R,U$DF€ḌS

livecoding 

Lynn

Posted 2016-02-22T21:11:02.640

Reputation: 55 648

2Is it me or do I see that code secretly stealing some U$D? – gcampbell – 2016-05-21T08:20:11.597

5

CJam, 15 14 bytes

Thanks to Martin for shaving a byte!

ri,:)_W%si\si+

Try it online!

GamrCorps

Posted 2016-02-22T21:11:02.640

Reputation: 7 058

1 byte less if you flip the string instead of the numeric array: ri,:)s_W%i\i+ – Luis Mendo – 2016-02-23T01:23:22.663

Sorry, I think my version doesn't work for 10 – Luis Mendo – 2016-02-23T10:55:33.243

1This code is secretly happy. :) – Cyoce – 2016-02-24T00:08:27.813

4

Pyth, 12 10 bytes

ssMjLk_BSQ

Thanks to @FryAmTheEggman for 2 bytes!

Q is the input, S turns it into [1, 2, ..., input()], _B bifurcates it over _ (reverse) to create [rng, rev(rng)], jLk maps it over join by k (which is the "empty string" variable), sM maps int over this resulting array, and s finally calculates the sum.

Doorknob

Posted 2016-02-22T21:11:02.640

Reputation: 68 138

4

JavaScript (ES6), 70 67 64 bytes

a=>(z=[...Array(a)].map((b,c)=>c+1)).join``- -z.reverse().join``

Fixed to meet requirement, as old code was made under misunderstanding of the input.

Mwr247

Posted 2016-02-22T21:11:02.640

Reputation: 3 494

@TimmyD Added an explanation. – Mwr247 – 2016-02-22T21:52:32.947

@TimmyD OH! >_< My misunderstanding of the challenge is how... Yeah, I'll have to fix this. – Mwr247 – 2016-02-22T21:55:58.387

@TimmyD Took me long enough to get back online. It's fixed now, and thanks for catching that. – Mwr247 – 2016-02-23T16:53:59.393

As noted for another answer, this only works if the parameter a is between 1 and 12, that's really too little – edc65 – 2016-02-23T20:26:34.227

@edc65 Per OP's comment, that's big enough.

– Mwr247 – 2016-02-23T20:29:06.350

3

Python 3, 74

Saved 6 bytes thanks to DSM.

Nothing too exciting, join the ranges and then convert to ints and add them.

lambda x:sum(int(''.join(list(map(str,range(1,x+1)))[::i]))for i in(1,-1))

Morgan Thrapp

Posted 2016-02-22T21:11:02.640

Reputation: 3 574

3

Retina, 71

Because its blatantly the wrong tool for the job.

.+
$*a:$&$*
+`^(a+)a\b(.*)\b1(1+)$
$1 $& $3
 ?(\w)+ ?
$#1
\d+:?
$&$*c
c

Try it online.

Works for inputs up to 6, but the online interpreter times out after that.

Digital Trauma

Posted 2016-02-22T21:11:02.640

Reputation: 64 644

1You can shorten it to 74 by removing the last line and changing (c)+ to c. – daavko – 2016-02-22T22:52:36.770

@daavko yes, of course, thanks! – Digital Trauma – 2016-02-22T22:59:26.217

Also, $&$*c -> $*c and \d+:? -> \d+ and it's 70. And for some reason it keeps working... – daavko – 2016-02-22T23:03:43.107

3

JavaScript (ES6), 67 66 bytes

n=>(a=[...Array(n+1).keys()].slice(1)).join``- -a.reverse().join``

Yes, that's a space. Ugh. At least @Downgoat helped me save a byte.

Neil

Posted 2016-02-22T21:11:02.640

Reputation: 95 035

1You can remove the first + and make the + + -> - - to save a byte – Downgoat – 2016-02-23T01:07:53.777

n=>(a=[...Array(n)].map(_=>n--)).join- -a.reverse().join – edc65 – 2016-02-23T09:07:41.017

Note: using simple js arithmetic this is limited to values 1 .. 12 – edc65 – 2016-02-23T09:08:18.707

3

Jolf, 9 bytes

Try it here! Replace with \x10.

+P►γzjP_γ
    zj    range 1...j
   γ      γ = ^
  ►        ^ .join("")
 P         as a number
+     P_γ  and γ reversed

I may be able to golf it by moving around the type casting.

Conor O'Brien

Posted 2016-02-22T21:11:02.640

Reputation: 36 228

You beat pyth and doorknob! – Cyoce – 2016-02-26T00:05:02.900

@Cyoce so I did O_O – Conor O'Brien – 2016-02-26T00:05:33.183

2

05AB1E, 5 bytes

LJDR+

Explanation:

L     # Pushes an array containing 1 .. [implicit] input
 J    # Join the array to a string (eg. [1, 2, 3] -> 123)
  D   # Duplicate the array
   R  # Reverse the duplicate
    + # Add them together

Try it online!

Okx

Posted 2016-02-22T21:11:02.640

Reputation: 15 025

2

Seriously, 12 bytes

,R;Rεj≈@εj≈+

Try it online!

Explanation:

,R;Rεj≈@εj≈+
,R;           push two copies of range(1, input()+1)
   R          reverse one copy
    εj≈@εj≈   concatenate both and cast both to ints
           +  add

Mego

Posted 2016-02-22T21:11:02.640

Reputation: 32 998

2

PowerShell, 35 bytes

param($a)+-join(1..$a)+-join($a..1)

Converts the input to ranges with .., then -joins them together, and adds 'em up.

Will work for input numbers up to 138, while 139 will give Infinity, and 140 and above will barf out an awesomely verbose casting error:

Cannot convert value "12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413
5136137138139140" to type "System.Int32". Error: "Value was either too large or too small for an Int32."

AdmBorkBork

Posted 2016-02-22T21:11:02.640

Reputation: 41 581

2

JavaScript (ES6), 99

This adds digit by digit, so it can handle numbers well above the 53 bits of precision of javascript

n=>eval("for(a=b=c=r='';n;a+=n--)b=n+b;for(i=a.length;i--;r=c%10+r)c=(c>9)-(-a[i]-b[i]);c>9?1+r:r")

Test

f=n=>eval("for(a=b=c=r='';n;a+=n--)b=n+b;for(i=a.length;i--;r=c%10+r)c=(c>9)-(-a[i]-b[i]);c>9?1+r:r")

// Less golfed
U=n=>{
  for(a=b=c=r=''; n; --n)
      b=n+b, a+=n;
  for(i=a.length; i--; r = c%10+r) 
      c=(c>9)-(-a[i]-b[i]);
  return c>9? 1+r : r;
}

function test() {
  var n=+I.value
  R.textContent=f(n)
}  

test()
N: <input id=I value=11 oninput="test()"> -> <span id=R></span>

edc65

Posted 2016-02-22T21:11:02.640

Reputation: 31 086

Doesn't seem to work for 9. Also, why not initialise c with the other variables? – Neil – 2016-02-22T22:54:27.367

You have my upvote. – Neil – 2016-02-23T09:24:43.187

2

MATL, 13 bytes

:tP2:"wVXvU]+

EDIT (May 20, 2016) The code in the link uses Xz instead of Xv, owing to recent changes in the language.

Try it online!

:                % range [1,2,...,n], where n is input
 tP              % duplicate and flip
   2:"     ]     % do this twice
      w          % swap
       V         % convert array of numbers to string with numbers and spaces
        Xv       % remove spaces
          U      % convert to number
            +    % add the two numbers

Luis Mendo

Posted 2016-02-22T21:11:02.640

Reputation: 87 464

Doesn't work for 11 or 10. (Hint: reverse range before converting to string.) – Mama Fun Roll – 2016-02-23T03:32:26.977

@ӍѲꝆΛҐӍΛПҒЦꝆ Thanks! Corrected – Luis Mendo – 2016-02-23T09:57:09.380

Great! Have an upvote. – Mama Fun Roll – 2016-02-24T02:00:12.240

2

Pyth - 8 bytes

siRT_BSQ

Try it online here.

Maltysen

Posted 2016-02-22T21:11:02.640

Reputation: 25 023

2I think this doesn't work for 10 or 11 – Luis Mendo – 2016-02-23T09:59:19.890

2

Brachylog, 24 bytes

:1fLrcC,Lc+C=.,{,.:1re?}

Fatalize

Posted 2016-02-22T21:11:02.640

Reputation: 32 976

1

R, 34 60 64 bytes

f=pryr::f;g=f(as.numeric(paste(x,collapse='')));f(g(1:n)+g(n:1))

Assumes pryr package is installed. this gives f as a shorthand for creating functions.

Edit added 26 bytes but returns a function that works, not something entirely wrong.

Edit added another 4 bytes to handle cases above n=10 where strtoi (previously used) was returning NA

mnel

Posted 2016-02-22T21:11:02.640

Reputation: 826

1

Bash + coreutils, 39

eval echo {1..$1} + {$1..1}|tr -d \ |bc

Or:

bc<<<`eval printf %s {1..$1} + {$1..1}`

Ideone.

Digital Trauma

Posted 2016-02-22T21:11:02.640

Reputation: 64 644

1

Perl 6, 25 bytes

{([~] @_=1..$^n)+[R~] @_}
{
  (
    [~]           # reduce with the string concatenation infix op:
    @_ = 1 .. $^n # the range 1 to input ( also stored in @_ )
  )
  +               # add that to
  [R~] @_         # @_ reduced in reverse
}

Usage:

for 6, 11, 12 -> $n {
  say {([~] @_=1..$^n)+[R~] @_}( $n )
}
777777
2345555545332
244567776755433

Brad Gilbert b2gills

Posted 2016-02-22T21:11:02.640

Reputation: 12 713

I think you can do with $n instead of $^n – andlrc – 2016-02-22T22:56:52.570

@dev-null Not if I want it to be an input to the block. the -> $n { is a different one to $^n. – Brad Gilbert b2gills – 2016-02-22T22:58:57.800

1

Dyalog APL, 17 bytes

+/⍎¨∊¨⍕¨¨x(⌽x←⍳⎕)

prompt for input
' enumerate until input
x← store list in x
reverse x
x() prepend reversed list with original list
⍕¨¨ convert each number of each list into character string
∊¨ make each list of character strings into single character strings
⍎¨ convert each character string into a number
+/ sum the two numbers.

Adám

Posted 2016-02-22T21:11:02.640

Reputation: 37 779

1

Lua, 53 Bytes

This program takes n as a command-line argument.

s=""r=s for i=1,arg[1]do r,s=i..r,s..i end print(s+r)

I assumed that outputing a number with a decimal part of 0 was okay (in the form 777777.0 because this is the default way to output a number in lua (there's no distinction between integer and float)

Katenkyo

Posted 2016-02-22T21:11:02.640

Reputation: 2 857

Its not the string itself that is reversed, but the digits. Your code fails on n >= 10. – Moop – 2016-02-23T07:47:16.080

@Moop Corrected at the price of 1 byte ^^'. Thanks for the comment ^^' – Katenkyo – 2016-02-23T08:00:47.997

You can save 3 more using ... instead of arg[1] nice work on the reverse concat for r, didn't think of that in my answer. +1 – Moop – 2016-02-23T08:03:22.627

@Moop I saw your post, nice use of it, I didn't even know you could use ... like that! I'll keep it this way for the moment, because I can't use anything else than the online compiler and it can't handle that(I'd like to test it and play with it a little bit before putting it in a answer :)) – Katenkyo – 2016-02-23T08:07:30.803

1

Lua, 57

a=''b=''for i=1,...do a=a..i b=b.. ...-i+1 end return a+b

Moop

Posted 2016-02-22T21:11:02.640

Reputation: 723

1

Perl 5, 37 bytes

25 bytes, plus 1 for -p and 11 for -MList::Gen

$_=<[.]1..$_>+<[R.]1..$_>

Previous solution, 40 bytes: 39, plus one for -p

@a=reverse@_=1..$_;$"=$\;$_="@a"+"@_"

msh210

Posted 2016-02-22T21:11:02.640

Reputation: 3 094

1

Perl, 36 bytes

Includes +1 for -p

Run with on STDIN

perl -p reverse.pl <<< 6

reverse.pl

$_=eval join"",map{abs||"+"}-$_..$_

Ton Hospel

Posted 2016-02-22T21:11:02.640

Reputation: 14 114

0

QBIC, 24 bytes, nc

:[a|B=B+!b$]_FB|?!A!+!B!

Explanation

:       Read command line argument as 'a'
        Generate the sequence 1 ... a
[a|     For b = 1 to a step 1
B=B+!b$ Add b cast to string to the end of B$ (starts out empty)
]       Ends the FOR loop
_FB|    Reverse (Flip) B$ and assign the result to A$
?       Show on screen
!A!+!B! A$ cast to num + B$ cast to num

Non-competing, the _F was implemented way after this challenge was posted.

steenbergh

Posted 2016-02-22T21:11:02.640

Reputation: 7 772

0

Pushy, 10 bytes

RV@KjOjv+#

Try it online!

RV    \ Push the range to both stacks.
@Kj   \ Reverse and join the first stack
Oj    \ Join the second stack
v+    \ Sum the two resulting integers
#     \ Print result

FlipTack

Posted 2016-02-22T21:11:02.640

Reputation: 13 242

0

Mathematica, 64 bytes

Plus@@FromDigits/@#&[""<>ToString/@#&/@{#,Reverse@#}&[Range@#]]&

CalculatorFeline

Posted 2016-02-22T21:11:02.640

Reputation: 2 608

0

Retina, 80 bytes (ISO 8859-1 encoding)

'+
$0¶$0
+`^(('+)')
$2 $1
+`('('+))$
$1 $2
(')+( |$)?
$#1
(\d+)¶(\d+)
$1$*'$2$*'

IO is in unary with ' as the counting character. In theory supports any integer you throw at it, in practice...online interpreter refuses to process anything larger than 6 (unary '''''').

Try it online!
Try it online! (decimal IO - 91 bytes)

daavko

Posted 2016-02-22T21:11:02.640

Reputation: 824

0

, 12 chars / 15 bytes

⨭⟮⩤⁽1ï⟯⨝,Ⅰᴚ⨝

Try it here (Firefox only).

Meh.

Explanation

Takes a range [1,input], joins it; takes that same range, reverses it, then joins it; the sum of both ranges is the result.

Mama Fun Roll

Posted 2016-02-22T21:11:02.640

Reputation: 7 234

0

Ruby, 40 characters

->n{eval (l=[*1..n])*''+?++l.reverse*''}

Sample run:

irb(main):001:0> ->n{eval (l=[*1..n])*''+?++l.reverse*''}[11]
=> 2345555545332

irb(main):002:0> ->n{eval (l=[*1..n])*''+?++l.reverse*''}[6]
=> 777777

manatwork

Posted 2016-02-22T21:11:02.640

Reputation: 17 865

0

C#, 126 bytes

using System.Linq;a=>{var b=Enumerable.Range(1,a);return long.Parse(string.Concat(b))+long.Parse(string.Concat(b.Reverse()));}

Could possibly be golfed further. Not really sure.

LegionMammal978

Posted 2016-02-22T21:11:02.640

Reputation: 15 731

0

Groovy, 42 39 characters

{[1..it,it..1]*.join()*.toLong().sum()}

Sample run:

groovy:000> ({[1..it,it..1]*.join()*.toLong().sum()})(11)
===> 2345555545332

groovy:000> ({[1..it,it..1]*.join()*.toLong().sum()})(6)
===> 777777

manatwork

Posted 2016-02-22T21:11:02.640

Reputation: 17 865

0

Groovy, 112 characters

def r(n){if(n==1){return n;};return n+''+r(n-1)};n=6;s=r(args[0].toLong());print s.toLong()+s.reverse().toLong()

run with:

groovy filename.groovy *input*

Xgongiveittoya

Posted 2016-02-22T21:11:02.640

Reputation: 111

0

Perl 6, 25 bytes

Either one works

{([~] 1..$^n)+[R~] 1..$n}
{([~] 1..$^n)+[~] $n...1}

Hotkeys

Posted 2016-02-22T21:11:02.640

Reputation: 1 015

0

Haskell, 57 56 48 bytes

This could probably be golfed a bit more, but here it goes:

f x=read y+(read.reverse$y)where y=[1..x]>>=show

Edit: shaved off a space before the where.

Ryan McCleary

Posted 2016-02-22T21:11:02.640

Reputation: 61