构建ASCII梯形图


28

给定两个整数nm的输入,输出长度为n且大小为m的ASCII梯形图 。

这是长度为3,大小为3的ASCII阶梯:

o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

这是长度为5,大小为1的ASCII阶梯:

o-o
| |
+-+
| |
+-+
| |
+-+
| |
+-+
| |
o-o

这是长度为2,大小为5的ASCII阶梯:

o-----o
|     |
|     |
|     |
|     |
|     |
+-----+
|     |
|     |
|     |
|     |
|     |
o-----o

再具体一点:

  • 长度(n)代表梯子由多少个正方形组成。

  • 尺寸()表示每个正方形的内部宽度和高度,即不包括“边界”。

  • 每个正方形均由内部空间组成,内部空间由 -顶部和底部的|s,左侧和右侧的s以及+ s和所有四个角的s。

  • 正方形之间的边界合并在一起,因此连续两行 +--...--+合并为一条。

  • 整个梯子的拐角被替换为字符 o

  • 您可以选择输出尾随换行符。

梯子的长度(n)始终≥2,尺寸(m)始终≥1。

输入可以作为空格/逗号分隔的字符串,数组/列表/等或两个功能/命令行/等。论点。可以按照最方便/最复杂的顺序进行参数选择。

由于这是,因此以字节为单位的最短代码为准。

提示:上面的示例也可以用作测试用例。


我们必须先取长度,然后取尺寸吗​​?
RK。

@RK。您可以按照更方便的顺序购买它们。
门把手

1
能有一个领先的换行?
科纳·奥布莱恩

1
@CᴏɴᴏʀO'Bʀɪᴇɴ呃...我要去那一个。
Doorknob

1
好的:P值得一试。
科纳·奥布莱恩

Answers:


4

Pyth,34个字节

.NjjNm*QTvz*2YjC:M++J"+|o"m"- -"QJ

测试套件

在STDIN上使用换行符分隔的参数。

使用帮助函数,:该函数从三个字符构建每种类型的垂直字符串,然后根据需要进行复制,转置和加入换行符。


11

Ruby,71岁

->m,n{h=0;(?o+?+*(n-1)+?o).chars{|c|puts [?|+' '*m+?|]*h,c+?-*m+c;h=m}}

在测试程序中取消

f=->m,n{
  h=0                             #The number of | above the 1st rung is 0
  (?o+?+*(n-1)+?o).chars{|c|      #Make a string of all the rung ends o++...++o and iterate through it
    puts [?|+' '*m+?|]*h,         #draw h vertical segments |  ...  |
      c+?-*m+c                    #and a rung with the correct ends
    h=m                           #The number of | above all rungs except the 1st is m
  }
}


f[gets.to_i,gets.to_i]

高尔夫版本似乎存在一些小问题:需要;之后h=0,需要空间puts。但是您的分数只增加1个字符,因为前面还有多余的空格puts
manatwork 2013年

@manatwork oops,谢谢,已修复。我不知道那是怎么回事,我一定打过高尔夫球,以后再不跑了。
级圣河

9

CJam,43岁 42字节

我对分数并不感到惊讶。但是我不是丹尼斯,对吗?

