Triangle a number!

28

2

We are used to the term "squaring" n to mean calculating n2. We are also used to the term "cubing" n to mean n3. That being said, why couldn't we also triangle a number?

How to triangle a number?

  • First off, let's pick a number, 53716.

  • Position it in a parallelogram, whose side length equals the number of digits of the number, and has two sides positioned diagonally, as shown below.

        53716
       53716
      53716
     53716
    53716
    
  • Now, we want to ∆ it, right? To do so, crop the sides that do not fit into a right-angled triangle:

        5
       53
      537
     5371
    53716
    
  • Take the sums of each row, for this example resulting in [5, 8, 15, 16, 22]:

        5  -> 5
       53  -> 8
      537  -> 15
     5371  -> 16
    53716  -> 22
    
  • Sum the list [5, 8, 15, 16, 22], resulting in 66. This is the triangle of this number!

Specs & Rules

  • The input will be a non-negative integer n (n ≥ 0, n ∈ Z).

  • You may take input and provide output by any allowed mean.

  • Input may be formatted as an integer, a string representation of the integer, or a list of digits.

  • Default loopholes disallowed.

  • This is , so the shortest code in bytes wins!

More Test Cases

Input -> Output

0 -> 0
1 -> 1
12 -> 4
123 -> 10
999 -> 54 
100000 -> 6
654321 -> 91

Inspiration. Explanations are encouraged!

Mr. Xcoder

Posted 2017-08-04T19:49:19.347

Reputation: 39 774

are you sure that 645321 -> 91 ? – Rod – 2017-08-04T19:52:48.830

@Rod Sorry, you are right. I wrote 645321 instead of 654321. – Mr. Xcoder – 2017-08-04T19:54:35.623

1Can I take input as a list of digits? – totallyhuman – 2017-08-04T20:07:19.867

@totallyhuman Yes, see the second spec. – Mr. Xcoder – 2017-08-04T20:08:03.363

Why the downvote? I don't mind being downvoted, I just want to improve the challenge if anyone has suggestions. – Mr. Xcoder – 2017-08-05T09:33:08.180

1Interesting challenge. Glad you were inspired by mine! – Gryphon – 2017-08-05T23:09:07.710

Answers

17

Haskell, 13 bytes

sum.scanl1(+)

Try it online!

Takes input as list of digits. Calculates the cumulative sums then sums them.

H.PWiz

Posted 2017-08-04T19:49:19.347

Reputation: 10 962

12

Brain-Flak, 65, 50, 36 bytes

([])({<{}>{<({}[()])>[]}{}<([])>}{})

Try it online!

After lots of revising, I'm now very proud of this answer. I like the algorithm, and how nicely it can be expressed in brain-flak.

Most of the byte count comes from handling 0's in the input. In fact, if we could assume there were no 0's in the input, it would be a beautifully short 20-byte answer:

({{<({}[()])>[]}{}})

Try it online!

But unfortunately, brain-flak is notorious for bad handling of edge cases.

Explanation

First, an observation of mine:

If the input is n digits long, the first digit will appear in the triangle n times, the second digit will appear n-1 times, and so on onto the last digit, which will appear once. We can take advantage of this, since it's really easy to calculate how many digits of input are left in brain-flak, namely

[]

So here's how the code works.

# Push the size of the input (to account for 0's)
([])

# Push...
(

    # While True
    {

        # Pop the stack height (evaluates to 0)
        <{}>

        # For each digit *D*...

        # While true
        {

            # Decrement the counter (the current digit we're evaluating), 
            # but evaluate to 0
            <({}[()])>

            # Evaluate the number of digits left in the input
            []

        # Endwhile
        }

        # This whole block evaluates to D * len(remaining_digits), but 
        # without affecting the stack

        # Since we looped D times, D is now 0 and there is one less digit.
        # Pop D (now 0)
        {}

        # Push the stack height (again, evaluating it as 0)
        <([])>

    # End while
    }

    # Pop a 0 off (handles edge case of 0)
    {}

# end push
)

James

Posted 2017-08-04T19:49:19.347

Reputation: 54 537

My tip here can save you two bytes

– Post Rock Garf Hunter – 2017-08-05T04:18:52.243

12

Husk, 2 bytes

Thanks @H.PWiz for -2 bytes!

Σ∫

Try it online!

"Ungolfed"/Explained

Σ    -- sum all
 ∫   -- prefix sums

ბიმო

Posted 2017-08-04T19:49:19.347

Reputation: 15 345

11

Pyth - 6 4 bytes

ss._

Try it online here.

Nice 6 byte one that doesn't use prefix builtin:

s*V_Sl

Maltysen

Posted 2017-08-04T19:49:19.347

Reputation: 25 023

Nice! The best I could come up with is twice as long: s.e*bhk_ – Digital Trauma – 2017-08-04T21:10:16.757

10

