35
\$\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
  • 1
    \$\begingroup\$ First I read the title as "Digital Trauma" \$\endgroup\$
    – cat
    Commented Jun 10, 2016 at 18:03

38 Answers 38

25
\$\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\$
3
  • \$\begingroup\$ Welcome back by the way :) You haven't answered since 2015 :o \$\endgroup\$ Commented Jun 10, 2016 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
    Commented Jun 10, 2016 at 11:44
  • 10
    \$\begingroup\$ "Perfect for BF" is a concept that elludes me :-) \$\endgroup\$
    – Luis Mendo
    Commented Jun 10, 2016 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\$
7
\$\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\$
6
  • 5
    \$\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
    Commented Jun 10, 2016 at 3:32
  • 2
    \$\begingroup\$ @xsot That is... an amazing use of None! \$\endgroup\$
    – Sp3000
    Commented Jun 10, 2016 at 3:38
  • \$\begingroup\$ How does print return something? I don't know of the print function returning. \$\endgroup\$ Commented Jun 11, 2016 at 9:23
  • \$\begingroup\$ @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Oh wait, you mean Python's print function returning - yeah it returns None on completion \$\endgroup\$
    – Sp3000
    Commented Jun 11, 2016 at 9:33
  • \$\begingroup\$ I mean, how useful is None on slicing? \$\endgroup\$ Commented Jun 11, 2016 at 9:36
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\$

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\$
2
  • \$\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
    Commented Jun 10, 2016 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
    Commented Jun 10, 2016 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\$

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\$
2
  • \$\begingroup\$ I couldn't get this code to run. Can you post a link to it working online? \$\endgroup\$ Commented Jul 16 at 0:01
  • \$\begingroup\$ @AndrewBayly Indeed, it seems to have a typo, (extra [ and missing >); I think the code should start a=>a.map((_,i)=>(b=a,a=a.map etc. \$\endgroup\$
    – Neil
    Commented Jul 16 at 4:33
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\$
2
\$\begingroup\$

Haskell, 88 bytes

f=mapM putStrLn.(""%)
s%x@(_:y)=(s++(x>>=(:" ").last.show)):(' ':s)%zipWith(+)x y
_%_=[]

Try it online!

I chose the same I/O format and counted f= to compete fairly with the other Haskell answer.

Replacing the first line by just (""%) would give a 72-byte answer that returns a list of lines.

Instead of writing show.(`mod`10) or [mod(a+b)10|(a,b)<-zip x y], it turns out to be shorter to use last on the result of show, which is kinda cute.

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

R, 75 74 bytes

`?`=\(x,n=j)if(j<-sum(x|1)){cat(strrep(" ",n-j),x%%10,"\n");x[-j]+x[-1]?n}

Attempt This Online!

A function that accepts a vector of the integers and prints a formatted triangle. Conveniently, cat pastes spaces between the numbers by default. However, to produce the trailing spaces, I had to use strrep instead of rep since strrep outputs a single string, whereas rep makes a mess: it outputs a vector of space characters which are separated by the spaces inserted by cat.

\$\endgroup\$
4
  • \$\begingroup\$ -1 byte by making it recursive. \$\endgroup\$
    – pajonk
    Commented Jul 10 at 6:31
  • \$\begingroup\$ @pajonk thanks! although, I don't get it - how is n=j possible if j does not even exist yet? \$\endgroup\$ Commented Jul 10 at 8:01
  • 2
    \$\begingroup\$ @int21hGlorytoUkraine The n=j in the function definition just assigns the token n to j without evaluating until it's used in the function body. Luckily, j gets defined within the function body before n gets used. \$\endgroup\$ Commented Jul 10 at 9:46
  • \$\begingroup\$ @DominicvanEssen It seems that this is what is called the "lazy evaluation" then... \$\endgroup\$ Commented Jul 10 at 10:11
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\$
1
  • \$\begingroup\$ Hmm, I have a couple of ideas, to golf this down \$\endgroup\$
    – Bálint
    Commented Jun 10, 2016 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\$
2
1
\$\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\$
1
  • \$\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
    Commented Jun 14, 2016 at 13:34
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\$

J, 44 bytes

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

Based on this solution.

\$\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\$
4
  • \$\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\$ Commented Jul 19, 2016 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\$ Commented Aug 2, 2016 at 9:23
  • \$\begingroup\$ Wow... 2 bytes closer to Pyth and Jelly! Thanks! \$\endgroup\$ Commented Aug 2, 2016 at 9:37
  • 1
    \$\begingroup\$ @GiacomoGarabello "2 bytes closer to Pyth and Jelly!" Hehe. 'Always look on the bright side of life.' ;) \$\endgroup\$ Commented Aug 2, 2016 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
1
\$\begingroup\$

05AB1E, 11 bytes

A translation of Adnan's answer to modern 05AB1E.

vT%DðýNú,ü+

Try it online!

ú pads a string with a given number of spaces and ü applies a binary function between pairs of adjacent items.

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

PowerShell Core, 99 69 bytes

($a=$args)|%{"$s$a"
$a=$a|%{($p+$_)%10;$p=$_}|select -skip 1
$s+=" "}

Try it online!

-99 bytes thanks to @mazzy !

\$\endgroup\$
1
  • 1
    \$\begingroup\$ in the PowerShell style Try it online! :) \$\endgroup\$
    – mazzy
    Commented Jun 8, 2021 at 12:22
1
\$\begingroup\$

Stax, 14 bytes

üε↕Φ¬ⁿ╣VU6Co'm

Run and debug it

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

Jelly, 14 bytes

SƝƬ%⁵µ⁶oṚżK€ṖY

Try it online!

Full program which prints the result

How it works

SƝƬ%⁵µ⁶oṚżK€ṖY - Main link. Takes a list L on the left
  Ƭ            - Until reaching a fixed point:
S              -   Take the sum of:
 Ɲ             -     All overlapping pairs
   %⁵          - Mod each by 10
     µ         - Begin a new link with the list of steps as the argument:
      ⁶o       - Replace all elements with spaces
        Ṛ      - Reverse
          K€   - Join each list with spaces
         ż     - Zip together
            Ṗ  - Remove the last line of spaces
             Y - Join on newlines
\$\endgroup\$
1
\$\begingroup\$

Vyxal C, 10 bytes

λḢ+Ṫ₀%;↔vṄ

Try it Online!

λ     ;    # Push a lambda
 Ḣ         # Remove first  item
  +        # Vectorised addition to original
   Ṫ       # Remove last item
    ₀%     # For each item, modulo 10
       ↔   # Repeat on input while output is truthy
        vṄ # Foreach, join by spaces
           # (C flag) Center and join by newlines.

-6 thanks to Aaron Miller.

Old version, 16 bytes:

L(ðn*₴DṄ,0p+vtḢṪ

Try it Online!

L(               # Length times
  ðn*            # (iteration number) spaces
     ₴           # Output without a newline
      D          # Triple current array
       Ṅ,        # Output first joined by spaces
         0p      # Prepend a 0 to the second
           +     # Vectorised addition
            vt   # Foreach, get last digit
              ḢṪ # And get rid of first + last items
\$\endgroup\$
1
1
\$\begingroup\$

Zsh, 99 80 bytes

a=($@)
for j;{<<<$s$a;for i ({2..$#a})b+=($[(a[i-1]+a[i])%10])
s+=\ ;a=($b);b=;}

try it online!   99 bytes

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

Pip -s, 20 bytes

Wg&OlPBxg:_+BMP Pg%t

Takes the numbers as command-line arguments. Try it online!

Explanation

We'll be leaning heavily on the -s flag, which sets the list output format to "join on spaces." A list of three integers [1 2 3] is printed as 1 2 3; a list of three empty strings ["" "" ""] is printed as (two spaces).

Wg&OlPBxg:_+BMP Pg%t
                      g is list of cmdline args; l is []; x is ""; t is 10 (implicit)
Wg                    While g is truthy (nonempty)
  &                   and the following is also truthy...
    lPBx              Append the empty string to l in-place
   O                  and output l (joined on spaces) with no trailing newline
                      The shenanigans with l 1) output 0, 1, 2, etc. spaces at the start of
                      each iteration, and 2) always evaluate as truthy (non-empty list),
                      thereby not affecting the while loop condition
                      Inside the loop:
                 g%t    Take each value in g, mod 10
                P       Print that list (joined on spaces) with a trailing newline
             MP         To each pair of numbers in the list, map this function:
          _               The first number
           +B             plus the second number
        g:              Assign that result back to g
\$\endgroup\$
1
\$\begingroup\$

Uiua, 29 bytes

∧(◿10≡/+◫2&p⊂↯:@ ⊙⊸/$"_ _")°⊏

Try it

°⊏          # range of 0 to the input's length
∧(          # fold over this (N), with the input as the initial value:
  ⊙⊸/$"_ _" #   to the value, without consuming it: join on spaces
  &p⊂↯:@    #   prepend N spaces to this string and print it
  ◿10≡/+◫2  #   take the sums of pairwise windows, mod 10;
)           #     this is the next value for the loop
\$\endgroup\$
1
\$\begingroup\$

K (ngn/k), 42 bytes

{`0:({x#" "}'!#x),'{" "/$x}'-1_{1_+':x}\x}

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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