29
\$\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\$

43 Answers 43

17
\$\begingroup\$

Javascript, 22 bytes

n=>"\\/"[n%2].repeat(n)

Defines an anonymous function.

If only * repeated strings in Javascript. sighs

\$\endgroup\$
  • 1
    \$\begingroup\$ Finally you have found the right operator \$\endgroup\$ – Leaky Nun Aug 30 '16 at 23:21
  • \$\begingroup\$ @LeakyNun What are you talking about? \$\endgroup\$ – DanTheMan Aug 30 '16 at 23:22
  • \$\begingroup\$ You were using the ternary operator to choose the character, no? \$\endgroup\$ – Leaky Nun Aug 30 '16 at 23:22
  • \$\begingroup\$ @LeakyNun Initially, yes, but if you look at chat, I also posted this about a minute later. \$\endgroup\$ – DanTheMan Aug 30 '16 at 23:23
  • 2
    \$\begingroup\$ @Jordumus You could either assign the function to a variable: f=n=>..., you could directly call it: (n=>...)(5). (Or if you are using the Node.js REPL, then you could use this._, which stands for the last thing entered) \$\endgroup\$ – DanTheMan Sep 1 '16 at 14:22
16
\$\begingroup\$

Python, 20 bytes

lambda n:'\/'[n%2]*n
\$\endgroup\$
  • \$\begingroup\$ Great, simple and elegant ^_^ \$\endgroup\$ – ABcDexter Sep 2 '16 at 13:19
10
\$\begingroup\$

05AB1E/2sable, 15 11 9 8 bytes

DÈ„/\sè×

-2 bytes thanks to Leaky Nun

-1 byte thanks to Emigna

Try it online! in 05AB1E
or in 2sable

\$\endgroup\$
  • \$\begingroup\$ ftfy \$\endgroup\$ – Leaky Nun Aug 31 '16 at 0:21
  • 18
    \$\begingroup\$ It says sè× 😮 \$\endgroup\$ – DanTheMan Aug 31 '16 at 4:56
  • 2
    \$\begingroup\$ "/\" can be „/\ \$\endgroup\$ – Emigna Aug 31 '16 at 7:06
9
\$\begingroup\$

Perl, 20 bytes

Includes +1 for -p

Run with input on STDIN:

squigly.pl <<< 6

squigly.pl

