28
\$\begingroup\$

Well, sum it down really.

Write a program or function that takes in a nonempty list of decimal integers (0-9) and outputs a downward pointing "triangle" of digits with the input list at the top where every digit after the first line is the sum of the two digits above it modulo 10.

For example, the input [7, 5, 0, 9] has output

7 5 0 9
 2 5 9
  7 4
   1

because 2 is (7 + 5) mod 10, 5 is (5 + 0) mod 10, 9 is (0 + 9) mod 10, etc. all the way to 1 being (7 + 4) mod 10.

If the list has only one item, then the output matches the input; e.g. an input of [4] will yield

4

Here are some additional examples:

[0]

0

[1, 2]

1 2
 3

[8, 7]

8 7
 5

[0, 0]

0 0
 0

[1, 4, 2]

1 4 2
 5 6
  1

[0, 1, 0]

0 1 0
 1 1
  2

[1, 0, 0, 0]

1 0 0 0
 1 0 0
  1 0
   1

[1, 2, 3, 4]

1 2 3 4
 3 5 7
  8 2
   0

[1, 2, 3, 5, 8]

1 2 3 5 8
 3 5 8 3
  8 3 1
   1 4
    5

[9, 2, 4, 5, 3, 2, 2]

9 2 4 5 3 2 2
 1 6 9 8 5 4
  7 5 7 3 9
   2 2 0 2
    4 2 2
     6 4
      0

Note that in the output:

  • The first line does not have leading spaces.
  • Each subsequent line has one more leading space than the line previous.
  • Digits are separated by a single space.
  • Each line is allowed to have up to one trailing space.
  • There may be a single optional trailing newline.
  • You must use the characters for normal decimal digits (0 through 9).

The shortest code in bytes wins. Tiebreaker is earlier answer.

\$\endgroup\$
  • 1
    \$\begingroup\$ First I read the title as "Digital Trauma" \$\endgroup\$ – cat Jun 10 '16 at 18:03

23 Answers 23

24
\$\begingroup\$

BrainF**k, 396 391 bytes

>+>>++++[-<++++++++>]->,----------[++++++++++.>>++++++++[-<++++<------>>]<.,----------]-<+[-<+]->>+[-<<<<<++++++++++.[-]>[-<+>>.<]<[->+<]>+>>>[[->+]->>+<<<+[-<+]->]>+[-<->[[->+]->+>>+<<<<+[-<+]->]<+>->+[->+]->>[->+<]>+>++++++++++>>-<<[-<-[>>]<]<->>>+[-<<<+>>>[-<->]<+++++++++>>>+]++++++++[-<++++<++++++>>]<<<[-<<<<+[-<+]-<+>>+[->+]->>>>+<]>.>.[-]<[-]<<<[->+<]<<+[-<+]>+]>>[-]<<<-<+[-<+]->>+]

I couldn't resist the temptation to do this one. At least the triangle is pointy-side down.

Input comes in as a string of numeric characters followed by a single newline.

Output will contain a single trailing space on every line.

Examples:

$ bf sd.bf
010
0 1 0 
 1 1 
  2 

$ bf sd.bf
123456
1 2 3 4 5 6 
 3 5 7 9 1 
  8 2 6 0 
   0 8 6 
    8 4 
     2 

$ bf sd.bf
9245322
9 2 4 5 3 2 2 
 1 6 9 8 5 4 
  7 5 7 3 9 
   2 2 0 2 
    4 2 2 
     6 4 
      0 

Explanation

Since it's rather difficult to explain the code from a functional perspective, we can instead look at it from the perspective of the state of the tape at various times. The core idea here is that the triangle we output is initialized as a tightly-packed (for BF, anyway) array that shrinks in size by 1 every iteration of a loop. Another important thought is that we use 255 to indicate a "placeholder" that we can search for on the tape.

Initialization

This is the easiest step. At the start of the program, we execute the following:

>+>>++++[-<++++++++>]->

This forces the tape into the following state (where >N< indicates the location of the pointer on the tape)

[ 0 1 32 255 >0< 0 0 ...]

