18
\$\begingroup\$

Given as input a positive integer n>=1, output the first n rows of the following triangle:

                  1
                1 0 1
              0 0 1 0 0
            1 1 1 0 1 1 1
          0 0 0 0 1 0 0 0 0
        1 1 1 1 1 0 1 1 1 1 1
      0 0 0 0 0 0 1 0 0 0 0 0 0
    1 1 1 1 1 1 1 0 1 1 1 1 1 1 1
  0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1

The rows alternate between all zeroes and all ones, except the center column is flipped.

Test cases

  • Input: 3

  • Output:

        1
      1 0 1
    0 0 1 0 0
    
  • Input: 10

  • Output:

                      1
                    1 0 1
                  0 0 1 0 0
                1 1 1 0 1 1 1
              0 0 0 0 1 0 0 0 0
            1 1 1 1 1 0 1 1 1 1 1
          0 0 0 0 0 0 1 0 0 0 0 0 0
        1 1 1 1 1 1 1 0 1 1 1 1 1 1 1
      0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
    1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1
    

Your code must work for any n<100. This is , hence the shortest code in bytes wins!

Trailing spaces / newlines and leading newlines are allowed!

\$\endgroup\$
  • \$\begingroup\$ Is excess white space acceptable and if so, which (leading lines / leading / trailing / training lines)? \$\endgroup\$ – Jonathan Allan Aug 13 '17 at 17:39
  • 1
    \$\begingroup\$ Can we return a a list of lists of numbers? \$\endgroup\$ – Erik the Outgolfer Aug 13 '17 at 17:42
  • 8
    \$\begingroup\$ @EriktheOutgolfer list of lists is fine! \$\endgroup\$ – user72269 Aug 13 '17 at 17:50
  • 1
    \$\begingroup\$ Since a list of lists is fine, I'm assuming that the centered alignment is not required, is it? \$\endgroup\$ – Luis Mendo Aug 13 '17 at 20:39
  • 1
    \$\begingroup\$ It's your challenge, but in my opinion if you are flexible enough to allow a list of lists it doesn't make any sense to be strict with the formatting \$\endgroup\$ – Luis Mendo Aug 13 '17 at 22:59

23 Answers 23

7
\$\begingroup\$

Jelly, 7 bytes

Ṭ=Ḃµ€ŒB

Try it online!

-1 byte thanks to Erik the Outgolfer

Explanation

Ṭ=Ḃµ€ŒB  Main link
    €    For each element in (implicit range of) the input:
Ṭ        List 1s and 0s with 1s in the indices in the left argument (generates `[0, 0, ..., 1]`)
 =Ḃ      Is this equal to `(z % 2)` where `z` is the range number? (Every other row is flipped)
     ŒB  Reflect each row
\$\endgroup\$
  • \$\begingroup\$ You can replace ¶Ç with µ for -1. \$\endgroup\$ – Erik the Outgolfer Aug 13 '17 at 17:58
  • \$\begingroup\$ @EriktheOutgolfer ooh thanks! \$\endgroup\$ – HyperNeutrino Aug 13 '17 at 17:58
4
\$\begingroup\$

Python 2, 50 bytes

lambda n:[i*`i%2`+`~i%2`+i*`i%2`for i in range(n)]

Try it online!

This returns the rows as a list of Strings.

Python 2, 67 65 63 bytes (formatted)

n=input()
for i in range(n):k=i*`i%2`;print(n-i)*" "+k+`~i%2`+k

Try it online!

This outputs with a trailing space on each line.

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

Jelly, 8 bytes

⁼€=ḂŒḄµ€

Try it online!

-2 thanks to HyperNeutrino.

\$\endgroup\$
  • \$\begingroup\$ Oh seriously.... split second ninjad :p \$\endgroup\$ – Jonathan Allan Aug 13 '17 at 17:53
  • \$\begingroup\$ @JonathanAllan It was really a rule change...btw I think this is golfable too... \$\endgroup\$ – Erik the Outgolfer Aug 13 '17 at 17:54
  • \$\begingroup\$ yeah I had a 15 byte grid then the 10 byte lists... \$\endgroup\$ – Jonathan Allan Aug 13 '17 at 17:55
  • 1
    \$\begingroup\$ @JonathanAllan Hyper is being good... \$\endgroup\$ – Erik the Outgolfer Aug 13 '17 at 17:57
  • \$\begingroup\$ ¬^Ḃ can become =Ḃ because NOT (XOR (A B)) is just IFF (A B) edit apparently I golfed more than I thought I had o_O lol \$\endgroup\$ – HyperNeutrino Aug 13 '17 at 17:58
3
\$\begingroup\$

Python 2, 50 bytes

lambda n:[[i%2]*i+[~i%2]+i*[i%2]for i in range(n)]

Try it online!

Python 2, 53 bytes

