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

First line is made with ceil(n/2) elements where each element is: <space><odd-number><space>

Second line is made with ceil(n/2) elements, but each element is / \ only.

You may assume n >= 0 and n <= 10.

Examples

Input: 3

 1  3
/ \/ \

Input: 10

 1  3  5  7  9
/ \/ \/ \/ \/ \

Example in Python 3, 103 bytes:

lambda a:print("".join([" "+str(i)+" "for i in range(1,a+1,2)]+["\n"]+["/ \\"for i in range(1,a+1,2)]))

Shortest code in bytes wins :)

share|improve this question
3  
Can you assume all input will be less then 11? – BlueEyedBeast yesterday
    
Yup, all input will be less than 11 ! – Sygmei yesterday
8  
Welcome to the site! Our default for code-golf is to count in bytes, not characters. If you want to override that, though, it's your choice. Also, I would recommend the Sandbox the next time :) – ErikGolferエリックゴルファー yesterday
    
I meant bytes you're right ! Is there a good bytes counter around ? – Sygmei yesterday
1  
How specifically do we have to handle whitespace? You say each element is <space><odd-number><space>, but the test cases don't have a space after the last odd number. Is it optional? Also, is the output for n=0 two empty lines? – xnor yesterday

29 Answers 29

up vote 10 down vote accepted

05AB1E, 19 15 14 12 bytes

05AB1E uses CP-1252 encoding.
Saved 4 bytes thanks to Adnan.
Saved 2 bytes thanks to carusocomputing

ÅÉðìDg…/ \×»

Try it online!

Explanation

ÅÉ               # list of uneven number up to input
  ðì             # prepend a space to each
    Dg           # get length of list
      …/ \       # push the string "/ \"
          ×      # repeat the string length-list times
           »     # join rows by spaces and columns by newlines
share|improve this answer
    
HOW LONG HAS Ï EXISTED?! That seems suuuper useful. – carusocomputing yesterday
2  
@carusocomputing A long time :p – Adnan yesterday
2  
LDÉÏ is the same as ÅÉ and „ ýðì can be replaced by ðì)» :). – Adnan yesterday
2  
You can remove the ), can't you? – carusocomputing yesterday
3  
ÅÉðìDg…/ \×» uses Dg instead of ¹;î for another byte save as well. – carusocomputing yesterday

Pyke, 16 bytes

S2%idm+dJil*"/ \

Try it here!

17 bytes and more awesome

S2%i`~Bd.:il*"/ \

Try it here!

This uses IMHO an AWESOME algorithm for making sure the first line is correctly aligned.

S                 - range(1, input+1)
 2%               -  ^[::2]
   i              -   i = ^
    `             -    str(^)
     ~Bd.:        -     ^.translate("><+-.,[]", " ") <-- awesome bit here
          il      -  len(i)
            *"/ \ - ^ * "/ \"

This replaces all the characters in the stringified list with spaces. ~B contains all the characters in the Brain**** language and this is the first time I've used this variable.