The first number here is a "buffer" location. We're not going to use it on a long-term basis, but it's useful to make little operations simpler and for copying data around.
The second number is the number of spaces that we'll be outputting at the start of each line, starting after the first line. The first line will have no leading spaces.
The third number is the space character we output.
The fourth number is a placeholder 255, so that we can get back to this position relatively easily.

Input

From this position, we will read in all of the characters. At the end of this step, we hope to be in the following situation:

[ 0 1 32 255 a b c d e f ... >255< 0 0 ... ]

Where a b c d e f ... indicates the string of numeric characters that was input (not the newline).

We accomplish this with the following:

,----------[++++++++++.>>++++++++[-<++++<------>>]<.,----------]-

There are some nuances to this. First of all, we will output each character as we get them, and then output a space after it. Secondly, we don't want to copy the ASCII value to the tape, we want to copy the actual numeric digit. Third, we want to stop when we hit a newline and leave ourselves in a good place at that time.
Say our input is 6723. Then, upon reading the first 6, our tape looks like this:

[ 0 1 32 255 >54< 0 0 ...]

We check that this value is not equal to 10 (an ASCII newline) with ,----------[++++++++++. We then print out the value and continue by simultaneously subtracting 48 from the input value and adding 32 to the value next to it (>>++++++++[-<++++<------>>]<), leaving us here:

[ 0 1 32 255 6 >32< 0 ...]

Notice how throughout this process we can assume that all digits to the right of our input are 0--this means that we're not in danger of ruining any previous state if we use values to the right to calculate 6 * 8 and 4 * 8.
Now we output the space character we just generated, and take in a new input, deleting the space we calculated there. Eventually, the input will be terminated by a new line and the loop will exit, leaving a 255 where the newline would have been (,----------]-). This is the second placeholder character we will use to navigate the tape. At this point in our scenario, our tape is exactly this:

[ 0 1 32 255 6 7 2 3 >255< 0 0 ... ]

Calculation

The way this works is that the list of digits between our 255 placeholders is going to shrink by one every iteration of the loop. When it only has 1 digit left in it, we're done and should halt immediately (Note that, at this point, every digit in that list has already been output, so we don't have to worry about outputting it again).

