33
\$\begingroup\$

All credits to Adnan for coming up with this challenge.

My last challenge, before I go on break.

Task

Given positive integer n, if n is odd, repeat / that many times; if n is even, repeat \ that many times.

(Seriously, the testcases would be much clearer than this description, so just look at the testcases.)

Specs

Testcases

n output
1 /
2 \\
3 ///
4 \\\\
5 /////
6 \\\\\\
\$\endgroup\$

63 Answers 63

2
\$\begingroup\$

Actually, 10 bytes

Golfing suggestions welcome. Try it online!

;'\'/2(%I*

How it works

       Implicit input of n
;      Duplicate n
'\'/   The strings "/" and "\"
2(%    n mod 2
I      If n mod 2, then "/", else "\"
*      Multiply by n. Implicit print at the end.
\$\endgroup\$
2
\$\begingroup\$

Python 3, 43 Bytes

n=int(input())
a='\\'*n
if n%2:a='/'*n
print(a)

In python the \ symbol is also used as an operator when inside a string (e.g: \n means newline) so \\ has to be used to get the backslash symbol.

This code works by assuming the input (n) is odd, and then checks if it is even. If so, then it redefines the variable a (the output) before displaying it.

This is shorter than using an if-else statement by 5 bytes as it does the checking after defining the variable, meaning that the else command is not needed.

\$\endgroup\$
4
  • \$\begingroup\$ You could save bytes by changing to Python2, since int(input()) could be changed to input() and print wouldn't need parentheses. Also, there's an unnecessary whitespace in n%2: . \$\endgroup\$
    – Yytsi
    Commented Aug 31, 2016 at 12:12
  • \$\begingroup\$ Also, you may hook the character from a string (selecting n%2-th) character, but that would end up being the same answer as @xnor has. It's a nice trick for the future! \$\endgroup\$
    – Yytsi
    Commented Aug 31, 2016 at 12:16
  • \$\begingroup\$ Indeed, '\/'[n%2]*n is pretty much as short as it can be. \$\endgroup\$
    – SylvainD
    Commented Sep 1, 2016 at 9:58
  • \$\begingroup\$ Thanks for the tips, I'll bear them in mind for next time \$\endgroup\$
    – AvahW
    Commented Sep 1, 2016 at 11:25
2
\$\begingroup\$

><>, 15 + 3 = 18 bytes

\/:l2-),:2%0go:

+3 bytes for the -v flag to initialise the stack with the input. Try it online!

><> is a toroidal 2D language, so the following runs in a loop:

\/          Mirrors that reflect the instruction pointer. Since the code is
            one row high, the reflection wraps and the IP ends up moving in the
            same direction anyway, so these are no-ops.

:l2-)       Push (input > length of stack - 1) - note that the actual subtraction
            is by 2 to account for the fact that we duplicated an element with :

,           Divide the input by the above. If (input == length of stack - 1),
            then the program errors out due to division by 0. Otherwise, the
            input is unchanged.

:2%0g       Push the char at (input % 2, 0), which will be one of the two slashes
            at the beginning of the code

o           Output this char

:           Duplicate the input, increasing the length of the stack by 1
\$\endgroup\$
2
\$\begingroup\$

PHP, 63 52 bytes

Version 1 - 63 bytes

$i=$argv[1];$x=($i%2?"/":"\\");echo sprintf("%'".$x.$i."s",$x);

Version 2 - 52 bytes

Thanks to manatwork for saving 11 bytes

$i=$argv[1];$x=$i%2?"/":"\\";printf("%'$x{$i}s",$x);

Run with php -f squiggle.php <number>

https://repl.it/DFdi/2 (remember to change the input on repl)

\$\endgroup\$
2
  • 1
    \$\begingroup\$ No need for parenthesis around the ternary expression. Why using sprintf() to return a value just to echo it and not directly printf() it? And is shorter to use variable expansion than concatenating the format string: "%'$x{$i}s". \$\endgroup\$
    – manatwork
    Commented Sep 2, 2016 at 13:28
  • \$\begingroup\$ @manatwork thanks for the great tips! I've modified my answer. \$\endgroup\$
    – ʰᵈˑ
    Commented Sep 2, 2016 at 13:38
2
\$\begingroup\$

Bash + coreutils, 29 28 bytes