#!/usr/bin/perl -p
$_=$_%2x$_;y;01;\\/
\$\endgroup\$
  • \$\begingroup\$ It might just be my version of Perl (I'm still on 5.10) but this throws an error unless I add an extra ; to the end. I think it's because it you're using the semi-colon as a separator for y and you need one more to finish the statement (and would need two if you had more lines of code after this) \$\endgroup\$ – theLambGoat Aug 31 '16 at 12:51
  • \$\begingroup\$ @theLambGoat Are you sure you are using the -p option ? I use ; in the transliterate exactly because -p has an implicit ; at the end of the code so I can save 1 more byte. This has worked since at least perl 5.6 (probably as long as the -p option existed in fact) \$\endgroup\$ – Ton Hospel Aug 31 '16 at 13:29
  • \$\begingroup\$ @theLambGoat Mm, I found an old redhat with perl 5.10 where indeed it does not work. Either this is a redhat patch or it indeed did not work for around 5.10 (I'm sure it worked in older perls and it also works in newer perls) \$\endgroup\$ – Ton Hospel Aug 31 '16 at 13:43
  • \$\begingroup\$ I'm running on SUSE Enterprise Server 11 so it's not just a redhat thing. But I think as long as it works in some versions, it should still be a valid answer. (I also just checked in 5.08, the only other version I have access to at the moment and it doesn't work there either) \$\endgroup\$ – theLambGoat Aug 31 '16 at 14:50
  • 1
    \$\begingroup\$ That trick with the ; added by -p is quite awsome, well done. \$\endgroup\$ – Dada Sep 1 '16 at 0:21
7
\$\begingroup\$

Retina, 21

.+
$*/
T`/`\\`^(..)+$

Try it online (First line added to allow multiple testcases to be run).

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

C#, 42 bytes

string f(int n)=>new string("\\/"[n%2],n);

Selects the correct character, then creates a new string consisting of that character repeated n times.

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

PHP, 38 bytes

for(;$i++<$a=$argv[1];)echo'\/'[$a%2];

(variant 38 bytes)

while($i++<$a=$argv[1])echo'\/'[$a%2];

(variant 38 bytes)

<?=str_pad('',$a=$argv[1],'\/'[$a%2]);

(variant 40 bytes)

<?=str_repeat('\/'[($a=$argv[1])%2],$a);
\$\endgroup\$
6
\$\begingroup\$

C, 40 bytes

i;f(n){for(i=n;i--;)putchar(n%2?47:92);}

Try it on Ideone

\$\endgroup\$
  • 2
    \$\begingroup\$ putchar(92-n%2*45) is the same length. \$\endgroup\$ – mbomb007 Sep 2 '16 at 13:46
6
\$\begingroup\$

J, 10 bytes

#'\/'{~2|]

This is a six-train verb, consisting of:

# ('\/' {~ 2 | ])

This is a hook between # and ('\/' {~ 2 | ]); a hook (f g) y expands to y f (g y), so this expands to y # (... y), which, for single-characters, yields a list of y characters.

The second part is a 5-train, consisting of:

'\/' {~ 2 | ]

This evaluates to two forks:

'\/' {~ (2 | ])

The inner fork, 2 | ], is modulus two. The outer fork, therefore, is:

'\/' {~ mod2

Which takes ({~) the mod2 index (mod2) from the string /.

Then, using the hook from above:

y # (apt char)

This yields what we want, and we are done.

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

Haskell, 25 bytes

f n=cycle"\\/"!!n<$[1..n]

-1 byte thanks to Damien with cycle.

\$\endgroup\$
  • 1
    \$\begingroup\$ f n=cycle"\\/"!!n<$[1..n] \$\endgroup\$ – Damien Aug 31 '16 at 6:20
  • \$\begingroup\$ @Damien Wow, how did I forget cycle. \$\endgroup\$ – xnor Aug 31 '16 at 6:22
  • \$\begingroup\$ I don't know. But I'm glad to have had the opportunity to "beat" you once :) \$\endgroup\$ – Damien Aug 31 '16 at 6:31
6
\$\begingroup\$

Mathematica, 34 32 28 bytes

If[OddQ@#,"/","\\"]~Table~#&

Anonymous function. Takes an integer as input and returns a list of characters as output.

\$\endgroup\$
  • \$\begingroup\$ You can use ~Table~#. \$\endgroup\$ – Martin Ender Aug 31 '16 at 6:37
  • \$\begingroup\$ I think it was added in 10.2. \$\endgroup\$ – Martin Ender Aug 31 '16 at 10:09
  • \$\begingroup\$ Also, I think you can ditch the <>"" and return a list of characters. \$\endgroup\$ – Martin Ender Aug 31 '16 at 10:11
  • 1
    \$\begingroup\$ @MartinEnder They must have also added ~Do~Infinity and such in 10.2+ as well... \$\endgroup\$ – LegionMammal978 Aug 31 '16 at 11:35
5
\$\begingroup\$

Jelly, 5 bytes

ị⁾/\x

Try it online! or Verify all testcases.

ị⁾/\x

ị⁾/\    modular-indexing into the string "/\"
    x   repeat
\$\endgroup\$
5
\$\begingroup\$

Powershell, 30 27 bytes

Update:

param($n)('\','/')[$n%2]*$n

Switching to param, thanks to timmyd.


"$("\/"[$args[0]%2])"*$args[0]

or slightly more readable

("\","/")[$args[0]%2]*$args[0]

Test:

> 1..10 | % { ./run.ps1 $_ }
/
\\
///
\\\\
/////
\\\\\\
///////
\\\\\\\\
/////////
\\\\\\\\\\
\$\endgroup\$
  • 3
    \$\begingroup\$ Welcome to PPCG! Nice to see another PowerShell user around here. You can shave a few bytes by taking input as param($n) instead of $args, like follows for 27 bytes -- param($n)('\','/')[$n%2]*$n \$\endgroup\$ – AdmBorkBork Aug 31 '16 at 12:29
5
\$\begingroup\$

Mathematica, 29 bytes

"\\"["/"][[#~Mod~2]]~Table~#&

Cruelly exploits the fact that [[1]] returns the first argument of a function while [[0]] returns the function (head) itself, applied to the strangely valid function named "\\" which is being "evaluated" at "/".

\$\endgroup\$
  • \$\begingroup\$ It's slightly less weird when you consider that something of the form a[b] is just a generic expression with head a (index 0) and element b (index 1), and functions are just special kinds of expression (actually, it would be more correct to say that functions aren't expressions at all, but are simply rules for transforming expressions which usually have form f[x...]). :) \$\endgroup\$ – Martin Ender Aug 31 '16 at 10:16
  • 2
    \$\begingroup\$ I've seen many languages abused on this site, but I think this is the first abuse of Mathematica that I've seen. Good job! \$\endgroup\$ – DanTheMan Aug 31 '16 at 13:43
4
\$\begingroup\$

Ruby, 15 bytes

->n{'\/'[n%2]*n}

See it on eval.in: https://eval.in/632030

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

Fourier, 27 bytes

92~SI~N%2{1}{47~S}N(Sai^~i)

Try it online!

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

Brachylog, 15 bytes

:2%:"\/"rm:?jbw

Try it online!

Explanation

:2%                Input mod 2…
   :"\/"rm         …is the index of the element in string "\/",…
          :?j      …element that we juxtapose Input times to itself…
             bw    …and print to STDOUT after removing one slash/backslash
\$\endgroup\$
4
\$\begingroup\$

CJam, 9 bytes

ri_"\/"=*

Try it online!

Explanation

ri     e# Read input and convert to integer N.
_      e# Duplicate N.
"\/"=  e# Use N as cyclic index into "\/", giving '\ for even and '/ for odd inputs.
*      e# Repeat N times.
\$\endgroup\$
4
\$\begingroup\$

><> (Fish), 30 Bytes

:2%?'/'o1-:?!;30.
30.  >'\'50p

First time using this language, but I think I at least saved a little room by conditionally using the / as either part of the output or a mirror to redirect flow. Probably still horribly inefficient though, I feel like it could probably be cut down a little more at the very least.

Input is the initial stack, output is stdout

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Welcome to Programming Puzzles & Code Golf! \$\endgroup\$ – Dennis Sep 1 '16 at 3:22
  • \$\begingroup\$ @Dennis Thanks! I appreciate the welcome. \$\endgroup\$ – Callum Kerr Sep 1 '16 at 4:28
4
\$\begingroup\$

Dyalog APL, 11 bytes

Requires ⎕IO←0 which is default on many systems.

⊢⍴'\/'⊃⍨2|⊢

the argument

reshapes (repeats)

'\/'⊃⍨ the string "/" selected by

2|⊢ the division remainder when the argument is divided by two

TryAPL online!

\$\endgroup\$
  • \$\begingroup\$ Cool! Very similar to J. \$\endgroup\$ – Conor O'Brien Aug 31 '16 at 0:04
  • \$\begingroup\$ @ConorO'Brien Yes, the only difference is that 2-trains in J are hooks, while they are atops in Dyalog, so an explicit left tine is needed. \$\endgroup\$ – Adám Aug 31 '16 at 0:13
  • \$\begingroup\$ Ah, I was wondering why the argument was there. \$\endgroup\$ – Conor O'Brien Aug 31 '16 at 0:31
  • 1
    \$\begingroup\$ Finally an APL answer with all characters rendered correctly for me! \$\endgroup\$ – Cyoce Aug 31 '16 at 15:21
  • \$\begingroup\$ @Cyoce Yeah, I wish we could specify (and embed) fonts on SE. \$\endgroup\$ – Adám Aug 31 '16 at 15:44
3
\$\begingroup\$

Java 7, 68 65 bytes

void c(int i){for(int x=0;x++<i;)System.out.print(i%2<1?92:'/');}

3 bytes saved thanks to @user902383 and @SeanBean.

Just like with this answer, the shortest code-golf seems to loop and print. Both recursive and
void c(int i){System.out.print(new String(new char[i]).replace("\0",i%2<1?"\\":"/"));}
seems to be longer.

Ungolfed & test code:

Try it here.

class M{
  static void c(int i){
    for(int x = 0; x++ < i;){
      System.out.print(i % 2 < 1
                        ? 92
                        : '/');
    }
  }

  public static void main(String[] a){
    for(int i = 0; i < 10; i++){
      c(i);
      System.out.println();
    }
  }
}

Output:

/
\\
///
\\\\
/////
\\\\\\
///////
\\\\\\\\
/////////
\$\endgroup\$
  • \$\begingroup\$ Hi Kevin. Why not a Lambda Expression? \$\endgroup\$ – Vale Aug 31 '16 at 8:45
  • \$\begingroup\$ @Vale Hi Vale. Because I'm an old-fashion Java 7 programmer. :) If you have a Java 8 or 9 answer that is slightly different than my answer, feel free to post it. \$\endgroup\$ – Kevin Cruijssen Aug 31 '16 at 8:58
  • 2
    \$\begingroup\$ @Vale (he's odd like that :P) \$\endgroup\$ – Shaun Wild Aug 31 '16 at 9:24
  • 1
    \$\begingroup\$ i think if you change x=-1;++x<i to x=0;x++<i you can reduce by one byte \$\endgroup\$ – user902383 Aug 31 '16 at 10:00
  • 1
    \$\begingroup\$ Also you can replace "\\" : "/" with 92:'/' ;) \$\endgroup\$ – Shaun Wild Aug 31 '16 at 10:24
3
\$\begingroup\$

R, 47 46 bytes

n=scan();cat(rep(c("\\","/")[n%%2+1],n),sep="")

In R, you have to escape backslashes. the argument sep also has to be fully specified since it comes after .... Thus annoyingly few opportunities to save chars :(

Thanks to bouncyball for golfing away a byte.

\$\endgroup\$
  • 1
    \$\begingroup\$ Save one byte by using indexing: n=scan();cat(rep(c('\\','/')[n%%2+1],n),sep='') \$\endgroup\$ – bouncyball Aug 31 '16 at 20:54
3
\$\begingroup\$

T-SQL 50 bytes

Of course no STDIN here, so let's assume a hardcoded INT variable like this: DECLARE @ INT then the solution is:

PRINT IIF(@%2=0,REPLICATE('\',@),REPLICATE('/',@))
\$\endgroup\$
3
\$\begingroup\$

Pip, 8 bytes

"\/"@aXa

Straightforward. Uses modular indexing to select the character and string repetition to multiply it. Try it online!


This question presents an interesting comparison between Pip, Pyth, and Jelly, the latter two each having scored 5 bytes. All three languages have implicit output, with single-char operators for modular indexing and string repetition, and no requirement to escape backslashes in strings. There are two key differences, though:

  1. Under certain circumstances, Pyth and Jelly need only one delimiter to define a string;
  2. Pyth and Jelly have syntax such that the input doesn't need to be explicitly represented in the code (though for very different reasons, as Maltysen explained to me).

Neither one of these features is likely to show up in Pip1 (I don't like the aesthetics of unbalanced delimiters, and point-free syntax or implicit operands seem like they would be too alien to my infix expression parser), but I'm okay with playing third fiddle. Even though "readability" is extremely relative when golfing, I'd argue that those three extra bytes make the Pip program a lot easier to understand at a glance--and in my book, that's a worthwhile tradeoff.

1 Although, single-character strings in Pip use a single ' delimiter, inspired by CJam and by quoting in Lisp.

\$\endgroup\$
  • \$\begingroup\$ I'm not sure that readability is a plus, in code golf? Not at the cost of bytes ! \$\endgroup\$ – GreenAsJade Aug 31 '16 at 11:02
  • \$\begingroup\$ @GreenAsJade I expect a lot of people feel the same. I would just make one distinction: code golf != golflang design. Now you may well argue that the same principle (shorter is always better) applies to language design too. I'm just saying that for me, usability and even aesthetics are considerations. \$\endgroup\$ – DLosc Aug 31 '16 at 15:59
  • \$\begingroup\$ Pro tip for making a golfing language: don't use infix \$\endgroup\$ – Cyoce Aug 31 '16 at 22:50
  • \$\begingroup\$ @Cyoce chat.stackexchange.com/transcript/message/31933195 \$\endgroup\$ – DLosc Sep 1 '16 at 0:52
  • \$\begingroup\$ pyth doesn't have implicit point free syntax. it works pretty much the same way it does in python, making it readable yet short. your comment about the unbalanced delimiters on the other hand is pretty true \$\endgroup\$ – Maltysen Sep 2 '16 at 4:26
2
\$\begingroup\$

Pyth, 5 bytes

*@"\/

Test suite.

Modular-indexing into the string \/ and then repeat.

\$\endgroup\$
  • 13
    \$\begingroup\$ You're FGITW'ing your own challenge? \$\endgroup\$ – xnor Aug 30 '16 at 23:44
  • \$\begingroup\$ @xnor it isn't exactly my challenge. \$\endgroup\$ – Leaky Nun Aug 30 '16 at 23:49
2
\$\begingroup\$

Perl 6, 16 bytes

{<\ />[$_%2]x$_}

Usage:

for 1..6 {
  say $_, {<\ />[$_%2]x$_}( $_ )
}
1/
2\\
3///
4\\\\
5/////
6\\\\\\
\$\endgroup\$
2
\$\begingroup\$

Julia, 20 bytes

!x="$("/\\"[x%2])"^x
\$\endgroup\$
2
\$\begingroup\$

SpecBAS - 28 bytes

1 INPUT n: ?"\/"(ODD(n)+1)*n

ODD returns 1 if number is odd, then uses that as an index to print the correct character n number of times. Have to add 1 as SpecBAS strings start at character 1.

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

Java 8, 56 bytes

(i,j)->{for(j=i;j-->0;)System.out.print(i%2<1?92:'/');};

I'd like to thank @Kevin Cruijssen in advanced for golfing my answer further.

Ungolfed Test Program

public static void main(String[] args) {
    BiConsumer<Integer, Integer> consumer = (i, j) -> {
        for (j = i; j-- > 0;) {
            System.out.print(i % 2 < 1 ? 92 : '/');
        }
    };

    consumer.accept(5, 0);
    consumer.accept(1, 0);
    consumer.accept(8, 0);
}
\$\endgroup\$
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\$

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.