We now use this trick to navigate to the first 255 placeholder: <+[-<+]-. This effectively searches the tape to the left for a 255, changing nothing in between. Now that we've moved the pointer, we can check our exit condition: if there's only one digit in the list, then the cell two spaces to the right will hold 255. Thus, we check against that and start a loop: >>+[-<<

The first step in our loop is to output a newline. So we move to the first cell (our buffer cell), add 10 to it and output. The next step is to output all leading space characters. After outputting them, we increment our count for number of leading spaces. These steps are accomplished by the following:

-<<<<<++++++++++.[-]>[-<+>>.<]<[->+<]>+>>>

Which leaves us in this state:

[ 0 2 32 255 >6< 7 2 3 255 0 0 0 0 0 0 ]

Our next step is to copy the first value in the list over, past the second placeholder 255:

[[->+]->>+<<<+[-<+]->]

We essentially do this by hopping back and forth between our placeholder 255s, leaving us here:

[ 0 2 32 255 >0< 7 2 3 255 0 6 0 0 ... ]

We now start a loop, iterating through the rest of the list, stopping when we hit 255 : >+[-<

At this point, the digit to our immediate left is always 0. So, because we love them, we pop a placeholder 255 in there so that we can come back to our place in the list. The next step is to move the second place in the list to locations surrounding where we moved the first place to, past the second placeholder 255. These steps are accomplished by the following:

->
[[->+]->+>>+<<<<+[-<+]->]

Leaving us here: [ 0 2 32 255 255 >0< 2 3 255 7 6 7 0 ] Now, both the 6 and 7 have been moved to a location where the calculation can occur. We need two copies of the 7 because the next number in the list will need it as well. The 7 immediately after the 255 serves this purpose, whereas the other 7 will be consumed by the calculation.

First, we add the two digits:

<+>->+[->+]->>
[->+<]>

Leaving us here:

[ 0 2 32 255 0 255 2 3 255 7 0 >13< 0 ]

The next combination of steps is the most complicated. We need to see if the number we're pointing to is larger than 10, and if it is, we subtract 10. In reality, what we do is we subtract 10 from it and see if it hits 0 at any point in the subtraction. If it does, we add 10 back on later. At the end of this, we should have the sum modulo 10.

Prepare a 10 to the right
+>++++++++++
Leave yet another 255 for a loop condition later
>>-<<
If the number is greater than 10 end up one space to the left
else one space to the right
[-<-[>>]<]<->
Check if the previous 255 is two spaces to the right and if it is
add 10 back to our sum--we've subtracted too much
>>+[-<<<+>>>[-<->]<+++++++++>>>+]

At this point, we've accomplished the goal. We have the sum modulo 10! Also, whether or not the number was greater than 10, we'll end up here:

[ 0 2 32 255 0 255 2 3 255 7 0 3 0 0 >0< ]

Our next goals are to output this new sum, follow it with a space, and inject it back into our list. We do this all with our previous techniques of 255-hopping and adding 48 to our sum, so I won't cover it in detail.

++++++++[-<++++<++++++>>]
<<<[-<<<<+[-<+]-<+>>+[->+]->>>>+<]
>.>.

And we're here: [ 0 2 32 255 3 255 2 3 255 7 0 0 51 >32< ] Notice how we put an additional 255 placeholder after our newly-injected 3 so that we don't lose place in the list. At this point, we have output our sum and its space, so we need to clean up and revert to a state where the next iteration of this loop is going to work. We need to clear out our 51 and 32 cells, move the 7 once to the right, and navigate to our list placeholder so that we can start over.

[-]<[-]<<<[->+<]<<+[-<+]

Now, we're here: [ 0 2 32 255 3 >0< 2 3 255 0 7 0 ... ]
Which is exactly where we want to be for our next iteration. So check for 255 and move on! (>+])

When we get dropped off from the loop, we're going to have a whole new list--made up of the sums from the previous list. The first time, it'll look like this:

 [ 0 2 32 255 3 9 5 0 >0< ]

Now we want to repeat that whole process on our new list, so we plop a 255 down to the left and start all over! We need to do a little bit of cleanup with >>[-]<<, and then drop our placeholder with <-. After that, we're in exactly the same place as we were after input, so we can get away with doing the same checks: <+[-<+]->>+, and boom! We've got our full loop! All we need is the closing bracket, and when it ends we've already output everything, so we're done: ].

\$\endgroup\$
  • \$\begingroup\$ Welcome back by the way :) You haven't answered since 2015 :o \$\endgroup\$ – Calvin's Hobbies Jun 10 '16 at 5:33
  • 1
    \$\begingroup\$ @HelkaHomba I know! I still visit with some frequency, but I just couldn't resist writing the code for this one. It's perfect for the language :) \$\endgroup\$ – BrainSteel Jun 10 '16 at 11:44
  • 9
    \$\begingroup\$ "Perfect for BF" is a concept that elludes me :-) \$\endgroup\$ – Luis Mendo Jun 10 '16 at 13:52
7
\$\begingroup\$

Jelly, 20 19 18 bytes

Ṛ+2\Ṗп%⁵z”@ṚZGḟ”@

Try it online!

Background

Generating the numbers is straightforward in Jelly. The output is a bit more complicated.

Jelly has a built-in grid atom (G) that displays a 2D list with newlines between rows and spaces between columns. We take the 2D array of numbers (generated with each row reversed), and transpose it with fill value @. After revering the resulting array and transposing again, applying G yield the following.

9 2 4 5 3 2 2
@ 1 6 9 8 5 4
@ @ 7 5 7 3 9
@ @ @ 2 2 0 2
@ @ @ @ 4 2 2
@ @ @ @ @ 6 4
@ @ @ @ @ @ 0

To obtain the desired triangular shape, all we have to do is remove the fill value.

How it works