MATL, 3 bytes

Yss

Try it online!

Takes the input as a list of digits.

James

Posted 2017-08-04T19:49:19.347

Reputation: 54 537

8

Haskell, 25 bytes

Takes input as list of digits

f[]=0
f x=sum x+f(init x)

Try it online!

Haskell, 41 bytes

Takes input as string representation

f[]=0
f x=sum(map(read.(:[]))x)+f(init x)

Try it online!

Post Rock Garf Hunter

Posted 2017-08-04T19:49:19.347

Reputation: 55 382

8

Jelly, 3 bytes

+\S

Try it online! Uses the same technique as my Japt answer: cumulative addition, then sum.

ETHproductions

Posted 2017-08-04T19:49:19.347

Reputation: 47 880

Oh, of course! :) – Jonathan Allan – 2017-08-04T20:25:20.763

7

Japt, 7 6 4 bytes

å+ x

Try it online!

Explanation

å+ x    Implicit: input = digit list
å+      Cumulative reduce by addition. Gives the sum of each prefix.
   x    Sum.

Old solution:

å+ ¬¬x

Try it online!

Explanation

å+ ¬¬x   Implicit: input = string
å+       Cumulative reduce by concatenation. Gives the list of prefixes.
   ¬     Join into a single string of digits.
    ¬    Split back into digits.
     x   Sum.
         Implicit: output result of last expression

ETHproductions

Posted 2017-08-04T19:49:19.347

Reputation: 47 880

Uh sandbox much? Or you read the question, wrote code and posted it all within one minute?! – Jonathan Allan – 2017-08-04T19:54:12.367

@JonathanAllan This was not sandboxed. It is much easier than you might think. – Mr. Xcoder – 2017-08-04T19:55:01.517

1Uh, well I cant even read the question in the time it took – Jonathan Allan – 2017-08-04T19:55:30.940

@JonathanAllan No sandbox reading, just happened to catch the question just after it was posted and come up with an algorithm almost immediately. – ETHproductions – 2017-08-04T19:58:48.360

Welp it took me ~4min to read the question, so +1 for speed-reading/speed-understanding :) – Jonathan Allan – 2017-08-04T19:59:46.780

It's really not as hard as it looks: I just looked at the example and noticed that he was just summing of the digits of each prefix – ETHproductions – 2017-08-04T20:00:39.997

Yeah - exactly what I did in my answer. – Jonathan Allan – 2017-08-04T20:01:13.487

7

Brain-Flak, 28 bytes

(([]){[{}]({}<>{})<>([])}{})

Try it online!

14 bytes if we don't need to support zeros (which we do)

({({}<>{})<>})

Try it online!

DJMcMayhem has a cool answer here you should check out. Unfortunately for him I wasn't about to let him win at his own language :P

How does it work?

Lets start with the simple version.

({({}<>{})<>})

The main action here is ({}<>{})<>, that takes the top of the left stack and adds to to the top of the right stack. By looping this operation we sum up the current stack (until it hits a zero) placing the sum on the off stack. That's pretty mundane, the interesting part is that we sum up the results of all these runs as our result. This will calculate the desired value. Why? Well lets take a look at an example, 123. On the first grab we just get 1 so our value is 1

1

On the next grab we return 1 plus the 2

1
1+2

On the last run we have all three together

1
1+2
1+2+3

Do you see the triangle? The sum of all the runs is the "triangle" of the list.


Ok but now we need it to work for zeros, here I used the same trick as DJMcMayhem, plus some fancy footwork. Instead of looping until we hit a zero we loop until the stack is empty.

([])({<{}>({}<>{})<><([])>}{})

I then used this tip, written by none other than yours truly, to golf off another 2 bytes.

(([]){[{}]({}<>{})<>([])}{})

And there we have it. I would be surprised if there was a shorter solution, but then again stranger things have happened.

Post Rock Garf Hunter

Posted 2017-08-04T19:49:19.347

Reputation: 55 382

Unfortunately for him I wasn't about to let him win at his own language :P I expect nothing less from you. :D – James – 2017-08-05T17:36:48.897

6

JavaScript (ES6), 28 bytes

a=>a.map(d=>t+=c+=d,t=c=0)|t

Takes input as a list of digits.

ETHproductions

Posted 2017-08-04T19:49:19.347

Reputation: 47 880

5

Python 3, 37 bytes

f=lambda n:len(n)and sum(n)+f(n[:-1])

Try it online!

Business Cat

Posted 2017-08-04T19:49:19.347

Reputation: 8 927

5...Why the downvote? – Business Cat – 2017-08-04T20:36:32.150

I think you could change len to sum as well, though I don't believe that helps anything. – ETHproductions – 2017-08-04T20:39:31.180

@ETHproductions Yeah. I was hoping I could make use of the fact that sum([]) is 0, but nothing was quite coming together... there might be a way though – Business Cat – 2017-08-04T20:41:57.540

