用数字三角形总结


28

好吧,总结一下。

编写一个程序或函数,该程序或函数接受一个非空的十进制整数列表(0-9),并输出一个向下的数字“三角形”,输入列表在顶部,其中第一行之后的每个数字都是两位数字的总和以10为模

例如,输入[7, 5, 0, 9]有输出

7 5 0 9
 2 5 9
  7 4
   1

因为2(7 + 5) mod 105(5 + 0) mod 109(0 + 9) mod 10,等一路1(7 + 4) mod 10

如果列表中只有一项,则输出与输入匹配;否则,输出与输入匹配。例如[4]将产生的输入

4

以下是一些其他示例:

[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

注意在输出中:

  • 第一行没有前导空格。
  • 随后的每一行都比前一行多一个领先的空间。
  • 数字之间用一个空格隔开。
  • 每行最多可以有一个尾随空格。
  • 可能只有一个可选的尾随换行符。
  • 您必须使用正常十进制数字(0到9)的字符。

以字节为单位的最短代码获胜。抢七是较早的答案。


1
首先,我读了“数字创伤”的标题

Answers:


24

BrainF ** K,396个 391字节

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

我无法抗拒这样做的诱惑。至少三角形的尖端朝下。

输入是一串数字字符,后跟一个换行符。

输出将在每行上包含一个尾随空格。

例子:

$ 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 

说明

由于从功能的角度来解释代码相当困难,因此我们可以从磁带在不同时间的状态的角度来看它。这里的核心思想是将我们输出的三角形初始化为一个紧密堆积的数组(对于BF,无论如何),该数组的大小在每次循环迭代时缩小1。另一个重要的思想是,我们255用来指示可以在磁带上搜索的“占位符”。

初始化

这是最简单的步骤。在程序开始时,我们执行以下操作:

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

这将使磁带进入以下状态(其中>N<指示指针在磁带上的位置)

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

这里的第一个数字是“缓冲区”位置。我们不会长期使用它,但是使小操作更简单并复制数据很有用。
第二个数字是我们将在每一行的开头从第一行开始)输出的空格数。第一行将没有前导空格。
第三个数字是我们输出的空格字符。
第四个数字是占位符255,因此我们可以相对轻松地返回此位置。

输入值

从这个位置,我们将阅读所有字符。在此步骤结束时,我们希望处于以下情况:

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

其中,a b c d e f ...表示输入的数字字符的字符串(不是换行符)。

我们通过以下方式完成此任务:

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

这有一些细微差别。首先,我们将在获取每个字符时输出它们,然后在其后输出一个空格。其次,我们不想将ASCII值复制到磁带上,而是要复制实际的数字。第三,我们想在碰到换行符时停下来,并让自己处于一个好的位置。
说我们的输入是6723。然后,在阅读第一篇文章时6,我们的磁带如下所示:

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

我们使用来检查该值是否等于10(ASCII换行符),----------[++++++++++。然后,我们打印出该值,并从输入值中同时减去48,然后在其旁边的值(>>++++++++[-<++++<------>>]<)上加上32,继续进行操作:

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

请注意,在整个过程中,我们可以假设输入右边的所有数字均为0 -这意味着,如果我们使用右边的值来计算6 * 8and ,就不会有破坏任何先前状态的危险4 * 8
现在,我们输出刚生成的空格字符,并接受一个新的输入,删除我们在那里计算的空格。最终,输入将由新行终止,并且循环将退出,并在新行的原处保留255,----------]-)。这是我们用来导航磁带的第二个占位符。在我们的场景中,此时的磁带正好是这样的:

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

计算方式

这种工作方式是,255每次循环迭代时,占位符之间的数字列表将缩小一。当它只剩下1位数字时,我们就完成了,应该立即停止操作(请注意,此时,该列表中的每个数字都已经输出,因此我们不必担心再次输出它)。