Ṛ+2\Ṗп%⁵z”@ṚZGḟ”@  Main link. Argument: A (list of integers)

Ṛ                   Reverse A.
    Ṗп             While there's more than one element:
 +2\                  Compute the pairwise sum.
                    Collect all intermediate results in a list.
       %⁵           Take all resulting integers modulo 10.
         z”@        Transpose with fill value '@'.
            Ṛ       Reverse the order of the rows.
             Z      Transpose.
              G     Grid.
               ḟ”@  Filter; remove the fill value.
\$\endgroup\$
5
\$\begingroup\$

Pyth - 18 bytes

j.e+*dkjdbP.ueM+Vt

Test Suite.

j                                       Join by newlines
 .e                                     Loop over seq in var b and index in var k
  +                                     Concatenate
   *dk                                  Space repeated k times
    jdb                                 Join b by spaces
  P                                     [:-1] to get rid of empty line
   .u             (Q implicit)          Cumulative fixed point over input (var G)
    eM                                  Mod 10 mapped over list
     +V                                 Vectorized addition
      t(G implict)                      G[1:]
      (G implict)                       Vectorize cuts this off to G[:-1]
\$\endgroup\$
5
\$\begingroup\$

Python 3.5, 74 72 71 bytes

f=lambda L,*S:f([sum(x)%10for x in zip(L,L[1:print(*S,*L)]or 1)],'',*S)

Input is a list of integers (e.g. f([1,2,3,5,8])), output is to STDOUT. The %10 and the fact that map returns a map object in Python 3 is a bit annoying, meaning we can't do map(lambda*x:sum(x)%10,L,L[1:]) or similar.

The function errors out, but by then the output would have completed. Thanks to @xsot for -1 byte by finding a good place to stick the print.

\$\endgroup\$
  • 3
    \$\begingroup\$ I don't have 3.5 installed but this should work: f=lambda L,*S:f([sum(x)%10for x in zip(L,L[1:print(*S,*L)]or 1)],'',*S) \$\endgroup\$ – xsot Jun 10 '16 at 3:32
  • 1
    \$\begingroup\$ @xsot That is... an amazing use of None! \$\endgroup\$ – Sp3000 Jun 10 '16 at 3:38
  • \$\begingroup\$ How does print return something? I don't know of the print function returning. \$\endgroup\$ – Erik the Outgolfer Jun 11 '16 at 9:23
  • \$\begingroup\$ @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Oh wait, you mean Python's print function returning - yeah it returns None on completion \$\endgroup\$ – Sp3000 Jun 11 '16 at 9:33
  • \$\begingroup\$ I mean, how useful is None on slicing? \$\endgroup\$ – Erik the Outgolfer Jun 11 '16 at 9:36
5
\$\begingroup\$

05AB1E, 20 19 17 bytes

Code:

DvNð×?T%Ððý,¦‚ø€O

Explanation:

D                     # Duplicate the input.
 v                    # Map over it, running the following len(input) times.
  Nð×                 # Multiply the iteration number with a space.
     ?                # Pop and print without a newline.
      T%              # Take all integers modulo 10.
        Ð             # Triplicate the array.
         ðý,          # Join by spaces and print with a newline.
            ¦         # Remove the first element of the array.
             ‚        # Wrap it up, (pop a, b push [a, b]).
              ø       # Zip.
               €O     # Sum up each element.

Uses the CP-1252 encoding. Try it online!.

\$\endgroup\$
4
\$\begingroup\$

MATL, 32 30 29 28 27 26 25 24 bytes

t"X@qZ"y1X9&VhDTTH&Y+10\

1 Byte saved thanks to @Luis

Try it Online!

Modified version for all test cases

Explanation

        % Implicitly grab input
t       % Duplicate the input
"       % For each element of the input (really just a shortcut to loop numel(input) times)
  X@q   % Determine the current loop index and subtract 1
  Z"    % Create an array of blanks this size (these are the padding to the left)
  y     % Copy the current array of numbers from the stack
  1X9   % Get the pre-defined output format of %.15g from the clipboard
  &V    % Convert the input to it's character representation with single spacing
  h     % Horizontally concatenate the left padding and the numbers
  D     % Display the result (consumes the string)
  TT    % Create a two-element vector of 1's ([1 1])
  H&Y+  % Convolve [1 1] with the array (computes the pair-wise sum)
  10\   % Mod 10 the result
        % Implicitly close for loop
