12
\$\begingroup\$

Challenge

Given a sequence of non-negative integers, create a function that output a descendant pyramid where the children are the sum of both parent numbers.

The result is outputted as an string using tab \t.

Note: trailing tabs on each line are not required

1\t\t2\t\t3\n\t3\t\t5\t\n\t\t8\t\t results in 
1       2       3
    3       5   
        8       

Optionally result can be outputted as an array using an empty position as space.

[[1,,2,,3],
[,3,,5,],
[,,8,,]]

Example:

Given 4,5,7,3,4,2 Output:

4       5       7       3       4       2
    9       12      10      7       6
        21      22      17      13
            43      39      30
                82      69
                    151

Rules

  • Standard rules apply
  • Input can be a string using any separator or an array
  • Leading/trailing newlines and tabs are permitted (but not required as long as the output is an inverted pyramid)

Test Cases

Input: 1,3,5

1       3       5
    4       8
        12


Input: 9,8,7,6,5

9       8       7       6       5
    17      15      13      11
        32      28      24
            60      52
                112


Input: 5,5,2,5

[[5,,5,,2,,5],
[,10,,7,,7,],
[,,17,,14,,],
[,,,31,,,]]

Input: 3,3,3

[[3,,3,,3],
[,6,,6,],
[,,12,,]]

Winning criteria is


Note: This challenge is very close to Generate Pascal's triangle. The difference is the custom starting sequence (pascal goes from 1 and in ascendant mode, this from an input and in descendant mode).

Sandbox post

\$\endgroup\$
10
  • \$\begingroup\$ Somewhat related. \$\endgroup\$ Commented Jul 3, 2018 at 17:47
  • \$\begingroup\$ non-negative integers do we have to handle 0? There are some golfing possibilities if empty spaces are filled with 0s. \$\endgroup\$ Commented Jul 3, 2018 at 18:00
  • \$\begingroup\$ May we return an array with tabs or empty strings/arrays in the empty positions? \$\endgroup\$
    – Adám
    Commented Jul 3, 2018 at 18:07
  • 2
    \$\begingroup\$ "Leading/trailing newlines and tabs are permitted" - May we include empty result(s) at the bottom in the array output too? \$\endgroup\$ Commented Jul 3, 2018 at 18:26
  • 1
    \$\begingroup\$ @JonathanAllan trailing newlines and tabs are permitted \$\endgroup\$
    – Adám
    Commented Jul 3, 2018 at 18:28

17 Answers 17

4
\$\begingroup\$

Jelly,  14  13 bytes

14 -> 13 assumes trailing spaces-only entry is allowed in the list format output; if not I shall revert to the 14 (asked)

+ƝƬK€z⁶Zṙ"JC$

A monadic link. Output is a list of lists using space characters as the spaces (includes a single trailing spaces-only entry).

Try it online! (includes a footer to show the list structure since running the monadic link as a full program will print smashed output implicitly.)

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

APL (Dyalog Unicode), 31 28 bytesSBCS

Tacit prefix function. Uses a single space as empty slot marker. Returns list of lists of numbers/spaces.

⍳∘≢{∊(⍺⍴''),,∘' '¨2+/⍣⍺⊢⍵}¨⊂

Try it online!

⍳∘≢{}¨⊂ apply the below function for each of
the ɩndices  of  the tally with
the entire argument:

⊢⍵ yield the right argument (the original input)

2+/⍣⍺ apply pairwise sum as many times as indicated by the left argument

,∘' '¨ append a space to each number

(), append that to the following:

  ⍺⍴'' left-argument elements of the empty string (padded with spaces)

ϵnlist (flatten)

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

05AB1E, 15 14 bytes

-1 bytes thanks to Kevin Cruijssen

vD„		ý'	N×ì,ü+

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ That's a lot of spaces... tabs? \$\endgroup\$ Commented Jul 3, 2018 at 18:10
  • \$\begingroup\$ ...or zero spaces and a few tabs :p \$\endgroup\$ Commented Jul 3, 2018 at 18:10
  • \$\begingroup\$ Indeed, those are tabs :) \$\endgroup\$
    – Emigna
    Commented Jul 3, 2018 at 18:11
  • \$\begingroup\$ gF can be v for -1. \$\endgroup\$ Commented Nov 23, 2022 at 7:40
3
\$\begingroup\$

Wolfram Language (Mathematica), 74 bytes

