ASCII三角形


30

您的任务是编写一个打印ASCII三角形的程序或函数。他们看起来像这样:

|\
| \
|  \
----

您的程序将采用单个数字输入n,并带有约束0 <= n <= 1000。上面的三角形的值为n=3

ASCII三角形将具有n反斜杠(\)和竖线(|),n+1线和破折号(-),并且每行除最终行外还将具有等于行号(从0开始,即第一行为行0)的空格。 。

例子:

输入:

4

输出:

|\
| \
|  \
|   \
-----

输入:

0

输出:


在此测试用例中,输出必须为空。没有空格。

输入:

1

输出:

|\
--

输入和输出必须完全是我指定的方式。

这是,因此请争取尽可能短的代码!

code-golf  ascii-art  code-golf  rubiks-cube  code-golf  path-finding  maze  regular-expression  code-golf  math  rational-numbers  code-golf  kolmogorov-complexity  graphical-output  code-golf  tips  code-golf  string  permutations  code-golf  sorting  base-conversion  binary  code-golf  tips  basic  code-golf  number  number-theory  fibonacci  code-golf  date  code-golf  restricted-source  quine  file-system  code-golf  code-golf  math  code-golf  ascii-art  code-golf  math  primes  code-golf  code-golf  math  matrix  code-golf  string  math  logic  factorial  code-golf  palindrome  code-golf  quine  stateful  code-golf  interactive  code-golf  board-game  code-golf  math  arithmetic  code-golf  string  code-golf  math  matrix  code-golf  math  abstract-algebra  polynomials  code-golf  date  code-golf  string  array-manipulation  sorting  code-golf  game  code-golf  string  code-golf  ascii-art  decision-problem  code-golf  number  sequence  code-golf  code-golf  code-golf  sequence  fibonacci  code-golf  math  geometry  random  code-golf  code-golf  math  decision-problem  fractal  rational-numbers  code-golf  number  number-theory  code-golf  combinatorics  permutations  card-games  code-golf  math  sequence  array-manipulation  fibonacci  code-golf  sequence  decision-problem  graph-theory  code-golf  ascii-art  parsing  lisp  code-golf  string  math  natural-language  logic  code-golf  math  logic  code-golf  string  alphabet  code-golf  string  code-golf  string 

4
它需要是一个程序还是一个函数?
fəˈnɛtɪk

7
我认为,如果case 0可能有任何意外输出会更好,因为这是一种边缘情况(尤其是因为您要求破折号的数量必须比输入数字多一)
Kritixi Lithos

4
@Okx提问者经常在哪里提问程序,但实际上是程序或功能。您可能需要澄清,您正在要求一个完整的程序
fəˈnɛtɪk

9
肯定会去程序和功能。如果未指定其他任何内容,则这是默认规则。我还将删除0边的情况,因为它直接违反了“ n + 1行和破折号(-) ”。
Stewie Griffin

3
如果没有size = 0例外情况,挑战将非常简单。挑战的一部分是找出一种以最少的额外代码来解决此问题的方法。
17Me21年

Answers:


3

Jelly, 14 bytes

’⁶x⁾|\jṄµ€Ṫ”-ṁ

Try it online!

How it works.

’⁶x⁾|\jṄµ€Ṫ”-ṁ  Main link. Argument: n

        µ       Combine the links to the left into a chain.
         €      Map the chain over [1, ..., n]; for each k:
’                 Decrement; yield k-1.
 ⁶x               Repeat the space character k-1 times, yielding a string.
   ⁾\j            Join the character array ['|', '\'], separating by those spaces.
      Ṅ           Print the result, followed by a linefeed.
         Ṫ      Tail; extract the last line.
                This will yield 0 if the array is empty.
          ⁾-ṁ   Mold the character '-' like that line (or 0), yielding a string
                of an equal amount of hyphen-minus characters.  

11

C, 58 bytes

i;f(n){for(i=2*n;~i--;printf(i<n?"-":"|%*c\n",2*n-i,92));}

--

Thanks to @Steadybox who's comments on this answer helped me shave a few bytes in my above solution


1
I managed to reach 68, was pretty proud of myself.. and then I scrolled :( -- Well done!
Quentin

1
Very nice! Have a +1
Steadybox

I have 2*n in there twice and it bothers me, can anyone think of a clever way to shorten it somehow?
Albert Renshaw

7

Javascript (ES6), 97 85 81 75 74 bytes

n=>(g=(n,s)=>n?g(--n,`|${" ".repeat(n)}\\
`+s):s)(n,"")+"-".repeat(n&&n+1)

Turns out I wasn't using nearly enough recursion

f=n=>(g=(n,s)=>n?g(--n,`|${" ".repeat(n)}\\
`+s):s)(n,"")+"-".repeat(n&&n+1)

console.log(f(0))
console.log(f(1))
console.log(f(2))
console.log(f(3))
console.log(f(4))


6

05AB1E, 16 15 16 bytes

Saved a byte thanks to Adnan

FðN×…|ÿ\}Dg'-×»?

Try it online!

Explanation

F       }         # for N in range [0 ... input-1]
 ðN×              # push <space> repeated N times
    …|ÿ\          # to the middle of the string "|\"
         Dg       # get length of last string pushed
           '-×    # repeat "-" that many times
              »   # join strings by newline
               ?  # print without newline

ð×.svy¦…|ÿ\}¹>'-×», guess my idea of .s wasn't as good as I thought. Nice use of ÿ, haven't seen that before.
Magic Octopus Urn

@carusocomputing: I considered .s as well as starting with <Ýð× but ran into trouble with the special case with those methods.
Emigna

FðN×…|ÿ\}Dg'-×» for 15 bytes
Adnan

@Adnan: Nice catch with Dg! Thanks :)
Emigna

.s also resulted in nested arrays and flattening which required more bytes.
Magic Octopus Urn

5

V, 18 17 16 bytes

1 byte saved thanks to @nmjcman101 for using another way of outputting nothing if the input is 0

é\é|ÀñÙá ñÒ-xÀ«D

Try it online!

Hexdump:

00000000: e95c e97c c0f1 d9e1 20f1 d22d 78c0 ab44  .\.|.... ..-x..D

Explanation (outdated)

We first have a loop to check if the argument is 0. If so, the code below executes (|\ is written). Otherwise, nothing is written and the buffer is empty.

Àñ     ñ            " Argument times do:
  é\é|              " Write |\
      h             " Exit loop by creating a breaking error

Now that we got the top of the triangle, we need to create its body.

Àñ   ñ              " Argument times do:
  Ù                 " Duplicate line, the cursor comes down
   à<SPACE>         " Append a space

Now we got one extra line at the bottom of the buffer. This has to be replaced with -s.

Ó-                  " Replace every character with a -
   x                " Delete the extra '-'

This answer would be shorter if we could whatever we want for input 0

V, 14 13 bytes

é\é|ÀñÙá ñÒ-x

Try it online!


I should not have tried that hard for a byte Try it online!
nmjcman101

@nmjcman101 Ah, « of course. Clever! :)
Kritixi Lithos

4

C#, 93 bytes

n=>{var s=n>0?new string('-',n+1):"";while(n-->0)s="|"+new string(' ',n)+"\\\n"+s;return s;};

Anonymous function which returns the ASCII triangle as a string.

Full program with ungolfed, commented function and test cases:

using System;

class ASCIITriangles
{
    static void Main()
    {
      Func<int, string> f =
      n =>
      {
          // creates the triangle's bottom, made of dashes
          // or an empty string if n == 0
          var s = n > 0 ? new string('-', n + 1) : "";

          // a bottom to top process
          while ( n-- > 0)
          // that creates each precedent line
            s = "|" + new string(' ', n) + "\\\n" + s;

          // and returns the resulting ASCII art
          return s;
      };

      // test cases:
      Console.WriteLine(f(4));
      Console.WriteLine(f(0));
      Console.WriteLine(f(1));
    }
}

3

Python 2, 69 bytes

lambda x:'\n'.join(['|'+' '*n+'\\'for n in range(x)]+['-'*-~x*(x>0)])

Try it online!


If you're printing it, you can save a few bytes by changing to python3, removing "".join and replacing it with the * operator and the sep argument in the sleep function, so lambda x:print(*['|'+' '*n+'\\'for n in range(x)]+['-'*-~x*(x>0)],sep="\n")
sagiksp

