Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 \\\\\\
share|improve this question

40 Answers 40

Javascript, 22 bytes

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

Defines an anonymous function.

If only * repeated strings in Javascript. sighs

share|improve this answer
1  
Finally you have found the right operator – Leaky Nun 2 days ago
    
@LeakyNun What are you talking about? – DanTheMan 2 days ago
    
You were using the ternary operator to choose the character, no? – Leaky Nun 2 days ago
    
@LeakyNun Initially, yes, but if you look at chat, I also posted this about a minute later. – DanTheMan 2 days ago
    
Oh, I didn't notice; my fault. – Leaky Nun 2 days ago

Python, 20 bytes

lambda n:'\/'[n%2]*n
share|improve this answer

Perl, 20 bytes

Includes +1 for -p

Run with input on STDIN:

squigly.pl <<< 6

squigly.pl

#!/usr/bin/perl -p
$_=$_%2x$_;y;01;\\/
share|improve this answer
    
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) – theLambGoat yesterday
    
@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) – Ton Hospel yesterday
    
@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) – Ton Hospel yesterday
    
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) – theLambGoat yesterday
1  
That trick with the ; added by -p is quite awsome, well done. – Dada 23 hours ago

05AB1E, 15 11 9 8 bytes

DÈ„/\sè×

-2 bytes thanks to Leaky Nun

-1 byte thanks to Emigna

Try it online!

share|improve this answer
    
ftfy – Leaky Nun yesterday
14  
It says sè× 😮 – DanTheMan yesterday
2  
"/\" can be „/\ – Emigna yesterday

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.

share|improve this answer

Retina, 21

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

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

share|improve this answer

Mathematica, 34 32 28 bytes

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

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

share|improve this answer
    
You can use ~Table~#. – Martin Ender yesterday
    
I think it was added in 10.2. – Martin Ender yesterday
    
Also, I think you can ditch the <>"" and return a list of characters. – Martin Ender yesterday
1  
@MartinEnder They must have also added ~Do~Infinity and such in 10.2+ as well... – LegionMammal978 yesterday

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 "/".

share|improve this answer
    
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...]). :) – Martin Ender yesterday
2  
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! – DanTheMan yesterday

C, 40 bytes

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

Try it on Ideone

share|improve this answer

Jelly, 5 bytes

ị⁾/\x

Try it online! or Verify all testcases.

ị⁾/\x

ị⁾/\    modular-indexing into the string "/\"
    x   repeat
share|improve this answer

Fourier, 27 bytes

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

Try it online!

share|improve this answer

Dyalog APL, 11 bytes

⊢⍴'\/'⊃⍨2|⊢

the argument

reshapes (repeats)

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

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

TryAPL online!

share|improve this answer
    
Cool! Very similar to J. – Conor O'Brien yesterday
    
@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. – Adám yesterday
    
Ah, I was wondering why the argument was there. – Conor O'Brien yesterday
1  
Finally an APL answer with all characters rendered correctly for me! – Cyoce yesterday
    
@Cyoce Yeah, I wish we could specify (and embed) fonts on SE. – Adám yesterday

Haskell, 25 bytes

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

-1 byte thanks to Damien with cycle.

share|improve this answer
    
f n=cycle"\\/"!!n<$[1..n] – Damien yesterday
    
@Damien Wow, how did I forget cycle. – xnor yesterday
    
I don't know. But I'm glad to have had the opportunity to "beat" you once :) – Damien yesterday

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
share|improve this answer

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.

share|improve this answer

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 $_ }
/
\\
///
\\\\
/////
\\\\\\
///////
\\\\\\\\
/////////
\\\\\\\\\\
share|improve this answer
2  
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 – TimmyD yesterday

><> (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!

share|improve this answer
    
Welcome to Programming Puzzles & Code Golf! – Dennis 20 hours ago
    
@Dennis Thanks! I appreciate the welcome. – Callum Kerr 19 hours ago

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);
share|improve this answer

Ruby, 15 bytes

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

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

share|improve this answer

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 input and 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 point-free syntax (though I don't know exactly how this works in Pyth).

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 seems like it 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.

Disclaimer: I'm not super familiar with Pyth and haven't used Jelly at all, so if my analyses are inaccurate, please correct me.

share|improve this answer
    
I'm not sure that readability is a plus, in code golf? Not at the cost of bytes ! – GreenAsJade yesterday
    
@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. – DLosc yesterday
    
Pro tip for making a golfing language: don't use infix – Cyoce yesterday
    

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.
share|improve this answer

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:

/
\\
///
\\\\
/////
\\\\\\
///////
\\\\\\\\
/////////
share|improve this answer
    
Hi Kevin. Why not a Lambda Expression? – Vale yesterday
    
@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. – Kevin Cruijssen yesterday
1  
@Vale (he's odd like that :P) – Basically Alan Turing yesterday
1  
i think if you change x=-1;++x<i to x=0;x++<i you can reduce by one byte – user902383 yesterday
1  
Also you can replace "\\" : "/" with 92:'/' ;) – Basically Alan Turing yesterday

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.

share|improve this answer
1  
Save one byte by using indexing: n=scan();cat(rep(c('\\','/')[n%%2+1],n),sep='') – bouncyball yesterday

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('/',@))
share|improve this answer

Perl 6, 16 bytes

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

Usage:

for 1..6 {
  say $_, {<\ />[$_%2]x$_}( $_ )
}
1/
2\\
3///
4\\\\
5/////
6\\\\\\
share|improve this answer

Julia, 20 bytes

!x="$("/\\"[x%2])"^x
share|improve this answer

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.

share|improve this answer

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);
}
share|improve this answer

PHP, 63 bytes

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

Run with php -f squiggle.php <number>

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

share|improve this answer

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.

share|improve this answer
    
@LeakyNun I was used with the Bash and pure Bash terms until I started here. I updated my answer. – seshoumara yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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