现在,我们使用此技巧来导航到第一个255占位符:<+[-<+]-。这样可以有效地在磁带的左侧搜索a 255,而这两者之间没有任何改变。现在,我们已经移动了指针,我们可以检查退出条件:如果列表中只有一位数字,则右边两个空格的单元格将保留255。因此,我们对此进行检查并开始循环:>>+[-<<

循环的第一步是输出换行符。因此,我们移到第一个单元格(我们的缓冲单元),向其添加10并输出。下一步是输出所有前导空格字符。输出它们后,我们增加前导空格数的计数。这些步骤通过以下步骤完成:

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

这使我们处于这种状态:

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

我们的下一步是将列表中的第一个值复制到第二个占位符之后255

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

我们基本上是通过在占位符之间来回跳来完成此操作255的,而将我们留在这里:

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

现在,我们开始循环,遍历列表的其余部分,并在单击时停止255>+[-<

此时,最左边的数字始终为0。因此,由于我们喜欢它们,255因此在其中弹出了一个占位符,以便可以返回到列表中的位置。下一步是将列表中的第二个位置移动到我们将第一个位置移动到第二个占位符之后的位置255。这些步骤通过以下步骤完成:

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

让我们离开这里:[ 0 2 32 255 255 >0< 2 3 255 7 6 7 0 ] 现在,67都已移动到可以进行计算的位置。我们需要的两个副本,7因为列表中的下一个数字也将需要它。该7立即之后255服务于这个目的,而其他7将被计算消耗。

首先,我们将两个数字相加:

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

离开我们这里:

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

接下来的步骤组合是最复杂的。我们需要查看所指向的数字是否大于10,如果是,则减去10。实际上,我们要做的是从中减去10,然后看它是否0在减法的任何点都命中。如果是这样,我们10稍后再添加。最后,我们应该将模的总和设为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
>>+[-<<<+>>>[-<->]<+++++++++>>>+]

至此,我们已经完成了目标。我们的模数总和为10!此外,无论数字是否大于10,我们都会在这里结束:

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

我们的下一个目标是输出这个新的总和,在其后加上一个空格,然后将其重新添加到我们的列表中。我们使用我们以前的255-hopping并将其加到48总和上的技术来完成所有这些工作,因此我将不做详细介绍。

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

我们在这里:[ 0 2 32 255 3 255 2 3 255 7 0 0 51 >32< ] 请注意我们如何255在新注入的对象之后放置一个额外的占位符,3以免在列表中失去位置。此时,我们已经输出了总和及其空间,因此我们需要清理并恢复为该循环的下一个迭代将起作用的状态。我们需要清除5132单元格,将7一次移至右侧,然后导航到列表占位符,以便我们可以重新开始。

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

现在,我们在这里:[ 0 2 32 255 3 >0< 2 3 255 0 7 0 ... ]
下一个迭代正是我们想要的位置。因此,请检查255,然后继续!(>+]

当我们退出循环时,我们将拥有一个全新的列表-由上一个列表的总和组成。第一次,它看起来像这样:

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

现在,我们要在新列表中重复整个过程,因此我们255向左下拉并重新开始!我们需要使用进行一些清理>>[-]<<,然后使用删除占位符<-。之后,我们将与输入后的位置完全相同,因此我们可以做同样的检查:<+[-<+]->>+和繁荣!我们有完整的循环!我们需要的只是结束括号,结束时我们已经输出了所有内容,因此我们完成了:]


顺便欢迎您回来:)自2015年以来,您还没有回答:o
卡尔文的爱好

1
@HelkaHomba我知道!我仍然会经常访问,但是我忍不住为此写了代码。它非常适合该语言:)
BrainSteel

9
“完美的高炉”概念使我难以理解:-)
Luis

7

果冻20 19 18 字节

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

在线尝试!

背景

在Jelly中生成数字很简单。输出有点复杂。

Jelly有一个内置的网格原子(G),可显示一个2D列表,其中行之间有换行符,列之间有空格。我们采用2D数字数组(每行反转生成),并用fill value对其进行转置@。验证生成的数组并再次转置之后,应用G以下命令。

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

为了获得所需的三角形形状,我们要做的就是删除填充值。

怎么运行的

Ṛ+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.

5

Pyth-18个字节

j.e+*dkjdbP.ueM+Vt

测试套件

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]

5

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.


3
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)
xsot

1
@xsot That is... an amazing use of None!
Sp3000

How does print return something? I don't know of the print function returning.
Erik the Outgolfer

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Oh wait, you mean Python's print function returning - yeah it returns None on completion
Sp3000

I mean, how useful is None on slicing?
Erik the Outgolfer

5

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!.


4

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

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)
Luis Mendo

@LuisMendo Thanks for the tip! Yea I got the format spec from D which uses that single-space-between numbers by default.
Suever

2

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

2

Mathematica, 67 Bytes

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

Example:enter image description here


2

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.

1

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)}

Hmm, I have a couple of ideas, to golf this down
Bálint


1

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

1

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


@Mego ​ ​ fixed
Brad Gilbert b2gills

1

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)


1

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 

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
Giacomo Garabello

@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);}.
Kevin Cruijssen

Wow... 2 bytes closer to Pyth and Jelly! Thanks!
Giacomo Garabello

@GiacomoGarabello "2 bytes closer to Pyth and Jelly!" Hehe. 'Always look on the bright side of life.' ;)
Kevin Cruijssen

1

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


0

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`
`

0

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;
}

0

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


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()
Sok

0

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)

0

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



0

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.