ArrayPad[Riffle[#,],k++,]&/@NestList[k=0;BlockMap[Tr,#,2,1]&,#,Tr[1^#]-1]&

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Husk, 22 bytes

zoΣ~+R"	"oJ"		"msNU¡Ẋ+

Try it online!

Explanation

z(Σ~+R" "(J"  "ms))NU¡Ẋ+  -- example input: [1,2,3]
                     ¡    -- infinitely do and collect in list
                      Ẋ+  -- | sum adjacent
                          -- : [[1,2,3],[3,5],[8],[],[],...
                    U     -- keep up until first repetition: [[1,2,3],[3,5],[8],[]]
z(                )N      -- zip with natural numbers under (example on 1 [1,2,3])
   ~+    (       )        -- | join arguments modified by
     R" "                 -- | | replicate tab: " "
               ms         -- | | show each: ["1","2","3"]
          J"  "           -- | | join with 2 tabs: ["1","  ","2","  ","3"]
                          -- | : [" ","1","  ","2","  ","3"]
  Σ                       -- | concatenate: " 1  2  3"
                          -- : [" 1  2  3","  3  5","   8"]
\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 73 bytes

Weird source code ... Anyway, that's !

Includes leading and trailing whitespace.

f=(a,p=`
`)=>p+a.join`		`+(1/(y=a.shift())?f(a.map(x=>y+(y=x)),p+`	`):'')

Try it online!

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

Perl 5 -a, 62 bytes

$,="\t\t";do{say"\t"x$i++,@F;map$_+=$F[++$q[@F]],@F}while$#F--

Try it online!

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

Python 3, 101 93 80 bytes

Saved 7 bytes (map(str,x) instead of for in and init y as '') and got rid of the trailing newlines (x and[ instead of print(), thanks to Jo King.

Saved 13 bytes ([*map(sum,zip(x,x[1:]))] instead of [x[j]+x[j+1]for j in range(len(x)-1)]) thanks to ovs.

f=lambda x,y='':x and[y+'		'.join(map(str,x))]+f([*map(sum,zip(x,x[1:]))],y+'	')

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ @ovs: Ah, cool. I should have realized I could map the sum. Thanks! \$\endgroup\$
    – Emigna
    Commented Jul 4, 2018 at 9:45
1
\$\begingroup\$

Retina, 35 bytes

+¶<`\d+ *(?=(\d+)?)
    $#1*$.(*_$1*)   

Try it online! Explanation:

+

Repeat until the buffer stops changing,

¶<`

Print the contents of the buffer before the substitution, with a trailing newline, and

\d+ *(?=(\d+)?)
    $#1*$.(*_$1*)   

Substitute a single number with a pair of tabs, but a number followed by another number with a tab, the sum, and another tab.

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

Red, 151 bytes

func[b][m: length? b repeat n m[loop n - 1[prin"^-"]print replace/all
form b" ""^-^-"c: copy[]repeat i -1 + length? b[append c b/(i) + b/(i + 1)]b: c]]

Try it online!

More readable:

f: func [ b ] [
    m: length? b
    repeat n m [
        loop n - 1 [ prin tab ]
        print replace/all form b " " rejoin [ tab tab ]
        c: copy []
        repeat i (length? b) - 1 [
            append c b/(i) + b/(i + 1)
        ]
        b: c
    ]
]
\$\endgroup\$
1
\$\begingroup\$

Perl 6, 50 48 bytes

{$_,{say "	"x$++~.join("		");$_[1..*]Z+@$_}...0}

Try it online!

Anonymous code block that takes a list of integers and prints the inverted pyramid.

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

C# (Visual C# Compiler), 163 bytes

b=>{var s="";var c=b.Length;for(int i=0;i<c;i++){for(int z=0;z<i;z++)s+="\t";for(int x=0;x<c-i;x++){s+=b[x]+"\t\t";b[x]=x==c-i-1?0:b[x]+b[x+1];}s+="\n";}return s;}

Try it online!

Readable:

b =>    {
            var s = "";
            var c = b.Length;
            for (int i = 0; i < c; i++)
            {
                for (int z = 0; z < i; z++)
                    s += "\t";
                for (int x = 0; x < c - i; x++)
                {
                    s += b[x] + "\t\t";
                    b[x] = x == c - i - 1 ? 0 : b[x] + b[x + 1];
                }
                s += "\n";
            }
            return s;
        }
\$\endgroup\$
1
\$\begingroup\$

Japt -Rx, 20 18 bytes

The second line includes a trailing tab.

Nc¡=ä+
Ëq' ² iEç'  

Try it


Explanation

                  :Implicit input of array U
N                 :The array of inputs (NOT the input array)
 c                :Concatenate
  ¡               :  Map U
    ä+            :    Consecutive sums of U
   =              :    Reassign to U for next iteration
\n                :Reassign the resulting 2D-array to U
Ë                 :Map each array at index E
 q                :  Join with
  '\t             :   Tab
     ²            :   Repeated twice
       i          :  Prepend
          '\t     :   Tab
         ç        :   Repeated
        E         :   E times
                  :Implicitly join with newlines, trim (not strictly necessary) and output.
\$\endgroup\$
0
1
\$\begingroup\$

C (clang), 112 109 bytes

  • -3 from @ceilingcat
j,k;f(*i,c){for(j=c;j;j-=puts("")){for(k=c-j;k--;)putchar(9);for(;++k<j;i[k]+=i[k+1])printf("%d\t\t",i[k]);}}

Try it online!

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

Vyxal, 18 bytes

2lṠ)↔ðdvj:ẏ$꘍⁋ð9CV

Try it Online!

I think this works? Output format is annoying.

   )↔              # Repeat until no change, collecting values
  Ṡ                # Sums of
2l                 # Consecutive pairs
       vj          # Join each by...
     ðd            # Double spaces
           $꘍      # Pad left with spaces by
         :ẏ        # range(0, len(list)
             ⁋     # Join by newlines
                 V # Replace
              ð    # Spaces
               9C  # With tabs
\$\endgroup\$
1
\$\begingroup\$

Python 3, 79 75 70 bytes

Has leading tabs. Prints the required output then prints trailing tabs and newlines forever.

def f(x,y='\n'):print(y,*x,sep='        ');f([*map(sum,zip(x,x[1:]))],y+'   ')

Try it online!

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

Ruby, 67 bytes

A straightforward recursive solution.

F=->a,n=0{puts ?\t*n+a*"		"
a[0]&&F[a.each_cons(2).map(&:sum),n+1]}

Attempt This 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.