lambda n:[(([i%2]*i+[~i%2])*2)[:-1]for i in range(n)]

Try it online!

Python 2, 67 bytes

lambda n:[[[i%2,~i%2][j==i]for j in range(2*i+1)]for i in range(n)]

Try it online!

\$\endgroup\$
  • 2
    \$\begingroup\$ Haha, now we're tied :) \$\endgroup\$ – Mr. Xcoder Aug 13 '17 at 17:54
  • \$\begingroup\$ 65 bytes (for the longer one) \$\endgroup\$ – Mr. Xcoder Aug 13 '17 at 18:43
3
\$\begingroup\$

Japt, 12 9 bytes

õÈÇ¥Y^uÃê

Test it online!

Quite Slightly sad compared to Jelly, but Japt doesn't have anything like so I must make do with what I have...

Explanation

 õÈ   Ç   ¥ Y^ uà ê
UõXY{XoZ{Z==Y^Yu} ê}      Ungolfed
                          Implicit: U = input number
Uõ                        Create the range [1..U].    [1, 2, 3, 4]
  XY{              }      Map each item X and 0-index Y in this to
     Xo                     Create the range [0..X).  [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
       Z{      }            Map each item Z in this to
         Z==Y                 Z is equal to Y         [[1], [0, 1], [0, 0, 1], [0, 0, 0, 1]]
             ^Yu              XORed with Y % 2.       [[1], [1, 0], [0, 0, 1], [1, 1, 1, 0]]
                  ê         Bounce.                   [[1],
                                                       [1, 0, 1],
                                                       [0, 0, 1, 0, 0],
                                                       [1, 1, 1, 0, 1, 1, 1]]
                          Implicit: output result of last expression
\$\endgroup\$
  • \$\begingroup\$ Hooray for builtins :P :P :P \$\endgroup\$ – HyperNeutrino Aug 13 '17 at 18:11
  • \$\begingroup\$ Yaay, someone broke the chain Python-Jelly-Python-Jelly! \$\endgroup\$ – Mr. Xcoder Aug 13 '17 at 18:12
  • \$\begingroup\$ @Mr.Xcoder Where Jelly is really implemented in Python. :p \$\endgroup\$ – Erik the Outgolfer Aug 13 '17 at 18:14
3
\$\begingroup\$

Mathematica, 77 bytes

Table[CellularAutomaton[51,{{1},0},#,{All,All}][[i]][[#-i+2;;-#+i-2]],{i,#}]&

@Not a tree golfed it down to 48 bytes!

Mathematica, 48 bytes

#&@@@NestList[CellularAutomaton@51,{{1},0},#-1]&
\$\endgroup\$
  • \$\begingroup\$ Huh I didn't think of considering it a cellular automata. Nice! \$\endgroup\$ – HyperNeutrino Aug 13 '17 at 21:44
  • 2
    \$\begingroup\$ The same thing but golfier: #&@@@NestList[CellularAutomaton@51,{{1},0},#-1]&, 48 bytes \$\endgroup\$ – Not a tree Aug 13 '17 at 21:48
3
\$\begingroup\$

Pyth, 14 bytes

Thanks to @Jakube for saving 2 bytes!

ms_+Bm%d2d%hd2

Try it here!

Pyth, 15 bytes

Thanks a lot to @Jakube for -1 byte

m++K*d]%d2%td2K

Try it here.

Pyth, 16 bytes

m++K*d`%d2`%td2K

Try it here.

\$\endgroup\$
  • \$\begingroup\$ Remove the second ] in the first code. \$\endgroup\$ – Jakube Aug 14 '17 at 12:54
  • \$\begingroup\$ @Jakube Yeah, thanks. Forgot about auto-listification for appending elements to lists. \$\endgroup\$ – Mr. Xcoder Aug 14 '17 at 12:57
  • \$\begingroup\$ And here is a 14 bytes solution: ms_+Bm%d2d%hd2 \$\endgroup\$ – Jakube Aug 14 '17 at 12:58
  • \$\begingroup\$ @Jakube Yes, I was thinking of bifurcation right now, but I couldn't do it since I am on mobile. Thanks a lot again! \$\endgroup\$ – Mr. Xcoder Aug 14 '17 at 12:59
3
\$\begingroup\$

R, 73 bytes

Thanks to Giuseppe! Nice catch.

n=scan();for(i in 1:n)cat(c(rep(" ",n-i),x<-rep(1-i%%2,i-1)),i%%2,x,"\n")

Try it online!

R, 78 bytes

n=scan();for(i in 1:n)cat(x<-c(rep(" ",n-i),rep(1-i%%2,i-1)),i%%2,rev(x),"\n")

Try it online!

R, 82 bytes

n=scan();for(i in 1:n){j=i%%2;x=c(rep(" ",n-i),rep(1-j,i-1));cat(x,j,rev(x),"\n")}

Try it online!

R, 110 bytes - output to stdout

m=matrix(x<-rep_len(0:1,n<-scan()),n,n-1);m[upper.tri(m,T)]=" ";for(i in 1:n)cat(rev(m[i,]),1-x[i],m[i,],"\n")

Try it online!

R, 130 bytes - output to a file

m=matrix(x<-rep_len(0:1,n<-scan()),n,n-1);m[upper.tri(m,T)]=" ";for(i in 1:n)cat(rev(m[i,]),1-x[i],m[i,],"\n",file="a",append=i>1)

Try it online!

Writing out to a file as I do not know how to fit it in the console if n==99 (see the result here).

\$\endgroup\$
  • 2
    \$\begingroup\$ I don't think you need to worry about the console wrapping it for larger n's. Personally I would ditch the ,file="a" as the output to STDOUT is correct. \$\endgroup\$ – MickyT Aug 13 '17 at 20:36
  • 1
    \$\begingroup\$ 73 bytes \$\endgroup\$ – Giuseppe Aug 15 '17 at 6:38
1
\$\begingroup\$

Pascal, 181 154 bytes

27 bytes saved thanks to @ThePirateBay

procedure f(n:integer);var i,j:integer;begin for i:=1to n do begin write(' ':(n-i+1)*2);for j:=1to i*2-1do write((ord(j<>i)+i)mod 2,' ');writeln()end end;

Try it online!

Unglofed

procedure f (n: integer);
    var i, j: integer;
    begin
        for i := 1 to n do
        begin
            write(' ': (n-i+1) * 2);
            for j := 1 to i*2-1 do
                write((ord(j<>i) + i) mod 2, ' ')
            writeln()
        end
    end;
\$\endgroup\$
  • 1
    \$\begingroup\$ 126 bytes \$\endgroup\$ – tsh Aug 15 '17 at 2:03
1
\$\begingroup\$

Retina, 25 bytes

.+
$*0
0
1$`¶
T`d`10`¶.*¶

Try it online! Explanation: The first stage converts the input into a string of zeros of that length. The second stage then takes all of the prefixes of that string (not including the string itself) and prefixes a 1 to them. The third stage then toggles the bits on alternate lines.

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

05AB1E, 24 21 18 bytes

FNÉN×NÈJûIN>-úˆ}¯»

