22
\$\begingroup\$

Information

Create a diagonal line given its length (let’s call the variable, say, \$n\$ where \$n > 0\$)

  • The diagonal line starts from the top left and goes to the bottom right.
  • You must use the ASCII character \ for the line.
  • The input number can be given from STDIN or if your program doesn’t support that, use a hardcoded value in your code or pass it as an argument while running the program.
  • For padding, only use the space character 0x20
  • Trailing spaces and/or newlines are allowed.
  • The length of the line is the non whitespace characters

Here is an example program (59 bytes):

n = int(input())
for i in range(n):
  print(' ' * i + '\\')

Try it online!

Example:

Input: 4
Output
\
 \
  \
   \

Rules

  • Use standard I/O when possible.
  • Standard loopholes are forbidden.
  • This is code golf, so the shortest answer in bytes wins.
  • Please explain the code that you wrote.
\$\endgroup\$
9
  • \$\begingroup\$ This was on Sandbox for a couple of days :) \$\endgroup\$
    – zoomlogo
    Jun 4, 2021 at 14:32
  • \$\begingroup\$ Does the explanation count towards the byte count :? \$\endgroup\$
    – Wezl'
    Jun 4, 2021 at 14:34
  • \$\begingroup\$ The explanation is only for how the program works \$\endgroup\$
    – zoomlogo
    Jun 4, 2021 at 14:37
  • 5
    \$\begingroup\$ I suggest removing the rule "Use Standard I/O when possible". We have well-accepted default rules for I/O, and it would be unfair to force the use of standard I/O just because it is possible for a given language \$\endgroup\$
    – Luis Mendo
    Jun 4, 2021 at 17:00
  • 9
    \$\begingroup\$ I'd suggest not accepting an answer (or at least not accepting one so quickly) in the future, as it may discourage others from answering. \$\endgroup\$
    – user
    Jun 4, 2021 at 17:10

53 Answers 53

26
\$\begingroup\$

Canvas, 1 byte

Better tool for the job ;)

Try it here!

Given an integer, this draws a diagonal of that string. If you pass a string instead, this prints the string along the diagonal. There is matching anti-diagonal builtin as well.

\$\endgroup\$
3
  • 9
    \$\begingroup\$ lol, wow. definitely the perfect tool to pick :p \$\endgroup\$
    – hyper-neutrino
    Jun 4, 2021 at 15:15
  • \$\begingroup\$ 13 hours too late for this :p \$\endgroup\$
    – Razetime
    Jun 5, 2021 at 4:31
  • \$\begingroup\$ @Razetime 5 minutes too late to comment this... \$\endgroup\$
    – hakr14
    Jun 5, 2021 at 4:37
10
\$\begingroup\$

Charcoal, 2 bytes

↖N

Try it online!

right tool for the job

\$\endgroup\$
1
7
\$\begingroup\$

APL (Dyalog Unicode), 9 bytes (SBCS)

Anonymous tacit prefix function. Returns a list of string, as per meta consensus.

'\'↑⍨¨-∘⍳

Try it online!

∘⍳ indices one through \$n\$, then:

- negate those

¨ for each:

↑⍨ take (when negative: from the rear) that many characters (padding with spaces) from:

  '\' the backslash character

\$\endgroup\$
6
\$\begingroup\$

Jelly, 7 bytes

=þị⁾\ Y

Try it online!

Ḷ⁶ẋp”\Y

Try it online!

How they work

=þị⁾\ Y - Main link. Takes N on the left
=þ      - Yield the identity matrix of size N
  ị⁾\   - Index into "\ ", replacing 1 with "\" and 0 with " "
      Y - Join by newlines

Ḷ⁶ẋp”\Y - Main link. Takes N on the left
Ḷ       - Range [0, ..., N-1]
 ⁶ẋ     - Repeat that many spaces for each
   p”\  - Append "\" to each
      Y - Join by newlines
\$\endgroup\$
6
\$\begingroup\$

Japt -R, 5 bytes

õ!ù'\

Try it

õ!ù'\     :Implicit input of integer
õ         :Range [1,input]
 !ù'\     :For each, left pad "\" to that length with spaces
          :Implicit output joined with newlines

Japt -mR, 5 bytes

'\iUç

Try it

'\iUç     :Implicit map of each U in the range [0,input)
'\i       :Prepend to "\"
   Uç     :  Space repeated U times
          :Implicit output joined with newlines
\$\endgroup\$
6
\$\begingroup\$

51AC8, 10 bytes

R[\ ×\\+t]

Try it Online!

-2 bytes due to an update.

-7 bytes due to an update introducing for_each loops and range.

-1 byte online interpreter and implicit input.

Explanation

       # Implicit Input (STDIN) and push to stack
