12
\$\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\$
8
  • \$\begingroup\$ This was on Sandbox for a couple of days :) \$\endgroup\$ – Maanas B Jun 4 at 14:32
  • \$\begingroup\$ Does the explanation count towards the byte count :? \$\endgroup\$ – Wzl Jun 4 at 14:34
  • \$\begingroup\$ The explanation is only for how the program works \$\endgroup\$ – Maanas B Jun 4 at 14:37
  • 2
    \$\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 at 17:00
  • 8
    \$\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 at 17:10

37 Answers 37

18
\$\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\$
4
  • 7
    \$\begingroup\$ lol, wow. definitely the perfect tool to pick :p \$\endgroup\$ – hyper-neutrino Jun 4 at 15:15
  • 4
    \$\begingroup\$ an answer shorter than charcoal??? \$\endgroup\$ – Maanas B Jun 4 at 16:09
  • \$\begingroup\$ 13 hours too late for this :p \$\endgroup\$ – Razetime Jun 5 at 4:31
  • \$\begingroup\$ @Razetime 5 minutes too late to comment this... \$\endgroup\$ – hakr14 Jun 5 at 4:37
5
\$\begingroup\$

Charcoal, 2 bytes

↖N

Try it online!

right tool for the job

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Knew it. I was thinking charcoal is gonna be the winner for this :P \$\endgroup\$ – Maanas B Jun 4 at 14:42
  • 2
    \$\begingroup\$ Also 2 bytes \$\endgroup\$ – caird coinheringaahing Jun 4 at 14:56
5
\$\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\$
5
\$\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\$
5
\$\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\$
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\$ – Maanas B Jun 4 at 14:34
  • 1
    \$\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 at 14:42
  • 1
    \$\begingroup\$ @MaanasB, I have (almost) all of the characters Japt uses on my phone's keyboard. \$\endgroup\$ – Shaggy Jun 4 at 15:20
  • \$\begingroup\$ :/ two byte character literals. I'm disappointed in you, jelly :P \$\endgroup\$ – Wzl Jun 4 at 17:14
  • \$\begingroup\$ @Wzl ? (filler filler) \$\endgroup\$ – hyper-neutrino Jun 4 at 17:15
4
\$\begingroup\$

J, 10 bytes

' \'{~=@i.

Try it online!

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

Python 2, 37 bytes

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

Try it online!

\$\endgroup\$
4
\$\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 at 1:53
  • \$\begingroup\$ @att Nice. That leads to a 37-byte version with clang. Undefined behavior for the win! ;-) \$\endgroup\$ – Arnauld Jun 5 at 10:31
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\$

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 at 2:36
  • \$\begingroup\$ 58 bytes \$\endgroup\$ – ceilingcat Jun 7 at 6:59
2
\$\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.

\$\endgroup\$
1
  • \$\begingroup\$ n o o o friggin ninjas \$\endgroup\$ – Makonede Jun 4 at 15:42
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\$ – Dominic van Essen Jun 4 at 19:00
  • \$\begingroup\$ @DominicvanEssen Thanks! updated \$\endgroup\$ – digEmAll Jun 4 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\$ – caird coinheringaahing Jun 4 at 19:57
  • \$\begingroup\$ @cairdcoinheringaahing Thanks! I'll update it with a new version that takes input \$\endgroup\$ – SlamJammington Jun 4 at 20:09
  • 2
    \$\begingroup\$ I'm not a PHP expert, but I can help improve your answer to 49 bytes. \$\endgroup\$ – dingledooper Jun 4 at 22:32
  • 2
    \$\begingroup\$ ...and down to 35 bytes: Try it online! \$\endgroup\$ – Sisyphus Jun 5 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 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\$ – Chris Jun 5 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\$ – Redwolf Programs Jun 5 at 3:22
  • \$\begingroup\$ you can get 33 with a full program, and 30 with a lambda. \$\endgroup\$ – Razetime Jun 5 at 4:38
  • 1
    \$\begingroup\$ Thanks for the welcome @redwolf-programs! Nice one @Razetime, 33! \$\endgroup\$ – Luis Esteban Jun 6 at 7:46
2
\$\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\$
2
\$\begingroup\$

AWK, 34 bytes

{for(;$1--;x=x" ")y=y x"\\\n"}$0=y

Try it online!

