非常简单的三角形


47

编写一个程序或函数,该程序或函数采用正整数(通过stdin,命令行或函数arg),并打印或返回一个由许多小三角形平铺在一起的字符串,并交替显示它们的指向:

 /\
/__\

如果输入为,则唯一的三角形是输出1

如果输入为2,则输出为

  ____
 /\  /
/__\/

如果输入为3,则输出为

  ____
 /\  /\
/__\/__\

如果输入为4,则输出为

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

等等。你的程序必须支持的投入高达2 16个 - 1 = 65535。

细节

  • 最左边的三角形始终指向上方。
  • 可能有尾随空格,但可能没有多余的前导空格。
  • 可能会有一个可选的尾随换行符。
  • 请注意,1输出为两行,否则为三行。这是必需的。
  • 以字节为单位的最短提交获胜。

Answers:


32

佩斯,44 42

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

第一行:

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.

另两个线通过注意到第二行包括产生" /""\ "交替输入+ 1次,并且第三行由"/""__\"以相同的方式交替。


158
删除了44仍然是正常44 :(
Optimizer

4
42当然!
mbomb007'3

48
@Optimizer:我无休止地发现,您对44出现的悲伤所获得的票数超过了问题答案的数量。
Alex A.

6
在被淘汰的44链中仅得到10个答案的深处
狮子座

3
@AlexA。我发现,对于Optimizer对44的出现感到悲伤的无休止获得的票数超过了问题或答案,这让我感到无穷无尽。
isaacg

24

SQL,182个 175 173 187字节

并不是说这将是最短的,但是尝试最小化sql仍然很有趣;)我在Oracle 11中做到了,但是,这些应该是基本的SQL。指出,[edit]我没有应用when input = 1规则-仅显示2行。我想不出一种更好的方法,但是,我确实通过修改v逻辑节省了几个字节;

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

[edit1]删除了一些不必要的空格[/ edit1] [edit2]将&& i更改为&i。它削减了2个字符,但是迫使用户两次输入三角形的数量...:PI意识到使用&& i的“良好编码习惯”使成本为2个字节!惊恐的事件!![/ edit2]

说明 (注意:我在此说明中使用&& 1,因此它仅提示一次,上面的&1节省了代码空间,但提示多次;))

 select  -- line 1
     decode(&&1,1,'',   -- don't need line 1 if input is 1
     rpad('  ',v,'____') || z ) || -- every pair of triangles
     -- line 2
     rpad(' /',v,'\  /') ||  -- every pair of triangles
          decode(y,1,'\') || z || -- add the final triangle, input: 1,3,5 etc.
     -- line 3
     rpad('/',v-1,'__\/') ||  -- every pair of triangles
          decode(y,1,'__\')   -- add the final triangle, input: 1,3,5 etc.
from (select 2+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);

输出量

  SQL> accept i
  1
  SQL> /

   /\
  /__\


  SQL> accept i
  2
  SQL> /

    ____
   /\  /
  /__\/


  SQL> accept i
  3
  SQL> /

    ____
   /\  /\
  /__\/__\


  SQL> accept i
  12
  SQL> /

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


  SQL>

1
删除后面的空格是否可行from?如果是这样,可以为您节省一个字节。
Alex A.

噢,上帝啊。刚刚尝试了..然后“去镇上”去掉了我可以用的空间...哦,这个吸盘现在不可读..但是它仍然可以工作;)大声笑(我不敢相信别名仍然可以那样工作..哦,呵呵)
同上

我对投票感到困惑!哦,距离最小的尺寸还差得远。哇!
同上

2
赞词通常表示人们喜欢您的提交,因为它具有创造力,使用的语言不常见或多种原因。以我的经验,最短的代码高尔夫球答案也被投票最高是罕见的。因此,尽管这可能不是最短的答案,但社区认为这是一个很好的答案。:)
Alex A.

@Alex ..酷,肉汁:)(我接下来必须在Excel中尝试一下……大声笑)
同上

11

Python 2,89 88 87 85 83已命名/ 81未命名

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

(感谢@orlp提供一个字节,感谢@xnor提供另外三个字节)

该函数接受一个int值,n并使用逐行方法将三角形作为字符串返回。

例如print f(10)

  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/