R      # Range from 0 to input (exclusive)
[      # Start for each
  \    # Push ' ' to the stack
  ×    # Multiply the top 2 elements on the stack
  \\   # Push '\'
  +    # Add top 2 elements
  t    # Pop and print top of stack
]      # End of while loop
\$\endgroup\$
5
\$\begingroup\$

Python 2, 37 bytes

x='\\'
exec'print x;x=" "+x;'*input()

Try it online!

\$\endgroup\$
5
\$\begingroup\$

C (clang), 37 bytes

f(n){printf("%*c\n",n--,92,n&&f(n));}

Try it online!


C (gcc), 39 bytes

A recursive version suggested by @att.

f(n){--n&&f(n);printf("%*c\n",n+1,92);}

Try it online!


C (gcc), 44 bytes

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

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ 39 bytes \$\endgroup\$
    – att
    Jun 5, 2021 at 1:53
  • \$\begingroup\$ @att Nice. That leads to a 37-byte version with clang. Undefined behavior for the win! ;-) \$\endgroup\$
    – Arnauld
    Jun 5, 2021 at 10:31
5
\$\begingroup\$

Dyalog APL, 16 14 bytes

Solution - Takes in number of lines as input from user, and returns a string of diagonal line.

' \'[1+∘.=⍨⍳⎕]

Explanation

⎕            ⍝ ⎕ takes input from the user (number of lines)
             ⍝ In the below explanation, I have assumed ⎕ = 9 as input
⍳⎕            ⍝ 1 to 9 : [1,2,3,4,5,6,7,8,9]
∘.=          ⍝ Outer Product with Equality
⍨            ⍝ Apply a function with same argument on both sides
∘.=⍨⍳⎕       ⍝ ∘.=⍨ function applied to array ⍳⎕ = [1,2..9]
             ⍝ This is same as (⍳9) ∘.= (⍳9), which produces Identity Matrix of size 9
1+∘.=⍨⍳⎕     ⍝ Add 1 to each element of previous matrix (since APL uses 1-based index)
' \'[1+∘.=⍨⍳⎕] ⍝ From the string ' \', select characters specified by indices in 1+∘.=⍨⍳⎕
\$\endgroup\$
3
  • \$\begingroup\$ actually reads from the input section on TIO, but the way the program is run it doesn't implicitly output, you would need to prepend ⎕← to get output. The way to "enable" implicit output is to wrap the program into a tradfn and call that: Try it online! \$\endgroup\$
    – ovs
    Sep 30, 2021 at 14:08
  • \$\begingroup\$ @ovs How exactly is a tradfn different from a normal function definition? And how do you "enable" implicit I/O in tryapl.org (or, if this is not possible from the site, from Dyalog APL Windows Editor) ? \$\endgroup\$ Oct 1, 2021 at 17:55
  • \$\begingroup\$ Oh sorry I misread your post, tryapl.org indeed does not support . If you want to add a link for others to try this online, you could use the TIO one I sent above. I don't have Windows but I would assume that you can run ' \'[1+∘.=⍨⍳⎕] and then enter the number (like this). And tradfn is short for traditional function \$\endgroup\$
    – ovs
    Oct 1, 2021 at 21:14
5
\$\begingroup\$

brainfuck, 113 bytes

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

Try it online.

First time poster. This was a fun exercise! Please provide criticism, I pretty much went in cold when writing this.

, how long the line should be via char code
>

initialize cell 1 with "\"
>+++++++[<+++++++++++++>-]<+
> 

initialize cell 2 with "\n"
++++++++++
>

initialize cell 3 with " "; go back to beginning
>++++[<+++++>-]<
<<<

start loop at cell 0
[
    >>>> go to cell 4
    [
        ->+>+<< copy the pad value to cells 5 and 6
    ]
    
    > now we move cell 5 to cell 4
    [
        -<+> cell 4 keeps track how much padding we'll need for our next iteration
    ]
    >

    cell 6 keeps track of how many spaces we need to print currently
    [
        <<<  go to space char
        .    print it
        >>>- decrease counter
    ]

    <<<<< move to line char
    .>.   print line and newline
    >>+   move to cell 4 and increase our padding by 1
    <<<<- back to cell 0; subtract line counter
]
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$ Apr 22, 2022 at 20:18
4
\$\begingroup\$

Jelly, 7 bytes

Ṭ€ị⁾\ Y

Try it online!

Working on golfing. This is longer than I remember it being possible. The JHT exercise allows other characters so I can't get this to 5 bytes because of that :/

Ṭ€ị⁾\ Y    Main Link
 €         For each (implicit range)
Ṭ          Generate a boolean list with 1s at the indices
  ị        Index that into
   ⁾\      "\ "
      Y    and join on newlines