yes $1_45r2%*92+P|sed $1q|dc

Previous answer, easier to understand:

yes $[92-$1%2*45]P|sed $1q|dc

In the new script I just transferred the calculation of the ASCII code from bash to dc entirely.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ @LeakyNun I was used with the Bash and pure Bash terms until I started here. I updated my answer. \$\endgroup\$
    – seshoumara
    Commented Aug 31, 2016 at 14:39
2
\$\begingroup\$

Husk, 6 bytes

R¹!"/¦

Try it online!

-4 bytes from Zgarb.

¦ is an alias for \ in a string.

Husk, 10 bytes

*⁰;!⁰"/\\"

Try it online!

Explanation

*⁰;!⁰"/\\"
   !⁰"/\\" get element at index n in string "/\" (wraps around)
  ;        create singleton list from it
*⁰         repeat list n times
\$\endgroup\$
0
2
\$\begingroup\$

Japt, 7 bytes

çUg"\\/

Try it

\$\endgroup\$
2
+50
\$\begingroup\$

Forth (gforth), 55 bytes

: b 1- dup for dup 2 mod if 92 else 47 then emit next ;

Try it online!

called as <number> b.

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

05AB1E, 7 5 bytes

-2 bytes thanks to @Neil.

„\/è×

Try it online!

     è   # 0-based index...
         # implicit input...
     è   # implicit mod 2 in...
 „\/     # "\/"
      ×  # repeat implicit input times
         # implicit output
\$\endgroup\$
1
  • \$\begingroup\$ è is a) modular, so you don't need É, and b) commutative, so you don't need s. \$\endgroup\$
    – Neil
    Commented Nov 22, 2020 at 16:44
2
\$\begingroup\$

Vyxal, 8 bytes

?£₂k/i¥ẋ

Try it Online!

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

Vyxal, 31 bits1, 3.875 bytes

‛\/iẋ

Try it Online!

'\/    # string literal "\\/"
   i   # modular index
    ẋ  # repeat
\$\endgroup\$
2
\$\begingroup\$

TypeScript's Type System, No Ignore, 541 311 155 148 140 118 bytes

Based off of a previous even/odd answer

type E<N>=N extends`11${infer R}`?R extends""?"/":E<R>:"\\"
type X<A,B=A>=B extends`1${infer R}`?`${E<A>}${X<A,R>}`:""

X takes in a repeated 1 N times to represent the number N, for example X<"11111"> represents 5 passed to the X function.

TypeScript Playground && Tests

  • Drastic improvements by Jacob via even/odd, input simplification, and joining together types
\$\endgroup\$
7
  • \$\begingroup\$ 175 bytes tsplay.dev/WPgoKm \$\endgroup\$ Commented May 2, 2023 at 21:37
  • \$\begingroup\$ I do want to make sure I didn't mess it up - was that 175 bytes of improvement or 175 bytes total? (If it was total, it seems I couldn't do the minification right - I was only able to shave off 230 bytes by minifying your solution - the extra improvements came from dropping the unneeded conditional on Join and simplifying infer _ to any) \$\endgroup\$ Commented May 2, 2023 at 23:24
  • \$\begingroup\$ 175 total - the part after the blank line is footer, which shouldn't be counted, unless you still want to take input in decimal. But then I'm sure there's a shorter way of converting decimal to unary, I didn't attempt to golf that section. Good idea with the ${any} -- I didn't think of that. \$\endgroup\$ Commented May 2, 2023 at 23:49
  • \$\begingroup\$ Oh right! Thanks, I'll edit the solution with that input instead. \$\endgroup\$ Commented May 2, 2023 at 23:53
  • \$\begingroup\$ 148 bytes (I think you copy-pasted from the wrong link I posted earlier) tsplay.dev/Nll1XN \$\endgroup\$ Commented May 3, 2023 at 0:07
2
\$\begingroup\$

Uiua, 11 bytes

▽∶?@/@\\◿2.

Try it!

▽∶?@/@\\◿2.
          .  # duplicate
        ◿2   # modulo two
  ?@/@\\     # choose slash depending on result
▽∶           # repeat it input times
\$\endgroup\$
2
  • \$\begingroup\$ Tried all sorts of ideas only to get a tie or 1 longer :/ \$\endgroup\$
    – Bubbler
    Commented Oct 23, 2023 at 6:18
  • \$\begingroup\$ @Bubbler Wow, that's a lot of ideas! \$\endgroup\$
    – chunes
    Commented Oct 23, 2023 at 6:28