The program `~Bd.: does this:

`~Bd.: - input = [1, 3, 5, 7]
`      - str(input)  # stack now ["[1, 3, 5, 7]"]
 ~B    - "><+-.,[]"  # stack now ["[1, 3, 5, 7]", "><+-.,[]"]
   d   - " "         # stack now ["[1, 3, 5, 7]", "><+-.,[]", " "]
    .: - translate() # stack now [" 1  3  5  7 "]
share|improve this answer
    
...this is...just awesome? You know you just beat 05AB1E and everyone, right? – ErikGolferエリックゴルファー yesterday
    
I have tried Jelly; it will surely be much longer. – ErikGolferエリックゴルファー yesterday
    
"I used the BF charset to evenly space an array of numbers" The things you never thought you'd say... – ETHproductions yesterday
    
This is really clever :) Well done – Sygmei yesterday
    
@ErikGolferエリックゴルファー Not beating 05AB1E any more. – boboquack yesterday

Python 2, 63 bytes

lambda n:' '.join(n%2*`n`for n in range(n+1))+'\n'+-~n/2*'/ \\'

Little trick for the first line: it don't print the even numbers, but take them as an empty string, which leads to starting empty space (0 would be there), and double spaces between the numbers without any modification on the range, the downside is a leading space in the even numbered n

share|improve this answer

Python 2 3, 67 65 63 60 Bytes

Nothing too crazy here, I think the first section can probably be done shorter but I'm not quite sure how. I use the fact that in this case -~n/2 will work for ceil.

lambda n:-~n//2*' %d '%(*range(1,n+1,2),)+'\n'+-~n//2*'/ \\'

Below are alternative 61 and 65 byte solutions in Python 2:

lambda n:-~n/2*' %d '%tuple(range(1,n+1,2))+'\n'+-~n/2*'/ \\'
lambda n:' '+'  '.join(map(str,range(1,n+1,2)))+'\n'+-~n/2*'/ \\'

Thanks to Rod for saving 2 bytes and Artyer for saving another byte by switching version :)

share|improve this answer
    
If you move to Python 3, you can replace %(tuple(...)) with %[*...], but you would have to do -~n//2 – Artyer yesterday
    
@Artyer Tried this, but it throws a bunch of errors. I think I would need to cast range to a list because 3's range is like Python 2's xrange. – Kade yesterday
    
you can also drop the parentheses that are surrounding the tuple() – Rod yesterday
    
You can do (*<iterable>,) to cast to tuple in Python 3. This saves 1 byte though after you turn n/2 into n//2 for Python 3. – Artyer yesterday
    
@Rod and Artyer thanks a bunch! :) – Kade yesterday

JavaScript (ES6), 55 bytes

f=n=>n%2?f(n-1).replace(`
`,` ${n} 
/ \\`):n?f(n-1):`
`
<input type=number min=1 max=10 oninput=o.textContent=f(this.value)><pre id=o>

Note the space on the end of the second line.

share|improve this answer
    
Dangit, I thought .replace might be better but I didn't bother to check... – ETHproductions yesterday
    
The question says "you may assume..." – Solomon Ucko yesterday
1  
@SolomonUcko The HTML is not part of the answer, it merely serves to demonstrate its operation. As such, it might as well limit the value to between 1 and 10, since the result wouldn't be valid otherwise. – Neil yesterday
    
I see. You would have to determine the correct spacing otherwise – Solomon Ucko yesterday

Mathematica, 65 bytes

" "<>Range[1,#,2]~StringRiffle~"  "<>"
"<>"/ \\"~Table~⌈#/2⌉&

Anonymous function. Takes a number as input and returns a string as output. The Unicode characters, respectively, are U+2308 LEFT CEILING for \[LeftCeiling] and U+2309 RIGHT CEILING for \[RightCeiling].

share|improve this answer

Vim, 73 59 bytes

This is a really high byte count IMO for what seems like a simple problem. I feel like I'm missing something obvious.

caw="/2*2
caw1357911/"
DYp:s/./\/ \\/g
k:s/./ \0 /g

Try it online!

Unprintables:

^Acaw^R=^R"/2*2
^[^Acaw1357911^[/^R"
DYp:s/./\/ \\/g
k:s/./ \0 /g

I can write more about the strategy later, I really want to try and lower this byte count if possible

share|improve this answer
    
Nice, I always upvote vim! However, unprintable characters also count as bytes, so this solution really is 73 bytes. Sorry about that! – DrMcMoylex yesterday
    
I do have some tips however. 1) If you use a different seperator on your substitute command, you won't need to escape the forward slash, so you can do :s;.;/ \\;g. 2) on your second substitute command, you can leave the search empty and it will use your last search (which just so happens to be the same). Also, & is equivalent to \0 and one byte shorter. So you get :s// & /g – DrMcMoylex yesterday

WinDbg, 100 bytes

.echo;.for(r$t1=1;@$t1<=2*@$t0+@$t0%2;r$t1=@$t1+2){j@$t1<=@$t0 .printf"\b %d \n",@$t1;.printf"/ \\"}

Input is done by setting a value in the pseudo-register $t0.

Looks like it's shortest here just to print the string as it's being built rather than try to build it first and display the whole thing. I'd have a shorter solution if WinDbg would let me write to address 0.

How it works:

.echo;                                            * Print a new line that'll be deleted
.for(r$t1=1; @$t1 <= 2*@$t0+@$t0%2; r$t1=@$t1+2)  * Enumerate 1 to 4*ceil($t0/2), count by 2
{
    j@$t1<=@$t0                                   * If $t1 <= $t0...
        .printf"\b %d \n",@$t1;                   * ...Print $t1 (and newline for last n)
        .printf"/ \\"                             * ...Else print the / \'s
}

Output for each value of n:

0:000> .for(r$t0=0;b>@$t0;r$t0=@$t0+1){.printf"\n\nn=%d\n",@$t0; .echo;.for(r$t1=1;@$t1<=2*@$t0+@$t0%2;r$t1=@$t1+2){j@$t1<=@$t0 .printf"\b %d \n",@$t1;.printf"/ \\"}}


n=0



n=1
 1 
/ \

n=2
 1 
/ \

n=3
 1  3 
/ \/ \

n=4
 1  3 
/ \/ \

n=5
 1  3  5 
/ \/ \/ \

n=6
 1  3  5 
/ \/ \/ \

n=7
 1  3  5  7 
/ \/ \/ \/ \

n=8
 1  3  5  7 
/ \/ \/ \/ \

n=9
 1  3  5  7  9 
/ \/ \/ \/ \/ \

n=10
 1  3  5  7  9 
/ \/ \/ \/ \/ \
share|improve this answer

Python 2, 53 bytes

lambda n:" 1  3  5  7  9"[:-~n/2*3]+'\n'+-~n/2*"/ \\"

Takes advantage of the restriction n <= 10 to generate the top line by chopping off a piece from a hardcoded string.

The outputs for 1 to 10 are

 1 
/ \
 1 
/ \
 1  3 
/ \/ \
 1  3 
/ \/ \
 1  3  5 
/ \/ \/ \
 1  3  5 
/ \/ \/ \
 1  3  5  7 
/ \/ \/ \/ \
 1  3  5  7 
/ \/ \/ \/ \
 1  3  5  7  9
/ \/ \/ \/ \/ \
 1  3  5  7  9
/ \/ \/ \/ \/ \

The output for 0 is two empty lines.

share|improve this answer

C#6, 95 bytes

n=>{var o="";int i=1;for(;i<=n;i+=2)o+=$" {i} ";o+='\n';for(i=1;i<=n;i+=2)o+="/ \\";return o;};

Full lambda:

Func<int, string> a = n=>
{
    var o="";int i=1;
    for(;i<=n;i+=2)
        o+=$" {i} ";
    o+='\n';
    for(i=1;i<=n;i+=2)
        o+="/ \\";
    return o;
};
share|improve this answer

CJam, 26 23 bytes

Sri,:)2%_S2**N@,"/ \\"*

Test it!

-3 thanks to 8478 (Martin Ender)

share|improve this answer
    
You can save 3 bytes by avoiding some of the stack manipulation: Sri,:)2%_S2**N@,"/ \\"* – Martin Ender yesterday
    
@MartinEnder Oh, so that's why I couldn't remove that +. And I swear, I really used ed! ...shorter than Pyth. – ErikGolferエリックゴルファー yesterday

><> (Fish) 52 63 62 bytes

<v!?:-1:!?-1%2:
 >~la}}" "72.
v!?-2lno<o"  "
o
>:?!;"\ /"ooo1-

Try it online!

To use simply place n on the stack and away you go!

Much of this is taken from @Teal-Pelican's answer :).

Edit: The output is actually not aligned correctly in either ><> submission! Fixing...

Edit2: I had to sacrifice some bytes, but the output is actually correct now.

Edit3: No more fun with \ / mirrors and I save 1 byte.

Output:

 1  3  5  7  9
/ \/ \/ \/ \/ \
share|improve this answer
    
Thanks for spotting the error in the printing, I'm editing my answer now (fairly trivial for mine) it's interesting seeing the base answer the same but a lot of byte saves. – Teal pelican yesterday
    
No problem, I was happy to see a ><> submission! It's gonna be interesting to see which one ends up being smaller now as these changes hurt mine pretty bad haha. – redstarcoder yesterday
    
Looks like I'm juuuust 5 bytes smaller :p. – redstarcoder yesterday
    
I'm going to have another look at mine now to see if I can squeeze a few mote bytes out aha. – Teal pelican yesterday
1  
I got home and had an idea for a new way to go about it. My new answer is 55 bytes! :D - Thanks for making me work on this, it's been fun. – Teal pelican 18 hours ago

Java, 118 115 Bytes

Edit: Saved 3 Bytes thanks to @peech

Golfed:

String M(int n){String o=" ";int i=0;for(;i<n;i++)if(i%2>0)o+=i+"  ";o+="\n";for(i=0;i<n/2;i++)o+="/ \\";return o;}

Ungolfed:

public String M(int n) {
    String o = " ";
    int i=0;
    for (; i < n;i++)
        if(i % 2 > 0)
            o += i + "  ";

    o += "\n";

    for (i = 0; i < n/2; i++)
        o += "/ \\";

    return o;       
}

Testing:

    OddMountains om = new OddMountains();
    System.out.println(om.M(1));
    System.out.println();
    System.out.println(om.M(3));
    System.out.println();
    System.out.println(om.M(5));
    System.out.println();
    System.out.println(om.M(7));
    System.out.println();
    System.out.println(om.M(10));

 1  
/ \

 1  3  
/ \/ \

 1  3  5  
/ \/ \/ \

 1  3  5  7  9  
/ \/ \/ \/ \/ \
share|improve this answer
    
Ahhhh, you've beat me to it :) i also wanted to post a Java answer. anyhow, here are some suggestions to golf it a bit more: you dont need to initialize i in your first for loop, it could look like this for(; i < n; i++). You can golf it even further with this change: o += i + " "; changes to o += i++ + " "; and for loop becomes for(; i < n; ). That is if you want to keep if statement. You could change your increment of i to i += 2 and delete the whole if statement, but in that case my second proposition doesnt apply :) (ps: i havent tested this :) ) – peech yesterday
    
@peech If it's any consolation, it's normally a race for me to get the first C# answer in. If that's gone, I fumble my way through a Java answer :) Thanks for the tips. I've removed the i initialisation from the for loop, but the other things got it stuck in a loop. I might need to play around with it a little more :) – Pete Arden 22 hours ago
    
Huh, I'm so glad that in my previous comment I said "i havent tested this" ... of course it doesnt work with o += i++ + " "; :). Btw, you have a tiny bug in your code :) since Java uses floor() on integer division (4 / 3 = 1), you should do it like this: int i = 1; n += 1; for (; i < n; i += 2) { ... jada jada ... }. if you increment i by i += 2, you don't need that if statement checking for parity. It also saves another 3 bytes :) try it here: ideone.com/ekaUUH – peech 2 hours ago

C, 100 79 77 bytes

#define P(s)for(i=0;i++<n;printf(s,i++));puts("");
i;f(n){P(" %d ")P("/ \\")}
share|improve this answer

R, 70 69 68 58 bytes

cat(paste("",z<-seq(,scan(),2)),"\n");for(i in z)cat("/ \\")

3:
#>  1  3 
#> / \/ \

10:
#>  1  3  5  7  9 
#> / \/ \/ \/ \/ \
share|improve this answer

Game Maker Language (GM 8.0), 97 bytes

m=ceil(argument0/2)e=""for(i=1;i<2*m;i+=2)e+=" "+string(i)+" "return e+"#"+string_repeat("/ \",m)

Given that the input is at most 10, chr(48+i) will work in place of string(i), although the number of bytes is the same.

Readable:

m = ceil(argument0/2)
e = ""
for (i = 1; i < 2*m; i += 2 )
  e += " " + string(i) + " "
return e + "#" + string_repeat("/ \", m)
share|improve this answer

Pyth, 24 22 bytes

K-SQyMS5+dj*2dK*lK"/ \

Thanks to 42545 (ETHproductions) for -1 byte

Online interpreter

11 test cases

share|improve this answer
    
Save a quote with *lK"/ \\ – ETHproductions yesterday
    
@ETHproductions You can then use \ instead of \\ :) – ErikGolferエリックゴルファー yesterday

Bash, 64, 59, 57, 51, 49, 48, 45 bytes

EDIT:

  • minus 3 bytes (use $1 instead of STDIN)
  • one more byte off by replacing -s "" with -s\
  • minus 2 bytes by replacing printf with seq -f (Thanks @Adam!)
  • refactored to script instead of function (to beat the ><>)
  • removed superfluous spaces
  • optimized the sed expression a bit

Golfed

Chunk (45 byte):

seq -f" %g " -s\  1 2 $1|sed 'p;s| . |/ \\|g'

Function (original version) (57 bytes):

M() { printf " %s %.0s" `seq 1 $1`|sed 'p;s| . |/ \\|g';}

Test

--- mountains.sh ----
#!/bin/bash
seq -f" %g " -s\  1 2 $1|sed 'p;s| . |/ \\|g'

>./mountains.sh 10
 1  3  5  7  9 
/ \/ \/ \/ \/ \

>M 10
 1  3  5  7  9 
/ \/ \/ \/ \/ \
share|improve this answer
2  
The sed is brilliant. By not using a function nor printf, you save 10 bytes : seq -f" %g " -s "" 1 2 $1|sed 'p;s| . |/ \\|g' – Adam yesterday
    
That's a nice advice ! Thank you ! I still use cat to read the input from STDIN, as IMO it is not really fair to use a pre-defined variable to pass the data in. – zeppelin yesterday
1  
$1 is just the first parameter transmitted to the program. I don't think it's cheating see meta.codegolf.stackexchange.com/questions/2447/… – Adam 23 hours ago
    
Yep, you are correct. Thanks again ! – zeppelin 21 hours ago

Befunge 93, 64 bytes

Try it Online!

 &61p1   v+2,,,"/ \"
_v#!`" ":<+2.," ":
 <^p00p10"|<"