Didn't see this otherwise I'd have given you my improvement. – Jonathan Allan – 2017-08-04T20:57:20.843

@JonathanAllan No worries :P – Business Cat – 2017-08-04T22:35:54.147

Funny that I ended up with a similar one only that it takes string and is longer.. :D – officialaimm – 2017-08-05T06:16:11.927

5

C# (.NET Core), 59 bytes

using System.Linq;N=>N.Reverse().Select((d,i)=>i*d+d).Sum()

Try it online!

Substantially different from the other C# answers. Input is a list of digits. All test cases included in the TIO link.

Could save a bunch of bytes if allowed to take input as a backwards list of digits with leading 0.

Kamil Drakari

Posted 2017-08-04T19:49:19.347

Reputation: 3 461

Nice idea! Some fierce codegolfing in C#. – Grzegorz Puławski – 2017-08-04T20:55:06.263

Nice solution! But isn't the input specified to be a non-negative number, not a list of digits? – Ian H. – 2017-08-05T07:03:40.310

@IanH. Rule 2: You may take input and provide output by any allowed mean. When it comes to the format, you can take the input as an integer, as a String representation of the integer or as a list of digits. – Kamil Drakari – 2017-08-05T11:59:00.523

5

Python 3, 35 bytes

I just noticed that this is only really a slight golf of Business Cat's answer in the end though!

f=lambda a:a>[]and sum(a)+f(a[:-1])

Try it online!

Jonathan Allan

Posted 2017-08-04T19:49:19.347

Reputation: 67 804

Funny that I ended up with a similar one only that it takes string and is longer.. :D – officialaimm – 2017-08-05T06:15:56.227

4

J, 7 bytes

