Sum the rows of the concatenated triangle

16

1

Consider the following triangle.

1
23
456
7891
01112
131415
1617181
92021222
324252627
2829303132
33343536373
839404142434
4454647484950
51525354555657
585960616263646
5666768697071727
37475767778798081

As you probably noticed, the first row is of length 1, and each row thereafter is 1 digit longer than to the previous one and that it contains the digits of the positive integers concatenated.

You will be given an integer N. Your task is to find the sum of the digits that lie on Nth row of the above triangle.

Rules

  • You can choose either 0 or 1 indexing. Please specify that in your answer.

  • Default Loopholes apply.

  • You can take input and provide output by any standard mean, and in any reasonable format.

  • This is OEIS A066548, and this sequence is the triangle itself (except that we do not remove leading zeros).

  • This is , so the shortest code in bytes (in every language) wins. Have fun golfing!

Test Cases

Input  |  Output

0  |  1
1  |  5
2  |  15
3  |  25
4  |  5
5  |  15
6  |  25
7  |  20
8  |  33
9  |  33
10 |  43
11 |  46
12 |  64

Note that the above are 0-indexed. If you are looking for 1-indexed test cases, increment the input by 1.

On a quite unrelated note, I recently changed my profile picture and that inspired me to write this challenge.

Mr. Xcoder

Posted 2017-09-02T12:52:28.703

Reputation: 39 774

Answers

8

Husk, 7 bytes

1-indexed

Σ!CNṁdN

Try it online!

Explanation

    ṁ     Map then concatenate
     d    Integer digits
      N   Over the natural numbers
  CN      Cut into lists of lengths corresponding to the natural numbers
 !        Index it
Σ         Sum

H.PWiz

Posted 2017-09-02T12:52:28.703

Reputation: 10 962

4

Python 2, 69 bytes

This could probably be quite a bit shorter.

1-indexed

Edit: -7 bytes thanks to @Mr.Xcoder

lambda n:sum(map(int,"".join(map(str,range(1,n*n+1)))[~-n*n/2:][:n]))

Try it online!

Halvard Hummel

Posted 2017-09-02T12:52:28.703

Reputation: 3 131

1n**2 is n*n. – Mr. Xcoder – 2017-09-02T13:07:37.823

69 bytes. Using Gauss' formula, sum(range(n)) = ~-n*n/2 = (n - 1) * n / 2 – Mr. Xcoder – 2017-09-02T13:12:47.640

1@Mr.Xcoder I think he does... – Erik the Outgolfer – 2017-09-02T13:21:30.987

@EriktheOutgolfer You're right, my bad – Mr. Xcoder – 2017-09-02T13:22:18.380

3

05AB1E, 8 bytes

nLS¹L£θO

Try it online!

-1 thanks to Emigna.

1-indexing.

Erik the Outgolfer

Posted 2017-09-02T12:52:28.703

Reputation: 38 134

You can remove your S if you replace J with S. – Emigna – 2017-09-04T08:33:58.707

@Emigna duh.... – Erik the Outgolfer – 2017-09-04T08:35:55.343

3

Perl 6, 47 45 42 bytes

{[~](1..$_²).substr(:1[^$_],$_).comb.sum}

Try it online!

1-indexed

nwellnhof

Posted 2017-09-02T12:52:28.703

Reputation: 10 037

3

Haskell, 57 bytes

f n=sum[read[d]|d<-take n$drop(div(n*n-n)2)$show=<<[1..]]

Try it online!

Laikoni

Posted 2017-09-02T12:52:28.703

Reputation: 23 676

2

Mathematica, 96 bytes