@ >91+,$1v
share|improve this answer

><> (FISH), 69 60 68 55 bytes

5|v&+%1:,2
1->:?!v:
8~v!?l<on$o:*4
a&/o
1->:?!;"\ /"ooo

Paste it into this online interpreter!

The number 5 on the first line is your input value (hard coded as 5, replaced by 0-a or i for user input).

Edit 1: Moved new line placement into the first line space (was empty) to save 9 bytes overall on space from a new line.

Edit 2: As noted by user7150406 the output was wrong (no spaces printing) this has been fixed with a loss of 8 bytes.

Edit 3: completely changed the logic, there is no point checking if the number is odd - rather put all numbers on the stack and remove every second one. Byte saved 13!

share|improve this answer

Ruby 82 60 Bytes

Quick and dirty Ruby solution could definitely be better optimized if I was better with Ruby

puts "",1.step($*[0].to_i,2).map{|x|$><<" #{x} ";"/ \\"}*""

Usage: prog.rb 10
Output:

 1  3  5  7  9
/ \/ \/ \/ \/ \

edit: numerous edits and optimisations by @Manatwork!

share|improve this answer
    
print$><< and use string interpolation " #{x} ". But the best would be to reduce the number of .each by outputting the 1st line directly from the callback and building up the 2nd line in a variable: s="";(1..$*[0].to_i).step(2){|x|$><<" #{x} ";s+="/ \\"};puts"",s. Or even puts"",(1..$*[0].to_i).step(2).map{|x|$><<" #{x} ";"/ \\"}*"". – manatwork 22 hours ago
    
