Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Create a function that has three parameters:

  • Domino amount
  • Knock over position
  • Knock over direction (left or right)

The function must return the specified amount of dominos, displayed in the following fashion:

| upright
\ knocked left
/ knocked right

So if the parameters passed are 10, 5, 'r' then the function should return ||||//////

Use as few amount of Unicode characters as possible.

share|improve this question
    
Should the third parameter be a string or will a bool/int do like 0:left , 1:right? –  user80551 20 hours ago
    
Your example suggests that if there are 10 dominoes, and 5 are knocked right, we should display six of the ten dominoes knocked over. –  algorithmshark 20 hours ago
    
@algorithmshark I think we should show the result if the fifth domino is knocked right. –  user80551 20 hours ago
    
@rybo111 Can you allow the third parameter to be an int as that can make comparison operations shorter. Simply if(third_parameter) instead of if(third_paramter=='l') –  user80551 20 hours ago
    
Can we choose the order of the parameters? –  Quincunx 20 hours ago
show 5 more comments

19 Answers

Ruby, 38 (46) characters

e=->n,k,r{k-=r;'\|'[r]*k+'|/'[r]*n-=k}

This function takes the direction as an integer (1 for right, 0 for left). A function that takes a string is 8 characters longer:

d=->n,k,r{n-=k;r<?r??\\*k+?|*n :?|*~-k+?/*-~n}

Usage examples:

puts e[10, 5, 1] # or d[10, 5, 'r']
||||//////
puts e[10, 5, 0] # or d[10, 5, 'l']
\\\\\|||||
share|improve this answer
add comment

Haskell, 70

f R i l=(i-1)#'|'++(l-i+1)#'/'
f L i l=i#'\\'++(l-i)#'|'
(#)=replicate

assuming there is a type Direction, which has constructors R and L.

share|improve this answer
add comment

J - 32 26 char

J can't handle more than two arguments without using a list, and it can't handle non-homogenous lists without boxing. So having the input as a list of three integers is ideal. The parameter order is the reverse of the standard one: 0 for left or 1 for right, then position, then total number of dominoes. The reason for this is because J will end up going through them right-to-left.

{`(('|/\'{~-@>:,:<:)1+i.)/

I will add a more in-depth explanation later, but here's the gist of what's happening: F`G/ applied to a list x,y,z will evaluate x F (y G z). y G z constructs both possible ways the dominoes could have toppled, and then F uses x to select which of the two to use.

   {`(('|/\'{~-@>:,:<:)1+i.)/ 1 3 10
||////////
   {`(('|/\'{~-@>:,:<:)1+i.)/ 0 3 10
\\\|||||||

At the expense of a few characters, we can make the order the standard order: just append @|. to the end of the function. Adapting this to work with a string argument for direction would be much more costly, however.

share|improve this answer
add comment

Golfscript (53)

My first ever Golfscript program. Took me way longer than it should have and can probably be done in a smarter, more concise way (I'm sure someone will prove that :) ):

:d;:j;:i,{:x j<d'l'=&'\\'{x i j)->d'r'=&'/''|'if}if}%

A sample input is 10 5 'r'.

Ungolfed:

:d;:j;:i      # save input in variables and discard from stack, except total length i
,             # create an array of numbers of length i
{             # start block for map call
  :x          # save current element (= index) in variable
  j<          # check whether we are left of the first knocked over domino
  d'l'=       # check whether the direction is to the left
  &           # AND both results
  '\\'        # if true, push a backslash (escaped)
  {           # if false, start a new block
    x i j)->  # check whether we are on the right of the knocked over domino
    d'r'=     # check whether the direction is to the right
    &         # AND both results
    '/'       # if true, push a slash
    '|'       # if false, push a non-knocked over domino
    if
  }
  if
}%            # close block and call map
share|improve this answer
1  
Proof done ;-) although I am not happy with my solution yet. –  Howard 8 hours ago
1  
Some tips: you may choose d to be 0/1 instead of 'l'/'r' which gives you some shorter code. Otherwise, if you store d'l'= in a variable oyu may use it instead of the second comparison with d. In the term x i j you can save both whitespaces if you use a non-alphanumeric variable name instead of i. –  Howard 8 hours ago
    
@Howard Thanks for the tips! I chose 'l'/'r' because at the time I didn't see yet that we are free to use integers. The non-alphanumeric trick is slick, thanks! Maybe I'll update the answer later. –  Ingo Bürk 8 hours ago
add comment

Python2/3 - 54

That last added on rule was quite nice (the 0/1 instead of 'l'/'r'). Made mine actually smaller than the existing python solution. 0 is left, 1 is right

def f(a,b,c):d,e='\|/'[c:2+c];h=b-c;return d*h+e*(a-h)

# Usage:
print(f(10,5,1)) # => ||||//////
print(f(10,5,0)) # => \\\\\|||||
share|improve this answer
add comment

GolfScript, 28 23 characters

'\\'@*2$'|/'*$-1%1>+@/=

Arguments on top of stack, try online:

> 10 5 1
||||//////

> 10 5 0
\\\\\|||||
share|improve this answer
    
Amazing. Love to learn from all these golfscript solutions :) –  Ingo Bürk 8 hours ago
add comment

PowerShell, 59 57

filter d($n,$k,$d){'\'*$k*!$d+'|'*($n-$k-$d)+'/'*++$k*$d}

Probably the same idea as every one else had.

  • Takes either 0 or 1 as the direction parameter (for left and right, respectively)
share|improve this answer
add comment

JS (ES6) - 79 74 72 65

The 3rd param is a boolean (0: left / 1: right)

d=(a,b,c)=>"\\"[r="repeat"](!c&&a-b+1)+"|"[r](--b)+"/"[r](c&&a-b)

// Test
d(10,3,1); // => "||////////"
d(10,3,0); // => "\\\\\\\\||"

or

d=(a,b,c,d=b--)=>"\\|"[c].repeat(c?b:a-b)+"|/"[c].repeat(c?a-b:b)
share|improve this answer
1  
this entry could be a reference card for ECMAScript 6 :D –  bebe 19 hours ago
    
@bebe haha, and it's not even its final form. ES6 can be very dirty. –  xem 19 hours ago
1  
65: d=(a,b,c)=>"\\"[r="repeat"](!c&&a-b+1)+"|"[r](--b)+"/"[r](c&&a-b) –  nderscore 11 hours ago
1  
great! I also found this crazy thing but it's longer (67): d=(a,b,c,d=a-b+1)=>"\\|"[c].repeat(c?b-1:d)+"|/"[c].repeat(c?d:b-1) –  xem 7 hours ago
add comment

Python 2.7, 68 65 61 59 58 chars

Use d=1 for left and d=0 for right

f=lambda a,p,d:['|'*(p-1)+'/'*(a-p+1),'\\'*p+'|'*(a-p)][d]

Note: Thanks to @TheRare for further golfing it.

share|improve this answer
1  
Why not d and'\\'...or'/'...? –  TheRare 19 hours ago
    
@TheRare Done, thanks. –  user80551 10 hours ago
    
You could also do ('\\'...,'/'...)[d] –  TheRare 6 hours ago
    
@TheRare I would need two of those lists. –  user80551 6 hours ago
    
I don't think so. f=lambda a,p,d:('|'*(p-1)+'/'*(a-p+1),'\\'*p+'|'*(a-p))[d] –  TheRare 5 hours ago
show 1 more comment

Python - 45 52

This requires 1 for right and 0 for left.

x=lambda n,k,d:'\\|'[d]*(k-d)+"|/"[d]*(n-k+d)

Here's a version that takes r and l correctly, at 58:

def x(n,k,d):d=d=='r';return'\\|'[d]*(k-d)+"|/"[d]*(n-k+d)

Some usage examples...

>>> print(x(10,3,0))
\\\|||||||
>>> print(x(10,3,1))
||////////
>>> print(x(10,5,1))
||||//////
>>> print(x(10,5,0))
\\\\\|||||
>>> print(x(10,3,0))
\\\|||||||
share|improve this answer
add comment

PowerShell (107 96)

function d($a,$b,$c){-join(1..$a|%{if($_-ge$b-and$c){'/'}elseif($_-le$b-and!$c){'\'}else{'|'}})}

If we're allowed to treat the third parameter as an integer (0=l,1=r), then I can shave a little off here.

Test input:

d 10 5 r
||||//////
d 10 5 l
\\\\\|||||

Update:

d 10 5 1
||||//////
d 10 5 0
\\\\\|||||

If anyone by chance wants an explanation I will gladly add one. And as always I'm open to suggestions.

Original:

function d($a,$b,$c){-join(1..$a|%{if($_-ge$b-and$c-eq'r'){'/'}elseif($_-le$b-and$c-eq'l'){'\'}else{'|'}})}
share|improve this answer
add comment

Perl, 67 Characters

sub l{($t,$p,$d)=@_;$p--if$d;($d?'|':'\\')x$p.($d?'/':'|')x($t-$p)}

Assign the first three params (total, position, direction as an integer [0 left, 1 right]). Extras go into the ether. Subtract 1 from the position if we're headed right so the domino in position X is flipped, too.

share|improve this answer
add comment

C++ 181

#define C(x) cin>>x;
#define P(x) cout<<x;
int n,k,i;char p;
int main(){C(n)C(k)C(p)
for(;i<n;i++){if(p=='r'&&i>=k-1)P('/')else if(p=='l'&&i<=k-1)P('\\')else P('|')}
return 0;}
share|improve this answer
add comment

VBScript 109

I wish there was a better to do if/then

function f(a,p,d)
 f=string(a-p,"|")
 if d="r"then
   f=f+string(p,"/")
 else
   f=string(p,"\")+f
 end if
end function
share|improve this answer
add comment

C - 62 64 ('l':left, 'r':right)

f(a,b,c){for(b=a-b;a--;)putchar(c&2?a<b?47:124:a>b-2?92:124);}

C - 58 (0:left,1:right)

f(a,b,c){for(b=a-b;a--;)putchar(124-(a<b-!c?c*77:!c*32));}
share|improve this answer
    
This segfaults for me, probably because printf expects a const char* instead of an int (using putchar instead works). It also looks like this always knocks the dominoes over towards the right (i.e. for 10,5,'l' it prints something like ||||\\\\\\ instead of \\\\\|||||). –  Ventero 19 hours ago
add comment

AWK, 76

{ORS="";for(i=1;i<$2;i++)print"|";for(i=$2;i<=$1;i++)print($3=="r"?"/":"\\")}

Usage:

echo 10 5 r | awk '{ORS="";for(i=1;i<$2;i++)print"|";for(i=$2;i<=$1;i++)print($3=="r"?"/":"\\")}'

Although I'm wondering if I can nest ternary operators to make this shorter (although I'm playing around in bash right now and it doesn't seem like you can).

share|improve this answer
add comment

C# 124 ('\':left, '/':right)

String d(int c,int p,char d) {String result=""; for (int i=0;i<c;i++) {if(i>=c-p) {result+=d; } else {result+='|'; } } return result; }

first answer hope it satisfies request.

share|improve this answer
    
Would be even shorter if you rename result and get rid of the additional whitespaces. –  Padarom 8 hours ago
add comment

PHP, 89 Characters

function o($a,$p,$d){for($i=0;$i<$a;$i++)echo$d==0?($i+1>$p)?'|':'\\':($i+1<$p?'|':'/');}

Just because I love PHP.

share|improve this answer
add comment

PHP - 81

echo substr_replace(str_repeat('|',$l),str_repeat($r?'\\':'/',$f),$r?0:$f*-1,$f);
// Or the long version:
echo substr_replace(
            str_repeat('|',$l), // string
            str_repeat($r?'\\':'/',$f), // replace
            $r?0:$f*-1, //start
            $f// length
        );

$r = go to Right? boolean
$l = total Lenght
$f = Fallen dominos

Example results:

$r = true;  $l = 10; $f = 4; -> \\\\||||||
$r = false; $l = 10; $f = 5; -> |||||/////
$r = false; $l = 10; $f = 2; -> ||||||||//
share|improve this answer
add comment

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.