[:+/+/\

Try it online! Takes a list of digits, such as f 6 5 4 3 2 1.

Explanation

[:+/+/\    (for explanation, input = 6 5 4 3 2 1)
      \    over the prefixes of the input:
     /         reduce:
    +              addition (summation)
           this gives is the cumulative sum of the input:  6 11 15 18 20 21
[:         apply to the result:
  +/           summation
           this gives the desired result:   90

A little more true to the original problem would be [:+/@,]/, which is "sum" (+/) the flattened (,) prefixes of the input (]\).

Conor O'Brien

Posted 2017-08-04T19:49:19.347

Reputation: 36 228

4

Vim, 60 59 32 keystrokes

Thanks a lot @CowsQuack for the tip with the recursive macro and the h trick, this saved me 27 bytes!

qqYp$xh@qq@qVHJ:s/./&+/g⏎
C<C-r>=<C-r>"0⏎

Try it online!

Ungolfed/Explained

This will build the triangle like described (only that it keeps it left-aligned):

qq       q    " record the macro q:
  Yp          "   duplicate the line
    $x        "   remove last character
      h       "   move to the left (this is solely that the recursive macro calls stop)
       @q     "   run the macro recursively
          @q  " run the macro

The buffer looks now like this:

53716
5371
537
53
5

Join all lines into one and build an evaluatable expression from it:

VH             " mark everything
  J            " join into one line
   :s/./&+/g⏎  " insert a + between all the characters

The " register now contains the following string (note missing 0):

5+3+7+1+6+ +5+3+7+1+ +5+3+7+ +5+3+ +5+ +

So all we need to do is append a zero and evaluate it:

 C                " delete line and store in " register
  <C-r>=       ⏎  " insert the evaluated expression from
        <C-r>"    " register "
              0   " append the missing 0

inside vim

ბიმო

Posted 2017-08-04T19:49:19.347

Reputation: 15 345

You can use & (the whole match) instead of \1 in the substitute command – user41805 – 2017-08-07T12:59:07.233

1qqYp$xq:exe"norm".col('.')."@q"⏎ can become qqYp$xh@qq@q. This recursive macro will encounter a breaking error when there is one character on the line, after which it will stop. – user41805 – 2017-08-07T13:15:37.207

So the substitution can just become :s/./&+/g. Also :%j⏎ can become V{J. And, Di can become C (I've already commented about this in another one of your Vim answers). Try it online!

– user41805 – 2017-08-07T13:21:23.513

3

Perl 5, 19 + 1 (-p) = 20 bytes

s/./$\+=$p+=$&/ge}{

Try it online!

How?

$\ holds the cumulative total, $p holds the total of the digits on the current line. Each line of the parallelogram is simply the previous line with the next digit of the number appended. Therefore, it is the sum of the previous line plus the new digit. This iterates over all of the digits, calculating the sums as it goes. The actual substitution is irrelevant; it's just a means to iterate over the digits without creating an actual loop. At the end, $\ is printed implicitly by the -p option.

Xcali

Posted 2017-08-04T19:49:19.347

Reputation: 7 671

3

Python 2, 49 45 bytes

-4 bytes thanks to Mr. Xcoder.

lambda n:sum(-~i*n[~i]for i in range(len(n)))

Try it online!

Takes input as a list of digits.

totallyhuman

Posted 2017-08-04T19:49:19.347

Reputation: 15 378

3

Bash + GNU utilities, 32 24

tac|nl -s*|paste -sd+|bc

Input read from STDIN.

Update: I see the input may be given as a list of digits. My input list is newline-delimited.

Try it online.

Explanation

tac                       # reverse digit list
   |nl -s*                # prefix line numbers; separate with "*" operator
          |paste -sd+     # join lines onto one line, separated with "+" operator
                     |bc  # arithmetically evaluate

Digital Trauma

Posted 2017-08-04T19:49:19.347

Reputation: 64 644

3

APL, 4 bytes

+/+\

This takes the input as a list of digits, e.g.:

      (+/+\) 5 3 7 1 6
66

Explanation

+/    sum of
  +\  partial sums of input

marinus

Posted 2017-08-04T19:49:19.347

Reputation: 30 224

3

Taxi, 1478 bytes

Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.[a]Switch to plan "b" if no one is waiting.Pickup a passenger going to The Babelfishery.Go to Zoom Zoom:n 1 l 3 r.1 is waiting at Starchild Numerology.Go to Starchild Numerology:w 4 l 2 r.Pickup a passenger going to Addition Alley.Go to Addition Alley:w 1 r 3 r 1 r 1 r.Pickup a passenger going to Addition Alley.Go to The Babelfishery:n 1 r 1 r.Go to Chop Suey:n 6 r 1 l.Switch to plan "a".[b]Go to Addition Alley:n 1 l 2 l.Pickup a passenger going to Cyclone.[c]Go to Zoom Zoom:n 1 l 1 r.Go to Cyclone:w.Pickup a passenger going to The Underground.Pickup a passenger going to Multiplication Station.Go to The Babelfishery:s 1 l 2 r 1 r.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:n 1 r 2 l.Pickup a passenger going to Addition Alley.Go to The Underground:n 2 l 1 r.Switch to plan "d" if no one is waiting.Pickup a passenger going to Cyclone.Go to Addition Alley:n 3 l 1 l.Switch to plan "c".[d]Go to Addition Alley:n 3 l 1 l.[e]Pickup a passenger going to Addition Alley.Go to Zoom Zoom:n 1 l 1 r.Go to Addition Alley:w 1 l 1 r.Pickup a passenger going to Addition Alley.Switch to plan "f" if no one is waiting.Switch to plan "e".[f]Go to Zoom Zoom:n 1 l 1 r.Go to Addition Alley:w 1 l 1 r.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:n 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.

Try it online!

Un-golfed:

[ Pickup stdin and split into digits ]
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to Chop Suey.
Go to Chop Suey: north 1st right 1st left 4th right 1st left.
[a]
[ Count the digits ]
Switch to plan "b" if no one is waiting.
Pickup a passenger going to The Babelfishery.
Go to Zoom Zoom: north 1st left 3rd right.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: west 4th left 2nd right.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: west 1st right 3rd right 1st right 1st right.
Pickup a passenger going to Addition Alley.
Go to The Babelfishery: north 1st right 1st right.
Go to Chop Suey: north 6th right 1st left.
Switch to plan "a".
[b]
Go to Addition Alley: north 1st left 2nd left.
Pickup a passenger going to Cyclone.
[c]
[ Multiply each digits by Len(stdin)-Position(digit) ]
Go to Zoom Zoom: north 1st left 1st right.
Go to Cyclone: west.
Pickup a passenger going to The Underground.
Pickup a passenger going to Multiplication Station.
Go to The Babelfishery: south 1st left 2nd right 1st right.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: north 1st right 2nd left.
Pickup a passenger going to Addition Alley.
Go to The Underground: north 2nd left 1st right.
Switch to plan "d" if no one is waiting.
Pickup a passenger going to Cyclone.
Go to Addition Alley: north 3rd left 1st left.
Switch to plan "c".
[d]
Go to Addition Alley: north 3rd left 1st left.
[e]
[ Sum all the products ]
Pickup a passenger going to Addition Alley.
Go to Zoom Zoom: north 1st left 1st right.
Go to Addition Alley: west 1st left 1st right.
Pickup a passenger going to Addition Alley.
Switch to plan "f" if no one is waiting.
Switch to plan "e".
[f]
[ Output the results ]
Go to Zoom Zoom: north 1st left 1st right.
Go to Addition Alley: west 1st left 1st right.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: north 1st right 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st left 1st right.

Engineer Toast

Posted 2017-08-04T19:49:19.347

Reputation: 5 769

2

SNOBOL4 (CSNOBOL4), 79 bytes

	N =INPUT
D	N LEN(1) . D REM . N	:F(O)
	X =X + D
	Y =Y + X	:(D)
O	OUTPUT =Y
END

Try it online!

Input from stdin, output to stdout.

Giuseppe

Posted 2017-08-04T19:49:19.347

Reputation: 21 077

2

Python 2, 56 bytes

lambda x:sum(i*int(`x`[-i])for i in range(1,1+len(`x`)))

Try it online!

Rod

Posted 2017-08-04T19:49:19.347

Reputation: 17 588

54 bytes or 45 bytes with input as lists oft digits. – ovs – 2017-08-04T20:11:47.607

2

Jelly,  5  4 bytes

Ṛæ.J

A monadic link taking a list of decimal digits and returning the triangle of the number that list represents.

Try it online!

How?

Ṛæ.J - Link: list of numbers (the decimal digits), d   e.g. [9,4,5,0]
Ṛ    - reverse d                                            [0,5,4,9]
   J - range(length(d))                                     [1,2,3,4]
 æ.  - dot-product            (0*1 + 5*2 + 4*3 + 9*4 = 58)  58

Jonathan Allan

Posted 2017-08-04T19:49:19.347

Reputation: 67 804

I had thought removing would still work. Pity... – ETHproductions – 2017-08-04T20:04:54.040

@ETHproductions ...and yet there's a built-in to help! – Jonathan Allan – 2017-08-04T20:11:55.793

...okay, wow... – ETHproductions – 2017-08-04T20:14:07.460

@ETHproductions ooops had to reverse it >_< – Jonathan Allan – 2017-08-04T20:19:55.203

2

Java 8, 53 bytes

I implemented a lambda for each acceptable input type. They each iterate through the number's digits, adding the proper multiple of each to an accumulator.

Integer as input (53 bytes)

Lambda from Integer to Integer:

n->{int s=0,i=1;for(;n>0;n/=10)s+=n%10*i++;return s;}

String representation as input (72 bytes)

Lambda from String to Integer:

s->{int l=s.length(),n=0;for(int b:s.getBytes())n+=(b-48)*l--;return n;}

Digit array as input (54 bytes)

Lambda from int[] (of digits, largest place value first) to Integer:

a->{int l=a.length,s=0;for(int n:a)s+=n*l--;return s;}
  • -7 bytes thanks to Olivier Grégoire

Jakob

Posted 2017-08-04T19:49:19.347

Reputation: 2 428

1a->{int l=a.length,s=0;for(int n:a)s+=n*l--;return s;} 54 bytes for the array version. – Olivier Grégoire – 2017-08-23T22:41:24.663

2

Retina, 13 bytes

.
$`$&
.
$*
1

Try it online! Link includes test cases. Explanation: The first stage generates all the prefixes of the original number, the second stage converts each digit to unary, and the third stage takes the total.

Neil

Posted 2017-08-04T19:49:19.347

Reputation: 95 035

2

Mathematica, 49 bytes

Tr@Array[Tr@s[[;;#]]&,Length[s=IntegerDigits@#]]&

J42161217

Posted 2017-08-04T19:49:19.347

Reputation: 15 931

You can take the input as a list of digits. #.Range[Length@#,1,-1]& – alephalpha – 2017-08-05T03:01:11.863

Improving @alephalpha 's solution: #.Range[Tr[1^#],1,-1]& – JungHwan Min – 2017-08-05T03:06:51.517

Tr@*Accumulate – alephalpha – 2017-08-05T12:10:21.697

2

Pari/GP, 20 bytes

Takes the input as a list of digits.

a->a*Colrev([1..#a])

Try it online!


Pari/GP, 17 bytes

Takes the input as a polynomial. For example, 5*x^4 + 3*x^3 + 7*x^2 + x + 6 means 53716.

a->x=1;eval(a+a')

Try it online!

alephalpha

Posted 2017-08-04T19:49:19.347

Reputation: 23 988

2

Neim, 3 bytes


Explanation:

        Get prefixes of input, including itself
        Implicitly join elements together, and create an array with all the digits
        Sum

Try it online!

Alternative answer:


Explanation:

       Get prefixes of input, including itself
        Join
        Implicitly convert to a digit array, and sum

Try it online!

Okx

Posted 2017-08-04T19:49:19.347

Reputation: 15 025

2

Pyt, 9 6 bytes

ąĐŁř↔·

Explanation:

                 Implicit input
ą                Convert to array of digits
 Đ               Duplicate digit array
   Łř↔           Create a new array [len(array),len(array)-1,...,1]
      ·          Dot product with digit array
                 Implicit output

mudkip201

Posted 2017-08-04T19:49:19.347

Reputation: 833

2

Common Lisp, 53 52 bytes

(loop as(x . y)on(reverse(read))sum(+(reduce'+ y)x))

Input as list of digits.

Try it online!

-1 byte thanks to @ceilingcat.

Renzo

Posted 2017-08-04T19:49:19.347

Reputation: 2 260

@ceilingcat, some Common Lisp compilers will actually fail when apply is applied against very long lists because of the call-arguments-limit.

– Renzo – 2018-01-31T10:00:48.870

2

Python 3, 94 58 54 bytes

Thanks to Mr. Xcoder for helping me save quite some bytes!

lambda n:sum(int(v)*(len(n)-i)for i,v in enumerate(n))

Try It Online!

Takes input as a string. It simply multiplies each digit by the number of times it needs to be added and returns their sum.

Manish Kundu

Posted 2017-08-04T19:49:19.347

Reputation: 1 947

Nice first answer, but please make your submission a serious contender by removing unnecessary whitespace, and making all variable / function names 1 byte long. 69 bytes

– Mr. Xcoder – 2018-01-21T09:24:16.073

58 bytes. – Mr. Xcoder – 2018-01-21T09:26:33.457

@Mr.Xcoder Thanks. I will keep that in mind. – Manish Kundu – 2018-01-21T09:32:50.890

1You may not assume that it will always be called with 0. If p must always be 0, you should replace the p with p=0 in the lambda declaration. However, you can just remove p entirely to get 54 bytes – caird coinheringaahing – 2018-01-21T15:44:00.930

1

PowerShell, 54 48 40 bytes

param($a)$a|%{$o+=$_*($a.count-$i++)};$o

Try it online!

Takes input as a list of digits.

Note that the output is just the input digit multiplied by its corresponding negative index in the string and then cumulatively summed. So, that's what we do here.

We loop over each element in the input list, each iteration perform a multiplication, and then sum the results together into the total $o+=. That's left on the pipeline, output is implicit.

AdmBorkBork

Posted 2017-08-04T19:49:19.347

Reputation: 41 581

1

05AB1E, 3 bytes

Code

ηSO

Try it online!

Explanation

η      # Take the prefixes of the number
 S     # Split into single numbers
  O    # Sum all the numbers

Adnan

Posted 2017-08-04T19:49:19.347

Reputation: 41 965

1

JavaScript (ES6), 34 bytes

f=(n,i=1)=>n&&n%10*i+f(n/10|0,i+1)

Test cases

f=(n,i=1)=>n&&n%10*i+f(n/10|0,i+1)

console.log(f(0)) // -> 0
console.log(f(1)) // -> 1
console.log(f(12)) // -> 4
console.log(f(123)) // -> 10
console.log(f(999)) // -> 54 
console.log(f(100000)) // -> 6
console.log(f(654321)) // -> 91

Arnauld

Posted 2017-08-04T19:49:19.347

Reputation: 111 334

Literally exactly what I had. However I do also have a 1-byte-shorter solution taking input as a string... – ETHproductions – 2017-08-04T20:01:15.147

@ETHproductions Ah, I first tried with a string but ended up with something longer. – Arnauld – 2017-08-04T20:06:34.633

1

Gaia, 4 3 bytes

…_Σ

Function accepting a list of digits and leaving the result on the stack.

Try it online!

Explanation

…    Prefixes
 _   Flatten
  Σ  Sum

Business Cat

Posted 2017-08-04T19:49:19.347

Reputation: 8 927

1Crossed out 4 is still 4 :( – Mr. Xcoder – 2017-08-04T20:14:46.187

What's the footer for? – Okx – 2017-08-07T12:30:18.113

@Okx Each line in Gaia is a function (like Jelly), so the footer is just calling it. – Business Cat – 2017-08-07T15:34:38.613

So, why doesn't it work without the footer? – Okx – 2017-08-07T15:44:32.717

@Okx Because I haven't yet made it detect a list from the input format, so I have to eval it (e) first – Business Cat – 2017-08-07T15:47:35.560

1

C# (.NET Core), 80 bytes

n=>{int v=0,i=0;for(;i<n.Length;)v+=int.Parse(n[i]+"")*(n.Length-i++);return v;}

Try it online!

Takes a string as input and outputs the triangled number.


Explanation:

For each character in the input string, convert the char to an int and multiply it by the length of the string minus the index of the char.

Ian H.

Posted 2017-08-04T19:49:19.347

Reputation: 2 431

1

Python 3, 58 bytes

lambda n:sum(-~i*int(c)for i,c in enumerate(str(n)[::-1]))

Try it online!

Halvard Hummel

Posted 2017-08-04T19:49:19.347

Reputation: 3 131

1

C# (.NET Core), 84 68 bytes

a=>a.Select((x,i)=>a.Take(i+1).Sum(c=>c-48)).Sum()

Byte count also includes

using System.Linq;

Try it online!

Explanation:

a=>                     // Take a string
    a                   // Take the string as collection of chars
    .Select((x,i)=>     // Replace the collection with
        a.Take(i+1)     // Substrings increasing in size
        .Sum(c=>c-48))  // Sum each substring's digits (as ints) together
    .Sum()              // Sum the new collection of sums

I know it's a little bigger than there's already posted C# answer, but mine is coming from a different approach so I thought I will post it anyway.

Grzegorz Puławski

Posted 2017-08-04T19:49:19.347

Reputation: 781

1

TXR Lisp, 67 40 bytes

(opip digits reverse conses flatten sum)

Run:

1> (opip digits reverse conses flatten sum)
#<intrinsic fun: 0 param + variadic>
2> [*1 53716]
66

Note that if we take advantage of the input being a list of integers representing digits, this reduces to:

(opip reverse conses flatten sum)

and if the digits may be in reverse order already, then just

(opip conses flatten sum)

Note also that this is a "useless use of opip"; all the terms are function names, and so [chain digits reverse conses flatten sum] could be used, and that would be the recommended way to code this; it's just one character longer.

Kaz

Posted 2017-08-04T19:49:19.347

Reputation: 372

1

PHP, 51 55 bytes

+4 bytes—original version failed on all inputs with 0 as a digit.

<?php while($x!=$d=array_pop($argv))$t+=++$p*$d;echo$t;

Try it online!

EXPLANATION:

<?php

The programme takes separate digits as CLI parameter arguments, which arrive in the code as an array, $argv.

Each character at a time is popped from the end of the array. When the array is empty array_pop returns null. Null is detected by comparing the result to an undeclared variable $x, a saving of 2 code bytes over using null itself. (Without this comparison any 0 digit evaluates to false and the loop ends early.)

while ($x != $d = array_pop($argv))

$p is the position from the end i.e. the last digit (the first one popped) is in position 1. $p is undeclared and so equals 0, but is incremented before it is used each time, so starts off as 1.

The position is multiplied by the digit and added to the total $t.

    $t += ++$p * $d;

The final result is printed.

echo $t;

WebSmithery

Posted 2017-08-04T19:49:19.347

Reputation: 221

1

Python 2, 46 bytes

  • Takes in string, returns integer
f=lambda a:a and sum(map(int,a))+f(a[:-1])or 0

Try it online!

officialaimm

Posted 2017-08-04T19:49:19.347

Reputation: 2 739

1

Ruby, 32 bytes

->a{b=a.pop;a[0]?b+a.sum+f[a]:b}

Try it online!

Idva

Posted 2017-08-04T19:49:19.347

Reputation: 97

1

Python 2, 56 bytes

lambda a:sum((i+1)*int(a[-i-1])for i in range(0,len(a)))

Try it online!

Some edit as suggested by @Mr.Xcoder

Python 2, 50 bytes

lambda a:sum(-~i*int(a[~i])for i in range(len(a)))

Try it online!

Rohit-Pandey

Posted 2017-08-04T19:49:19.347

Reputation: 169

150 bytes (-6 bytes). (i+1) means bitwise -~i, thus requiring no brackets and -i-1 is just ~i, again bitwise. range(0,len(a)) is equivalent to the unary range range(len(a)). – Mr. Xcoder – 2017-08-05T20:29:32.033

1

Excel VBA Immediate Window, 60 bytes

a=StrReverse([A1]):For i=1 ToLen(a):b=b+i*Mid(a,i,1):Next:?b

Input is in cell A1 of the active sheet. Output is to the VBA immediate window.

Engineer Toast

Posted 2017-08-04T19:49:19.347

Reputation: 5 769

1

Clojure, 26 bytes

#(apply +(reductions + %))

There's a built-in, but in standard Clojure fashion, it's a long-ass word. Takes input as a list of digits.

MattPutnam

Posted 2017-08-04T19:49:19.347

Reputation: 521

Can you add a testing link or instructions on how to run it? – Mr. Xcoder – 2017-08-07T15:40:04.223

1

Röda, 31 21 bytes

{i=0{[i]if i+=_}|sum}

Try it online!

Takes the input as a stream of digits.

31 bytes

{addHead 0|reduceSteps _+_|sum}

Try it online!

Takes the input as a stream of digits.

Explanation:

{addHead 0|reduceSteps _+_|sum} /* An anonymous function */
 addHead 0                      /* Append 0 to the beginning of the stream */
          |reduceSteps _+_      /* Create a cumulative sum */
                          |sum  /* Sum all numbers in the stream */

The reduceSteps function does not return the first item in the stream, so it is necessary to add a zero at the head of the stream.

fergusq

Posted 2017-08-04T19:49:19.347

Reputation: 4 867

1

TI-BASIC, 4 bytes

sum(cumSum(Ans

Takes a list of digits as input, and calculates the sum of the cumulative sum (i.e. prefix sum) of the list.

The cumSum( token is 2 bytes large.

calc84maniac

Posted 2017-08-04T19:49:19.347

Reputation: 165

1

Math++, 56 bytes

?>n
n>g
o+g%10>o
_(g/10)>g
3+3*!g>$
_(n/10)>n
2+6*!n>$
o

SuperJedi224

Posted 2017-08-04T19:49:19.347

Reputation: 11 342

1

Excel VBA, 57 Bytes

Anonymous VBE immediate window function that takes input from the range [A1], and outputs the triangle sum described above to the VBE immediate window

l=[Len(A1)]:For i=1To l:s=s+Mid([A1],i,1)*(l+1-i):Next:?s

Taylor Scott

Posted 2017-08-04T19:49:19.347

Reputation: 6 709

1

Scala, 64 bytes

def f(s:String)=s.indices.flatMap(i=>s.take(i+1).map(_-'0')).sum

6infinity8

Posted 2017-08-04T19:49:19.347

Reputation: 371

1

Python 3, 106 bytes

a=input()
c=[]
d=0
b=[int(g) for g in a]
for i in range(1,len(a)+1):
    c+=b[0:i]
for t in c:
    d+=t
print(d)

Try It Online!

My original code was:

a,c,d=input(),[],0
b=[int(g) for g in a]
for i in range(1,len(a)+1):
    c+=b[0:i]
for t in c:
    d+=t
print(d)

But then I realized that by initializing all of my variables on one line, I gained two characters. :P

Nathan Dimmer

Posted 2017-08-04T19:49:19.347

Reputation: 511

Ah Ah Ah! I am not the loser! – sergiol – 2018-04-05T11:49:38.707

1

Add++, 11 6 bytes

L~,¬+s

Try it online!

caird coinheringaahing

Posted 2017-08-04T19:49:19.347

Reputation: 13 702

1

R, 75 bytes

function(x,b=nchar(x))sum(sapply(x%/%10^(0:b),function(y)y%/%10^(0:b)%%10))

Try it online!


I did not see an R solution yet, so here goes..

Florian

Posted 2017-08-04T19:49:19.347

Reputation: 201

49 bytes -- I had actually solved this but it was a snippet rather than a full program/function so yours is better. – Giuseppe – 2018-01-24T16:54:22.900

@Giuseppe 51 bytes: sum(cumsum(as.numeric(el(strsplit(scan(,""),""))))), but your version is 2 bytes shorter... – Andreï Kostyrka – 2018-04-05T19:29:47.217

1

@AndreïKostyrka we can join forces and get to 47 bytes!

– Giuseppe – 2018-04-05T19:39:25.910

1

Perl 6, 13 bytes

Takes a list of digits

{[+] [\+] @_}

Try it online!

Perl 6 has a produce routine, which can be more tersely invoked using the 'triangle reduce' meta operator: [\ ]. Seems like it was made for this task.

Jarrod Funnell

Posted 2017-08-04T19:49:19.347

Reputation: 121

0

Ruby 29 bytes

f=->n{*a,b=n;b ?n.sum+f[a]:0}

Try it online!

Asone Tuhid

Posted 2017-08-04T19:49:19.347

Reputation: 1 944

0

C (gcc), 51 50 bytes

-1 byte thanks to @ceilingcat

i,r;f(t,l)int*t;{for(;l;)for(i=--l;~i;)r+=t[i--];}

Try it online!

vazt

Posted 2017-08-04T19:49:19.347

Reputation: 311

0

Tcl, 97 bytes

proc T n {time {incr s [expr [regsub -all (.) $n +\\1]]
regsub .$ $n "" n} [string len $n]
set s}

Try it online!

Tcl, 105 bytes

proc T n {time {incr s [expr [join $L +]]
set L [lreplace $L e e]} [llength [set L [split $n ""]]]
set s}

Try it online!

sergiol

Posted 2017-08-04T19:49:19.347

Reputation: 3 055

0

Gol><>, 8 bytes

IEh@+:@+

Try it online!

Input format is space-separated digits.

How it works

IEh@+:@+

I         Take next input as number
 E        If last input was EOF...
  h       Print the top as number and halt
          Otherwise...
          The stack looks like [sum_of_digits triangle digit]
   @      Move 3rd from top (sum_of_digits) to the top
    +     Add top two (update `sum_of_digits`)
     :    Duplicate top
      @+  Add `sum_of_digits` to `triangle`
          Repeat from the beginning

Bubbler

Posted 2017-08-04T19:49:19.347

Reputation: 16 616

0

EXCEL, 55 bytes

Using Immediate Window.

[A65:A89]="=MID(REPT(CHAR(ROW())&CHAR(ROW()+1),2),1,3)"

remoel

Posted 2017-08-04T19:49:19.347

Reputation: 511

0

Zsh, 60 bytes

f(){echo $((${(j:+:)${(@f)$(for i in $@;echo $((x+=i)))}}))}

Try it online!

Takes input as individual parameters

Noskcaj

Posted 2017-08-04T19:49:19.347

Reputation: 421