3

CJam, 24 22 21 bytes

Saved 1 byte thanks to Martin Ender

ri_{S*'|\'\N}%\_g+'-*

Try it online!

Explanation

ri                     e# Take an integer from input
  _                    e# Duplicate it
   {                   e# Map the following to the range from 0 to input-1
    S*                 e#   Put that many spaces
      '|               e#   Put a pipe
        \              e#   Swap the spaces and the pipe
         '\            e#   Put a backslash
           N           e#   Put a newline
            }%         e# (end of map block)
              \        e# Swap the top two stack elements (bring input to the top)
               _g+     e# Add the input's signum to itself. Effectively this increments any 
                       e#  non-zero number and leaves zero as zero.
                  '-*  e# Put that many dashes

2

SmileBASIC, 51 bytes

INPUT N
FOR I=0TO N-1?"|";" "*I;"\
NEXT?"-"*(N+!!N)

2

PowerShell, 51 67 bytes

param($n)if($n){1..$n|%{"|"+" "*--$_+"\"};write-host -n ('-'*++$n)}

Try it online!

(Byte increase to account for no trailing newline)

Takes input $n and verifies it is non-zero. Then loops to construct the triangle, and finishes with a line of -. Implicit Write-Output happens at program completion.


The program prints a trailing newline but I asked output to be exactly as specified, sorry!
Okx

@Okx Changed at a cost of 16 bytes.
AdmBorkBork

2

Retina, 39 bytes

.*
$*
*\`(?<=(.*)).
|$.1$* \¶
1
-
-$
--

Try it online

Convert decimal input to unary. Replace each 1 with |<N-1 spaces>\¶, print, and undo replace. Replace each 1 with a hyphen, and the last hyphen with 2 hyphens. Tadaa!


2

Common Lisp, 89 86 bytes

Creates an anonymous function that takes the n input and prints the triangle to *standard-output* (stdout, by default).

Golfed

(lambda(n)(when(< 0 n)(dotimes(i n)(format t"|~v@t\\~%"i))(format t"~v,,,'-<~>"(1+ n))))

Ungolfed

(lambda (n)
  (when (< 0 n)
    (dotimes (i n)
      (format t "|~v@t\\~%" i))
    (format t "~v,,,'-<~>" (1+ n))))

I'm sure I could make this shorter somehow.


2

C 101 93 75 bytes

f(n){i;for(i=0;i++<n;)printf("|%*c\n",i,92);for(;n--+1;)prin‌​tf("-");}

Ungolfed version

void f(int n)
{
  int i;

  for(i=0;i++<n;)
    printf("|%*c\n",i,92);

  for(;n--+1;)
    printf("-");

}

@Steadybox Thanks for pointing out, makes a lot of sense.


1
You can shave off a few bytes by replacing character constants with their ASCII value and moving the first i++ in the loop body. And why is printf("%c",'_'); so verbose?
Jens

@Jens stimmt, Danke sehr :) Updated
Abel Tom

This can be cut down to 74 bytes: i;f(n){for(i=0;i++<n;)printf("%c%*c\n",124,i,92);for(;n--+1;)printf("-");}
Steadybox

To 69 bytes, actually: i;f(n){for(i=0;i++<n;)printf("|%*c\n",i,92);for(;n--+1;)printf("-");}
Steadybox

@Steadybox 68: n--+1 can be shortened to ~n--
Albert Renshaw

2

Charcoal, 15 bytes

Nβ¿β«↓β→⁺¹β↖↖β»

Try it online!

Breakdown

Nβ¿β«↓β→⁺¹β↖↖β»
Nβ               assign input to variable β
   ¿β«         »  if β != 0:
      ↓β           draw vertical line β bars long
        →⁺¹β       draw horizontal line β+1 dashes long
            ↖      move cursor up one line and left one character
             ↖β    draw diagonal line β slashes long

Very late comment, but the closing » can be omitted.
DLosc

2

Japt, 20 bytes

Saved 2 bytes thanks to @ETHproductions

o@'|+SpX +'\Ãp-pUÄ)·

Try it online!

Explanation

o@'|+SpX +'\Ãp-pUÄ)·
o                       // Creates a range from 0 to input
 @                      // Iterate through the array
  '|+                   // "|" + 
     SpX +              // S (" ") repeated X (index) times +
          '\Ã            // "\" }
             p-pU       // "-" repeated U (input) +1 times
                 Ä)·    // Join with newlines

1
Nice one! You can save a byte by pushing the last row before joining: o@'|+SpX +'\Ãp'-pUÄ)· and due to a bug (really an unintentional side effect of auto-functions), you can then remove the ' in '-.
ETHproductions

Actually, it's like that with all lowercase letters, not just p. That's so you can do e.g. m*2 to double each element, or mp2 to square each
ETHproductions

2

J, 20 bytes

-13 bytes thanks to bob

*#' \|-'{~3,~2,.=@i.

Try it online!

original: 33 bytes

(#&'| \'@(1,1,~])"0 i.),('-'#~>:)

ungolfed

(#&'| \' @ (1,1,~])"0 i.) , ('-'#~>:)

Try it online!


25 bytes with *,&'-' '|',.'\'{."0~_1-i.
miles

22 bytes with *,&'-' '|',.' \'{~=@i.
bob

@bob That was very clever to use identity matrix
miles

@bob thanks for the suggestion. i've updated the post
Jonah


1

Python2, 73 bytes

n=input()
w=0
exec'print"|"+" "*w+"\\\\"+("\\n"+"-"*-~n)*(w>n-2);w+=1;'*n

A full program. I also tried string interpolation for the last line, but it turned out be a couple bytes longer :/

exec'print"|%s\\\\%s"%(" "*w,("\\n"+"-"*-~n)*(w>n-2));w+=1;'*n

Another solution at 73 bytes:

n=j=input()
exec'print"|"+" "*(n-j)+"\\\\"+("\\n"+"-"*-~n)*(j<2);j-=1;'*n

Test cases

0:

1:
|\
--

2:
|\
| \
---

3:
|\
| \
|  \
----

6:
|\
| \
|  \
|   \
|    \
|     \
-------

I apologise for my previous comment, functions are now allowed.
Okx

@Okx No problem. This stands as a full program. I don't think I'll look into the fashion of a function solution :)
Yytsi

1

MATL, 19 bytes

?'\|- '2GXyYc!3Yc!)

Try it online!

?         % Implicit input. If non-zero
  '\|- '  %   Push this string
  2       %   Push 2
  G       %   Push input
  Xy      %   Identity matrix of that size
  Yc      %   Prepend a column of 2's to that matrix
  !       %   Transpose
  3       %   Push 3
  Yc      %   Postpend a column of 3's to the matrix
  !       %   Transpose
  )       %   Index into string
          % Implicit end. Implicit display

1

QBIC, 41 bytes

:~a>0|[a|?@|`+space$(b-1)+@\`][a+1|Z=Z+@-

Explanation

:~a>0|  Gets a, and checks if a > 0
        If it isn't the program quits without printing anything
[a|     For b=1; b <= a; b++
?@|`+   Print "|"
space$  and a number of spaces
(b-1)   euqal to our current 1-based line - 1
+@\`    and a "\"
]       NEXT
[a+1|   FOR c=1; c <= a+1; c++
Z=Z+@-  Add a dash to Z$
        Z$ gets printed implicitly at the end of the program, if it holds anything
        The last string literal, IF and second FOR loop are closed implicitly.

1

R, 101 bytes

for(i in 1:(n=scan())){stopifnot(n>0);cat("|",rep(" ",i-1),"\\\n",sep="")};cat("-",rep("-",n),sep="")

This code complies with the n=0 test-case if you only consider STDOUT !
Indeed, the stopifnot(n>0) part stops the script execution, displays nothing to STDOUT but writes Error: n > 0 is not TRUE to SDTERR.

Ungolfed :

for(i in 1:(n=scan()))
    {
    stopifnot(n>0)
    cat("|", rep(" ", i-1), "\\\n", sep = "")
    }

cat("-", rep("-", n), sep = "")

1
Might want to fix the spelling of ungolfed
fəˈnɛtɪk

1

Python 2, 62 bytes

n=input();s='\\'
exec"print'|'+s;s=' '+s;"*n
if n:print'-'*-~n

Try it online!

Prints line by line, each time adding another space before the backslash. If a function that doesn't print would be allowed, that would likely be shorter.


Apparently, functions do not have to print.
Yytsi

1

JavaScript (ES6), 71 bytes

f=
n=>console.log(' '.repeat(n).replace(/./g,'|$`\\\n')+'-'.repeat(n+!!n))
<form onsubmit=f(+i.value);return!true><input id=i type=number><input type=submit value=Go!>

Outputs to the console. Save 6 bytes if printing to the SpiderMonkey JavaScript shell is acceptable. Save 13 bytes if returning the output is acceptable.


That regex is ingenious. I first tried something along those lines. I din't know about the $` pattern, but don't know if I still would've thought of it. Nice.
Jan


1

Python 3, 60 bytes

f=lambda n,k=0:k<n and'|'+' '*k+'\\\n'+f(n,k+1)or'-'[:n]*-~n

Try it online!

Two more solutions with the same byte count.

f=lambda n,k=0:n and'|'+' '*k+'\\\n'+f(n-1,k+1)or-~k*'-'[:k]
f=lambda n,s='|':-~n*'-'[:n]if s[n:]else s+'\\\n'+f(n,s+' ')

1

Perl, 63 bytes

$n=shift;print'|',$"x--$_,"\\\n"for 1..$n;print'-'x++$n,$/if$n

Ungolfed:

$ perl -MO=Deparse triangle.pl
$n = shift @ARGV;
print '|', $" x --$_, "\\\n" foreach (1 .. $n);
print '-' x ++$n, $/ if $n;

$" is the list separator, which defaults to " ". $/ is the output record separator, which defaults to "\n". $_ is the implicit loop variable.


1
probably could save some by reading the input off of stdin?$n=<>?
Ven

1

Haskell, 82 65 bytes

g 0=""
g n=((take n$iterate(' ':)"\\\n")>>=('|':))++([0..n]>>"-")

Try it online! Usage:

Prelude> g 4
"|\\\n| \\\n|  \\\n|   \\\n-----"

Or more nicely:

Prelude> putStr $ g 4
|\
| \
|  \
|   \
-----

1

Pyth, 23 18 bytes

VQ++\|*dN\\)IQ*\-h

Test suite available online.
Thanks to Ven for golfing off 5 bytes.

Explanation

VQ++\|*dN\\)IQ*\-h
 Q           Q    Q  [Q is implicitly appended, initializes to eval(input)]
       d             [d initializes to ' ' (space)]
VQ         )         For N in range(0, eval(input)):
      *dN             Repeat space N times
   +\|                Prepend |
  +      \\           Append \
                      Implicitly print on new line
            IQ       If (input): [0 is falsy, all other valid inputs are truthy]
                 hQ   Increment input by 1
              *\-     Repeat - that many times
                      Implicitly print on new line