\$\endgroup\$
  • \$\begingroup\$ Nice! I was trying to find a way to get the leading spaces. I forgot V allows format spec. You can save 1 byte using Z" instead of O: see this link (I'm having trouble with the format in the comment) \$\endgroup\$ – Luis Mendo Jun 10 '16 at 9:18
  • \$\begingroup\$ @LuisMendo Thanks for the tip! Yea I got the format spec from D which uses that single-space-between numbers by default. \$\endgroup\$ – Suever Jun 10 '16 at 12:45
2
\$\begingroup\$

Actually, 43 bytes

;l;D+#"{:^%d}"%╗W;' j1╟╜f.;pXZ`i+9u@%`MdXWX

Try it online!

This program prints a single trailing newline after the output.

Explanation:

;l;D+#"{:^%d}"%╗W;' j1╟╜f.;pXZ`i+9u@%`MdXWX
;l;D+                                        calculate the width of the field (2L-1 where L = len(input))
     #"{:^%d}"%╗                             push to a list, make a Python new-style format string for centering text, save in reg0
                W;' j1╟╜f.;pXZ`i+9u@%`MdXW   while the top of the stack is truthy:
                 ;' j1╟                        duplicate list, join with spaces, push string to a list
                       ╜f.                     center string and print  
                          ;pXZ                 zip list with itself shifted forward by 1 (zip(a,a[1:]))
                              `i+9u@%`M        map: add each pair and mod by 10
                                       dX      discard the last value (which was not added with anything)
                                          X  discard the now-empty list after the loop to avoid printing it
\$\endgroup\$
2
\$\begingroup\$

Mathematica, 67 Bytes

MatrixForm@NestList[Mod[Total/@Partition[#,2,1],10]&,#,Length@#-1]&

Example:enter image description here

\$\endgroup\$
2
\$\begingroup\$

CJam, 25 bytes

q~{_2ew::+Af%}h;]eeSff*N*

Try it online!

Explanation

This uses a fairly neat trick to generate the triangle layout.

q~      e# Read and evaluate input.
{       e# While the list of digits is non-empty...
  _2ew  e#   Duplicate and get all sublists of length 2.
  ::+   e#   Sum each pair.
  Af%   e#   Take each result modulo 10.
}h
;]      e# Discard the final empty list and wrap the others in an array.
ee      e# Enumerate the array. E.g. for input `[7 5 0 9]` we now get this:
        e# [[0 [7 5 0 9]]
        e#  [1 [2 5 9]]
        e#  [2 [7 4]]
        e#  [3 [1]]]
Sff*    e# Perform S* on each element at depth two. For the integers from the
        e# enumeration this gives a string of that many spaces, i.e. the correct
        e# indentation. For the lists of digits this inserts a space character
        e# between every two digits, thereby spacing out the digits as necessary.
N*      e# Put linefeeds between the pairs of indentation and digit list.
\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES6) 147 bytes

a=>{o=0;e=(c=>console.log(' '.repeat(o++)+c.join` `));l=1;while(l){p=0,d=[],e(a),a.map(b=>{p?d.push((v+b)%10):0;p=1,v=b});d.length<2?l=0:a=d};e(d)}
\$\endgroup\$
  • \$\begingroup\$ Hmm, I have a couple of ideas, to golf this down \$\endgroup\$ – Bálint Jun 10 '16 at 11:36
1
\$\begingroup\$

Julia, 60 59 bytes

\(x,s="")=x==[]?"":s*join(x," ")"
"*(diag(x'.+x,1)%10\" "s)

Based on @Sp3000's answer. The function \ accepts an array as input and returns a string.

Try it online!

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

Pyke, 21 bytes

lVDm}R$],FsT%)od*pKDP