对于第一行,而不是(n>1)*我们使用1%n*,因为1%nif是0,如果if是n == 11 n > 1


1
您可以刮掉一个字符," /\\ "变成" /\ "
orlp 2015年

这个lambda不能在Python 3中使用吗?
mbomb007'3

2
@ mbomb007那里有一个楼层划分
Sp3000

@orlp现在允许我添加进一步的混乱,但删除我的评论;)
FryAmTheEggman 2015年

我怀疑这"\n".join()3个项目,即使该列表用于有条件地删除第一个元素。也许像b*(x+"\n")+y+"\n"+z更短的东西?
xnor 2015年

7

的JavaScript(ES6),101 109

太久了

f=(n,z=a=>a.repeat(n/2))=>(n>1?'  '+z('____')+'\n ':' ')+z('/\\  ',w=' /'[++n&1]+'\n')+w+z('/__\\')+w

说明

使用粗箭头定义函数。此外,没有{}块:函数主体是单个表达式,它是返回值。f=(a,b,c)=>expr相当于

function f(a,b,c)
{
  return expr;
}

在单个表达式内,您不能使用诸如if或的语句var,但是

  • 具有默认值的参数可用作局部变量
  • 条件表达式?:可以代替if else
  • 您可以使用逗号运算符添加更多的子表达式,甚至可以将其更好地用作函数的未使用参数。在这种情况下,的分配w是该函数的第二个(未使用的)参数z

我们可以将f函数重写为

f = function(n) {
  var z = function(a) { // use current value of n (that changes)
    return a.repeat(n/2);
  };
  var result;
  if (n > 1) {
    result = '  ' + z('____') + '\n '; // top row if more than 1 triangle
  else
    result = ' '; // else just the blank
  ++n; // increase n, so invert even/odd
  w = ' /'[n&1]+'\n'; //  blank if n is now even, else '/' if n is now odd
  // the next rows will end in "/\" or "\  /" based on n even/odd
  result +=  z('/\\  ') + w; // offset by the blank char added before
  result += z('/__\\') + w;
  return result;
}

在Firefox / FireBug控制台中测试

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

输出量

 /\   
/__\ 

  ____
 /\  /
/__\/

  ____
 /\  /\   
/__\/__\ 

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

  ________________
 /\  /\  /\  /\  /\   
/__\/__\/__\/__\/__\ 

做得很好!昨天我花了太长时间试图缩短它,充其量只能以不同的方式重现109。-8相当不错。
DocMax 2015年

凉。你能发表一个解释吗?我不完全了解w
BadHorsie 2015年

添加了@BadHorse说明(确实是这次)
edc65

出于兴趣,我尝试不带空格地做到这一点,并提出n=>(n>1?' '+'____'.repeat(n/2)+'\n':'')+' /\\ '.repeat(n).slice(0,n*2+2-n%2)+'\n'+'/__\\'.repeat(n).slice(0,n*2+1+n%2)119(故意不使用模板字符串等来匹配您的答案)。
尼尔


6

哈斯克尔155 153 139 131个字节

我发现一种略有不同的方法,结果比我原来的方法要短。我的原始尝试保存在下面。和以前一样,高尔夫球技巧也受到赞赏。

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

感谢Nimi提供的高尔夫技巧。


上一次尝试197179字节

t n=putStr.unlines.dropWhile(all(==' ')).z(flip(++))(if odd n then["","\\","__\\"]else repeat"").z(++)["  "," /","/"].map(take(4*div n 2).cycle)$["____","\\  /","__\\/"]
z=zipWith

4
打高尔夫球的一些提示:(mod n 2)==0even n或更好地使用odd n和交换thenand else部分。concat.take(div n 2).repeattake(4*div n 2).cycle因为所有列表元素的长度都是4。将短名称分配给长名称的函数,例如z=zipWith-然后使用z。您可以踢出一些空格...repeat""else[...
nimi

@nimi感谢您的提示!使用它们,我能够将原始解决方案扩展到179个字节。通过重新考虑我的方法,我还能够将解决方案减少到155字节。
ankh-morpork 2015年

1
提示,第二部分:foldr z["","",""]foldr1 z,因为要折叠的列表永远不会为空。而不是all(==' ') 可以使用==" "(<-中间两个空格),因为在n = 1的情况下它用于删除空行,此处的第一行是" "。的第一个定义t可以写成一行:t n|odd...
nimi 2015年

4

CJam,73 68 63 62 60字节

这肯定需要打高尔夫球...

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

在这里测试。

说明

"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 '__\'.";

4

朱莉娅115字节

n->(m=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))

这将创建一个未命名的函数,该函数可以接受整数并打印三角形。要给它起个名字,例如f=n->(...)

取消+说明:

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

输出示例:

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

我很沮丧,这是如此之久。我敢肯定有很多打高尔夫的机会,但目前我还不清楚。如果您有任何建议或想进一步解释,请告诉我!


3

CJam,68 62 60字节

据我所知,这是与其他CJam解决方案完全不同的方法。这可以打很多球。

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

在这里在线尝试


3

C#190

void f(int n){string s=(n>1)?"\n  ":"",t=" /",u = "/";bool b=true;int m=n;while(m-->0){s+=(n>1&&b&&m>0)?"____":"";t+=b?"\\":"  /";u+=b?"__\\":"/";b=!b;}Console.Write("{0}\n{1}\n{2}",s,t,u);}

不打高尔夫球

void f(int n)
{
string s = (n > 1) ? "\n  " : "", t = " /", u = "/";
bool b = true;
int m = n;
while(m-->0)
{
s += (n > 1 && b && m>0) ? "____" : "";
t += b ? "\\" : "  /";
u += b ? "__\\" : "/";
b = !b;
}
Console.Write("{0}\n{1}\n{2}",s,t,u);
}

1
干得好!请注意,使用while循环而不是使用for循环永远不会更好。在这种情况下,您可以通过m在for循环初始化b=!b中以及最后调用的内容中包含的定义来节省2个字节。您也可以通过更换节省开支stringboolvar。您也不需要“()”周围的n>1子句,并且在s+=子句中可以使用非短路,&而不是&&因为没有副作用或取消引用会出错。最后,1>0短于true;)
VisualMelon 2015年

