Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Write a program or function that takes in a positive integer (via stdin, command line, or function arg) and prints or returns a string of that many of these small triangles tiled together, alternating which way they point:

 /\
/__\

This sole triangle is the output if the input is 1.

If the input is 2, the output is

  ____
 /\  /
/__\/

If the input is 3, the output is

  ____
 /\  /\
/__\/__\

If the input is 4, the output is

  ________
 /\  /\  /
/__\/__\/

And so on. Your program must support inputs up to 216 - 1 = 65535.

Details

  • The leftmost triangle always points upwards.
  • There may be trailing spaces but there may not be unnecessary leading spaces.
  • There may be an optional trailing newline.
  • Note that for 1 the output is two lines long but otherwise it's three. This is required.
  • The shortest submission in bytes wins.
share|improve this question

12 Answers 12

Pyth, 44 42

ItQpdd*\_*4/Q2)jbms<*dQhQ,c" /\ "2,\/"__\\

The first line:

ItQpdd*\_*4/Q2)
ItQ           )    If the input is not 1
   pdd             Print two spaces
      *\_*4/Q2     Then groups of 4 underscores, repeated input/2 times.

The other two lines are generated by noticing that the second line consists of " /" and "\ " alternating input + 1 times, and the third line consists of "/" and "__\" alternated in the same fashion.

share|improve this answer
13  
striked out 44 is still normal 44 :( –  Optimizer 16 hours ago
    
42. Of course! –  mbomb007 3 hours ago

Python 2, 89 88 named / 86 unnamed

f=lambda n:"\n".join(["  "+n/2*4*"_",(" /\ "*n)[:2+2*n],("/__\\"*n)[:2*n-~(n%2)]][n<2:])

(Thanks to @orlp for a byte)

This is a function which takes in an int n and returns the triangles as a string using the row-by-row approach.

e.g. print f(10) gives

  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/
share|improve this answer
    
You can shave off a character, turning " /\\ " into " /\ ". –  orlp 9 hours ago
    
Doesn't this lambda work in Python 3 also? –  mbomb007 3 hours ago
    
@mbomb007 There's a floor division in there –  Sp3000 1 hour ago
    
@orlp Allow me now, to add further confusion, but deleting my comment ;) –  FryAmTheEggman 31 mins ago

SQL: 182 bytes

Not that this'll ever be the shortest, but it's still amusing to try to minimize sql ;) lol I did this in Oracle 11, however, these should be basic SQL.