Try it here!

I'd like to think this method's a little bit different.

[1, 2, 3, 5, 8] - take the input
[2, 4, 6, 10, 16] - double it
[1, 2, 3, 5, 8] - take the input again
[1, 1, 2, 3] - get the deltas
[[2,1], [4,1], [6,2], [10,3]] - transpose them together
[3, 5, 8, 13] - apply addition
[3, 5, 8, 3] - mod 10
\$\endgroup\$
1
\$\begingroup\$

Perl 6,  65 63 62  61 bytes

{put ' 'x my$++,$_ for @_,{.rotor(2=>-1).map(*.sum%10).list}...1}
{put ' 'x my$++,$_ for @_,{@(.rotor(2=>-1).map(*.sum%10))}...1}
{put ' 'x my$++,$_ for @_,{@(map *.sum%10,.rotor(2=>-1))}...1}
{put ' 'x my$++,$_ for @_,{[map *.sum%10,.rotor(2=>-1)]}...1}

Explanation:

{ # anonymous block that takes the list as input (@_)

  put # print with trailing newline

    ' ' x ( my $ )++, # pad with one more space than previous iteration
    $_                   # the list to print for this iteration
    # The 「.Str」 method on a List puts spaces between elements
    # which is what 「put」 calls on anything that isn't a Str

  for # do that for every list produced from the following

    @_, # the input list

    { # anonymous block that takes the previous list as input ($_)

      [ # turn the following from a Seq into an Array

        map
          *.sum % 10, # sum the values and modulus 10 of the following:

          # take the previous list 2 at a time, backing up one
          $_.rotor( 2 => -1 )

      ]

    }

    ... # repeatedly call that block until:

    1   # the result is only one element long
}

Example:

my &digital-triangle-sum = {put ' 'x my$++,$_ for @_,{[map *.sum%10,.rotor(2=>-1)]}...1}

for [7,5,0,9], [0,1,0], [1,0,0,0], [9,2,4,5,3,2,2] -> \List {
   digital-triangle-sum List

   put '';
}
7 5 0 9
 2 5 9
  7 4
   1

0 1 0
 1 1
  2

1 0 0 0
 1 0 0
  1 0
   1

9 2 4 5 3 2 2
 1 6 9 8 5 4
  7 5 7 3 9
   2 2 0 2
    4 2 2
     6 4
      0
\$\endgroup\$
1
\$\begingroup\$

TSQL, 198 194 191 bytes

By using GOTO instead of one of the WHILE, I was able to golf 3 characters

Golfed

DECLARE @ varchar(100)= '1 2 3 4 5 6 7'

DECLARE @j INT=1,@i INT=LEN(@)a:
PRINT @
WHILE @i>@j
SELECT
@=STUFF(@,@i-1,2,RIGHT(SUBSTRING(@,@i-2,1)+SUBSTRING(@,@i,1)*1,1)+' '),@i-=2SELECT
@=STUFF(@,@j,1,' '),@j+=1,@i=LEN(@)IF @i>0GOTO a

Try it online(using old script with 2*WHILE)

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

Java 7, 230 215 213 bytes

int c=0;void m(int[]a){int l=a.length,j=-1,i=-1;if(l<1)return;int[]x=new int[l-1];while(++j<c)p(" ");for(;++i<l;p(a[i]+" "))if(i<l&i>0)x[i-1]=(a[i-1]+a[i])%10;p("\n");c++;m(x);}<T>void p(T s){System.out.print(s);}

This ended up being a bit longer than I thought.. Maybe it can be golfed a bit more though, since I kinda messed up I think..

Some bytes saved thanks to @GiacomoGarabello.

Ungolfed & test code:

Try it here.

class Main{
  static int c = 0;

  static void m(int[] a){
    int l = a.length,
        j = -1,
        i = -1;
    if(l < 1){
      return;
    }
    int[] x = new int[l-1];
    while(++j < c){
      p(" ");
    }
    for(; ++i < l; p(a[i] + " ")){
      if(i < l & i > 0){
        x[i - 1] = (a[i - 1] + a[i]) % 10;
      }
    }
    p("\n");
    c++;
    m(x);
  }