Try it online!


Edit: Well, it is my first 05AB1E golf so I'm not surprised things can be golfed. Edit history:

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

Perl 5, 58 + 1 (-n) = 59 bytes

say$"x(2*--$_).($/=$i%2 .$")x$i.(1-$i%2).$".$/x$i++while$_

Try it online!

# Perl 5, 59 + 1 (-n) = 60 bytes

say$"x(2*--$_).($i%2 .$")x$i.(1-$i%2).($".$i%2)x$i++while$_

Try it online!

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

Mathematica, 90 bytes

Array[(x=Table[1,f=(2#-1)];x[[⌈f/2⌉]]=0;If[#==1,{1},If[OddQ@#,x/.{1->0,0->1},x]])&,#]&
\$\endgroup\$
0
\$\begingroup\$

SOGL V0.12, 13 bytes

∫:2\r*Kr1κ+╥T

Try it Here!

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

Charcoal, 18 bytes

EN⪫IE⁺¹ι﹪⁺ι¬λ² ‖O←

Try it online! Link is to verbose version of code. Explanation:

EN              For each of the input number of rows
  ⪫             Join with spaces
   I            Convert to string
    E⁺¹ι        For each column
        ﹪⁺ι¬λ²  Calculate the digit
‖O←             Reflect to the left
\$\endgroup\$
0
\$\begingroup\$

JavaScript, 140 132 bytes (with proper formatting)

n=>{A=Array;a='';b=0;for(x of A(n)){for(c of A(n-b))a+=' ';for(c of A(b))a+=b%2;a+=(b+1)%2;for(c of A(b))a+=b%2;a+='\n';b++}return a}

Try It Online

\$\endgroup\$
  • \$\begingroup\$ If you didn't know, you can use A=Array to save 8 bytes. \$\endgroup\$ – user72349 Aug 13 '17 at 22:36
  • \$\begingroup\$ Good point, I didn't think of that \$\endgroup\$ – David Bailey Aug 14 '17 at 9:43
  • \$\begingroup\$ You can save at least 3 more bytes by: 1) Instead of A=Array; you can init variable A on first array call (ie. for(x of(A=Array)(n))) which saves 1 byte, 2) Replace '\n' with literal new line (use grave accents), 3) You don't need parentheses in (b+1)%2 because it is equivalent to b+1&1. \$\endgroup\$ – user72349 Aug 14 '17 at 18:01
0
\$\begingroup\$

JavaScript (ES6), 74 73 71 68 64 bytes

-7 bytes by @Neil

f=n=>n--?[...f(n), [...Array(n-~n)].map((v,i)=>(n+(i==n))%2)]:[]

Try it online!

Simple recursive function that generates the lines one by one. Outputs as array of array of numbers.


Outputs as formatted string:

JavaScript (ES6), 122 119 118 bytes

f=(n,w=2*n+1,N=n,s=" ".repeat((N-n)*2))=>(--n?f(n,w,N)+s+[...Array(n-~n)].map((v,i)=>(n+(i==n))%2).join(" "):s+1)+"\n"

Try it online!

\$\endgroup\$
  • \$\begingroup\$ (n%2+(i==n))%2 can be simplified to (n+(i==n))%2. \$\endgroup\$ – Neil Aug 14 '17 at 13:15
  • \$\begingroup\$ Or 1&n^i==n might work, but I haven't tested it. \$\endgroup\$ – Neil Aug 14 '17 at 13:17
  • \$\begingroup\$ Also try n--?...:[]. (And you don't need the ; in code golf.) \$\endgroup\$ – Neil Aug 14 '17 at 13:17
  • \$\begingroup\$ 2*n+1 might be n-~n, but I can never remember for sure. \$\endgroup\$ – Neil Aug 14 '17 at 13:18
  • \$\begingroup\$ @Neil Thanks! Added the ones I could get working \$\endgroup\$ – Birjolaxew Aug 14 '17 at 13:23
0
\$\begingroup\$

Haskell, 54 bytes

Straight forward list comprehension:

f n=[k++[mod i 2]++k|i<-[1..n],k<-[mod(i+1)2<$[2..i]]]

Try it online!

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

J, 32 bytes

3 :'-.^:(2|y)(=|.)i.>:+:y'&.>@i.

Try it online! This is an anonymous function that returns a boxed list of values.

I like to imagine that the explicit function definition saves bytes by virtue of removing caps and such, but it probably adds a few bytes in comparison to a tacit answer.

Explanation

3 :'-.^:(2|y)(=|.)i.>:+:y'&.>@i.
                              i. For i = 0 ... input - 1
3 :'-.^:(2|y)(=|.)i.>:+:y'        Explicit function: compute nth row
                    >:+:y          2n+1
                  i.               Range [0,2n+1)
             (=|.)                 Equate range to reversed range
                                    (yield 0 0 0 ... 1 ... 0 0 0)
                                   If
                                    n = 1 (mod 2)
                                   Then
                                    Negate each value
                          &.>     Box
\$\endgroup\$
0
\$\begingroup\$

05AB1E, 11 bytes

FN°SRNF_}ûˆ

Try it online!

Explanation

F             # for N in range [0 ... input-1] do:
 N°           # push 10^N
   S          # split to list of digits
    R         # reverse
     NF_}     # N times do: logical negation
         û    # palendromize
          ˆ   # add to global list
              # implicitly display global list
\$\endgroup\$
0
\$\begingroup\$

J, 17 bytes

(2&|~:0=i:)&.>@i.

Try it online!

Outputs a list of boxed arrays.

Explanation

(2&|~:0=i:)&.>@i.  Input: n
               i.  Range from 0 to n, exclusive end
           & >     Unbox each and perform on each x
        i:           Range from -x to x, inclusive
      0=             Equal to 0
    ~:               Not equal
 2&|                 x mod 2
           &.>       Perform inverse of unbox (box)
\$\endgroup\$
0
\$\begingroup\$

Java 8, 121 111 109 101 bytes

n->{String r[]=new String[n],t;for(int i=0,j;i<n;r[i++]=t+i%2+t)for(j=0,t="";j++<i;t+=i%2);return r;}

My current byte-score (101) is also a row of the binary triangle. :)

Explanation:

Try it here.

n->{                         // Method with integer parameter and String-array return-type
  String r[]=new String[n],  //  Result String-array
         t;                  //  Temp String
  for(int i=0,j;             //  Some index-integers
      i<n;                   //  Loop (1) from 0 to `n` (exclusive)
      r[i++]=                //    After every iteration, set the next row to:
        t+                   //     `t` +
        i%2                  //     Center digit (`i` has already been raised by 1 now)
        +t)                  //     + `t` again
    for(j=0,t="";            //   Reset index `j` and the temp-String `t`
        j++<i;               //   Inner loop (2) from 0 to `i` (exclusive)
      t+=i%2                 //    Append `t` with an outer digit
    );                       //   End of inner loop (2)
                             //  End of loop (1) (implicit / single-line body)
  return r;                  //  Return resulting String-array
}                            // End of method
\$\endgroup\$
0
\$\begingroup\$

GolfScript, 49 bytes

~.:a;0\{..1+2%.!""+@*+" "a(:a*+.1>-1%\+"\n"+\)}*;

Try it online!

\$\endgroup\$

Your Answer

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