1
\$\begingroup\$

S.I.L.O.S, 55 bytes

readIO
c=i
c%2
c*45
c-92
c|
lbla
printChar c
i-1
if i a

Try it online!

Port of this answer in C.

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

Haskell, 32 bytes

f n=replicate n$"\\/"!!(mod n 2)
\$\endgroup\$
1
1
\$\begingroup\$

RETURN, 21 bytes

[$2÷%'/'\2øø4ø2␂{␋},]

Try it here.

Anonymous lambda. Usage:

5[$2÷%'/'\2øø4ø2␂{␋},]!

Explanation

[                    ]  [lambda]%
 $2÷%                   [copy input and mod 2]%
     '/'\2øø            [choose either / or \ depending on input mod 2]%
            4ø          [get input again]%
              2␂{      [copy the /\ char and the input into a new stack]%
                  ␋},   [repeat the stack by the input and output the stack]%
\$\endgroup\$
1
\$\begingroup\$

Bash, 63 bytes

q(){ seq -s0 0 $1|cut -c-$1|tr 0-9 $(($1%2))|sed 'y/10/\/\\/';}
\$\endgroup\$
2
  • \$\begingroup\$ Weird. If you know the tr command, then why used sed for the 2nd transliteration? \$\endgroup\$
    – manatwork
    Commented Aug 31, 2016 at 7:05
  • \$\begingroup\$ Move your code outside of the function and drop the q(){} part. Also, you can drop both tr and sed conversions by doing something like this: c=(\\ /);seq -s${c[$1%2]} 0 $1|tr -d [0-9]. For an even shorter way see my answer \$\endgroup\$
    – seshoumara
    Commented Aug 31, 2016 at 14:29
1
\$\begingroup\$

Rust, 210 190 Bytes

fn main(){let x:usize=std::env::args().nth(1).unwrap().parse::<usize>().unwrap();let l:&str=match x%2{0=>"\\",1=>"/",_=>"",};println!("{}",std::iter::repeat(l).take(x).collect::<String>());}

Ungolfed:

fn main() {
    let x : usize = std::env::args().nth(1)
                                    .unwrap()
                                    .parse::<usize>()
                                    .unwrap();
    let l : &str = match x % 2 {
        0 => "\\",
        1 => "/",
        _ => "",
    };
    println!("{}", std::iter::repeat(l).take(x)
                                       .collect::<String>());
}

I don't usually golf (so I bet this isn't a great score, at least for Rust), but I figured this would be good Rust practice. This compiles into an executable run as squiggly.exe x where x is the number of times to repeat the character.

\$\endgroup\$
1
  • \$\begingroup\$ Cut off 20 bytes by realizing that direct referencing (std::env::args(), std::iter::repeat(l)) is more effective than use clauses \$\endgroup\$ Commented Sep 1, 2016 at 15:36
1
\$\begingroup\$

awk, 26 bytes

NF=$1,$1=OFS=$1%2?"/":"\\"

$1 is the input and then part of the output

NF is the number of fields

OFS is the output field separator

It prints if the expression before the comma is truthy.

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

Forth, 58 54 bytes

Leaves n%2 as junk on the stack. Output is sent to stdout. 47 is /, and 92 is \. Computes y=92-45*x, where x is n%2 and emits (outputs) the character with that codepoint.

: f dup 2 mod swap 0 DO dup 92 swap 45 * - emit LOOP ;

Try it online

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

Lua (33 44 Bytes)

Never tried golfing with Lua before.

Shortest program I could come up with:

n=io.read()print(({'\\','/'})[n%2+1]:rep(n))

\$\endgroup\$
1
  • \$\begingroup\$ Your code should handle either input or parameter. \$\endgroup\$
    – manatwork
    Commented Sep 2, 2016 at 13:31
1
\$\begingroup\$

PL-SQL (Oracle), 530 characters

DECLARE
-- Enter your input here, here example is taken as 3 ---
  n number := 3 ;
  k varchar2(20);