  static <T> void p(T s){
    System.out.print(s);
  }

  static void printAndReset(int[] a){
    m(a);
    c = 0;
    System.out.println();
  }

  public static void main(String[] a){
    printAndReset(new int[]{ 7, 5, 0, 9 });
    printAndReset(new int[]{ 0 });
    printAndReset(new int[]{ 1, 2 });
    printAndReset(new int[]{ 8, 7 });
    printAndReset(new int[]{ 0, 0 });
    printAndReset(new int[]{ 1, 4, 2 });
    printAndReset(new int[]{ 0, 1, 0 });
    printAndReset(new int[]{ 1, 0, 0, 0 });
    printAndReset(new int[]{ 1, 2, 3, 4 });
    printAndReset(new int[]{ 1, 2, 3, 5, 8 });
    printAndReset(new int[]{ 9, 2, 4, 5, 3, 2, 2 });
  }
}

Output:

7 5 0 9 
 2 5 9 
  7 4 
   1 

0 

1 2 
 3 

8 7 
 5 

0 0 
 0 

1 4 2 
 5 6 
  1 

0 1 0 
 1 1 
  2 

1 0 0 0 
 1 0 0 
  1 0 
   1 

1 2 3 4 
 3 5 7 
  8 2 
   0 

1 2 3 5 8 
 3 5 8 3 
  8 3 1 
   1 4 
    5 

9 2 4 5 3 2 2 
 1 6 9 8 5 4 
  7 5 7 3 9 
   2 2 0 2 
    4 2 2 
     6 4 
      0 
\$\endgroup\$
  • \$\begingroup\$ Create a function void p(String s){System.out.print(s);} and replace the standard print. For the println use p("\n"). Move the int i and int j near the int c=0; (int c=0,i,j;) and move the print(a[i]+" ") inside the for condition so you can remove the brackets for a total of -11 \$\endgroup\$ – Giacomo Garabello Jul 19 '16 at 13:05
  • \$\begingroup\$ @GiacomoGarabello I learned this shorter print variant today: <T>void p(T s){System.out.print(s);} instead of void p(String s){System.out.print(s);}. \$\endgroup\$ – Kevin Cruijssen Aug 2 '16 at 9:23
  • \$\begingroup\$ Wow... 2 bytes closer to Pyth and Jelly! Thanks! \$\endgroup\$ – Giacomo Garabello Aug 2 '16 at 9:37
  • \$\begingroup\$ @GiacomoGarabello "2 bytes closer to Pyth and Jelly!" Hehe. 'Always look on the bright side of life.' ;) \$\endgroup\$ – Kevin Cruijssen Aug 2 '16 at 9:47
1
\$\begingroup\$

C# 6, 125+31 125+18 = 143 bytes

string f(int[] n,string s="")=>s+string.Join(" ",n)+"\n"+(n.Length>1?f(n.Zip(n.Skip(1),(a,b)=>(a+b)%10).ToArray(),s+" "):"");

The +18 is for using System.Linq;

Thanks to @TheLethalCoder for saving 13 bytes, by pointing out a unnecessary using statement

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

JavaScript (ES6), 77 bytes