q~:Z;'-'o{[\Z*1$N]}:X~['-_'+X\'|XZ*]@*1>1$

输入为2个空格分隔的项目。长度优先

2 3
o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

说明

q~:Z;'-'o{[\Z*1$N]}:X~['-_'+X\'|XZ*]@*1>1$
q~                                         e# read input
  :Z;                                      e# Record the size in Z and discard
     '-'o{[\Z*1$N]}:X~                     e# Create the initial line (and final). also creates a shorcut to do this later
           \                               e# Capture two arguments
            Z*                             e# The separator is repeated size times
              1$                           e# Repeat the first argument
                N                          e# Add newline
                                           e# X is a function to create line in a ladder
                      ['-_'+X\'|XZ*]       e# Design the repeating part
                                    @*     e# Repeat the pattern n times
                                      1>   e# Discard the initial
                                        1$ e# Since the final line is same than the initial, we just write it.
                                           e# Implicit printing

1
我喜欢你把它当作一个问题来表达。“我不是丹尼斯……对吗?”
undergroundmonorail

7

JavaScript(ES6),89

...重复,重复,重复...

(n,m,R=x=>x.repeat(m),b=R(`|${R(' ')}|
`),d=`o${c=R('-')}o
`)=>d+R(b+`+${c}+
`,m=n-1)+b+d

测试

F=(n,m,R=x=>x.repeat(m),b=R(`|${R(' ')}|
`),d=`o${c=R('-')}o
`)=>d+R(b+`+${c}+
`,m=n-1)+b+d

// Less golfed
U=(n,m)=>
{
  var R=x=>x.repeat(m),
      a=R(' '),
      b=R(`|${a}|\n`);
      c=R('-'),
      d=`o${c}o\n`;
  m=n-1;
  return d+R(b+`+${c}+\n`)+b+d
}

function test() {
  var i=I.value.match(/\d+/g)
  if (i) O.textContent=F(+i[0],+i[1])
  console.log(i,I.value)
}  
 
test()
N,M: <input id=I value="3,5" oninput=test()>
<pre id=O></pre>


我不知道document.getElementById('elem').可以用elem.!为此+1,但是请您指出一些有关此的文档吗?
F. Hauri

2
@ F.Hauri几乎可在所有浏览器中使用,但应避免使用(除非出于娱乐目的而编写)。信息和链接stackoverflow.com/questions/3434278/...
edc65

6

C#,1412字节

...我的第一个CodeGolf尝试,不太可能获胜,但可以成功,所以我们开始:

using System;

namespace Ascii_Ladders
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 0;
            int m = 0;

            Console.Write("Please enter Height: ");
            n = int.Parse(Console.ReadLine());
            Console.Write("Please Enter Width: ");
            m = int.Parse(Console.ReadLine());

            Console.Write("o");
            for (int i = 0; i < m; i++)
            {
                Console.Write("-");
            }
            Console.WriteLine("o");

            for (int k = 0; k < n; k++)
            {
                for (int i = 0; i < m; i++)
                {
                    Console.Write("|");
                    for (int j = 0; j < m; j++)
                    {
                        Console.Write(" ");
                    }
                    Console.WriteLine("|");
                }
                if (k != n - 1)
                {
                    Console.Write("+");
                    for (int i = 0; i < m; i++)
                    {
                        Console.Write("-");
                    }
                    Console.WriteLine("+");
                }
            }

            Console.Write("o");
            for (int i = 0; i < m; i++)
            {
                 Console.Write("-");
            }
            Console.WriteLine("o");

            Console.ReadKey();
        }
    }
}

9
欢迎来到编程难题和代码高尔夫球!您的代码中有很多空格可以删除以缩短代码,如果您想获得更多关于代码打高尔夫球的帮助,则可以查看C#中打高尔夫的技巧
Downgoat