\$\endgroup\$
5
  • \$\begingroup\$ How did you create the answer so fast?? I think you guys have some sort of unicode keyboard to enter theses characters very quickly :P \$\endgroup\$
    – zoomlogo
    Jun 4, 2021 at 14:34
  • 2
    \$\begingroup\$ @MaanasB I have the wiki pages bookmarked and then I just copy-paste, lol. This is a standard exercise from the Jelly Hyper-Training room and it's a pretty simple challenge (not that that's bad, of course!) \$\endgroup\$
    – hyper-neutrino
    Jun 4, 2021 at 14:42
  • 1
    \$\begingroup\$ @MaanasB, I have (almost) all of the characters Japt uses on my phone's keyboard. \$\endgroup\$
    – Shaggy
    Jun 4, 2021 at 15:20
  • \$\begingroup\$ :/ two byte character literals. I'm disappointed in you, jelly :P \$\endgroup\$
    – Wezl'
    Jun 4, 2021 at 17:14
  • \$\begingroup\$ @Wzl ? (filler filler) \$\endgroup\$
    – hyper-neutrino
    Jun 4, 2021 at 17:15
4
\$\begingroup\$

J, 10 bytes

' \'{~=@i.

Try it online!

\$\endgroup\$
4
\$\begingroup\$

C (clang), 90 77 60 bytes

i;main(n){for(scanf("%i",&n);i<n;printf("%*s\\\n",i++,""));}

Try it online!

My first work without int in it while still using it. I'm doing better now, aren't I?

Thanks to att for golfing 13 bytes. Thanks to ceilingcat for golfing 17 bytes.

\$\endgroup\$
2
  • \$\begingroup\$ -13 using for instead of while \$\endgroup\$
    – att
    Jun 5, 2021 at 2:36
  • \$\begingroup\$ 58 bytes \$\endgroup\$
    – ceilingcat
    Jun 7, 2021 at 6:59
4
\$\begingroup\$

convey, 46 bytes

[0>>,+1
   v"^
{,"=@#]}
 >^}"~v#'\\'
' '!""~/}

Try it online!

Visualization (i use '_' instead of space because the gif doesnt show the space char if i use it, but in the official page the output works whit spaces):

enter image description here

\$\endgroup\$
4
\$\begingroup\$

Vyxal M, 7 bytes