(d=Flatten[IntegerDigits/@Range[#^2]];Last@Table[Tr@Take[d,{i(i+1)/2+1,(i+1)(i+2)/2}],{i,0,#}])&  


Try it online! (in order to work on mathics "Tr" has to be replaced with "Total")

J42161217

Posted 2017-09-02T12:52:28.703

Reputation: 15 931

2

Jelly, 11 bytes

²RDFṁRS$ṫCS

Try it online!

Uses 1-based indexing.

Explanation

²RDFṁRS$ṫCS  Input: n
²            Square
 R           Range, [1, n^2]
  D          Decimal digits
   F         Flatten
    ṁ        Reshape to
       $     Monadic chain
     R         Range, [1, n]
      S        Sum
        ṫ    Tail
         C   Complement, 1-n
          S  Sum

miles

Posted 2017-09-02T12:52:28.703

Reputation: 15 654

2

R, 119 109 108 93 88 bytes

starting to golf.... 1-indexed

function(n){for(i in 1:n+n*(n-1)/2){F=F+strtoi(substr(paste(1:n^2,collapse=""),i,i))};F}

thanks @Zachary. your presumption is correct :) shaved 1 byte tnx to @Andrius and 15 more tnx to @user2390246

@Giuseppe - tnx for the strtoi. new to me. 5 bytes down :)

Zahiro Mor

Posted 2017-09-02T12:52:28.703

Reputation: 371

2I don't think you need the y=, nor the parens around n*(n-1)/2+1, and the language's name presumably isn't [R]. – Zacharý – 2017-09-03T18:20:58.330

1you can save 1 byte by changing as.integer with as.double – AndriusZ – 2017-09-04T09:47:28.403

wicked @AndriusZ tnx. – Zahiro Mor – 2017-09-04T09:49:08.733

1Rather than x, use F as this is already initialised to 0. – user2390246 – 2017-09-04T11:05:09.180

1Also, 1:n+a-1 gives the same as a:(a+n-1). In that case, you don't need to define a in advance, you can just put it straight in the for expression. That will also allow you to cancel out a +1/-1. – user2390246 – 2017-09-04T11:08:14.847

1strtoi instead of as.double, 1:n^2 instead of 1:(n^2) because ^ has precedence over : – Giuseppe – 2017-09-04T14:07:25.330

279 bytes. Used substring instead of substr since really this is just a sum over the indices of the substring. Also, it's always good to include a TIO link for your solutions :) +1, great work. – Giuseppe – 2017-09-04T15:02:09.567

@Giuseppe this is great - I tried to figure our how to get rid of the for loop....... – Zahiro Mor – 2017-09-05T08:29:25.843

2

Haskell, 69 64 bytes

n%x=sum[read[d]|d<-take n x]:(n+1)%drop n x
f=(1%(show=<<[1..])!!)

Try it online.

Saved 5 bytes thanks to Laikoni!

Here's the less golfed version:

-- continuous stream of digits representing
-- the concatenation of positive integers in
-- order: 1234567891011...
digitstream = show=<<[1..]

-- sequence that yields the rows of the triangle
triangle n xs |(a,b)<-splitAt n xs=a:triangle(n+1)b

digitSum xs = sum[read[d]|d<-xs]

-- sequence that sums up the digits in each row
rowSumSequence = map digitSum (triangle 1 digitstream)

-- the final function that just shows the value 
-- at a given index
g=(rowSumSequence!!)

Cristian Lupascu

Posted 2017-09-02T12:52:28.703

Reputation: 8 369

n%x=sum[read[d]|d<-take n x]:(n+1)%drop n x is some bytes shorter. – Laikoni – 2017-09-03T15:08:41.857

@Laikoni Thanks! Edited. I don't know why I thought the splitOn would save bytes. – Cristian Lupascu – 2017-09-03T17:36:04.497

2

Emojicode, 182 bytes

©a➡l➗✖a➕a 1 2ti 0▶lt➕i 1tti 10s 0gt➖l a a➕s g 10s

Defines a method called © that takes a and returns a . 1-indexed.

Try it online!

Explanation:

Note: a lot of emoji choice doesn't make much sense in Emojicode 0.5. It's 0.x, after all. 0.6 will fix this, so if you want to learn this (because who wouldn't want to), I recommend waiting a moment.

Emojicode is an object-oriented programming language featuring generics, protocols, optionals and closures, but this program uses no closures, and all generics and protocols can be considered implicit.

The program operates on only a few types: is the integer type and is the string type. Additionally s appear in conditions, which can take a value of either (true) or (false).

There are currently no operators in Emojicode, so addition, comparsions and other operations that are normally operators are implemented as functions, effectively making the expressions use prefix notation. Operators are also planned in 0.6.

©a➡

© takes one called a and returns a .

 l➗✖a➕a 1 2

Declare a frozen ("constant") l equal to the a-th triangular number (formula in prefix notation). This represents the length of the string of numbers we need to generate.

 t

Assign an empty string to the variable t.

 i 0

Assign i = 0.

 ▶lt

While the l is greater than the length of t

  ➕i 1

i += 1

  tti 10

Append the textual representation of i in base 10 to t.

 

End loop

 s 0

Assign s = 0

 gt➖l a a

Take a substring of t starting at l - a (a - 1th triangular number) of length a, iterate over all characters

  ➕s g 10

Convert the character to string, parse integer in base-10, unwrap the optional (nothingness is returned if the string is not a number) and add to the s variable.

 

End loop

 s

Return s


End method.

NieDzejkob

Posted 2017-09-02T12:52:28.703

Reputation: 4 630

1

PHP, 66+1 bytes

for($p=($n=$argn)*-~$n/2;$n--;)$r+=join(range(1,$p))[--$p];echo$r;

Run as pipe with -nR or try it online.

requires PHP 5.4 or later for indexing the expression.

Titus

Posted 2017-09-02T12:52:28.703

Reputation: 13 814

1

Pyth, 24 bytes

u+GsH<>jkS+*QQ2/*QhQ2hQ0

Try it here: http://pyth.herokuapp.com/

Karan Elangovan

Posted 2017-09-02T12:52:28.703

Reputation: 179

1

APL, 28 26 25 bytes

{+/⍎¨⍵↑⌽(+/⍳⍵)↑∊,/⍕¨⍳⍵×⍵}

Uses 1-based indexing

Try it online!

How?

  • ⍳⍵×⍵, 1 through the input squared
  • ⍕¨, turn each element into a string
  • ∊,/, concatenate them together
  • (+/⍳⍵)↑, grab the rows up to the input
  • ⍵↑⌽, grab the desired row
  • ⍎¨, turn each element into a number
  • +/, sum

Zacharý

Posted 2017-09-02T12:52:28.703

Reputation: 5 710

1

Clojure v1.8, 154 bytes

1-indexed

(fn[n](loop[i 1 s(clojure.string/join""(take(* n n)(iterate inc 1)))](if(= i n)(apply +(map #(Character/digit % 10)(take n s)))(recur(inc i)(subs s i)))))

Try it online!

Explanation

(take(* n n)(iterate inc 1))  Take the first N*N numbers
(clojure.string/join""...)    Combine them into a string
(loop[i 1 ...](if(= i n)...)  Loop N times
(apply +(map #(Character/digit % 10)(take n s)))  Take N characters from the string, convert to integers and add them
(recur(inc i)(subs s i))      Increment iterator, remove i characters from string

Chris

Posted 2017-09-02T12:52:28.703

Reputation: 31

1

Java 8, 116 98 bytes

n->{String t="";int r=0,i=0;for(;i++<n*n;t+=i);for(i=0;i<n;r+=t.charAt(i+++~-n*n/2)-48);return r;}

1-indexed

-18 bytes thanks to @Nevay

Explanation:

Try it here.

n->{                             // Method with integer as both parameter and return-type
  String t="";                   //  Triangle-String
  int r=0,                       //  Result-integer
      i=0;                       //  Index-integer
  for(;i++<n*n;                  //  Loop (1) from 0 to `n^2` (exclusive)
    t+=i                         //   And append String `t` with all the numbers
  );                             //  End of loop (1)
  for(i=0;i<n;                   //  Loop (2) from 0 to `n` (exclusive)
    r+=t.charAt(i+++~-n*n/2)-48  //   And raise the sum `r` by the digits
  );                             //  End of loop (2)
  return r;                      //  Return the resulting sum of digits
}                                // End of method

Kevin Cruijssen

Posted 2017-09-02T12:52:28.703

Reputation: 67 575

198 bytes: n->{String r="";int i=0,x=0;for(;x++<n*n;r+=x);for(x=0;x<n;)i+=r.charAt(x+++~-n*n/2)-48;return i;}. – Nevay – 2017-09-04T14:27:43.267

1

R, 99, 105, 97 bytes

a=diag(N<-scan());a[upper.tri(a,T)]=strtoi(strsplit(paste(1:N^2,collapse=""),"")[[1]]);sum(a[,N])

1-indexed

ungolfed version

a <- diag(N<-scan())
a[upper.tri(a, diag=TRUE)] <- strtoi(strsplit(paste(1:N^2, 
                                                  collapse=""),
                                            "")[[1]])
sum(a[,N])

Try it here!

thanks to @Giuseppe for saving 8 bytes

AndriusZ

Posted 2017-09-02T12:52:28.703

Reputation: 219

@Giuseppe in the description is mentioned: "You will be given an integer N." and this N is used in my solution. Or maybe I misunderstood something. – AndriusZ – 2017-09-04T14:33:46.977

See the linked "any standard mean" in the description :) – Giuseppe – 2017-09-04T14:39:13.060

@Giuseppe change and used your suggestion about strtoi – AndriusZ – 2017-09-04T14:49:37.403

197 bytes, with a warning message. It's always good to include a link to TIO in your description so others can test it! – Giuseppe – 2017-09-04T15:04:32.750

@Giuseppe I don't know no R, but maybe a function would use less bytes? – NieDzejkob – 2017-09-04T15:08:10.430

@Giuseppe the same warning message I have too. thanks for saving me 8 bytes – AndriusZ – 2017-09-04T15:10:22.297

@NieDzejkob see for example Zahiro Mor's response for proof of that suggestion.

– Giuseppe – 2017-09-04T15:10:52.733

1

Perl 6, 44 bytes

{[+] (1..*).flatmap(*.comb).rotor(1..*)[$_]}

Test it

Expanded:

{
  [+]        # reduce the result of the following using &infix«+»

  ( 1 .. * ) # infinite range starting at 1

  .flatmap(  # map, then flatten
    *.comb   # split into digits (100 ⇒ 1,0,0)
  )

  .rotor(    # break the sequence into pieces
    1 .. *   # start with 1 value, then 2 values, then 3, etc.
  )\

  [$_]       # index into that infinite sequence
}

Brad Gilbert b2gills

Posted 2017-09-02T12:52:28.703

Reputation: 12 713

0

Jelly, 16 bytes

Ṭ€Ẏ0;œṗ²D€Ẏ$$⁸ịS

Try it online!

1-indexed.

Erik the Outgolfer

Posted 2017-09-02T12:52:28.703

Reputation: 38 134

0

SOGL V0.12, 15 13 bytes

²Δr∑.δ∑⌡kmčr∑

Try it Here!
1-indexed.

While working on this I fixed a bug that made not work on number arrays and that m incorrectly took implicit input.

Explanation:

²              square the input
 Δ             get a range from 1 to that
  r∑           join as a string
    .δ         create a range 0 - input-1
      ∑        sum that
       ⌡       that many times do
        k        remove the 1st character of the joined string
         m     mold to the length of the input
          č    chop into characters
           r∑  convert to numbers and sum

dzaima

Posted 2017-09-02T12:52:28.703

Reputation: 19 048

0

JavaScript (ES6), 78 65 bytes

f=
n=>eval([...(g=n=>n?g(n-1)+n:``)(n*n).substr(n*~-n/2,n)].join`+`)
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>

1-indexed. Edit: Saved 13 bytes thanks to @tsh.

Neil

Posted 2017-09-02T12:52:28.703

Reputation: 95 035

n=>eval([...(g=n=>n?g(n-1)+n:'')(n*n)].join<+>.substr(~-n*n-1,2*n)) – tsh – 2017-09-07T08:05:58.967

@tsh Still golfier to put the join`+` at the end... – Neil – 2017-09-07T08:14:17.647

0

C++, 180 bytes

-17 bytes thanks to Zacharý

Index start at 1

#include<string>
int s(int n){std::string t;int i=0,p=0;for(;i<=n;)p+=i++;for(i=0;t.size()<p;t+=std::to_string(++i));t=t.substr(0,p).substr(p-n);i=0;for(auto&a:t)i+=a-48;return i;}

HatsuPointerKun

Posted 2017-09-02T12:52:28.703

Reputation: 1 891

Changing the last line to this should save two bytes: int s(int n){++n;std::string t;int i=0,p=0;for(;i<=n;)p+=i++;for(i=0;t.size()<p;t+=std::to_string(++i));t=t.substr(0,p);t=t.substr(t.size()-n);i=0;for(auto&a:t)i+=a-48;return i;} – Zacharý – 2017-09-03T17:58:28.097

Also, if you're currently taking input as 0-indexed, you can convert it to 1-index and drop the ++n; – Zacharý – 2017-09-03T18:09:32.520

@Zacharý Thanks. Btw, your code contains invisible unicode character for some reasons – HatsuPointerKun – 2017-09-03T18:24:00.043

Which one, my C++ suggestion, or my APL? APL uses its own codepage, and will probably not show up right if you do not have the right font. – Zacharý – 2017-09-03T18:38:19.797

@Zacharý The C++ suggestion you wrote in the comment. There's like 2 unicode characters before a zero, making errors like "0" identifier is unknown in visual studio. Same thing for to_string and size. You can see it if you copy-paste the code in notepad++, and convert encoding to ANSI, you will see some ?? in the editor – HatsuPointerKun – 2017-09-03T18:47:13.440

Would it be possible to combine the substr statements into this? t=t.substr(0,p).substr(p-n)? (If the size of t.substr(0,p) isn't p, replace p with the appropriate value) – Zacharý – 2017-09-03T19:27:12.367

@Zacharý I've tested, and no, it does not produce the same results. – HatsuPointerKun – 2017-09-03T19:28:44.807

I get that, with MSVC : 1 | 1, 2 | 5, 3 | 15, 4 | 18, 5 | 5, 6 | 15, 7 | 24, 8 | 11, 9 | 33, 10 | 33, 11 | 40, 12 | 38, 13 | 64 – HatsuPointerKun – 2017-09-03T19:39:30.967

Does replacing t.size() with p work? – Zacharý – 2017-09-03T19:49:48.470

@Zacharý Yes it does. Your TIO link is undecodable, btw. After thinking about it, it's normal that doing t.substr(0,p).substr(t.size()-n) doesn't work, it's because t is not reassigned before the 2nd substr method call – HatsuPointerKun – 2017-09-03T19:52:09.193

Oh, whoops. What I meant to do was combine the two substr statements into t.substr(0,p).substr(p-n)! Which is what you just did. Also, sorry for the spam, but I have one more golf: t=t.substr(0,p).substr(p-n);i=0; => t=t.substr(i=0,p).substr(p-n);. – Zacharý – 2017-09-03T19:54:18.717

0

Pyth,  15 14  13 bytes

s<>sMjkS^Q2sU

Try it here! or Check out the test suite.

13 bytes alternatives:

ssM<>jkS^Q2sU
ssM<>jkS*QQsU
s<>sMjkS^Q2sU

How?

s<>sMjkS^Q2sU    Full program. Q means input.

       S^Q2      The range [1, Q^2].
     jk          Join as a String.
   sM            Convert each character to integer.
  >              All the elements of the above, but the first Q*(Q-1)/2.
 <               All the element of the above but the last Q.
s                Sum.
                 Output implicitly.

Mr. Xcoder

Posted 2017-09-02T12:52:28.703

Reputation: 39 774

0

><>, 141+2 Bytes

::1+* 2,01\
@}})?/:0$\>$:@{{:
:%a:/?(1:< ,a-]{+1[4
  /~/     \+1~\
1:<]{+1[+4@:-1\?(
{1-}>{:}1(?\@1-@+
    \0}~{{\\n;
@:{{:<-1~$\!?)}}
     ~

1-Indexed

+2b for -v flag

Tio.run really doesn't seem to like my ><> programs recently... It can still be verified on https://fishlanguage.com though. Input goes in 'initial stack'.

Edit: It turns out tio.run doesn't like it because it handles '[' and ']' differently to fishlanguage.com. fishlanguage.com reverses the stack when creating or removing a new stack, but tio.run doesn't.

Sasha

Posted 2017-09-02T12:52:28.703

Reputation: 431

0

Perl 5, 62 + 1 (-p) = 63 bytes

$_=eval(substr((join'',1..$_*$_),($_**2-$_)/2,$_)=~s/./+$&/gr)

Try it online!

Result is 1 indexed.

How?

Concatenate more than enough digits together, then skip the irrelevant ones at the beginning (length of skip is sum of integers from 1 to n-1). Take the next n digits, place a + in front of each one, then evaluate that equation.

Xcali

Posted 2017-09-02T12:52:28.703

Reputation: 7 671