@Ven Thanks! You can cut off the last | for an additional byte.
Mike Bufardeci

0

Javascript 101(Full Program), 94(Function Output), 79(Return) bytes

Full Program

Will not run in Chrome (as process doesn't exist apparently)
Will not run in TIO (as prompt apparently isn't allowed)

x=prompt();s='';for(i=0;i<x;i++)s+='|'+' '.repeat(i)+`\\
`;process.stdout.write(s+'-'.repeat(x&&x+1))

Function with EXACT print

x=>{s='';for(i=0;i<x;)s+='|'+' '.repeat(i++)+`\\
`;process.stdout.write(s+'-'.repeat(x&&x+1))}

Try it Online

Function with return string

x=>{s='';for(i=0;i<x;)s+='|'+' '.repeat(i++)+`\\
`;return s+'-'.repeat(x&&x+1)}

Try it Online

Repeating characters in Javascript is dumb and so is suppressing newlines on output


0

Python 2, 82 bytes

def f(i,c=0):
 if c<i:print'|'+' '*c+'\\';f(i,c+1)
 print'-'*((c+1,c)[c<1]);exit()

Try it online!

Longer that the other Python answers but a recursive function just to be different.

It feels wasteful using two print statements but I can't find a shorter way round it. Also the exit() wastes 7 to stop it printing decreasing number of - under the triangle.


You can do -~c*(c>0) on the last line to save 3 bytes :)
Yytsi

Or better yet: c and-~c.
Yytsi
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.