This is pretty straightforward I suppose... Each time through the loop creates a string corresponding to one line of output. The control just counts decrements the first commandline argument until it's 0.

 for(;$1--;      )

The body of the loop appends the current output line to an accumulator variables, taking the current "padding" of blanks and appending \ and '\n` to it.

                  y=y x"\\\n"

The "end of loop" expression builds up the padding variable.

           x=x" "

Then once all the lines have been generated, assigning that output string to $0 as a truthy test, without an action, causes the output to be printed.

                               $0=y

Ly, 24 bytes

0(10)'\<n[>&:[o]p' <1-]<

Try it online!

This is really a translation of the approach, just in Ly. So I'm not adding a separate entry for it.

The first task is to push a null terminated string \\n onto the stack.

0(10)'\

Then shift to a new stack and read in the number of lines.

       <n

The construct to loop that many times shifts between stacks a decrements the top of the stack with the loop counter until it hits 0.

         [>        <1-]

The body of the loop, duplicates the stack with the output string on top of itself &: then prints up to the first \0, deletes that null and adds a space. So each iteration prints the current line and appends a space to the front in anticipation of the next iteration.

           &:[o]p' 

When the loop ends and all the lines have been printed, we just need to switch stacks to avoid printing what's left.

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

Lolwho.Cares, 183 bytes

* >2,*1210+10 0*+ 0>,02001*101v
                   ^ 010121   <
  ^           121021<
    >*+102021**+vv             <
v 120210021`1012<   +**120021 <
>*101*10102 2012 >*1012+201020`^

Given a decimal number N, will output a line of length N.

Explanation:

* >2,*1210+10 0*+ 0>,02001*101v
                   ^ 010121   <
  ^           121021<

This code reads from the input, and converts ascii decimal to a number. Side effect of it's working means it pushes N, followed by 0.

It does so by first reading a character, finishing when it read 0 (EOF). It then multiplies the current number by 10, and finally it subtracts 48 from the ASCII value and adds.

    >*+102021**+vv             <
v 120210021`1012<   +**120021 <
>*101*10102 2012 >*1012+201020`^

This code takes [N, 0] pushed by the other function and draws a line accordingly. This makes use of the fact that the stack is "initialised" with an infinite amount of 0s at the bottom.

This is basically an implementation of nested for loops; It checks whether enough lines have been printed, then prints X spaces, followed by \ and newline.

The language is a custom esoteric programming language, similar to BEFUNGE (as user pointed out here).

Note: Due to the implementation of number reading, care must be taken to omit any non-decimal characters, including leading/trailing spacing/newlines.

Online interpreter

New contributor
Robot is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
1
  • \$\begingroup\$ now i just need to see one in asciidots \$\endgroup\$ – Maanas B Jun 7 at 3:34
2
\$\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\$
1
\$\begingroup\$

Retina 0.8.2, 13 bytes

.+
$* 
 
$`\¶

Try it online! Note: Trailing spaces on lines 2 and 3. Explanation:

.+
$* 

Convert the input to a string of spaces.

 
$`\¶

Output each prefix of the string followed by a \, on its own line.

This program outputs two trailing newlines, one from the code, one from Retina 0.8.2's default output. The latter can be suppressed at a cost of 2 bytes by changing the third line to \` . Alternatively the following 14-byte Retina 1 program outputs no trailing newlines:

.+
* 
L$` 
$`\

Try it online! Note: Trailing spaces on lines 2 and 3. Explanation: Much like the Retina 0.8.2 program, except the repetition operator is simply * and the list matches command only inserts newlines between the substitutions.

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

Vyxal j, 6 bytes

ʁð*\\+

Try it Online!

ʁð*\\+    
ʁ         Push range(input)
  *       Repeat...
 ð        the string ' ' that many times for each
   \\+    Append a backslash to each

j flag: join on newlines
\$\endgroup\$
1
\$\begingroup\$

Python 3, 42 bytes

f=lambda n,s="\\\n":n*s and s+f(n-1,' '+s)

Try it online!

-2 bytes thanks to @ovs

\$\endgroup\$
2
  • 1
    \$\begingroup\$ -2 bytes by removing the need for the or .... \$\endgroup\$ – ovs Jun 4 at 15:20
  • \$\begingroup\$ @ovs thanks!!!! \$\endgroup\$ – Wasif Jun 4 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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