我在这里同意@Doᴡɴɢᴏᴀᴛ。我已经能够潜在地将其压缩533个字节。但这可能会更好。(警告:我不使用C#编程。)
user48538 '16

我用using System;class P{static int m;static void Main(){int n = int.Parse(Console.ReadLine());m = int.Parse(Console.ReadLine());M('o','-');for(int k=0;k<n;k++){for(int i=0;i<m;i++){M('|',' ');}if(k!=n-1){M('+','-');}}M('o','-');Console.ReadKey();}static void M(char x,char y){Console.WriteLine(x+new string(y,m)+x);}}
RedLaser

3
错过了几个空格,所以在310与using System;class P{static int m;static void Main(){int n=int.Parse(Console.ReadLine());m=int.Parse(Console.ReadLine());M('o','-');for(int k=0;k<n;k++){for(int i=0;i<m;i++){M('|',' ');}if(k!=n-1){M('+','-');}}M('o','-');Console.ReadKey();}static void M(char x,char y){Console.WriteLine(x+new string(y,m)+x);}}
RedLaser,2016年

2
降低到270,而使用的方法不变:using C=System.Console;class P{static void Main(){int i,k,n=int.Parse(C.ReadLine()),m=int.Parse(C.ReadLine());System.Action<char,char> M=(x,y)=>C.WriteLine(x+new string(y,m)+x);M('o','-');for(k=0;k<n;k++){for(i=0;i<m;i++){M('|',' ');}if(k<n-1){M('+','-');}}M('o','-');}}。但是,仅通过稍微改变做事方式,这很有可能会带来更多潜力。
乔伊,

6

朱莉娅87字节

f(n,m)=(g(x)=(b=x[1:1])x[2:2]^m*b*"\n";(t=g("o-"))join([g("| ")^m for i=1:n],g("+-"))t)

此函数接受两个整数并返回一个字符串。

取消高尔夫:

function f(n::Int, m::Int)
    # Create a function g that takes a string of two characters and
    # constructs a line consisting of the first character, m of the
    # second, and the first again, followed by a newline.
    g(x) = (b = x[1:1]) * x[2:2]^m * b * "\n"

    # Assign t to be the top and bottom lines. Construct an array
    # of length n where each element is a string containing the
    # length-m segment of the interior. Join the array with the
    # ladder rung line. Concatenate all of this and return.
    return (t = g("o-")) * join([g("| ")^m for i = 1:n], g("+-")) * t
end

5

pb -147字节

^t[B]>>[B]vw[T!0]{b[43]<[X]b[43]>w[B=0]{b[45]>}v[X-1]w[B=0]{b[124]^}v[X]t[T-1]}t[111]b[T]<w[X!0]{b[45]<}b[T]w[Y!0]{w[B!0]{^}b[124]^}b[T]^>>[B]vb[T]

从权利上说,铅应该真正擅长于这种挑战。用字符绘制简单的图片正是pb设计的目的。guess,我猜这只是一种罗word的语言。

首先输入输入长度,然后输入大小。采用字节值形式的输入,例如:python -c 'print(chr(5) + chr(7))' | ./pbi.py ladder.pb

看,有趣的动画!

有评论:

^t[B]            # Save length to T
>>[B]v           # Go to X=size+1, Y=0

w[T!0]{          # While T is not 0:
    b[43]            # Write a '+'
    <[X]b[43]        # Write a '+' on the left side as well
    >w[B=0]{b[45]>}  # Travel back to the right '+', writing '-' on the way
    v[X-1]           # Go down by X-1 (== size)
    w[B=0]{b[124]^}  # Travel back up to the '+', writing '|' on the way
    v[X]             # Go down by X (== size + 1, location of next '+')
    t[T-1]           # Decerement T
}

t[111]           # Save 'o' to T (it's used 4 times so putting it
                 # in a variable saves bytes)

b[T]             # Write an 'o' (bottom right)

<w[X!0]{         # While not on X=0:
    b[45]<           # Travel left, writing '-' on the way
}

b[T]             # Write an 'o' (bottom left)

w[Y!0]{          # While not on Y=0:
    w[B!0]{^}        # Skip nonempty spaces
    b[124]           # Write a '|'
    ^                # Travel up
}

b[T]             # Write an 'o' (top left, replaces existing '+')

^>>[B]v          # Go back to where the size is saved and go to X=size+1, Y=0

b[T]             # Write an 'o' (top right, replaces existing '+')

5

纯bash中,132个130 128 127字节

是的,我可以再丢弃1个字节来代替last ${p% *},但是我更喜欢这样:

p=printf\ -v;$p a %$1s;$p b %$2s;o="|$a|\n";h=+${a// /-}+\\n v=${a// /$o}
a=${b// /$h$v}${h//+/o};a=${a/+/o};${p% *} "${a/+/o}"

样品:

ladders() {
    p=printf\ -v;$p a %$1s;$p b %$2s;o="|$a|\n";h=+${a// /-}+\\n v=${a// /$o}
    a=${b// /$h$v}${h//+/o};a=${a/+/o};${p% *} "${a/+/o}"
}

ladders 3 4
o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

ladders 2 1
o--o
|  |
|  |
o--o

4

Haskell,100 97字节

l#s=unlines$t:m++[t]where _:m=[1..l]>>["+"!"-"]++("|"!" "<$u);t="o"!"-";o!i=o++(u>>i)++o;u=[1..s]

用法示例:

*Main> putStr $ 4 # 3
o---o
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
+---+
|   |
|   |
|   |
o---o

怎么运行的:

l#s=unlines$t:m++[t]         -- concat top line, middle part and end line
                             -- with newlines between every line
  where                      -- where
  _:m=                       -- the middle part is all but the first line of
     [1..l]>>                -- l times
         ["+"!"-"]           --    a plus-dashes-plus line
         ++("|"!" "<$u)      --    followed by s times a bar-spaces-bar line

  t="o"!"-"                  -- very first and last line
  o!i=o++(u>>i)++o           -- helper to build a line
  u=[1..s]

编辑:@Christian Irwan找到了3个字节。谢谢!


-1分的模式匹配m=init$[1..l]>>("|"!" "<$u)++["+"!"-"]=>(_:m)=[1..l]>>["+"!"-"]++("|"!" "<$u)
Akangka '16

令人惊讶的_:m=[1..l]>>["+"!"-"]++("|"!" "<$u)作品
Akangka

@ChristianIrwan:很好发现!谢谢!
nimi 2016年

3

Brainfuck-334字节

,[<+<<<<+>>>>>-]<[[>>]+[<<]>>-]<----[>---<----]--[>[+>>]<<[<<]>++++++]>[+.>>]-[<+>---]<+++++++>>--[<+>++++++]->---[<------->+]++++++++++[<++<]+++++[>[++++++>>]<<[<<]>-]>[-]>.-<<----[>>+++<<----]--[>+<--]>---<<<<++++++++++.,[>[>+>+<<-]>[<+>-]>[<<<<[>>>>>>[.>>]<<[<<]>>-]>>>>>[.>>]<<[<<]>-]<<<<+>-]>>>>[-]----[>---<----]>+.[>]<<<<<[.<<]

我希望这会短很多。

这就建立了一个“串”,看起来像| (...) |和一个看起来像+----(...)----+,打印每一个在必要时,用了一些特殊的外壳o在顶部和底部。

需要使用8位单元格的解释程序,并允许您从单元格0左移(无论是进入负数单元格还是循环)。以我的经验,这些是最常见的默认设置。

有评论:

,[<+<<<<+>>>>>-]<[[>>]+[<<]>>-] Get m from input; make a copy
                      Turn it into m cells containing 1 with empty cells between

<----[>---<----]      Put 67 at the beginning (again with an empty cell between)

--[>[+>>]<<[<<]>++++++]  Add 43 to every nonempty cell

>[+.>>]               Add 1 to each cell and print it

-[<+>---]<+++++++    Put 92 after the last 45 (no empty cell!)

>>--[<+>++++++]      Put 43 immediately after the 92

->---[<------->+]    Put 234 after 43

++++++++++           And 10 after that

[<++<]             Add two to the 234; 92; the empty spaces; and left of the 111

+++++[>[++++++>>]<<[<<]>-] Add 30 to each 2; the 94; and the 236

>[-]>.-<<----[>>+++<<----] Erase leftmost 32; Print 111; subtract 68 from it

--[>+<--]>---        Put 124 where the 32 was

<<<<++++++++++.,     Print a newline; override the cell with n from input

[                    n times:

  >[>+>+<<-]>[<+>-]    Make a copy of m

  >[                   m times:

    <<<<                 Look for a flag at a specific cell

    [                    If it's there:

      >>>>>>[.>>]          Go to the 43; print it and every second cell after

      <<[<<]>>-            Clear the flag

    ]

    >>>>>[.>>]           Go to the 124; print it and every second cell after

    <<[<<]>              Go back to the copy of m

  -]

  <<<<+>               Plant the flag

-]

>>>>

[-]----[>---<----]>+ Erase the 124; add 68 to 43

.[>]                 Print it; then head to the end

<<<<<[.<<] Go to the last 45; print it; then print every second cell to the left


2

Jolf,36个字节

在这里尝试!

ρpi,a+2J+2J"o-| "j"o(.+)o
o.+o'+$1+

说明

ρpi,a+2J+2J"o-| "j"o(.+)o\no.+o'+$1+
 pi              j                   repeat vertically j times
   ,a+2J+2J"o-| "                    a box with dimensions 2+J
ρ                 "o(.+)p\np.+o'     replace with regex
                                +$1+ with the -...-

2

Perl,98个字节

($n,$m)=@ARGV;print$h="o"."-"x$m."o\n",((("|".(" "x$m)."|\n")x$m.$h)x$n)=~s{o(-+)o(?=\n.)}{+$1+}gr

1
一个很好的第一答案。但是我+在您的代码中看不到任何迹象,您是否认为中间梯级的+两端都有迹象?
Level River St

感谢您的措辞非常好-我将加号完全隔开了!我也花了不少空间。还在考虑如何缩短它...除了省略了($n,$m)=@ARGV;并假设已经设置好了-不知道这是否符合要求。我得查一下
ZILjr'1

除非问题中另有说明,否则此处的规则为meta.codegolf.stackexchange.com/a/2422/15599。您不仅可以假设已设置了变量,还可以编写函数而不是程序(如果有帮助)。我不使用Perl,但我认为这样做可以为您省钱@ARGV。另外,在回复某人时,请记住包括@username,这样他们就会收到警报。我不需要这样做,因为这是您的帖子。
级圣河在

1

C,122字节

f(int m,int n,char*s){int i=0,w=3+m++;for(;i<w*m*n+w;++i)*s++=i%w>m?10:" |-+-o"[!(i/w%m)*2+!(i%w%m)+!(i/w%(m*n))*2];*s=0;}

在线尝试


1

Tcl,187个字节

lassign $argv n w
set c 0
while { $c < [expr {($w * $n) + ($n + 2)}]} {if {[expr {$c % ($n + 1)}] == 0} {puts "o[string repeat "-" $w ]o"} else {puts "|[string repeat " " $w ]|"}
incr c}

将此代码放入带有在命令行中输入参数的文件中。按此顺序提供盒子数和宽度。


1

PHP,81字节

需要2个参数,当直接调用PHP命令时传递。第一个是大小,第二个是步数。

$R=str_repeat;echo$P="o{$R('-',$W=$argv[1])}o
",$R("|{$R(' ',$W)}|
$P",$argv[2]);

可能需要一些改进。


0

Python 2,94字节

def F(n,m):a,b,c,d='o|+-';r=[a+d*m+a]+([b+' '*m+b]*m+[c+d*m+c])*n;r[-1]=r[0];print'\n'.join(r)

'无高尔夫球':

def F(n,m):
 # 'o---o'
 r = ['o'+'-'*m+'o']
 # ('|   |'*m+'+---+') n times
 r += (['|'+' '*m+'|']*m+['+'+'-'*m+'+'])*n
 # replace last +---+ with o---o
 r[-1] = r[0]
 print '\n'.join(r)

0

Perl 5,91 +1(-a)= 92字节

$_='|'.$"x$F[1].'|';push@a,y/| /+-/r,($_)x$F[1]while$F[0]--;$a[0]=y/| /o-/r;say for@a,$a[0]

在线尝试!


0

-l,35字节

(^YsXbRLaJW'-)XbWR^('|XbRLaJ'+)WR'o

在线尝试!

说明

(^YsXbRLaJW'-)XbWR^('|XbRLaJ'+)WR'o
                                     a is length, b is size, s is space (implicit)
   sXb                               String containing b spaces
      RLa                            List containing a copies of that string
         JW'-                        Join on "-" and wrap the result in "-" as well
  Y                                  Necessary for operator precedence reasons
 ^                                   Split into a list of characters
(            )Xb                     String-repeat each character in the list b times
                                     This list represents the central columns of the ladder

                    '|Xb             String containing b pipe characters
                        RLa          List containing a copies of that string
                           J'+       Join on "+"
                   (          )WR'o  Wrap in "o"
                  ^                  Split into a list of characters
                                     This list represents the outer columns of the ladder

                WR                   Wrap the left list in the right list, vectorizing

其他一些版本

我尝试了多种方法来捕捉Pyth ...

[Y'-XbWR'o;@>(sXbWR'|RLbPE'-XbWR'+RL:a)y]  41
Y^(t**b.1*:t**bX--a.1)" --"@yXbWR"|o+"@y   40
Y'|XbRLaJ'+YyWR'o;Z:sXbRLaJW'-RLbPEyAEy    39
t**:b(" |-o-+"<>2)@_@^t.1M$*Y[ttXa-1].1    39
J*Z:sXbRLaJW'-RLbWR:^('|XbRLaJ'+)WR'o      37
Y^$*Y[t**:btXa-1].1" --"@yXbWR"|o+"@y      37

我特别喜欢t**b使用数学生成梯子的垂直模式的代码:

        b           Size; e.g. 3
    t               Preset variable for 10
     **:            Set t to t**b (e.g. 1000)
           a        Length; e.g. 3
            -1      2
         tX         String-repeat (the new value of) t 2 times: 10001000
   [          ]     Put t and the above into a list: [1000; 10001000]
               .1   Append 1 to both of them: [10001; 100010001]
$*(              )  Fold on multiplication: 1000200020001

所述1000200020001然后可以用来产生图案o|||+|||+|||o- - - -,从而弥补了阶梯。不幸的是,我无法使这种方法比联接/包装方法更短。

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.