3

C#,257183字节

void C(int t){int i;var n="\r\n";var s="  "+string.Join("____",new string[1+t/2])+n;for(i=0;i++<=t;)s+=i%2<1?"\\ ":" /";s+=n;for(i=0;i++<=t;)s+=i%2<1?"__\\":"/";Console.WriteLine(s);}

编辑:感谢@VisualMelon的提示,节省了74个字节。

我知道它远非最佳语言,但是我最感兴趣的是学习C#的各种细微差别,而不是赢得比赛。这基本上是这个 Pyth答案的端口。

我在考虑for循环可以做得更好,但是考虑到其中嵌入的第三条语句,我不确定如何。

范例(1、2、3、10):

 /\   
/__\  
  ____
 /\  /
/__\/
  ____
 /\  /\ 
/__\/__\
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/

取消高尔夫:

void C2(int t)
{
    int i;
    var n="\r\n";
    var s="  "+string.Join("____",new string[1+t/2])+n;
    for(i=0;i++<=t;)
        s+=i%2<1?"\\ ":" /";
    s+=n;
    for(i=0;i++<=t;)
        s+=i%2<1?"__\\":"/";
    Console.WriteLine(s);
}

虽然StringBuilders s+=既快速又可爱,但是如果您希望字节数少的话,那就是您的朋友。确实,您的for循环可以变得更加紧凑。++--运算符的欢乐/恐怖意味着您可以在条件检查中完成大部分工作for(i=0;i++<=t;)(该检查是否i小于或等于t 然后进行递增)。您最好定义int i外部for循环,然后重新使用它,并且由于可以保证i永远不会为负,因此i%2==0可以将其替换为i%2<1。通过这些更改,可以轻松获得200字节以下的分数。
VisualMelon 2015年

1
另外,我怀疑您是用LINQPad或类似语言编写的,因为访问Enumerable通常需要一个using System.Linq指令,并且我认为通常打算包含这样的子句。但是,在这种情况下,唯一的LINQ可以被替换,var s=" "+string.Join("____",new string[1+t/2])+n;其中不包含LINQ,并且比当前代码短;)它将许多空字符串与我们真正关心的“ ____”(1 + t / 2)结合在一起是因为我们需要另一个空字符串来适应另一个“ ____”)。该变量n声明为“ \ r \ n”。
VisualMelon 2015年