Numeric#step accepts 2 parameter, so can avoid the lengthy range syntax that requires parenthesis around: (1..$*[0].to_i).step(2)1.step($*[0].to_i,2). – manatwork 21 hours ago
    
@manatwork really good suggestions! I can see myself using a lot of your advice in my future codegolf posts so I really appreciate the input. – Ben Hili 17 hours ago

JavaScript (ES6), 66 64 bytes

n=>(f=n=>n?f(n-1)+(n%2?n+s:s):s=" ")(n)+`
`+"/ \\".repeat(++n/2)

Recursively builds the first line, then appends the second. The first line is built with the observation that it's simply the range [0...n] with each item n transformed to a space if even, or n concatenated with a space if odd.

share|improve this answer

Python 2, 60 bytes

Saved 6 bytes thanks to @Kade!

lambda s:" "+"  ".join(`range(s+1)`[4::6])+"\n"+-~s/2*"/ \\"
share|improve this answer
    
You don't need to use a list() cast, removing it gets you to 60 :) – Kade yesterday
    
@Kade The backticks ```` make it a string. I can't do it like lambda s:" "+" ".join(range(s+1)[1::2])+"\n"+-~s/2*"/ \\"e because then it would give a list of ints and it dies – Oliver yesterday
    
Are you sure? – Kade yesterday
    