a=a.map((_,i)=>(b=a,a=[a.map((e,j)=>j>i?(e+a[j-1])%10:''),b.join` `)).join`
`
\$\endgroup\$
0
\$\begingroup\$

C, 138 bytes

Golfed

c,d;main(int a,char**b){b++;while(c++,d=0,--a)while(d<a)printf("%*c%c",!d?c:1,*b[d],(d+2>a)*10),++d<a?*b[d-1]=(*b[d-1]+*b[d]-96)%10+48:0;}

Ungolfed

c,d;
main(int a,char**b){
b++;
while(c++,d=0,--a)
    while(d<a)
        printf("%*c%c",
          !d?c:1,      //number of blanks in front of digit
          *b[d],       //digit
          (d+2>a)*10), //returns 10(new line) only for d+1 == a
        ++d<a
          ? *b[d-1]=(*b[d-1]+*b[d]-96)%10+48 //update digit 
          :  0;
}
\$\endgroup\$
0
\$\begingroup\$

C#, 167 bytes

Im actually pretty proud of this solution, lambda expressions are so fun once you get the hang of them

void f(List<int> a){int x=a.Count;for(int s=0;s<x;s++){Console.WriteLine(new String(' ',s)+string.Join(" ",a));a=a.Take(x-s-1).Select((v,i)=>(a[i+1]+v)%10).ToList();}}

here ungolfed for further improvements:

void f(List<int> a)
{
int x = a.Count;
for (int s = 0; s<x ;s++)
{
    Console.WriteLine(new String(' ',s)+string.Join(" ",a));
    a=a.Take(x-s-1).Select((v,i)=>(a[i+1]+v)%10).ToList();
}
}

try it out here

\$\endgroup\$
  • \$\begingroup\$ You can save 2 bytes by using an array for input rather than a list. List<int> a -> int[] a, int x=a.Count -> int x=a.Length, .ToList() -> ToArray() \$\endgroup\$ – Sok Jun 14 '16 at 13:34
0
\$\begingroup\$

Haskell, 139 bytes

f=mapM(\(r,s)->putStrLn$r++(s>>=(++" ").show)).zip(iterate(' ':)"").takeWhile(/=[]).iterate g where g(_:[])=[];g(y:p:ys)=mod(y+p)10:g(p:ys)

Takes input as an argument, outputs to STDOUT.

Ungolfed version:

f = mapM (\(r, s) -> putStrLn $ r ++ (s >>= (++ " ") . show))
    . zip (iterate (' ' :) "")
    . takeWhile (/= [])
    . iterate sumTerms
    where sumTerms (_:[]) = []
          sumTerms (y:p:ys) = mod (y+p) 10 : sumTerms (p:ys)
\$\endgroup\$
0
\$\begingroup\$

Python 3, 97 bytes

def f(x):print(*x);x[-1]==''or f(['']+[(x[i]+x[i+1])%10if''!=x[i]else''for i in range(len(x)-1)])

Prints a single trailing newline.

How it works

def f(x):                            function with input of list of numbers
print(*x)                            print the old line of the triangle
x[-1]==''or...                       if no more numbers, stop...
(x[i]+x[i+1])%10if''!=x[i]else''...  ...else compute the next entry in the new line if
                                     possible...
...for i in range(len(x)-1)          ...for all relevant digit pairs...
['']+...                             ...concatenate with empty string to force new leading
                                     space...
f(...)                               ...and pass to function

Try it on Ideone

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

J, 44 bytes

(#\.-#)|."_1#\.(":@{."_1)2(10|+/)\^:(]i.@#)]

Based on this solution.

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

Javascript (using external library) (198 bytes)

n=>{a=_.From(n);b=a.Write(" ");c=1;while(++c){a=a.BatchAccumulate(2).Where(y=>y.Count()==2).Select(z=>z.Sum()%10);if(a.Count()==0){break;}b+="\r\n"+_.Range(0,c).Write(" ",x=>"")+a.Write(" ")}return b}

Link to lib: https://github.com/mvegh1/Enumerable/

Code explanation: This was easy using the library! Doesn't win in bytes, but the code isn't too verbose and easy to read. So, the input "n' is an array of integers. Load it up into the library, stored in variable "a". "b" is the return string, store the joined string with " " as delimiter into b. c is the current iteration, use this to determine the number of spaces to insert. NOTE: This only seems to work nicely when the input is from 0-9. Then, while true, repeat a certain set of code. That code is to create adjacent batch sets of the current enumerable "a", i.e if we have [1,2,3,4,5,6] we get [1,2],[2,3],[3,4],...[6] ... then filter that so we only have the batches of size 2. Then we map that to a collection of the sums of the batches % 10. If a is empty, we are done, else we add the new line to our return. Finally return...

Picture coming in a few min.

enter image description here

\$\endgroup\$

Your Answer

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

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