很棒的提示!我忘了Enumerable需要System.Linq,这些天我几乎没有注意。for循环提示非常方便!
特伦特(Trent)2015年

有点晚了,但是您可以使用Console.Write而不是Console.WriteLine
Metoniem

2

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

说明

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

2

C# - 151 146 141 138

受到@bacchusbeale的答案的启发

string f(int n){string t="\n",s=n>1?"  "+new string('_',n/2*4)+t:"";for(var b=n<0;n-->=0;t+=b?"__\\":"/",b=!b)s+=b?"\\ ":" /";return s+t;}

不打高尔夫球

    string f(int n)
    {
        string t = "\n", s = n > 1 ? "  " + new string('_', n / 2 * 4) + t : "";
        for (var b = n < 0; n-- >= 0; t += b ? "__\\" : "/", b = !b)
            s += b ? "\\ " : " /";
        return s + t;
    }

1
很好,不确定在评论其他答案之前我怎么错过了这个!过载new String对我来说是新的!您似乎错过t=""了高尔夫版本,不过最好将其初始化t为“ \ n”。您可以通过添加到t翻转的位置来节省几个字节,将b“ {}”保存在for循环中:t+=(b=!b)?"/":"__\\"
VisualMelon 2015年

1
@tis,如果您t之前定义s并添加t到字符串而不是"\n";,则可以节省更多空间。)
VisualMelon 2015年

1

走, 156 144

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