@Kade Huh. It doesn't work online... Never mind, I don't know why I thought it didn't work... – Oliver yesterday

Batch, 107 bytes

@set s=
@set t=
@for /l %%i in (1,2,%1)do @call set s=%%s%%  %%i&call set t=%%t%%/ \
@echo%s%
@echo %t%
share|improve this answer

Scala, 99 95 Bytes

(? :Int)=>for(i<-0 to 1)println(1 to ?filter(c=>c%2>0)map(c=>if(i<1)s" $c "else"/ \\")mkString)

Ungolfed

(? :Int) => 
    for (i<-0 to 1)
        println(
            1 to ?filter(c=>c%2>0)
                  map(c=>if(i<1)s" $c "else"/ \\")
                  mkString
        )
share|improve this answer

Ruby, 48 bytes

->x{" 1  3  5  7  9 "[0..3*x-=x/2]+?\n+"/ \\"*x}
share|improve this answer

Octave, 45 bytes

f=@(n)reshape(sprintf(' /%d \',1:2:n),2,[]);

Test:
f(8)

 1  3  5  7
/ \/ \/ \/ \
share|improve this answer
    
When input = 0, there is a / left :) – Sygmei 23 hours ago
    
Didn't said your answer isn't correct ! Just noticed that small funny glitch :) – Sygmei 23 hours ago
    
I can not assume n==0 :( – rahnema1 23 hours ago

QBIC, 35 bytes

:[1,a,2|X=X+!b$+@ | Y=Y+@/ \|]?X ?Y

Explanation:

:           gets a CMD line param as INT 'a'
[1,a,2|     FOR b = 1 to a STEP 2
X=X+!b$+@ | Add to X$ the counter of our FOR loop and a trailing space
            Leading space is provided by the cast-to-string function.
Y=Y+@/ \|   Add to Y$ the mountain.
]           Close the first possible language construct (IF, DO or FOR). In this case: NEXT
?X ?Y       Print X$, Print Y$. The space adds a newline in the resulting QBASIC.
share|improve this answer

Kitanai, 140 bytes

$0[0]$1[int(input":")]$2[""]$3[""]$0#?(mod@2)($2[add(add(@" ")(string($0@)))"  "]
$3[add@"/ \"])?(neq@($1@))([add@1]&1)print($2@)print($3@)%
share|improve this answer

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.