select rpad('  ',2+v,'____')||z||rpad(' /',2+v,'\  /')||decode(y,1,'\')||z||rpad('/',1+v,'__\/')||decode(y,1,'__\') from (select floor(&&i/2)*4 v, mod(&&i,2) y, chr(10) z from dual);

Explanation

  select -- line 1
         rpad('  ',2+v,'____') || z || -- every pair of triangles
         -- line 2
         rpad(' /',2+v,'\  /') ||  -- every pair of triangles
              decode(y,1,'\') || z || -- add the final triangle, input: 1,3,5 etc.
         -- line 3
         rpad('/',1+v,'__\/') ||  -- every pair of triangles
              decode(y,1,'__\')   -- add the final triangle, input: 1,3,5 etc.
    from (select floor(&&i/2)*4 v,   -- common multiplier. 4 extra chars for every triangle pair
                 mod(&&i,2) y,  -- Flag for the final triangle (odd inputs, 1,3,5, etc)
                 chr(10) z  -- CR, here to save space.
            from dual);

Output

  SQL> accept i
  1
  SQL> /


   /\
  /__\


  SQL> accept i
  2
  SQL> /

    ____
   /\  /
  /__\/


  SQL> accept i
  3
  SQL> /

    ____
   /\  /\
  /__\/__\


  SQL> accept i
  12
  SQL> /

    ________________________
   /\  /\  /\  /\  /\  /\  /
  /__\/__\/__\/__\/__\/__\/


  SQL>
share|improve this answer

JavaScript (ES6), 109

Way too long

f=(n,z=(a,b)=>a.repeat(n).slice(0,n+n-b)+'\n')=>(n>1?'  '+z('____',n*2&2):'')+z(' /\\ ',-2)+z('/__\\',-n%2-1)

Test in Firefox/FireBug console

console.log(f(1),f(2),f(3),f(4),f(9))

Output

 /\ 
/__\

  ____
 /\  /
/__\/

  ____
 /\  /\ 
/__\/__\

  ________
 /\  /\  /
/__\/__\/

  ________________
 /\  /\  /\  /\  /\ 
/__\/__\/__\/__\/__\
share|improve this answer

Julia, 115 bytes

n->(m=n÷2;p=println;k=n%2>0?m+1:m;e=m<k?"":"/";t=" /\\ ";b="/__\\";if n>1 p("  "*"_"^4m)end;p(t^k*" "*e);p(b^k*e))

This creates an unnamed function which accepts an integer and prints the triangles. To call it, give it a name, e.g. f=n->(...).

Ungolfed + explanation:

function f(n)

    m = n ÷ 2                    # Number of upside down triangles
    p = println                  # Store println function to save space
    k = n % 2 > 0 ? m + 1 : m    # Number of right side up triangles
    e = m < k ? "" : "/"         # n even? End lines with a /

    # Top of the triangle
    t = " /\\ "

    # Bottom of the triangle
    b = "/__\\"

    # Print the bottoms of any upside down triangles
    # * performs string concatenation
    # ^ performs string repetition
    if n > 1
        println("  " * "_"^4m)
    end

    # Print the triangle tops (these have two trailing spaces
    # if the last triangle isn't upside down)
    println(t^k * " " * e)

    # Print the triangle bottoms
    println(b^k * e)
end

Example output:

julia> for i = 1:10 f(i) end
 /\  
/__\
  ____
 /\  /
/__\/
  ____
 /\  /\  
/__\/__\
  ________
 /\  /\  /
/__\/__\/
  ________
 /\  /\  /\  
/__\/__\/__\
  ____________
 /\  /\  /\  /
/__\/__\/__\/
  ____________
 /\  /\  /\  /\  
/__\/__\/__\/__\
  ________________
 /\  /\  /\  /\  /
/__\/__\/__\/__\/
  ________________
 /\  /\  /\  /\  /\  
/__\/__\/__\/__\/__\
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/

I'm pretty bummed that this is so long. I'm sure there are golfing opportunities aplenty but they aren't clear to me at the moment. Let me know if you have any suggestions or if you'd like any further explanation!

share|improve this answer

CJam, 68 62 60 bytes

As far as I can see, this is a completely different approach than the other CJam solution. This can be golfed a lot.

"/__\\ /\\"4/]ri:R(['/"  /"'_4*"__\\"'\L]3/R*<+zR1>SS+*\W%N*

Try it online here

share|improve this answer

CJam, 73 68 63 62 60 bytes

This definitely needs some golfing...

S2*l~:I2/'_4**N]I(g*S"\\  /"'\{I2md@*@@*'/\@}:F~N"__\\/"_W<F

Test it here.

Explanation

"Print the first line:";
S2*l~:I2/'_4**N]I(g*

S2*                  "Push a string with 2 spaces.";
   l~:I              "Read and eval the input, store it in I.";
       2/            "Divide by two to get the number of top segments.";
         '_4**       "Push '____' and repeat it by the number of segments.";
              N]     "Push a newline and wrap everything in an array.";
                I(g* "Get sign(I-1) and repeat the array that often. This is a no-op
                      for I > 1 but otherwise empties the array.";

"Print the other two lines. The basic idea is to define block which takes as arguments
 a repeatable 4-character string as well as another string which only gets printed for
 even I.";
S"\\  /"'\{I2md@*@@*'/\@}:F~N"__\\/"_W<F

S                                        "Push a space.";
 "\\__/"'\                               "Push the string '\__/' and the character \.";
          {             }:F~             "Store this block in F and evaluate it.";
           I2md                          "Get I/2 and I%2 using divmod.";
               @*                        "Pull up the second argument and repeat it I%2
                                          times. This turns it into an empty string for
                                          even I.";
                 @@                      "Pull up I/2 and the 4-character string.";
                   *                     "Repeat the string I/2 times.";
                    '/\@                 "Push a / and reorder the three line parts.";
                            N            "Push a newline.";
                             "__\\/"_W<F "Call F again, with '__\/' and '__\'.";
share|improve this answer

CJam, 55 bytes

ri:I2/4*"  "'_@*+" /\ "I*I)2*<"/__\\"I*I2*I2%)+<]I2<>N*

I tried porting my Python answer and it turned out to be shorter than the other CJams.

share

Haskell 155 Bytes

I found a slightly different approach that turned out to be shorter than my original method. My original attempt is preserved below. As with before, golfing tips are appreciated.

m n=putStrLn.unlines.dropWhile(all(==' ')).z["  "," /","/"].foldr z["","",""]$map t[1..n]
t n
 |odd n=["","\\","__\\"]
t _=["____","  /","/"]
z=zipWith(++)

Previous Attempt 197 179 Bytes

t n=putStr.unlines.dropWhile(all(==' ')).z(flip(++))(if odd n then["","\\","__\\"]else repeat"").z(++)["  "," /","/"].map(take(4*div n 2).cycle)$["____","\\  /","__\\/"]
z=zipWith
share|improve this answer
3  
Some hints for golfing: (mod n 2)==0 is even n or better use odd n and swap the then and else part. concat.take(div n 2).repeat is take(4*div n 2).cycle because all list elements are of length 4. Assign short names to functions with long names, e.g. z=zipWith - then use z. You can kick out a few spaces ...repeat""else[.... –  nimi 6 hours ago
    
@nimi Thanks for your hints! Using them, I was able to golf my original solution to 179 bytes. By reconsidering my approach, I was also able to reduce my solution to 155 Bytes. –  dohaqatar7 54 secs ago

Java, 185

String f(int n){int i;String s="";if(n>1){s="  ";for(i=0;i<n/2;i++)s+="____";s+='\n';}for(i=0;i<=n;)s+=i++%2<1?" /":"\\ ";s+='\n';for(i=0;i<=n;i++)s+=i%2<1?i<n?"/_":"/":"_\\";return s;}

Explanation

String f(int n) {
    int i;
    String s = "";
    if (n > 1) {
        s = "  ";
        for (i = 0; i < n / 2; i++) {
            s += "____";
        }
        s += '\n';
    }
    for (i = 0; i <= n; i++) {
        s += i % 2 < 1 ? " /" : "\\ ";
    }
    s += '\n';
    for (i = 0; i <= n; i++) {
        s += i % 2 < 1 ? i < n ? "/_" : "/" : "_\\";
    }
    return s;
}
share|improve this answer

C89, 144

r(p,q,n)char*p,*q;{n?printf(p),r(q,p,n-1):puts("");}main(c,v)char**v;{printf("  ");r("","____",c=atoi(v[1]));r(" /","\\ ",++c);r("/","__\\",c);}

An ungolfed version:

r(p, q, n) char *p, *q; {
  if(n > 0) {
    printf(p);
    r(q,p,n-1); /* swap q and p */
  } else {
    puts("");
  }
}

main(c, v) char**v; {
  c = atoi(v[1]);
  printf("  ");
  r("",   "____", c));
  r(" /", "\\ ",  c+1);
  r("/",  "__\\", c+1);
}

The output:

$ seq 1 3 10 | xargs -n1 ./triangles

 /\
/__\
  ________
 /\  /\  /
/__\/__\/
  ____________
 /\  /\  /\  /\
/__\/__\/__\/__\
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/

The stack overflows if I enter 65535, but theoretically it should work ;-)

share|improve this answer
    
You could declare main as main(c,v)**v; if that works. –  FUZxxl 2 hours ago
    
I was wondering if you could save something by having c or n as a global variable, so you don't have to pass that parameter to r(). I don't think your answer complies with Note that for 1 the output is two lines long but otherwise it's three. This is required. –  steveverrill 2 mins ago

Go, 156

func f(n int){a,b,c:="  ","","";for i:=0;i<=n;i++{if i<n/2{a+="____"};if i%2<1{b+=" /";c+="/";if i<n{c+="_"}}else{b+=`\ `;c+=`_\`}};print(a+"\n"+b+"\n"+c)}

Ungolfed:

func f(n int) {
    a, b, c := "  ", "", ""   // Initialize 3 accumulators
    for i := 0; i <= n; i++ { // For each required triangle
        if i < n/2 {          // Yay integer math
            a += "____"
        }
        if i%2 < 1 {          // Even, uneven, (are we drawing up or downslope?)
            b += " /"
            c += "/"
            if i < n {
                c += "_"
            }
        } else {
            b += `\ `
            c += `_\`
        }
    }
    print(a + "\n" + b + "\n" + c)
}

The only real trick here (and it isn't even a good one) is using 3 accumulators so I can condense the solution down to 1 loop.

The code can be run here: http://play.golang.org/p/urEO1kIjKv

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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