BEGIN 
     -- Checking the input number for odd --
     if mod(n,2)=1 then      
     for j in 1..n loop 
      k := k||'/';           
      end loop; 
      DBMS_OUTPUT.PUT_line (n||' '||k); 
     end if;

     -- Checking the input number for even --
         if mod(n,2)=0 then
         for j in 1..n loop
         k := k||'\';         
          end loop;
          DBMS_OUTPUT.PUT_line (n||' '||k); 
         end if; 
END;
\$\endgroup\$
2
  • \$\begingroup\$ Language name?. \$\endgroup\$
    – acrolith
    Commented Sep 2, 2016 at 21:43
  • \$\begingroup\$ Welcome to PPCG! Please put what language this is and the length in bytes at the top of your post. Also, remove as many extraneous characters as possible, including whitespace. Posters must make a serious effort to golf (shorten) their code for [code-golf] questions. \$\endgroup\$
    – mbomb007
    Commented Sep 2, 2016 at 21:43
1
\$\begingroup\$

Acc!!, 90 bytes

N
Count i while _%60-10 {
_*10+_%60*50-2880+N
}
_/60
Count j while _-j {
Write 92-_%2*45
}

Try it online!

With comments

# Read a line of stdin, convert it to a decimal number, and store it in the accumulator
N
Count i while _%60-10 {
    _*10+_%60*50-2880+N
}
_/60
# Loop that many times
Count j while _-j {
    # Output \ if accumulator mod 2 is 0, or / if it is 1
    Write 92-_%2*45
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Acc!! is a really fun language! \$\endgroup\$ Commented Aug 13, 2020 at 3:39
1
\$\begingroup\$

MAWP, 38 bytes

%@!!2P2WA{~[67W5M;1A].}~[99W25W1MM;1A]

Made using Dion's modulus function from here.

Try it!

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

x86-16 machine code, PC DOS, 18 bytes

Binary:

00000000: a082 002c 30a8 0191 b85c 0a74 02b0 2fcd  ...,0....\.t../.
00000010: 10c3                                     ..

Listing:

A0 0082     MOV  AL, BYTE PTR[82H]  ; first char of command line into AL
2C 30       SUB  AL, '0'            ; ASCII convert input char
A8 01       TEST AL, 1              ; set ZF if even
91          XCHG AX, CX             ; CL = number of times to repeat
B8 0A5C     MOV  AX, 0A5CH          ; AL = '\', AH = 0AH (BIOS write char)
74 02       JZ   WRITE              ; if even, write with a '\'
B0 2F       MOV  AL, '/'            ; otherwise change to a '/'
        WRITE:
CD 10       INT  10H                ; write AL to console CX number of times
C3          RET                     ; return to DOS

Standalone PC DOS executable (COM) program. Input n on command line (note: this is limited to single digit values).

enter image description here

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

Pyth, 5 bytes

*@"\/

Try it online!

*@"\/
@("\/", Q) * Q  // After implicit input is read and re-structured to appear more readable.
@("\/", Q)      // Get element at index Q(input)
@("\/", Q) * Q  // Repeat Q times.
\$\endgroup\$
1
\$\begingroup\$

Arturo, 31 bytes

$->n->repeat(0=n%2)?->{\}->"/"n

or

$->n[s:[{\}"/"]repeat s\[n%2]n]

Try it

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

Scala, 56 bytes

Golfed version. Try it online!

def c(i:Int)=for(_<-1 to i){print(if(i%2<1)"\\"else"/")}

Ungolfed version. Try it online!

object M {
  implicit class IntExtensions(val i: Int) extends AnyVal {
    def times[T](f: => T): Unit = {
      for (_ <- 1 to i) {
        f
      }
    }
  }
  //def c(i:Int)=print(Iterator.fill(i)(if(i%2<1)"\\"else"/").mkString)
  //def c(i:Int)=Iterator.fill(i)(if(i%2<1)"\\"else"/").foreach(print)
  def c(i: Int) = i.times { print(if (i % 2 < 1) "\\" else "/") }
  def main(args: Array[String]): Unit = {
    for (i <- 0 until 10) {
      c(i)
      println()
    }
  }
}
\$\endgroup\$
1
\$\begingroup\$

Rust, 28 bytes

|n|[r"\","/"][n%2].repeat(n)

Attempt This Online!

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

R, 32 bytes

\(n)intToUtf8(rep(92-45*n%%2,n))

Attempt This Online!

\$\endgroup\$

Your Answer

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

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