(nI\\+,

Try it Online!

Explanation:

(  # range from 0 to implict input
  n  # loop variable
   I  # push that many spaces
    \\  # backslash literal
      +  # concatenate the spaces with the backslash
       ,  # print
\$\endgroup\$
3
\$\begingroup\$

JavaScript (ES6), 33 bytes

f=(n,s=`\\
`)=>--n?s+f(n,' '+s):s

Try it online!

\$\endgroup\$
3
\$\begingroup\$

MATLAB/Octave, 32 31 bytes

-1 byte thanks to Luis Mendo

disp([60*eye(input(''))+32,''])

Try it online!
Reads the length from standard input, writes to standard output.
Makes use of identity matrix eye(x).


Alternatively, using function input/output, 22 21 bytes:

@(x)[60*eye(x)+32,'']

Try it online!
Anonymous function, outputs character array.

\$\endgroup\$
0
3
\$\begingroup\$

Stax, 3 bytes

■♦9

Run and debug it

Explanation

m'\)
m    map 1..n and print with newlines
 '\) pad \ on the left with spaces to given length
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 4 bytes

'\3Λ

Try it online!

Using the input as length, draw \ in direction 3 (down-right) with the canvas builtin Λ. See Kevin's tip for details on how the canvas works


6 bytes without the canvas builtin:

'\ILj»

Try it online!

For each number in the range IL == [1..input], pad the string "\" with leading spaces to this length (j). » joins the results by newlines.

Another 6 bytes solution suggested by Kevin Cruijssen:

L<'\ú»

Try it online!

For each number in the range L< == [0..input-1], pad the string "\" with that many leading spaces.

\$\endgroup\$
3
  • \$\begingroup\$ n o o o friggin ninjas \$\endgroup\$
    – Makonede
    Jun 4, 2021 at 15:42
  • \$\begingroup\$ Alternative 6-byter using ú: ݨ'\ú»/L<'\ú». \$\endgroup\$ Jul 29, 2021 at 9:48
  • \$\begingroup\$ @KevinCruijssen thanks, added the second suggestion. It would be really nice if j would automatically swap arguments for integer lists as well. \$\endgroup\$
    – ovs
    Jul 30, 2021 at 6:38
2
\$\begingroup\$

Python 3.8 (pre-release), 46 bytes

for i in range(int(input())):print(' '*i+'\\')

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ you should not answer your own question so soon \$\endgroup\$
    – Wasif
    Jun 4, 2021 at 14:41
  • \$\begingroup\$ welp sorry didnt know that \$\endgroup\$
    – zoomlogo
    Jun 4, 2021 at 14:43
2
\$\begingroup\$

Vyxal jṀ, 4 bytes

ƛ\\꘍

Try it Online!

Flags go brrr

ƛ\\꘍   Full Program
ƛ      For each (implicity loops from 0 to n - 1)
 \\    push '\'
   ꘍   prepend x spaces to '\'

is equivalent to mM, which makes implicit range start at 0 instead of 1 and end at n - 1 instead of n.

j joins the top of the stack on newlines at the end.

\$\endgroup\$
0
2
\$\begingroup\$

Red, 30 bytes

repeat i n[print pad/left"\"i]

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Java, 56 bytes

n->{for(var s="\\";n-->0;s=" "+s)System.out.println(s);}

Try it online!

\$\endgroup\$
2
\$\begingroup\$

CJam, 10 bytes

ri{S*'\N}%

Try it online!

Explanation

r             e# Read input
 i            e# Evaluate as an integer, n
  {     }%    e# Do the following for each k in [0 1 ... n-1]
              e# Push k (implicit)
   S          e# Push space
    *         e# Repeat. Gives a string with k spaces
     '\       e# Push character "\"
       N      e# Push newline
              e# Output the stack (implicit)
\$\endgroup\$
2
\$\begingroup\$

R, 35 bytes

cat(sep="\\
",strrep(" ",0:scan()))

Try it online!

\$\endgroup\$
2
\$\begingroup\$

R, 42, 39 bytes

  • -3 bytes thanks to @Dominic van Essen
write(strrep("\\",diag(x<-scan())),1,x)

Try it online!

Explanation:

  • take x from standard input,
  • create a diagonal matrix of size x
  • repeat the character '\' one time for each 1 of the matrix and 0-times for each 0 (= empty string)
  • print the matrix separating each character with a space
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 39 bytes using strrep... but I've found another approach that's still shorter (so far)... \$\endgroup\$ Jun 4, 2021 at 19:00
  • \$\begingroup\$ @DominicvanEssen Thanks! updated \$\endgroup\$
    – digEmAll
    Jun 4, 2021 at 20:05
2
\$\begingroup\$

PHP, 58 57 bytes

for($i=0;$i<$argv[1];$i++)echo str_repeat(' ',$i)."\\\n";

Try it here!

This is my first golf, so feel free to mention anything I can do to improve this!

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Welcome to Code Golf, and nice first answer! Be sure to check out our Tips for golfing in PHP page for ways you can golf your program. Note that assuming the input is saved in a variable (e.g. $n) is not an acceptable method of input. Instead, you should take input via command line arguments, as a function argument or via STDIN \$\endgroup\$ Jun 4, 2021 at 19:57
  • \$\begingroup\$ @cairdcoinheringaahing Thanks! I'll update it with a new version that takes input \$\endgroup\$ Jun 4, 2021 at 20:09
  • 2
    \$\begingroup\$ I'm not a PHP expert, but I can help improve your answer to 49 bytes. \$\endgroup\$ Jun 4, 2021 at 22:32
  • 2
    \$\begingroup\$ ...and down to 35 bytes: Try it online! \$\endgroup\$
    – Sisyphus
    Jun 5, 2021 at 4:50
2
\$\begingroup\$

Factor, 40 bytes

[ iota [ [ bl ] times "\\"print ] each ]

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Perl 5, 34 bytes

s//\\/;$==<>;s// / while(say,$=--)

Try it online!

This should be run from the command line like perl -E 's//\\/;$==<>;s// / while(say,$=--)' to activate the say feature without adding any bytes.

Ungolfed:

$_='\\'; #Set the default variable $_ to a single backslash
$==<>; #Take input into $=. This variable converts the input to an integer
while($=--){ #Decrement $= and loop
    say; #Prints $_ and a newline
    $_=" $_"; #Adds a space to the start of $_
}

Uses s// / as shorthand for $_=" $_" (i.e. to prepend a space to $_). Putting say into the while loop lets us drop the brackets from the loop body.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 24 bytes with the same idea: Try it online! \$\endgroup\$
    – Sisyphus
    Jun 5, 2021 at 4:58
  • \$\begingroup\$ @Sisyphus Wow, that's impressive. I had no idea you use x like that. Feel free to post that as your own answer- it's plenty different from mine. ;) \$\endgroup\$ Jun 5, 2021 at 5:35
2
\$\begingroup\$

Ruby, 41 bytes

puts Array.new(gets.to_i){|i|(' '*i+'\\')}

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Welcome to Code Golf! Nice first answer. \$\endgroup\$ Jun 5, 2021 at 3:22
  • \$\begingroup\$ you can get 33 with a full program, and 30 with a lambda. \$\endgroup\$
    – Razetime
    Jun 5, 2021 at 4:38
  • 1
    \$\begingroup\$ Thanks for the welcome @redwolf-programs! Nice one @Razetime, 33! \$\endgroup\$ Jun 6, 2021 at 7:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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