取消高尔夫:

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 += "/"
        } else {
            b += `\ `
            c += `__\`
        }
    }
    print(a + "\n" + b + "\n" + c)
}

这里唯一真正的技巧(甚至不是一个好办法)是使用3个累加器,因此我可以将解决方案压缩为1个循环。

该代码可以在此处运行:http : //play.golang.org/p/urEO1kIjKv


只需使用c += `__\` 而不是if i<n{c+="_"}
MarcDefiant

@MarcDefiant更新,谢谢
Kristoffer Sall-Storgaard

1

> <>(FISH) 215个 183 156字节

编辑:Notepad ++由于CR给了我5个额外的字节,因此相应地修改了计数

打高尔夫球的次数略多,但这是我到目前为止的第一个钓鱼程序> _ <对一个三角形没有空白的第一行的要求使该程序的大小增加了一倍。

99+0{:}1=?.~~"  "oo:2,:1%-v
-1  oooo  "____"  v!?  )0:/!
" /"oa~~.?=1}:{24~/:oo
v!?)0:-1o"\"v!?)0:/!-1ooo"  /"
/v   ~o"/"oa/!
!\:0)?!;"\__"ooo1-:0)?!;"/"o1-

可以在http://fishlanguage.com/上进行测试(长度为int的初始堆栈)

说明:

       Start with initial stack as input number
99+0   Push 18 and 0 to the top of the stack
{:}    Shift the stack to the left (wraps), copy the top value, and shift it back to the left (i.e. copy bottom of stack to the top)
1=     Check to see if the top of the stack is equal to 1, pushes 1 for true, 0 for false
?.     If top of stack is zero, skip the ., otherwise jumps to x,y coordinates on top of stack (18,0). This skips the next 8 instructions
~~     Pop the top 2 values from the stack (if they're not popped by the jump)
"  "   Push the string literal "  " onto the stack
oo     Pop the top two values of stack and output them as characters
:2,    Copy top value of stack, ad divide by 2
:1%-   Since ><> uses float division, and doesn't have >= notation, remove the decimal part (if exists)
v      Redirect pointer down
/      Redirect pointer left
:0)    Copy top of stack, and see if its greater than 0 (1 for true, 0 for false)
?!v    If top of stack is non-zero, then ! is executed, which skips the next instruction (redirect), otherwise, code is redirected
"____" Push the literal "____" to the stack
oooo   Pop the top four values of stack and output them as characters
1-     Decrement the top of the stack by 1
!/     Ignore the redirect action.
       When the loop gets to 0, it goes to next line, and gets redirected to the left.
~      Pops the top of the stack (0 counter)
42     Pushes 4 and 2 to the stack
{:}    As before, copies the bottom of the stack to the top
1=?.   Also as before, if the initial value is 1, jump to (2,4) (skipping next 4 instructions
~~     Pop 2 values from stack if these instructions haven't been skipped
ao     Push 10 onto the stack and output it as a character (LF)
"/ "oo Push the literal "/ " onto the stack and output it
://    Copies the top of the stack then redirects to the line below, which then redirects to the left
:0)    Copies top of the stack and compares if its greater than 0
?!v    If it is, redirect to next line
"\"o   Push "\" to stack, then output it as a character
1-     Decrement top value of stack
:0)?!v If loop is not greater than 0, redirect to next line
       Either mode of redirect will loop to the left, and (potentially) skip the far right redirect because of the !
ao     Push 10 to stack and output it as a character (LF)
"/"o~  Push "/" to stack, then output it as a character. Pop top value of stack (the 0 from previous loop)
v      Redirects to next line, which then redirects to the right
:0)?!; If the top of the stack is not greater than 0, terminate (;)
"\__"  Pushes "\__" to the stack
ooo    Outputs top 3 stack values as characters ("__\")
1-     Decrement top of stack by 1
:0)?!; If the top of the stack is not greater than 0, terminate (;)
"/"o   Push "/" to top of stack then output it as a character
1-     Decrement top of stack by 1
!\     Ignore the redirect

1
不错的翻译!你是自己做的吗?
Sp3000

一点也不。:PI广泛使用它来自学语言...并进行调试。我只是看到这种语言在浮动,并认为它非常有趣(也想尝试大理石游戏)。
Fongoid 2015年

1

perl的109 108 106

$i=<>;$t=join$/,$i-1?"  "."_"x($i/2)x4:(),$m.=(" /")[$_&1]||"\\ ",$b.=("/")[$_&1]||"__\\"for 0..$i;print$t

我认为这对我的第一个高尔夫球来说还不错,我在第一行中使用了Vynce的部分,其余的代码克服了1个三角形的新线问题。

现在看看我是否可以缩短它:)

编辑:空格

编辑2:替换"\n"$/

1:
 /\
/__\

4:
  ________
 /\  /\  /
/__\/__\/

1

C89、150

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

非高尔夫版本:

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

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

输出:

$ seq 1 3 10 | xargs -n1 ./triangles
 /\
/__\
  ________
 /\  /\  /
/__\/__\/
  ____________
 /\  /\  /\  /\
/__\/__\/__\/__\
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/

如果我进入堆栈,堆栈会溢出65535(但如果您用-O3!编译,则不会溢出),但从理论上讲,它应该可以工作;-)

编辑:程序现在满足以下要求:如果1传递给程序 ,则只能输出两行。编辑2:使用int*代替char*


你可以声明main作为main(c,v)**v;其是否正常工作。
FUZxxl 2015年

我想知道您是否可以通过具有cn作为全局变量来保存某些内容,因此不必将该参数传递给r()。我认为您的答案不符合Note that for 1 the output is two lines long but otherwise it's three. This is required.
Level River St

@FUZxxl不幸的是,这不起作用:-(error: expected declaration specifiers before ‘*’ token main(c,v)**v;{
MarcDefiant

@steveverrill修复了它,但是我需要延长代码。无法找到一个全球性的解决方案nc这两种较短。
MarcDefiant 2015年

@MarcDefiant你能通过int**吗?
FUZxxl 2015年

1

C ++ stdlib,194个字节

string f(int n){char* p[]={"____"," /\\ ","/__\\"};int x[]={(n-n%2)*2,n*2+2-n%2,n*2+1+n%2},i,j;string s=n>1?"  ":"";for (i=n>1?0:1;i<3;s+=++i<3?"\n":"")for (j=0;j<x[i];)s+=p[i][j++%4];return s;}

测试程序:

#include <string>
#include <iostream>

using namespace std;

string f(int n)
{
    char* p[]={"____"," /\\ ","/__\\"};
    int x[]={(n-n%2)*2,n*2+2-n%2,n*2+1+n%2},i,j;
    string s=n>1?"  ":"";
    for (i=n>1?0:1;i<3;s+=++i<3?"\n":"")
        for (j=0;j<x[i];)
            s+=p[i][j++%4];
    return s;
}

int main(int argc, char* argv[])
{
    cout << f(10);
    return 0;
}

1

击,166个 127 125 119 105字节

printf -v l %$[$1/2]s;(($1%2))&&r= j=$l\ ||r=/ j=$l;echo "  ${l// /____}
${j// / /\ } $r
${j// //__\\}"$r

在函数中:

triangle() {
    printf -v l %$[$1/2]s;(($1%2))&&r= j=$l\ ||r=/ j=$l;echo "  ${l// /____}
${j// / /\ } $r
${j// //__\\}"$r
}

通过一些演示:

for i in {1..5} 10 31;do
    paste -d\  <(
        figlet -fsmall $i |
             sed 's/^/         /;s/^ *\(.\{10\}\)$/\1  /;$d'
    ) <(triangle $i)
  done

可以渲染(如果已安装figlet):

        _      
       / |    /\  
       | |   /__\
       |_|   
      ___      ____
     |_  )    /\  /
      / /    /__\/
     /___|   
      ____     ____
     |__ /    /\  /\  
      |_ \   /__\/__\
     |___/   
     _ _       ________
    | | |     /\  /\  /
    |_  _|   /__\/__\/
      |_|    
      ___      ________
     | __|    /\  /\  /\  
     |__ \   /__\/__\/__\
     |___/   
   _  __       ____________________
  / |/  \     /\  /\  /\  /\  /\  /
  | | () |   /__\/__\/__\/__\/__\/
  |_|\__/    
    _____      ____________________________________________________________
   |__ / |    /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  
    |_ \ |   /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\
   |___/_|   

如果从变量而不是:103 输入,则节省2个字符$1

printf -v l %$[i/2]s;((i%2))&&r= j=$l\ ||r=/ j=$l;echo "  ${l// /____}
${j// / /\ } $r
${j// //__\\}"$r

进入循环:

for i in {1..3} {31..34};do
    [ $i == 31 ] && figlet -fsmall ...
    paste -d\  <(
        figlet -fsmall $i |
            sed 's/^/         /;s/^ *\(.\{10\}\)$/\1   /;$d'
    ) <(
        printf -v l %$[i/2]s;((i%2))&&r= j=$l\ ||r=/ j=$l;echo "  ${l// /____}
${j// / /\ } $r
${j// //__\\}"$r
    )
  done

将呈现(大约)相同:

        _       
       / |     /\  
       | |    /__\
       |_|    
      ___       ____
     |_  )     /\  /
      / /     /__\/
     /___|    
      ____      ____
     |__ /     /\  /\  
      |_ \    /__\/__\
     |___/    


 _ _ _ 
(_|_|_)

    _____       ____________________________________________________________
   |__ / |     /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  
    |_ \ |    /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\
   |___/_|    
  _______       ________________________________________________________________
 |__ /_  )     /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /
  |_ \/ /     /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/
 |___/___|    
  ________      ________________________________________________________________
 |__ /__ /     /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  
  |_ \|_ \    /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\
 |___/___/    
 _____ _        ____________________________________________________________________
|__ / | |      /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /
 |_ \_  _|    /__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/
|___/ |_|     

1
您应该发布有关figlet实现代码高尔夫的问题!
sergiol '17

1

木炭,27字节(无竞争)

停止竞争,因为该语言推迟了挑战。

FEN﹪鲫P×⁴_↗⊗¬ι↓P↘²↘⊗ι↑P↗⊗ι

在线尝试!链接是详细版本的代码。说明:

FEN﹪鲫

生成长度交替的列表,n并在它们上循环。

P×⁴_

绘制时____不移动光标。

↗⊗¬ι↓

在第一个和每个其他三角形上,绘制左侧/

P↘²

\不移动光标的情况下绘制侧面。

↘⊗ι↑

在第二个三角形以及每个其他三角形上,\再次绘制左侧以移动光标。

P↗⊗ι

在第二个三角形以及每个其他三角形上,在/不移动光标的情况下绘制右侧。


1
答案不再需要再标记为非竞争
乔·金

1

PowerShell116 95字节

非常感谢Mazzy和仅ASCII节省了21个字节

param($n)@("  "+"_"*4*($x=$n-shr1))[$n-eq1]
" /"+"\  /"*$x+"\"*($a=$n%2)
"/"+"__\/"*$x+"__\"*$a

在线尝试!

不允许n = 1的空行占用了14 10个字节。现在,只需很少的重复代码,该解决方案就非常聪明了。银行家的舍入仍然是真正的魔鬼。


是否允许使用空行???
仅ASCII的

@ASCII专用从OP中读取第4个项目符号。
Veskah


1
@ASCII

1
@mazzy,您无法生成第一行,否则将为102
仅ASCII的

0

C,368字节

void p(char* c){printf(c);}
int x(int s,int f){int t=0,p=s;for(int i=0;i<f;i++){if(p==1){t++;p=0;}else{p=1;}}return t;}
int main(int argc,char* argv[]){int t=atoi(argv[1]);if(t>1){p("  ");for(int i=0;i<x(0,t);i++)
{p("____");}p("\n");}for(int i=0;i<x(1,t);i++){p(" /\\ ");}if(t%2==0){p(" /");}p("\n");
for(int i=0;i<x(1,t);i++){p("/__\\");}if(t%2==0){p("/");}p("\n");}

如果您计算这些#include语句,则更多,但即使没有警告,它也会在gcc上编译,尽管有警告。我知道它并不是目前为止最短的,但是我仍然喜欢用C语言完成它。


该宏#define p(c)printf(c)比您的函数短。您可以忽略函数的返回类型(默认为int)。您也可以C89像这样定义样式的函数main(c,v)char**v;{}。这很短int main(int c, char** v){}
MarcDefiant 2015年

0

Perl的(简单)131 125 120

相当简单的第一遍:

$i=<>;print join"\n",$i-1?"  "."_"x(4*int($i/2)):(),join("",map{(" /","\\ ")[$_%2]}0..$i),join"",map{("/","__\\")[$_%2]}0..$i

哦,谁需要显式int?

$i=<>;print join"\n",$i-1?"  "."_"x($i/2)x4:(),join("",map{(" /","\\ ")[$_%2]}0..$i),join"",map{("/","__\\")[$_%2]}0..$i

0

Prolog,126个字节

A+B:-writef(A,B).
$N:-(N>1,"  %r\n"+['____',N//2];!),(0is N/\1,T='/';T='')," %r%w\n"+['/\\  ',N/2,T],"%r%w\n"+['/__\\',N/2,T].

调用喜欢$3

更具可读性:

triangle(N):-
    (   N > 1
    ->  writef("  %r\n", ['____', N//2])
    ;   true
    ),
    (   0 is N mod 2
    ->  T = '/'
    ;   T = ''
    ),
    writef(" %r%w\n", ['/\\  ', N/2, T]),
    writef("%r%w\n", ['/__\\', N/2, T]).

例:

?- findall(N,between(1,10,N),NN), maplist($, NN), !.
 /\  
/__\
  ____
 /\  /
/__\/
  ____
 /\  /\  
/__\/__\
  ________
 /\  /\  /
/__\/__\/
  ________
 /\  /\  /\  
/__\/__\/__\
  ____________
 /\  /\  /\  /
/__\/__\/__\/
  ____________
 /\  /\  /\  /\  
/__\/__\/__\/__\
  ________________
 /\  /\  /\  /\  /
/__\/__\/__\/__\/
  ________________
 /\  /\  /\  /\  /\  
/__\/__\/__\/__\/__\
  ____________________
 /\  /\  /\  /\  /\  /
/__\/__\/__\/__\/__\/
NN = [1, 2, 3, 4, 5, 6, 7, 8, 9|...].

0

C#:1行LINQ,198字节

string f(int n){return(n>1?"  ":"")+string.Join("\n",new[]{"____"," /\\ ","/__\\"}.Zip(new[]{(n-n%2)*2,n*2+2-n%2,n*2+1+n%2},(s,l)=>string.Join(s,new string[n+1]).Substring(0,l)).Where(x=>x.Any()));}

0

视网膜,88字节(无竞争)

停止竞争,因为该语言推迟了挑战。

K`  ____¶ /\  /¶/__\/
%`....$
$+*$&
%`(.+)\1$
$1
(  (____)*)__(¶.*)  /(¶.*)/
$1$3$4
G`\S

在线尝试!说明:

K`  ____¶ /\  /¶/__\/

用一对三角形替换输入。

%`....$
$+*$&

将三角形乘以原始输入。

%`(.+)\1$
$1

将三角形除以2。

(  (____)*)__(¶.*)  /(¶.*)/
$1$3$4

删除剩余的一半三角形。

G`\S

删除第一行(如果现在为空白)。


0

Perl 6、83个字节

{~["  {'____'x$_/2-.5}
"x($_>2),'/\  'x$_/2~($!='/'x$_%2),"
"~'/__\\'x$_/2~$!]}o*+1

在线尝试!

带有数字并返回字符串的匿名代码块。



0

05AB1E,37 个字节

≠iðð'_I2÷4*×J}„ /„\ ‚I>∍J'/…__\‚I>∍J»

在线尝试验证前10个输出

说明:

i            } # If the (implicit) input is NOT 1:
                #   i.e. 1 → 0 (falsey)
                #   i.e. 5 → 1 (truthy)
  ðð            #  Push two spaces "  "
    '_         '#  Push string "_"
      I         #  Push the input
       2÷       #  Integer-divide it by 2
                #   i.e. 5 → 2
         4*     #  And then multiply it by 4
                #   i.e. 2 → 8
           ×    #  Repeat the "_" that many times
                #   i.e. "_" and 8 → "________"
            J   #  Join everything on the stack together to a single string
                #   i.e. "  ________"
 /             # Push string " /"
   \           # Push string "\ "
               # Pair them together: [" /","\ "]
      I>        # Push the input+1
               # Extend the list to that size
                #  i.e. [" /","\ "] and 2 → [" /","\ "]
                #  i.e. [" /","\ "] and 6 → [" /","\ "," /","\ "," /","\ "]
         J      # Join the list together to a single string
                #  i.e. [" /","\ "] → " /\ "
                #  i.e. [" /","\ "," /","\ "," /","\ "] → " /\  /\  /\ "
'/             '# Push string "/"
  __\          # Push string "__\"
               # Pair them together: ["/","__\"]
       I>       # Push the input+1
               # Extend the list to that size
                #  i.e. ["/","__\"] and 2 → ["/","__\"]
                #  i.e. ["/","__\"] and 6 → ["/","__\","/","__\","/","__\"]
          J     # Join the list together to a single string
                #  i.e. ["/","__\"] → "/__\"
                #  i.e. ["/","__\","/","__\","/","__\"] → "/__\/__\/__\"
»               # Join the entire stack with a newline delimiter
                #  i.e. " /\ " and "/__\" → " /\ \n/__\"
                #  i.e. "  ________", " /\  /\  /\ " and "/__\/__\/__\"
                #   → "  ________\n /\  /\  /\ \n/__\/__\/__\"
                # (and output the result implicitly)

0

Java 11,122字节

n->(n>1?"  "+"_".repeat(n/2*4)+"\n":"")+" /\\ ".repeat(n).substring(0,++n*2)+"\n"+"/__\\".repeat(n).substring(0,n/2*4+n%2)

在线尝试。

说明:

n->                   // Method with integer parameter and String return-type
  (n>1?               //  If the input is larger than 1:
    "  "              //   Return two spaces
    +"_".repeat(      //   Appended with "_" repeated the following amount of times:
          n/2         //    The input integer-divided by 2
             *4)      //    And then multiplied by 4
    +"\n"             //   Appended with a newline
   :                  //  Else:
    "")               //   Return nothing
  +" /\\ ".repeat(n)  //  Appended with " /\ " repeated the input amount of times
    .substring(0,     //   After which we only leave the first `x` characters, where `x` is:
      ++n             //    Increase the input by 1 first with `++n`
         *2)          //    And then multiply it by 2
                      //     i.e. For input 1, `x` becomes 4 here
                      //     i.e. For input 6, `x` becomes 14 here
  +"\n"               //  Appended with a newline
  +"/__\\".repeat(n)  //  Appended with "/__\" repeated the input amount of times
    .substring(0,     //   After which we only leave the first `y` characters, where `y` is:
      n/2             //    The input+1 integer-divided by 2
         *4           //    Then multiplied by 4
           +n%2)      //    And then the input+1 modulo-2 added
                      //     i.e. For input 1, `y` becomes 4 here
                      //     i.e. For input 6, `y` becomes 13 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.