Easy binary triangle

18

0

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!

user72269

Posted 2017-08-13T17:35:36.183

Reputation:

Is excess white space acceptable and if so, which (leading lines / leading / trailing / training lines)? – Jonathan Allan – 2017-08-13T17:39:31.873

I recommend allowing trailing space/newline and leading newline or consistent leading whitespace. – Mr. Xcoder – 2017-08-13T17:41:26.893

1Can we return a a list of lists of numbers? – Erik the Outgolfer – 2017-08-13T17:42:56.703

@StepHen Right, but are you sure that's supposed to be part of the challenge? – totallyhuman – 2017-08-13T17:44:16.143

8@EriktheOutgolfer list of lists is fine! – None – 2017-08-13T17:50:55.057

1Since a list of lists is fine, I'm assuming that the centered alignment is not required, is it? – Luis Mendo – 2017-08-13T20:39:24.947

@LuisMendo List of lists is a list of lists, otherwise you must output what you see.Center aligment IS required. – None – 2017-08-13T20:58:28.970

1It'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 – Luis Mendo – 2017-08-13T22:59:42.877

Answers

7

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

HyperNeutrino

Posted 2017-08-13T17:35:36.183

Reputation: 26 575

You can replace ¶Ç with µ for -1. – Erik the Outgolfer – 2017-08-13T17:58:14.437

@EriktheOutgolfer ooh thanks! – HyperNeutrino – 2017-08-13T17:58:32.590

4

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.

Mr. Xcoder

Posted 2017-08-13T17:35:36.183

Reputation: 39 774

3

Jelly, 8 bytes

⁼€=ḂŒḄµ€

Try it online!

-2 thanks to HyperNeutrino.

Erik the Outgolfer

Posted 2017-08-13T17:35:36.183

Reputation: 38 134

Oh seriously.... split second ninjad :p – Jonathan Allan – 2017-08-13T17:53:49.093

@JonathanAllan It was really a rule change...btw I think this is golfable too... – Erik the Outgolfer – 2017-08-13T17:54:10.683

yeah I had a 15 byte grid then the 10 byte lists... – Jonathan Allan – 2017-08-13T17:55:17.987

1@JonathanAllan Hyper is being good... – Erik the Outgolfer – 2017-08-13T17:57:49.620

¬^Ḃ 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 – HyperNeutrino – 2017-08-13T17:58:20.250

3

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!

totallyhuman

Posted 2017-08-13T17:35:36.183

Reputation: 15 378

2Haha, now we're tied :) – Mr. Xcoder – 2017-08-13T17:54:48.223

65 bytes (for the longer one) – Mr. Xcoder – 2017-08-13T18:43:48.597

3

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

ETHproductions

Posted 2017-08-13T17:35:36.183

Reputation: 47 880

Hooray for builtins :P :P :P – HyperNeutrino – 2017-08-13T18:11:06.560

Yaay, someone broke the chain Python-Jelly-Python-Jelly! – Mr. Xcoder – 2017-08-13T18:12:49.803

@Mr.Xcoder Where Jelly is really implemented in Python. :p – Erik the Outgolfer – 2017-08-13T18:14:50.850

3

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.

Mr. Xcoder

Posted 2017-08-13T17:35:36.183

Reputation: 39 774

Remove the second ] in the first code. – Jakube – 2017-08-14T12:54:02.790

@Jakube Yeah, thanks. Forgot about auto-listification for appending elements to lists. – Mr. Xcoder – 2017-08-14T12:57:31.773

And here is a 14 bytes solution: ms_+Bm%d2d%hd2 – Jakube – 2017-08-14T12:58:25.797

@Jakube Yes, I was thinking of bifurcation right now, but I couldn't do it since I am on mobile. Thanks a lot again! – Mr. Xcoder – 2017-08-14T12:59:43.903

3

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

djhurio

Posted 2017-08-13T17:35:36.183

Reputation: 1 113

2I 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. – MickyT – 2017-08-13T20:36:27.033

173 bytes – Giuseppe – 2017-08-15T06:38:47.890

3

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]&

J42161217

Posted 2017-08-13T17:35:36.183

Reputation: 15 931

Huh I didn't think of considering it a cellular automata. Nice! – HyperNeutrino – 2017-08-13T21:44:57.943

2The same thing but golfier: #&@@@NestList[CellularAutomaton@51,{{1},0},#-1]&, 48 bytes – Not a tree – 2017-08-13T21:48:02.480

1

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;

Uriel

Posted 2017-08-13T17:35:36.183

Reputation: 11 708

1126 bytes – tsh – 2017-08-15T02:03:29.853

1

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.

Neil

Posted 2017-08-13T17:35:36.183

Reputation: 95 035

1

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]])&,#]&

user73398

Posted 2017-08-13T17:35:36.183

Reputation:

1

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!

Xcali

Posted 2017-08-13T17:35:36.183

Reputation: 7 671

1

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:

LarsW

Posted 2017-08-13T17:35:36.183

Reputation: 239

0

SOGL V0.12, 13 bytes

∫:2\r*Kr1κ+╥T

Try it Here!

dzaima

Posted 2017-08-13T17:35:36.183

Reputation: 19 048

0

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

Neil

Posted 2017-08-13T17:35:36.183

Reputation: 95 035

0

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

David Bailey

Posted 2017-08-13T17:35:36.183

Reputation: 141

If you didn't know, you can use A=Array to save 8 bytes. – None – 2017-08-13T22:36:14.423

Good point, I didn't think of that – David Bailey – 2017-08-14T09:43:12.660

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. – None – 2017-08-14T18:01:46.883

0

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!

Birjolaxew

Posted 2017-08-13T17:35:36.183

Reputation: 323

(n%2+(i==n))%2 can be simplified to (n+(i==n))%2. – Neil – 2017-08-14T13:15:26.053

Or 1&n^i==n might work, but I haven't tested it. – Neil – 2017-08-14T13:17:10.693

Also try n--?...:[]. (And you don't need the ; in code golf.) – Neil – 2017-08-14T13:17:36.307

2*n+1 might be n-~n, but I can never remember for sure. – Neil – 2017-08-14T13:18:25.800

@Neil Thanks! Added the ones I could get working – Birjolaxew – 2017-08-14T13:23:28.523

Perhaps n%2^i==n works? – Neil – 2017-08-14T14:23:37.723

0

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!

ბიმო

Posted 2017-08-13T17:35:36.183

Reputation: 15 345

0

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

cole

Posted 2017-08-13T17:35:36.183

Reputation: 3 526

0

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

Emigna

Posted 2017-08-13T17:35:36.183

Reputation: 50 798

0

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)

miles

Posted 2017-08-13T17:35:36.183

Reputation: 15 654

0

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

Kevin Cruijssen

Posted 2017-08-13T17:35:36.183

Reputation: 67 575

0

GolfScript, 49 bytes

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

Try it online!

Marcos

Posted 2017-08-13T17:35:36.183

Reputation: 171