Code Golf: Diamond Pattern - language-agnostic

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
The challenge
The shortest code by character count to output a a pattern of diamonds according to the input.
The input is composed of 3 positive numbers representing the size of the diamond and the size of the grid.
A diamond is made from the ASCII characters / and \ with spaces. A diamond of size 1 is:
/\
\/
The size of the grid consists from width and height of number of diamonds.
Test cases
Input:
1 6 2
Output:
/\/\/\/\/\/\
\/\/\/\/\/\/
/\/\/\/\/\/\
\/\/\/\/\/\/
Input:
2 2 2
Output:
/\ /\
/ \/ \
\ /\ /
\/ \/
/\ /\
/ \/ \
\ /\ /
\/ \/
Input
4 3 1
Output:
/\ /\ /\
/ \ / \ / \
/ \ / \ / \
/ \/ \/ \
\ /\ /\ /
\ / \ / \ /
\ / \ / \ /
\/ \/ \/
Code count includes input/output (i.e full program).

Golfscript - 50 chars
~#:3,[{[.3-~' '*\' '*'/'\.'\\'4$]2$*}%n*.-1%]*n*\;

Golfscript - 57 chars 50 chars
~\:b;\:a,{[.a-~" "*'/'#' '*.'\\'4$]b*}%n*.-1%](*n*
57 chars:
~:c;:b;:a,{:§;b{" "a§)-*."/"" "§2**#'\\'\}*]}%n*.-1%]c*n*

Mathematica - Pure Functional
A pure functional approach
f[a_, b_, c_]:=Grid[Array[If[(s = FindInstance [Abs[p =(2((2k+1)a + #1)-1)]
== (2#2-1), k, Integers])!={},
{"\\", , "/"}[[Sign[p] /. s[[1]]]]] &, 2 a {c, b}]]
Note that Mathematica is solving an equation for finding the function of the straight lines in the diamonds. It's a Diophantine equation in k:
Abs[(2((2 * k + 1)a + x)-1)] == (2 * y -1) (only find solutions for Integer k)
For each element, and then, if a solution is found, deciding the "\" or "/" based on the sign of the lhs of the equation. (in the {"\", , "/"}[[Sign[p] /. s[[1]] part )
Usage
f[2, 2, 2]
Or
Grid[f[2, 2, 2], f[1, 6, 2], f[4, 3, 3]]
for generating all test cases at once

Windows PowerShell, 124 123 121 119 116 112 chars
$s,$w,$h=-split$input
$(($a=1..$s|%{$x=' '*($s-$_--)
"$x/$(' '*$_)\$x"*$w})
$a|%{-join($_[-$s..($s-1)])*$w})*$h
If we allow the input to span three lines instead of being generally whitespace-separated we can get it down to 109:
$s,$w,$h=#($input)
$(($a=1..$s|%{$x=' '*($s-$_--)
"$x/$(' '*$_)\$x"*$w})
$a|%{-join($_[-$s..($s-1)])*$w})*$h
As arguments to the script (from within PowerShell) it'd be 105 bytes:
$s,$w,$h=$args
$(($a=1..$s|%{$x=' '*($s-$_--)
"$x/$(' '*$_)\$x"*$w})
$a|%{-join($_[-$s..($s-1)])*$w})*$h
This would then be called like this:
PS> .\diamond.ps1 2 2 2

Ruby - 115 bytes
a,b,c=gets.split.map &:to_i;puts (a...a+c*d=a*2).map{|y|(0...b*d).map{|x|x%d==y%d ?'\\':x%d==d-y%d-1?'/':' '}.to_s}

F#, 233 chars
let[|a;b;c|],(+),z,(!)=stdin.ReadLine().Split[|' '|]|>Array.map int,String.replicate," ",printfn"%s"
for r in 1..c do
for n in 1..a do !(b+(a-n+z^"/"^2*n-2+z^"\\"^a-n+z))
for n in 1..a do !(b+(n-1+z^"\\"^2*a-2*n+z^"/"^n-1+z))
Fun! A couple new bits for my F# code-golf arsenal:
using stdin rather than the cumbersome System.Console stuff
abusing operator overloading/redefinition

Perl - 161 (working program)
($s,$n,$m)=#ARGV;$i=$s;#a=qw(/ \\);--$a;do{$r.=sprintf("%${i}s".' 'x(($s-$i)*2)."%-${i}s",#a)x$n."\n";$i=1,$a=-$a,#a=#a[-1,0]unless$i+=$a}while$i<=$s;print$r x$m
Perl - 119 (second variant)
It's more cool idea... I'm using ability of interpolation of arrays to strings.
($s,$n,$m)=#ARGV;map{#a=#b=('')x$s;$a[-$_]='/';$b[$_-1]='\\';$z.="#a#b"x$n."\n";$x.="#b#a"x$n."\n"}1..$s;print"$z$x"x$m
Full second variant:
my ($s,$n,$m) = #ARGV; # take command line parameters
my ($z,$x); # variables for upper and lower parts of diamond
for (1..$s) { # lines of half diamond
my (#a,#b); # temporary arrays
#a=#b=('')x$s; # fill arrays with empty strings
$a[-$_]='/'; # left part of diamond
$b[$_-1]='\\'; # rigth part of diamond
$z .= "#a#b" x $n . "\n"; # adding n upper parts of diamonds
$x .= "#b#a" x $n . "\n"; # adding n lower parts of diamonds
}
print "$z$x" x $m; # "$z$x" - horizontal line of diamonds

JavaScript: 261 chars (Function)
function f(s,w,h){for(y=h,g=s*2;y--;){for(i=0,o=[];i<s;i++)for(x=0,o[i]=[],o[i+s]=[];x<w;x++){o[i][s-i-1+g*x]='/';o[i][s-i+i*2+g*x]='\\';o[i+s][g*x+i]='\\';o[i+s][g+g*x-i-1]='/'}for(a=0,z='';a<g;a++,console.log(z),z='')for(b=0;b<g*w;b++)z+=o[a][b]?o[a][b]:' '}}
JavaScript: 281 chars (Rhino Script with Standard Input/Output)
a=arguments;s=+a[0];w=+a[1];h=+a[2];for(y=h,g=s*2;y--;){for(i=0,o=[];i<s;i++)for(x=0,o[i]=[],o[i+s]=[];x<w;x++){o[i][s-i-1+g*x]='/';o[i][s-i+i*2+g*x]='\\';o[i+s][g*x+i]='\\';o[i+s][g+g*x-i-1]='/'}for(a=0,z='';a<g;a++,print(z),z='')for(b=0;b<g*w;b++)z+=o[a]?o[a][b]?o[a][b]:' ':' '}
Readable Rhino Version:
size = +arguments[0];
width = +arguments[1];
height = +arguments[2];
for (y = 0; y < height; y++) {
o = [];
for (i = 0; i < size; i++) {
// Will draw the top and bottom halves of each diamond row
// in a single pass. Using array o[] to store the data:
o[i] = [];
o[i + size] = [];
for (x = 0; x < width; x++) {
// Draw the top half of the diamond row:
o[i][(size - i - 1) + (size * 2 * x)] = '/';
o[i][(size - i) + (i * 2) + (size * 2 * x)] = '\\';
// Draw the bottom half of the diamond row:
o[i + size][(size * 2 * x) + i] = '\\';
o[i + size][(size * 2) + (size * x * 2) - i - 1] = '/';
}
}
// Output the full diamond row to console from array o[]:
for (a = 0; a < size * 2; a++) {
z = "";
for (b = 0; b < size * 2 * width; b++) {
z += o[a] ? o[a][b] ? o[a][b] : ' ' : ' ';
}
print(z);
}
}
Test Cases:
java org.mozilla.javascript.tools.shell.Main diamonds.js 4, 3, 2
/\ /\ /\
/ \ / \ / \
/ \ / \ / \
/ \/ \/ \
\ /\ /\ /
\ / \ / \ /
\ / \ / \ /
\/ \/ \/
/\ /\ /\
/ \ / \ / \
/ \ / \ / \
/ \/ \/ \
\ /\ /\ /
\ / \ / \ /
\ / \ / \ /
\/ \/ \/
java org.mozilla.javascript.tools.shell.Main diamonds.js 2, 6, 1
/\ /\ /\ /\ /\ /\
/ \/ \/ \/ \/ \/ \
\ /\ /\ /\ /\ /\ /
\/ \/ \/ \/ \/ \/
java org.mozilla.javascript.tools.shell.Main diamonds.js 1, 1, 1
/\
\/

Python, 125 chars
s,c,r=input()
l=[c*('%*c%*c%*s'%(s-i,47,2*i+1,92,s-i-1,''))for i in range(s)]
print'\n'.join(r*(l+[i[::-1]for i in l[::-1]]))
Input should be provided in comma-separated form, e.g. 1,6,2:
D:\CodeGolf> DiamondPattern.py
1,6,2
/\/\/\/\/\/\
\/\/\/\/\/\/
/\/\/\/\/\/\
\/\/\/\/\/\/
PS. if you prefer input separated with spaces (1 6 1), for the price of 21c replace first line with:
s,c,r=map(int,raw_input().split())
If you prefer command line arguments, for 25c more you can have
import sys;s,c,r=map(int,sys.argv[1:])

Python - 138 chars
s,r,c=eval("input(),"*3)
x=range(s);o="";l="\/";i=0
for k in x+x[::-1]:y=" "*(s-1-k);o+=(y+l[i<s]+" "*k+l[i>=s]+y)*c+"\n";i+=1
print o*r,
as a bonus it's also incredibly vulnerable to attack!

Haskell, 136 chars
r=readLn
main=do
n<-r;w<-r;h<-r;let d=2*n;y?x|mod(x+y-1)d==n='/'|mod(x-y)d==n='\\'|True=' '
mapM putStrLn[map(y?)[1..d*w]|y<-[1..d*h]]
Usage:
$ ./a.out
1
6
2
/\/\/\/\/\/\
\/\/\/\/\/\/
/\/\/\/\/\/\
\/\/\/\/\/\/

Python - 126 chars
s,w,h=input();z=s*2;w*=z;h*=z;
print("%s"*w+"\n")*h%tuple(
" \/"[(i/w%z==i%z)+((i/w+1)%z==-i%z)*2] for i in range(s*w,w*(h+s))
),
Line breaks and indentation added for clarity.

Clojure
(def ^:dynamic fc \/)
(def ^:dynamic sc \\)
(defn spaces [size]
(apply str (repeat size " ")))
(defn linestr[size line-no]
(let [sp (spaces size )
fh (doto (StringBuilder. sp)
(.setCharAt (- size line-no) fc)
(.toString))
sh (.replace (apply str (reverse fh)) fc sc) ]
(str fh sh)))
(defn linestr-x[number size line-no]
(apply str (repeat number (linestr size line-no))))
(defn print-all[number size]
(loop [line-no 1 lines []]
(if (> (inc size) line-no)
(recur (inc line-no) (conj lines (linestr-x number size line-no)))
lines)))
(defn diamond[number size]
(let [fh (print-all number size) ]
(binding [fc \\ sc \/]
(flatten [fh (reverse (print-all number size)) ]))))
(defn print-diamond[size cols rows]
(doseq [x (flatten (repeat rows (diamond cols size))) ]
(println x)))
(print-diamond 4 3 1)
user=> (print-diamond 1 10 3 )
/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\/\/\/\/\/\/
/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\/\/\/\/\/\/
/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\/\/\/\/\/\/

Related

How to use TLA+ to define sequential actions?

Say I have a simple set of sequential actions (which I will first define imperatively):
start(a, 1)
move(a, 3)
move(a, 5)
move(a, 4)
move(a, 2)
That is, we have a game piece a and start it at position 1. Then we move it sequentially first to 3, then to 5, then 4, then 2. Once per step.
How would you define this using TLA+? Trying to wrap my mind around how to specify complicated imperative action sequences in TLA+.
The behaviours sketched in the question could be described in TLA+ as follows:
---- MODULE Steps ----
VARIABLE a
Init == a = 1
Next == \/ /\ a = 1
/\ a' = 3
\/ /\ a = 3
/\ a' = 5
\/ /\ a = 5
/\ a' = 4
\/ /\ a = 4
/\ a' = 2
Spec == Init /\ [][Next]_a /\ WF_a(Next)
=====================
The behavior of variable a is specified by the temporal formula Spec (other variables can behave in arbitrary ways).
The variable a starts equal to 1 (by the conjunct Init), and a temporal step either leaves a unchanged, or it changes it from 1 to 3. If this change occurs, then the following temporal steps either leave a unchanged, or change it from 3 to 5. The changes of value to a may continue until a equals 2. Further changes to a are impossible. Once a becomes equal to 2, it remains forever equal 2. These are the possible changes of a, as specified by the conjunct [][Next]_a, which means [](Next \/ UNCHANGED a), i.e., [](Next \/ (a' = a)), with the symbol [] meaning "always".
The conjuncts Init and [][Next]_a specify a safety property. Safety is about what can happen, not what must happen. Liveness (what must happen) is specified with the conjunct WF_a(Next), which describes weak fairness. The formula WF_a(Next) requires that if a step that satisfies the formula Next and changes the value of variable a is enabled uninterruptedly, then such a step must eventually occur.
In other words, if it is possible to change variable a by taking a step that satisfies Next (a <<Next>>_a-step), then a cannot remain forever unchanged, but must eventually change in a way that is described by Next. Indeed, while a is not 2, but 1, 3, 5, or 4, action <<Next>>_a (which means Next /\ (a' # a), i.e., Next and a changes value) is enabled, so a will keep changing until it reaches the value 2. When a is 2, <<Next>>_a becomes disabled.
There are a large number of ways to do this, but here are two simple solutions which spring to mind; the first uses a macro:
---- MODULE Steps ----
VARIABLE a
move(start, end) ==
/\ a = start
/\ a' = end
Init ==
/\ a = 1
Next ==
\/ move(1, 3)
\/ move(3, 5)
\/ move(5, 4)
\/ move(4, 2)
Spec ==
/\ Init
/\ [][Next]_a
=====================
Note the above will only work as long as your sequence of moves doesn't return to the same state. If it does, you'll have to add something like a pc "program counter" variable and a sequence and yada yada yada... at that point you're probably better off using PlusCal, a TLA+ variant which often works better for writing sequential actions:
---- MODULE Steps ----
(* --algorithm Steps
variables a = 1;
begin
a := 3;
a := 5;
a := 4;
a := 2;
end algorithm; *)
=====================
This has to be translated into TLA+ before it can be run by TLC. Use
CTRL+T in the TLA+ toolbox
Parse module command in the VS Code extension
java pcal.trans Steps.tla with the CLI

Code Golf: Spider webs

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
The challenge
The shortest code by character count to output a spider web with rings equal to user's input.
A spider web is started by reconstructing the center ring:
\_|_/
_/ \_
\___/
/ | \
Then adding rings equal to the amount entered by the user. A ring is another level of a "spider circles" made from \ / | and _, and wraps the center circle.
Input is always guaranteed to be a single positive integer.
Test cases
Input
1
Output
\__|__/
/\_|_/\
_/_/ \_\_
\ \___/ /
\/_|_\/
/ | \
Input
4
Output
\_____|_____/
/\____|____/\
/ /\___|___/\ \
/ / /\__|__/\ \ \
/ / / /\_|_/\ \ \ \
_/_/_/_/_/ \_\_\_\_\_
\ \ \ \ \___/ / / / /
\ \ \ \/_|_\/ / / /
\ \ \/__|__\/ / /
\ \/___|___\/ /
\/____|____\/
/ | \
Input:
7
Output:
\________|________/
/\_______|_______/\
/ /\______|______/\ \
/ / /\_____|_____/\ \ \
/ / / /\____|____/\ \ \ \
/ / / / /\___|___/\ \ \ \ \
/ / / / / /\__|__/\ \ \ \ \ \
/ / / / / / /\_|_/\ \ \ \ \ \ \
_/_/_/_/_/_/_/_/ \_\_\_\_\_\_\_\_
\ \ \ \ \ \ \ \___/ / / / / / / /
\ \ \ \ \ \ \/_|_\/ / / / / / /
\ \ \ \ \ \/__|__\/ / / / / /
\ \ \ \ \/___|___\/ / / / /
\ \ \ \/____|____\/ / / /
\ \ \/_____|_____\/ / /
\ \/______|______\/ /
\/_______|_______\/
/ | \
Code count includes input/output (i.e full program).
Perl, 164 chars
195 184 171 167 164
print#o=((map{$z=_ x($x=1+$N-$_);$"x$x." /"x$_."\\$z|$z/".'\ 'x$_.$/}0..($N=<>)),
"_/"x++$N." ".'\_'x$N.$/);
y'/\\'\/',#o||y#_# #,$t++||y#_ # _#,print while$_=pop#o
First statement prints out the top half of the spider web. Second statement uses transliteration operations to create a reflection of the top half.
This next one weighs in closer to 314 chars (of productive code), but is more in the spirit of the season.
; "
Tr Ic
K| |t
Re aT
", "H
av e
A: -
)H AL LO W
ee N" ," En
jo y_ Yo ur
_ C&& y"; ##
&I (); $N= 1+
<>; $,= $/;#O =(( map
$" x($ X=$N-$_). ${ f}x$_.$
B.${U}x$X.$P.${U}x$X.$
F.${b}x$_,0..$N-1),${g}x$N.(${S}
x3).${c}x$N);sub I{($F,$B,$U, $P)
=qw (/ \\ _ |);; ${
S}= " ";$f=$S.$F;$g=$ U.
$F ;$b=$B.$S;$c=$B.${U};}#{ P}=
#{ O}; while($_=pop#{P} ){ #{
P} || y:_: :;$spooky++ || 0|
0 || y#_ # _#;y:/:8:; ; ;
; ;; y:\\:/:;y:8:\\:; #O =
( #O ,$_);}print#O; q{
Do !Discuss:Rel ig
io n,Politi cs
,& &T
heG rea
tP ump
ki n}
Hat tip to http://www.ascii-art.de/ascii/s/spider.txt
I constructed the spider shaped code by hand, but see the Acme::AsciiArtinator module on CPAN for help with automating (or at least semi-automating) the task.
Golfscript - 124 chars
All whitespace is significant! If you accidently add a newline to the end there will be an extra _ at the end of the output
~):#,{#\:&-:0' ': *& '/':/+*'\\':~'_':
0*.'|':|\/~ +&*n}%
/+#* ~
+#*n ~+#*
#/ +*n#,{):& *#&-:( ~+*/[
](!=&*.|\~/ +(*n}%
Golfscript - 129 chars
~):#,{#\:&-:0' ': *&' /'*'\\':~'_':
0*.'|'\'/'~ +&*n}%'_/'#* '\_'#*n ~+#*
#'/ '*n#,{):& *#&-:( ~+*'/'[
](!=&*.'|'\~'/ '(*n}%
Golfscript - 133 chars
~):#,{#\:&-:0' ': *&' /'*'\\':~'_':
0*.'|'\'/'~ +&*n}%'_/'#*3 *'\_'#*n' \\'#*3
*#'/ '*n#,{):& *#&-:( ~+*'/''_ '1/(!=&*.'|'\~'/ '(*n}%
Python - 212 chars
n=input()+1;b,f,p,u,s='\/|_ '
a=[s*(n-i)+' /'*i+b+u*(n-i)+p+u*(n-i)+f+'\ '*i+s*(n-i)for
i in range(n)]
print"\n".join(a+['_/'*n+s*3+'\_'*n,' \\'*n+u*3+'/ '*n]+[x[::-1]for
x in a[:0:-1]]+[a[0][::-1].replace(u,s)])
Perl: 161 characters
Note that this code includes the starting web in the source. (The doubled backslash at the end is a shame. An earlier version didn't have that.)
$_='
\_|_/
_/ \_
\___/
/_|_\\';
for$x(1..<>){
s|(.\S).*([/\\].)|$1$&$2|g;
s|\\(.*)/| \\_$1_/$` /$&\\ |;
s|(\s+)\K/(.*).$| \\$&/$1 /_$2_\\|
}
s|_(?=.*$)| |g;
print
The whitespace within $_ is significant (of course), but none of the rest is. If you have a minor suggestion that improves this, please feel free to just edit my code. For example, Kinopiko has nicely shaved off 6 characters!
Depending on how you count command-line switches, this might be shorter (154 by usual Perl golf rules if I can count correctly):
#!perl -ap
$_='
\_|_/
_/ \_
\___/
/_|_\\';
s|(.\S).*([/\\].)|$1$&$2|g,
s|\S(.*).| \\_$1_/$` /$&\\ |,
s|(\s+)\K/(.*).$| \\$&/$1 /_$2_\\|while$F[0]--;
s|_(?=.*$)| |g
Vb.net, windows console, Infer, Strict, Explicit ON.
Microsoft word is saying 442 characters without space
It might be possible to reduce it more but this is my last update(try #2)
Module z
Sub Main()
Dim i = CInt(Console.ReadLine), j = i + 1, h = j * 2 + 1, w = h * 2, z = "_", b = " "
For y = 0 To h
For x = 0 To w
Dim l = (x + y Mod 2 + i Mod 2) Mod 2, u = j + y, e = j - y, k = h + e, o = x = h Or x = h - 1
Console.Write(If(x = h, If(y = j, b, If(y = j + 1, z, "|")), "") & If(x = w, vbLf, If(y = j, If(x Mod 2 = 0 = (x < h), If(o, b, z), If(x < h, "/", "\")), If(x < k And x > u Or (x < u And x > k Or o) And y < h, z, If(x = k Or (x < u And y < j And x > e Or x > u And y > j And x < w + e) And l = 0, "/", If(x = u Or (x > k And y < j And x < h + u Or x < k And y > j And x > y - j - 1) And l = 1, "\", b))))))
Next
Next
End Sub
End Module
Python: 240 Characters
Nothing too tricky here; just printing line by line - 298 280 271 266 265 261 260 254 240 characters (ignore the last 2 line breaks)
u,b,f,s,a='_\/ |'
m=input()+1
print'\n'.join([(m-x)*s+x*' /'+b+(m-x)*u+a+(m-x)*u+f+x*'\ 'for x in
range(0,m)]+['_/'*m+s*3+'\_'*m+'\n'+(s+b)*m+u*3+'/ '*m]+[x*s+(m-x)*
' \\'+f+x*u+a+x*u+b+(m-x)*'/ 'for x in range(1,m)] + [s*m+f+s*m+a+s*m+b])
Lua, 290
n=...s=string r=s.reverse g=s.gsub a="\\|/"j=(" /"):rep(n+1)..a..("\\ "):rep(n+1) k=j o=k
l=n*4+7 for i=1,n+1 do k=g(k,"^(.- )/(.-)|(.*)\\(.-)$","%1%2_|_%3%4")o=k..o end
o=o..r(o)print((g(g(g(g(r(g(o:sub(1,l),"_"," ")..o:sub(l+1)),j,g(j," ","_")),("."):rep(l),"%1\n"),a," "),r(a),"___")))
Ruby1.9 - 181 chars
n=gets.to_i+1;s=' '
a=0.upto(n-1).map{|i|s*(j=n-i)+' /'*i+?\\+?_*j+'|'+?_*j+?/+'\ '*i+s*j}
d=a.reverse.map{|x|x.reverse};d[-1].tr!?_,s
puts a,'_/'*n+s*3+'\_'*n,' \\'*n+?_*3+'/ '*n,d
Ruby1.8 - 185 chars
Some improvements from JRL
n=gets.to_i+1;s=' '
u='_';a=0.upto(n-1).map{|i|s*(j=n-i)+' /'*i+'\\'+u*j+'|'+u*j+'/'+'\ '*i+s*j}
d=a.reverse.map{|x|x.reverse}
d[-1].tr!u,s;puts a,'_/'*n+s*3+'\_'*n,' \\'*n+u*3+'/ '*n,d
Ruby - 207 chars
Ruby seems to have some peculiar rules about the "\"
n=eval(gets)+1
b,f,p,u,s='\/|_ '.split""
a=0.upto(n-1).map{|i|s*(j=n-i)+' /'*i+b+u*j+"|"+u*j+f+"\\ "*i+s*j}
puts a,'_/'*n+s*3+'\_'*n,' \\'*n+u*3+'/ '*n,a[1..-1].reverse.map{
|x|x.reverse},a[0].reverse.tr(u,s)
Ruby1.8, 179
Run with ruby -n
n=$_.to_i+1
u,s,c=%w{_ \ \ \\}
z=(1..n).map{|i|k=n-i
s*i+c*k+'/'+u*i+'|'+u*i+"\\"+'/ '*k+s*i}
y=z.reverse.map{|a|a.reverse}
z[-1].tr!u,s
puts y,'_/'*n+s*3+'\_'*n,c*n+u*3+'/ '*n,z
In the first attempt below it seemed like a good idea to just generate one quadrant (I chose lower left), and then mirror twice to get the whole web. But gnibbler got better results generating both quadrants (of the top half) and then generating rather than patching up the inner area. So I revised mine to initially generate the other lower quadrant also, mirror only once, and also to leave the innermost row out of the mirror, which kind of converges with the other entry.
Ruby, 241
n=$_.to_i+1
m=2*n+1
u,s,b,f=%w{_ \ \\ /}
z=(0..n).map{|i|s*i+(s+b)*(n-i)+(i==0?u:f)+u*i}
q=z.reverse.map{|a|a.tr f+b,b+b+f}
q[n].gsub!' ','_'
q[n][m-1]=s
z=(q+z).map{|a|a+'|'+a.reverse.tr(f+b,b+b+f)}
z[n][m]=z[n+1][m]=s
z[m].gsub!u,s
puts z
C, 573 chars
Obviously it isn't even in the running w/regard to the character count. The 573 number is just the file size on my windows machine, so that probably counts a few ctrl-M's. On the other hand, maybe 573 is under-counting it, since I incurred the wrath of the compiler by jettisoning all the #include's to save space, warnings be damned!
But hey, this is my first time attempting one of these, and it will undoubtedly be good practice to try to re-express it in something more compact.
#define B puts("");
#define K '\\'+'/'
#define F '_'+' '
#define P(s) putchar(s);
#define I int
c(I s,I f){if(s){P(f)c(s-1,f);P(f)}else P('|')}
w(I lw,I s,I k,I f){if(s){P(' ')P(k)w(lw,s-1,k,f);P(K-k)P(' ')}else{P(K-k)c(1+lw,f);P(k)}}
h(I g,I s,I k,I f){I i;for(i=-1;i<g;++i)P(' ')w(g,s,k,f);}
t(I g,I s){if(s)t(g+1,s-1);h(g,s,'/','_');B}
b(I g,I s){h(g,s,'\\',s?'_':' ');B;if(s)b(g+1,s-1);}
m(I s,I k,I f){if(s){P(f)P(k)m(s-1,k,f);P(K-k)P(f)}else{P(F-f)P(F-f)P(F-f)}}
main(I ac,char*av[]){I s;s=atoi(av[1]);t(0,s);m(1+s,'/','_');B;m(1+s,'\\',' ');B;b(0,s);}
Python, 340 - 309 - 269 - 250 characters
Still room for improvement I think.
s=input()+1
f,b="/ ","\\"
r=range(s)
for i in r:w="_"*(s-i);print" "*(s+(i>=1)-i)+(f*i)[:-1]+b+w+"|"+w+"/"+"\ "*i
print"_/"*s+" "*3+"\_"*s+"\n"+" \\"*s+"_"*3+f*s
for i in r[::-1]:u="_ "[i<1]*(s-i);print" "*(s-i+(i>=1))+("\ "*i)[:-1]+"/"+u+"|"+u+b+f*i
-
Python (alternative version), 250 - 246 characters
s=input()+1;r=range(s);c="/","\\";y="/ ","\\ "
def o(i,r):u="_ "[i<1 and r]*(s-i);print" "*(s+(i>=1)-i)+(y[r]*i)[:-1]+c[r<1]+u+"|"+u+c[r]+(y[r<1]*i)[:-1]
for i in r:o(i,0)
print"_/"*s+" "*3+"\_"*s+"\n"+" \\"*s+"_"*3+"/ "*s
for i in r[::-1]:o(i,1)
Python and Ruby just about even*
I would rather have continued the comment thread above that briefly mentioned Python vs Ruby, but I need formatting to do this. Smashery is certainly classy but doesn't need to worry: it turns out that Python and Ruby are in a pretty close race by one measure. I went back and compared Python to Ruby in the eight code-golf's that I have entered.
Challenge Best Python Best Ruby
The Wave 161 99
PEMDAS no python entry (default victory?)
Seven Segs 160 175
Banknotes 83 (beat Perl!) 87
Beehive 144 164
RPN (no eval) 111 (157) 80 (107)
Cubes 249 233
Webs 212 181
Victories 3 4 (5?)
So the issue definitely isn't settled and got more interesting recently when gnibbler started entering on both sides. :-)
*I only counted fully functional entries.
dc - 262
A "straightforward" solution in dc (OpenBSD). Not a contender, but it is always fun. Line breaks for "readability"
[lcP1-d0<A]sA?sN[lK32sclAxRlNlK-l1scd0!=ARl3PlKl0sclAxRl9PlKlAxRl4PlNlK-
l2scd0!=AAPR]sW95s0124s9[ /]s1[\\ ]s292s347s4lN[dsKlWx1-d0<L]dsLx
[\\_][ ][_/][lN[rdPr1-d0<L]dsLxRRPlNlLxRR]dsBxAP[/ ][_ _][ \\]lBxAP[ \\]s1
[/ ]s247s392s41[dsKlWx1+dlN>L]dsLx32s032s9lNsKlWx
sample output
$ dc web.dc
3
\___|___/
/\__|__/\
/ /\_|_/\ \
_/_/_/ \_\_\_
\ \ \_ _/ / /
\ \/_|_\/ /
\/__|__\/
/ \
Perl 264 chars
shortened by in-lining the subroutines.
perl -E'$"="";($i=<>)++;#r=map{$p=$i-$_;#d=(" "x$_,(" ","\\")x$p,"/","_"x$_);($d="#d")=~y:\\/:/\\:;#d=reverse#d;$d.="|#d"}1..$i;say for reverse#r;$_=$r[0];y: _|:_ :;s:.(.*)\\.*/(.*).:$1_/ \\_$2:;say;y: _\\/:_ /\\:;say;$r[-1]=~y:_: :;say for grep{y:\\/:/\\:}#r;'
Expanded to improve readability.
perl -E'
$"="";
($i=<>)++;
#r=map{
$p=$i-$_;
#d=(
" "x$_,
(" ","\\")x$p,
"/",
"_"x$_
);
($d="#d")=~y:\\/:/\\:;
#d=reverse#d;
$d.="|#d"
}1..$i;
say for reverse#r;
$_=$r[0];
y: _|:_ :;
s:.(.*)\\.*/(.*).:$1_/ \\_$2:;
say;
y: _\\/:_ /\\:;
say;
$r[-1]=~y:_: :;
say for grep{y:\\/:/\\:}#r;
'
This is the code before I minimized it:
#! /opt/perl/bin/perl
use 5.10.1;
($i=<>)++;
$"=""; #" # This is to remove the extra spaces for "#d"
sub d(){
$p=$i-$_;
" "x$_,(" ","\\")x$p,"/","_"x$_
}
sub D(){
#d=d;
($d="#d")=~y:\\/:/\\:; # swap '\' for '/'
#d=reverse#d;
$d.="|#d"
}
#r = map{D}1..$i;
say for reverse#r; # print preceding lines
# this section prints the middle two lines
$_=$r[0];
y: _|:_ :;
s:.(.*)\\.*/(.*).:$1_/ \\_$2:;
say;
y: _\\/:_ /\\:;
say;
$r[-1]=~y:_: :; # remove '_' from last line
say for grep{y:\\/:/\\:}#r; # print following lines
(&)=(++) --9
f 0=[" \\_|_/","_/ \\_"," \\___/"," / | \\"] --52
f(n+1)=[s&h&u&"|"&u&g]&w(f n)&[s&g&s&"|"&s&h]where[a,b,c,d,e]=" _/\\|";[g,h]=["/","\\"];y=n+2;[u,s]=[r y b,r y a];p f s n x=let(a,b)=span(/=s)x in a&f b;i=dropWhile(==a);w[]=[];w[x]=[s&h&i(p(map(\x->if x==a then b else x))c d x)&g];w(l:e)|n==y*2-1=x%h:z|n>y=x&" "%" \\":z|n==y="_/"%"\\_":z|n<y=r(y-n)a&"\\ "%" /":z where n=length e;z=w e;x=r(n+1-y)a&g;(%)=(&).(&i l) --367
r=replicate --12
main=interact$unlines.f.read --29
Haskell entry weighing in at 469 characters. I'm sure there is a lot of room for improvement.
good luck trying to read it :)
here is a more readable version. Although there have been some changes since this version
spider 0=[" \\_|_/","_/ \\_"," \\___/"," / | \\"]
spider n=(s++"\\"++u++"|"++u++"/"):w m(spider(n-1))++[s++"/"++s++"|"++s++"\\"]
where
[a,b,c,d,e]=" _/\\|"
[m,y]=[y*2,n+1]
x=r y
[u,s]=[x b,x a]
t a b=map(\x->if x==a then b else x)
p f s n x=let(a,b)=span(/=s)x;(c,d)=span(/=n)b in a++f c++d
i=dropWhile(==a)
w _[]=[]
w _[x]=[s++"\\"++i(p(t a b)c d x)++"/"]
w(a+1)(l:e) |a==m-1=wrapline x l"\\":z
|a>y=wrapline(x++" ")l" \\":z
|a==y=wrapline"_/"l"\\_":z
|a<y=wrapline(r(y-a)' '++"\\ ")l" /":z
where
z=w a e
x=r(a+1-y)' '++"/"
wrapline b l a=b++i l++a
r=replicate
main=interact$unlines.spider.read

Code Golf: Beehive

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
The challenge
The shortest code by character count that will generate a beehive from user input.
A beehive is defined a a grid of hexagons in a size inputted by the user as two positive numbers greater than zero (no need to validate input). The first number (W) represents the width of the beehive - or - how many hexagons are on each row. The second number (H) represents the height of the beehive - or - how many hexagons are on each column.
A Single hexagon is made from three ASCII characters: _, / and \, and three lines:
__
/ \
\__/
Hexagons complete each other: the first column of the beehive will be 'low', and the second will be high - alternating and repeating in the same pattern forming W hexagons. This will be repeated H times to form a total of WxH hexagons.
Test cases:
Input:
1 1
Output:
__
/ \
\__/
Input:
4 2
Output:
__ __
__/ \__/ \
/ \__/ \__/
\__/ \__/ \
/ \__/ \__/
\__/ \__/
Input:
2 5
Output:
__
__/ \
/ \__/
\__/ \
/ \__/
\__/ \
/ \__/
\__/ \
/ \__/
\__/ \
/ \__/
\__/
Input:
11 3
Output:
__ __ __ __ __
__/ \__/ \__/ \__/ \__/ \__
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
Code count includes input/output (i.e full program).
Perl, 99 characters
#P=map{$/.substr$".'__/ \\'x99,$_,$W||=1+3*pop}0,(3,6)x pop;
chop$P[0-$W%2];print" __"x($W/6),#P
Last edit: Saved one character replacing -($W%2) with 0-$W%2 (thanks A. Rex)
Explanation:
For width W and height H, the output is 2+2 * H lines long and 3 * W+1 characters wide, with a lot of repetition in the middle of the output.
For convenience, we let $W be 3 * W + 1, the width of the output in characters.
The top line consists of the pattern " __", repeated W/2 == $W/6 times.
The even numbered lines consist of the repeating pattern "\__/ ", truncated to $W characters. The second line of output is a special case, where the first character of the second line should be a space instead of a \.
The odd numbered lines consist of the repeating pattern "/ \__", truncated to $W characters.
We construct a string: " " . "__/ \" x 99. Note that the beginning of this string is the desired output for the second line. This line starting at position 3 is the desired output for the odd lines, and starting at position 6 for the even numbered lines.
The LIST argument to the map call begins with 0 and is followed by H repetitions of (3,6). The map call creates a list of the substrings that begin at the appropriate positions and are $W = 3 * W + 1 characters long.
There is one more adjustment to make before printing the results. If W is odd, then there is an extra character on the second line ($P[0]) that needs to be chopped off. If W is even, then there is an extra character on the bottom line ($P[-1]) to chop.
Python 2.6 - 144 characters including newlines
I can save about 20 more characters if the inputs are allowed to be comma separated.
C,R=map(int,raw_input().split())
print C/2*" __"+"\n "+("__/ \\"*99)[:3*C-C%2]
r=0
exec'r+=3;print ("\__/ "*99)[r:r+3*C+1-r/6/R*~C%2];'*2*R
The version that takes input from the command line is 4 more bytes:
import sys
C,R=map(int,sys.argv[1:])
print C/2*" __"+"\n "+("__/ \\"*99)[:3*C-C%2]
r=0
exec'r+=3;print ("\__/ "*99)[r:r+3*C+1-r/6/R*~C%2];'*2*R
C89 (136 characters)
x;y;w;main(h){for(h=scanf("%d%d",&w,&h)*h+2;y++
<h;++x)putchar(x>w*3-(y==(w&1?2:h))?x=-1,10:
"/ \\__"[--y?y-1|x?(x+y*3)%6:1:x%6<4?1:5]);}
Perl, 160 characters
$w=shift;for$h(-1..2*shift){push#a,join'',(('\__','/ ')x($w+$h))[$h..$w+$h]}
$a[0]=~y#\\/# #;$a[1]=~s/./ /;s/_*$//for#a;$a[$w%2||$#a]=~s/. *$//;print$_,$/for#a
No cleverness involved at all: just fill the array with characters, then weed out the ones that look ugly.
strager's masterpiece is only 137 characters when ported to Perl, but all credit should go to him.
$w=shift;$\=$/;for$y(1..($h=2+2*shift)){print map+(split//,'_ \__/ ')
[$y-1?$y-2|$_?($_+$y%2*3)%6+2:1:$_%6<4],0..$w*3-!($w&1?$y-2:$y-$h)}
J, 143 characters
4(1!:2)~(10{a.)&,"1({.4 :0{:)".(1!:1)3
|:(18,(}:,32-+:#{:)3 3 8 1 1 10$~3*x){(,' '&(0})"1,' '&(0 1})"1)(,}."1)(}."1,}:"1)(3++:y)$"1'/\',:' _'
)
Using J feels very awkward when dealing with variable-length strings and the sort of console-oriented user interaction that is assumed in other languages. Still, I guess this is not too bad...
Stealing ideas once more (J is much easier to work with once you find a way of looking at the problem in an array-structured way), here's mobrule's masterpiece ported in 124 (ick, it's longer than the original):
4(1!:2)~({.4 :0{:)".(1!:1)3
(x}~' '_1}(x=.-1-+:2|x){])((10{a.),(' ',,99#'__/ \',:' __'){~(i.>:3*x)+])"0]595 0,3 6$~+:y
)
C#, 216 characters
class B{static void Main(string[]a){int b=0,i=0,w=int.Parse(a[0])+1,z=2*w*(int.Parse(a[1])+1);for(;i<z;b=(i%w+i/w)%2)System.Console.Write("\\/ "[i>w&(w%2>0?i<z-1:i!=2*w-1)?b>0?0:1:2]+(++i%w<1?"\n":b>0?"__":" "));}}
Less obfuscated:
class B{
static void Main(string[]a){
int b=0,
i=0,
w=int.Parse(a[0])+1,
z=2*w*(int.Parse(a[1])+1);
for(;i<z;b=(i%w+i/w)%2)
System.Console.Write(
"\\/ "[i>w&(w%2>0?i<z-1:i!=2*w-1)?b>0?0:1:2]
+
(++i%w<1?"\n":b>0?"__":" ")
);
}
}
I used the following method:
input: 4 2
cols: 0 00 1 11 2 22 3 33 4 44
row 0:" | | |__| | | |__| |"
1:" |__|/| |\|__|/| |\|"
2:"/| |\|__|/| |\|__|/|"
3:"\|__|/| |\|__|/| |\|"
4:"/| |\|__|/| |\|__|/|"
5:"\|__|/| |\|__|/| | |"
Iterate from zero to (W+1)*(H*2+1). The *2 is because each comb is 2 lines tall, and +1 to account for the first line and end of lines.
Render two "pieces" of a hexagon per iteration:
Decide between " ", "\", and "/" for the first part
Decide between "__", " ", and "\n" for the second part
The pattern is evident if you look at a large enough honeycomb. Half the logic is there only to address exceptions in the first row, the end of the second row, and the last cell.
Ruby, 164
$ ruby -a -p bh.rb
strager's masterpiece in Ruby...
w,h = $F; w=w.to_i
(1..(h = h.to_i * 2 + 2)).each { |y|
(0...(w * 3 + (y != ((w & 1) != 0 ? 2 : h) ? 1:0))).each { |x|
$> << ('_ \__/ ' [
y - 1 != 0 ?
(y - 2 | x) != 0 ?
(x + y % 2 * 3) % 6 + 2 : 1 : (x % 6 < 4) ? 1:0]).chr
}
$> << $/
}
aka
w,h=$F;w=w.to_i
(1..(h=h.to_i*2+2)).each{|y|(0...(w*3+(y!=((w&1)!=0?2:h)?1:0))).each{|x|$><<('_ \__/ '[y-1!=0?(y-2|x)!=0?(x+y%2*3)%6+2:1:(x%6<4)?1:0]).chr}
$><<$/}
NewLisp: 257 chars
I'm sure this is not an optimal solution:
(silent(define(i v)(println)(set v(int(read-line))))(i'w)(i'h)(set't(+(* 3 w)1))(set'l " __/ \\__/ ")(define(p s e(b 0))(println(slice(append(dup" "b)(dup(s 6 l)w))0 e)))(p 0 t)(p 4(- t(% w 2))1)(dotimes(n(- h 1))(p 6 t)(p 9 t))(p 6 t)(p 9(- t(%(+ w 1)2))))
Less obfuscated:
(silent
(define (i v)
(println)
(set v (int (read-line))))
(i 'w)
(i 'h)
(set 't (+ (* 3 w) 1))
(set 'l " __/ \\__/ ")
(define (p s e (b 0))
(println (slice (append (dup " " b) (dup (s 6 l) w)) 0 e)))
(p 0 t)
(p 4 (- t (% w 2)) 1)
(dotimes (n (- h 1))
(p 6 t)
(p 9 t))
(p 6 t)
(p 9 (- t(% (+ w 1)2))))
I'm sure I could write the loop differently and save two lines and a few characters, for instance, but it's late...
Golfscript, 88 characters
Based on the mobrule's solution. It was a lot of work to get it smaller than that one! Newlines are just for clarity.
~:r;:c 3*):W 6/" __"*n
[][0]r[3 6]*+{[" ""__/ \\"99*+>W<]+.},;
c 2%-1 1if:r%)[-1<]+r%
n*
Explanation:
~:r;,:c # read input into rows, columns
3 *):W # store c*3+1 into W
6 /" __"*n # write out " __" W/6 times, plus newline
[] # initialize output array
[0]r[3 6]*+ # create array [0] + [3,6] repeated r times
{ # for every entry in the input array...
[" ""__/ \\"99*+ # create the magic string
>W< # truncate it between [n:W], where n is the cur entry
]+ # store this line in the output array
.},; # repeat for every entry in array
# now to handle the extra cases:
c 2%-1 1if:r% # reverse the array if c is odd, do nothing if it's even
)[-1<] # take the last entry in the array, cut off the last char
+r% # put it back on the array, and un-reverse it
n* # now join the array with newlines
Here is my original entry at 118 characters:
Late entry, but it's 2nd smallest! (I'm just using these to learn Golfscript). Newlines are for clarity.
~:r;:c 2%:o;c 2/:b" __"*n:e
{e" ""\\"if"__/ \\"b*o{"__"e{"":e}"/"if}{"":e}if n
"/"" \\__/"b*o" \\"""if n}r*
"\\__/ "b o+*
C89 - 261 necessary chars
All white spaces can be removed. My solution uses rotation of the board...
x,y,W,h,B[999],*a,*b,*c,*d;
main(w){
for(scanf("%d%d",&h,&w);y<h;y++,*b++ = *c++ = 63)
for(x=0,
W=w*2+2-(h==1),
a=B+y*W*3+y%2,
b=a+W,
c=b+W,
d=c+W;x++<w;)
*a++ = 60,
*a++ = *d++ = 15,
*b++ = *c++ = 63,
*b++ = *c++ = 0,
*d++ = 60;
for(x=W;--x>=0;puts(""))
for(y=0;y<h*3+1;putchar(B[x+y++*W]+32));
}
F#, 303 chars
let[|x;y|]=System.Console.ReadLine().Split([|' '|])
let p=printf
let L s o e=p"%s"s;(for i in 1..int x do p"%s"(if i%2=1 then o else e));p"\n"
if int x>1 then L" "" "" __ ";L" ""__""/ \\"
else L" ""__"""
for i in 1..int y-1 do(L"/"" \\""__/";L"\\""__/"" \\")
L"/"" \\""__/"
L"""\\__/"" "
EDIT
Now that there are finally some other answers posted, I don't mind sharing a less-obfuscated version:
let [|sx;sy|] = System.Console.ReadLine().Split([|' '|])
let x,y = int sx, int sy
let Line n start odd even =
printf "%s" start
for i in 1..n do
printf "%s" (if i%2=1 then odd else even)
printfn ""
// header
if x > 1 then
Line x " " " " " __ "
Line x " " "__" "/ \\"
else
Line x " " "__" " "
// body
for i in 1..y-1 do
Line x "/" " \\" "__/"
Line x "\\" "__/" " \\"
// footer
Line x "/" " \\" "__/"
Line x "" "\\__/" " "
C# 377 chars
Didn't want to disappoint anyone waiting for the "funny" C# answer.
Unfortunately, it's not 250 lines though...;)
using System;
class P{
static void Main(string[] a){
int i,j,w=Int32.Parse(a[0]),h=Int32.Parse(a[1]);
string n="\n",e="",o=e,l="__",s=" ",r=s+s,b=#"\",f="/";
string[] t={r+r,l,b+l+f,r,l,f+r+b,e,f,b,s};
for(i=0;i<w;)o+=t[i++%2];
for(i=0;i<2*h;i++){
o+=n+(i%2==0?i!=0?b:s:e);
for(j=0;j<w;)
o+=t[((j+++i)%2)+4];
o+=i!=0?t[((w+i)%2)+6]:e;
}
o+=n;
for(i=0;i<w;)o+=t[i++%2+2];
Console.Write(o);
}
}
Groovy, #375 chars
Same logic & code that #markt implemented in c#, but have changed few places for Groovy :)
public class FunCode {
public static void main(a) {
int i,j,w=Integer.parseInt(a[0]),h=Integer.parseInt(a[1]);
String n="\n",e="",o=e,l="__",s=" ",r=s+s,b="\\",f="/";
def t=[r+r,l,b+l+f,r,l,f+r+b,e,f,b,s];
for(i=0;i<w;)o+=t[i++%2];
for(i=0;i<2*h;i++){
o+=n+(i%2==0?i!=0?b:s:e);
for(j=0;j<w;)
o+=t[((j+++i)%2)+4];
o+=i!=0?t[((w+i)%2)+6]:e;
}
o+=n;
for(i=0;i<w;)o+=t[i++%2+2]; println(o);
}
}
Lua, 227 characters
w,h,s=io.read("*n"),io.read("*n")*2+2," " for i=1,h do b=(i%2>0 and "/ \\__" or "\\__/ "):rep(w/2+1):sub(1,w*3+1) print(i==1 and b:gsub("[/\\]",s) or i==2 and b:gsub("^\\",s):gsub("/$",s) or i==h and b:gsub("\\$",s) or b) end
208 characters, when width and height are read from command line.
s,w,h=" ",... h=h*2+2 for i=1,h do b=(i%2>0 and "/ \\__" or "\\__/ "):rep(w/2+1):sub(1,w*3+1) print(i==1 and b:gsub("[/\\]",s) or i==2 and b:gsub("^\\",s):gsub("/$",s) or i==h and b:gsub("\\$",s) or b) end

Code Golf: Hourglass

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
The challenge
The shortest code by character count to output an hourglass according to user input.
Input is composed of two numbers: First number is a greater than 1 integer that represents the height of the bulbs, second number is a percentage (0 - 100) of the hourglass' capacity.
The hourglass' height is made by adding more lines to the hourglass' bulbs, so size 2 (the minimal accepted size) would be:
_____
\ /
\ /
/ \
/___\
Size 3 will add more lines making the bulbs be able to fit more 'sand'.
Sand will be drawn using the character x. The top bulb will contain N percent 'sand' while the bottom bulb will contain (100 - N) percent sand, where N is the second variable.
'Capacity' is measured by the amount of spaces () the hourglass contains. Where percentage is not exact, it should be rounded up.
Sand is drawn from outside in, giving the right side precedence in case percentage result is even.
Test cases
Input:
3 71%
Output:
_______
\x xx/
\xxx/
\x/
/ \
/ \
/__xx_\
Input:
5 52%
Output:
___________
\ /
\xx xx/
\xxxxx/
\xxx/
\x/
/ \
/ \
/ \
/ xxx \
/xxxxxxxxx\
Input:
6 75%
Output:
_____________
\x x/
\xxxxxxxxx/
\xxxxxxx/
\xxxxx/
\xxx/
\x/
/ \
/ \
/ \
/ \
/ \
/_xxxxxxxxx_\
Code count includes input/output (i.e full program).
C/C++, a dismal 945 characters...
Takes input as parameters:
a.out 5 52%
#include<stdio.h>
#include<memory.h>
#include<stdlib.h>
#define p printf
int h,c,*l,i,w,j,*q,k;const char*
z;int main(int argc,char**argv)
{h=atoi(argv[1]);c=(h*h*atoi(
argv[2])+99)/100;l=new int[
h*3];for(q=l,i=0,w=1;i<h;
i++,c=(c-w)&~((c-w)>>31
),w+=2)if(c>=w){*q++=
0;*q++ =0;* q++=w;}
else {*q++=(c+1)/
2;*q++=w-c;*q++
=c/2;}p("_");
for(i=0;i<h
;i ++)p (
"__");p
("\n"
);q
=
l+h
*3-1;
for (i=
--h;i>=0;
i--){p("%*"
"s\\",h-i,"")
; z= "x\0 \0x";
for(k=0;k<3;k++,q
--,z+=2)for(j=0;j<*
q;j++)p(z);q-=0;p("/"
"\n");}q=l;for(i=0;i<=h
;i++){z =i==h? "_\0x\0_":
" \0x\0 ";p("%*s/",h-i,"");
for(k=0;k<3;k++,q++,z+=2)for(
j=0;j<*q;j++)p(z);p("\\\n") ;}}
...and the decrypted version of this for us mere humans:
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>
#define p printf
int h, c, *l, i, w, j, *q, k;
const char *z;
int main(int argc, char** argv)
{
h = atoi(argv [1]);
c = (h*h*atoi(argv[2])+99)/100;
l = new int[h*3];
for (q = l,i = 0,w = 1; i<h; i++,c = (c-w)&~((c-w)>>31),w += 2) {
if (c>=w) {
*q++ = 0;
*q++ = 0;
*q++ = w;
} else {
*q++ = (c+1)/2;
*q++ = w-c;
*q++ = c/2;
}
}
p("_");
for (i = 0; i<h; i++) {
p("__");
}
p("\n");
q = l+h*3-1;
for (i = --h; i>=0; i--) {
p("%*s\\",h-i,"");
z = "x\0 \0x";
for (k = 0; k<3; k++,q--,z += 2) {
for (j = 0; j<*q; j++) {
p(z);
}
}
p("/\n");
}
q = l;
for (i = 0; i<=h; i++) {
z = i==h ? "_\0x\0_" : " \0x\0 ";
p("%*s/",h-i,"");
for (k = 0; k<3; k++,q++,z += 2) {
for (j = 0; j<*q; j++) {
p(z);
}
}
p("\\\n") ;
}
}
Perl, 191 char
205 199 191 chars.
$S=-int((1-.01*pop)*($N=pop)*$N)+$N*$N;$S-=$s=$S>++$r?$r:$S,
$\=$/.$"x$N."\\".x x($v=$s/2).$"x($t=$r++-$s).x x($w=$v+.5)."/$\
".$"x$N."/".($^=$N?$":_)x$w.x x$t.$^x$v."\\"while$N--;print$^x++$r
Explicit newline required between the 2nd and 3rd lines.
And with help of the new Acme::AsciiArtinator module:
$S=-int((1-.01*pop)*($N=pop
) *
$ N
) +
$ N
*$N;( ${B},$
F,${x})=qw(\\ / x
);while($N){;/l
ater/g;$S-=$s
=$S>++$r?$r
:$S;'than
you';#o
=(" "
x--
$ N
. $
B .
x x
( $
v =
$ s
/ 2
) .$"x($t= $
r++-$s).x x($w=$v+.5)
.$F,#o,$"x$N.$F.($^=$N?
$":_)x$w.x x$t.$^x$v.$B);
$,=$/}print$^x++$r,#o;think
Golfscript - 136 Chars (Fits in a Tweet)
Be sure not to have a newline after the % for the input
eg
$ echo -n 3 71%|./golfscript.rb hourglass.gs
You can animate the hourglass like this:
$ for((c=100;c>=0;c--));do echo -n "15 $c%"|./golfscript.rb hourglass.gs;echo;sleep 0.1;done;
Golfscript - 136 Chars
Make sure you don't save it with an extra newline on the end or it will print an extra number
);' ': /(~:
;0=~100.#-
.**\/:t;'_':&&
*.n
,{:y *.'\\'+{[&'x':x]0t(:t>=}:S~
(y-,{;S\+S+.}%;'/'++\+}%.{&/ *}%\-1%{-1%x/ *&/x*}%) /&[*]++n*
Golfscript - 144 Chars
);' ':|/(~:^.*:X
;0=~100.#-X*\/
X'x':x*'_':&
#*+:s;&&&+
^*n^,{:y
|*.[92
]+{s
[)
\#
:s;]
}:S~^(
y-,{;S\+
S+.}%;'/'+
+\+}%.{&/|*}
%\-1%{-1%x/|*&
/x*}%)|/&[*]++n*
How it works
First do the top line of underscores which is 2n+1
Create the top half of the hourglass, but use '_' chars instead of spaces, so for the 3 71% we would have.
\x__xx/
\xxx/
\x/
Complete the top half by replacing the "_" with " " but save a copy to generate the bottom half
The bottom half is created by reversing the whole thing
/x\
/xxx\
/xx__x\
Replacing all the 'x' with ' ' and then then '_' with 'x'
/ \
/ \
/ xx \
Finally replace the ' ' in the bottom row with '_'
/ \
/ \
/__xx_\
Roundabout but for me, the code turned out shorter than trying to generate both halves at once
Python, 213 char
N,p=map(int,raw_input()[:-1].split())
S=N*N-N*N*(100-p)/100
_,e,x,b,f,n=C='_ x\/\n'
o=""
r=1
while N:N-=1;z=C[N>0];s=min(S,r);S-=s;t=r-s;v=s/2;w=s-v;r+=2;o=n+e*N+b+x*v+e*t+x*w+f+o+n+e*N+f+z*w+x*t+z*v+b
print _*r+o
Rebmu: 188 chars
rJ N 0% rN Wad1mpJ2 S{ \x/ }D0 Hc&[u[Z=~wA Qs^RTkW[isEL0c[skQdvK2][eEV?kQ[tlQ]]pcSeg--B0[eZ1 5]3]prRJ[si^DspSCsQfhS]eZ1[s+DcA+wMPc2no]]]Va|[mpAj**2]prSI^w{_}Ls+W2 h1tiVsb1n -1 chRVs{_}hLceVn1
It's competitive with the shorter solutions here, though it's actually solving the problem in a "naive" way. More or less it's doing the "sand physics" instead of exploiting symmetries or rotating matrices or anything.
H defines a function for printing a half of an hourglass, to which you pass in a number which is how many spaces to print before you start printing "x" characters. If you're on the top half, the sand string is constructed by alternating appends to the head and the tail. If you're on the bottom it picks the insertion source by skipping into the middle of the string. Commented source available at:
http://github.com/hostilefork/rebmu/blob/master/examples/hourglass.rebmu
But the real trick up Rebmu's sleeve is it's a thin dialect that doesn't break any of the parsing rules of its host language (Rebol). You can turn this into a Doomsday visualization by injecting ordinary code right in the middle, as long you code in lowercase:
>> rebmu [rJ birthday: to-date (ask "When were you born? ") n: (21-dec-2012 - now/date) / (21-dec-2012 - birthday) Wad1mpJ2 S{ \x/ }D0 Hc~[u[Ze?Wa Qs^RTkW[isEL0c[skQdvK2][eEV?kQ[tlQ]]pcSeg--B0[eZ1 5]3]prRJ[si^DspSCsQfhS]eZ1[s+DcA+wMPc2no]]]Va|[mpAj**2]prSI^w{_}Ls+W2h1tiVsb1n -1 chRVs{_}hLceVn1]
Input Integer: 10
When were you born? 23-May-1974
_____________________
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\x xx/
\xxx/
\x/
/ \
/ \
/ xx \
/xxxxxxx\
/xxxxxxxxx\
/xxxxxxxxxxx\
/xxxxxxxxxxxxx\
/xxxxxxxxxxxxxxx\
/xxxxxxxxxxxxxxxxx\
/xxxxxxxxxxxxxxxxxxx\
O noes! :)
(Note: A major reason I'm able to write and debug Rebmu programs is because I can break into ordinary coding at any point to use the existing debugging tools/etc.)
Haskell. 285 characters. (Side-effect-free!)
x n c=h s++'\n':reverse(h(flip s)) where h s=r w '-'++s '+' b(w-2)0 p;w=(t n);p=d(n*n*c)100
s x n i o p|i>0='\n':l++s x n(i-2)(o+1)(max(p-i)0)|True=[] where l=r o b++'\\':f d++r(i#p)n++f m++'/':r o b;f g=r(g(i-(i#p))2)x
b=' '
r=replicate
t n=1+2*n
d=div
(#)=min
m=(uncurry(+).).divMod
Run with e.g. x 5 50
A c++ answer, is 592 chars so far, still having reasonable formatting.
#include<iostream>
#include<string>
#include<cstdlib>
#include<cmath>
using namespace std;
typedef string S;
typedef int I;
typedef char C;
I main(I,C**v){
I z=atoi(v[1]),c=z*z,f=ceil(c*atoi(v[2])/100.);
cout<<S(z*2+1,'_')<<'\n';
for(I i=z,n=c;i;--i){
I y=i*2-1;
S s(y,' ');
C*l=&s[0];
C*r=&s[y];
for(I j=0;j<y;++j)
if(n--<=f)*((j&1)?l++:--r)='x';
cout<<S(z-i,' ')<<'\\'<<s<<"/\n";
}
for(I i=1,n=c-f;i<=z;++i){
I y=i*2-1;
S s(y,'x');
C*l=&s[0];
C*r=&s[y];
for(I j=0;j<y;++j)
if(n++<c)*(!(j&1)?l++:--r)=(i==z)?'_':' ';
cout<<S(z-i,' ')<<'/'<<s<<"\\\n";
}
}
If i decide to just forget formatting it reasonably, i can get it as low as 531:
#include<iostream>
#include<string>
#include<cstdlib>
#include<cmath>
using namespace std;typedef string S;typedef int I;typedef char C;I main(I,C**v){I z=atoi(v[1]),c=z*z,f=ceil(c*atoi(v[2])/100.);cout<<S(z*2+1,'_')<<'\n';for(I i=z,n=c;i;--i){I y=i*2-1;S s(y,' ');C*l=&s[0];C*r=&s[y];for(I j=0;j<y;++j)if(n--<=f)*((j&1)?l++:--r)='x';cout<<S(z-i,' ')<<'\\'<<s<<"/\n";}for(I i=1,n=c-f;i<=z;++i){I y=i*2-1;S s(y,'x');C*l=&s[0];C*r=&s[y];for(I j=0;j<y;++j)if(n++<c)*(!(j&1)?l++:--r)=(i==z)?'_':' ';cout<<S(z-i,' ')<<'/'<<s<<"\\\n";}}
Bash: 639 - 373 characters
I thought I would give bash a try (haven't seen much code-golfing in it). (my version: GNU bash, version 3.2.48(1)-release (i486-pc-linux-gnu))
Based on Mobrule's nice python answer.
Optimizations must still be available, so all suggestions are welcome!
Start from the command line, e.g. : ./hourglass.sh 7 34%
function f () { for i in `seq $1`;do printf "$2";done; }
N=$1;S=$[$1*$1-$1*$1*$[100-${2/\%/}]/100]
b='\';o=$b;n="\n";r=1;while [ $N -gt 0 ];do
N=$[N-1];z=" ";s=$r;[ $N -eq 0 ]&& z=_;[ $S -lt $r ]&& s=$S
S=$[S-s];t=$[r-s];v=$[s/2];w=$[s-v];r=$[r+2]
o=$n`f $N " "`$b`f $v x;f $t " ";f $w x`/$o$b$n`f $N " "`/`f $w "$z";f $t x;f $v "$z"`$b
done;f $r _;echo -e "${o/\/\\\\//}"
Java; 661 characters
public class M{public static void main(String[] a){int h=Integer.parseInt(a[0]);int s=(int)Math.ceil(h*h*Integer.parseInt(a[1])/100.);r(h,h-1,s,true);r(h,h-1,s,false);}static void r(int h,int c,int r,boolean t){if(c<0)return;int u=2*(h-c)-1;if(t&&c==h-1)p(2*h+1,0,'_','_',true,0,false);int z=r>=u?u:r;r-=z;if(t)r(h,c-1,r,true);p(u,z,t?'x':((c==0)?'_':' '),t?' ':'x',t,c,true);if(!t)r(h,c-1,r,false);}static void p(int s,int n,char o,char i,boolean t,int p,boolean d){int f=(s-n);int q=n/2+(!t&&(f%2==0)?1:0);int e=q+f;String z = "";int j;for(j=0;j<p+4;j++)z+=" ";if(d)z+=t?'\\':'/';for(j=0;j<s;j++)z+=(j>=q&&j<e)?i:o;if(d)z+=t?'/':'\\';System.out.println(z);}}
I need to find a better set of golf clubs.
PHP - 361
<?$s=$argv[1];$x='str_pad';$w=$s*2-1;$o[]=$x('',$w+2,'_');
$r=$s*ceil($w/2);$w=$r-($r*substr($argv[2],0,-1)/100);$p=0;
$c=-1;while($s){$k=$s--*2-1;$f=$x($x('',min($k,$w),' '),$k,'x',2);
$g=$x($x('',min($k,$w),'x'),$k,' ',2);$w-=$k;$o[]=$x('',$p)."\\$f/";
$b[]=$x('',$p++)."/$g\\";}$b[0]=str_replace(' ','_',$b[0]);
krsort($b);echo implode("\n",array_merge($o,$b));?>
Python - 272 chars
X,p=map(int,raw_input()[:-1].split())
k=X*X;j=k*(100-p)/100
n,u,x,f,b,s='\n_x/\ '
S=list(x*k+s*j).pop;T=list(s*k+u*(2*X-j-1)+x*j).pop
A=B=""
for y in range(X):
r=S();q=T()
for i in range(X-y-1):r=S()+r+S();q+=T();q=T()+q
A+=n+s*y+b+r+f;B=n+s*y+f+q+b+B
print u+u*2*X+A+B
Exabyte18's java converted to C#, 655 bytes:
public class M {public static void Main(){int h = Convert.ToInt32(Console.ReadLine());
int s = Convert.ToInt32(h * h * Convert.ToInt32(Console.ReadLine()) / 100);r(h,h-1,s,true);
r(h,h-1,s,false);Console.ReadLine();}static void r(int h, int c, int r, bool t){
if(c<0) return;int u=2*(h-c)-1;if (t&&c==h-1)p(2*h+1,0,'_','_',true,0,false);
int z=r>=u?u:r; r-=z;if (t)M.r(h,c-1,r,true); p(u,z,t?'x':((c==0)?'_':' '), t?' ':'x',t,c,true);
if(!t)M.r(h,c-1,r,false);}static void p(int s, int n, char o, char i, bool t, int p, bool d)
{int f=(s-n);int q=n/2+(!t&&(f%2==0)?1:0);int e=q+f;string z="";int j;for(j=0;j<p+4;j++) z+=" ";if(d)z+=t?'\\':'/';
for (j=0;j<s;j++) z+=(j>=q&&j<e)?i:o; if(d)z+=t?'/':'\\';Console.WriteLine(z);}}
Ruby, 297 254 (after compression)
Run both with ruby -a -p f.rb
n,p = $F.map{|i|i.to_i}
r="\n"
y=''
g,s,u,f,b=%w{x \ _ / \\}
$> << u*2*n+u+r # draw initial underbar line
a=u
c=100.0/n/n # amount of sand a single x represents
e = 100.0 # percentage floor to indicate sand at this level
n.times{ |i|
d=2*n-1-2*i # number of spaces at this level
e-= c*d # update percentage floor
x = [((p - e)/c+0.5).to_i,d].min
x = 0 if x<0
w = x/2 # small half count
z = x-w # big half count
d = d-x # total padding count
$> << s*i+b+g*w+s*d+g*z+f+r
y=s*i+f+a*z+g*d+a*w+b+r+y
a=s
}
$_=y
Ruby, 211
This is mobrule's tour de force, in Ruby. (And still no final newline. :-)
m,p=$F.map{|i|i.to_i}
q=m*m-m*m*(100-p)/100
_,e,x,b,f=%w{_ \ x \\ /}
n="\n"
o=''
r=1
while m>0
m-=1
z=m>0?e:_
s=q<r ?q:r
q-=s
t=r-s
v=s/2
w=s-v
r=r+2
o=n+e*m+b+x*v+e*t+x*w+f+o+n+e*m+f+z*w+x*t+z*v+b
end
$_=_*r+o

Code Golf: Running Water

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
The challenge
The shortest code by character count to identify and mark water depressions in the ASCII representation of a land from input.
Input will be an ASCII representation of a landscape, having hills, valleys and flat lands. The program should simulate what the landscape would look like if if was flooded - filling all valleys with water (character x).
The landscape will always start and stop with the character _ and will be at least 2 characters long, making the shortest input __.
A hill is defined as a raise, and should not be filled with water:
__
_/ \_
A valley is defined as a depression and will be filled with water until a flatland is encountered:
_ _
\__/
Input can be assumed clean and will be composed only from the characters space (), newline (\n), underscore (_), and forward and backward slashes (/ and \). Input can be seen as a continuous line, and any input that contains ambiguous line input such as _/_ or
_ _
\_/
/ \
Is considered invalid.
Regarding underwater caves, water level should be maintained if cave level goes above water level.
Test cases
Input:
__/\__
\__
\ ___ ___________
/ / \_ \_
\_____/ \__ _/
\/
Output:
__/\__
\__
\ ___ ___________
/xxxxxx/ \xxxxxx\_
\xxxxx/ \xxxxx/
\/
Input:
__ ___
/ \_____/
/ _______
________ / \ /
_____/ \ /__ \ \_
____ / \ /__/ __/
\_ / \ ____/
\______\ /____/
Output:
__ ___
/ \xxxxx/
/ _______
________ / \ /
_____/ \xxx/__ \xxxx\_
____ / \xxxx/__/xxxxx/
\xxxxxxxx/ \xxxxxxxxx/
\xxxxxx\ /xxxx/
Input:
__ _
_ ____ ____ _____/ \ /
\ / \ __________/ \ __/ ___ /___\
\___/ \ \ \ \___/ /_
/________\ \___________\
Output:
__ _
_ ____ ____ _____/ \xxx/
\xxxxx/ \xxxxxxxxxxxxxxxxxx/ \xxxxxx/ ___ /xxx\
\xxx/ \xxxxxxx\ \xxx\___/xx/_
/xxxxxxxx\ \xxxxxxxxxxx\
Code count includes input/output (i.e full program).
C - 741 621 600 characters (but handles the new cases properly)
$ gcc water.c && ./a.out < test6.txt
__ ___
/ \xxxxx/
/ _______
________ / \ /
_____/ \xxx/__ \xxxx\_
____ / \xxxx/__/xxxxx/
\xxxxxxxx/ \xxxxxxxxx/
\xxxxxx\ /xxxx/
#include<stdio.h>
char d[99][99],*p,*e,*z,*s=d,c,S=' ',D='-',O='.',U='_';n,w,x,N=99,i;
g(y){for(i=0;!i;p+=N,e+=N){i=*p==D;for(z=p;z!=e;z+=y){if(*z!=O&&*z!=
D)break;*z=*z==O?S:U;}}}f(char*n,int r){if(*n==O||*n==D){*n=r>0?'x':
S;int k;for(k=0;k<9;k++)f(n+k/3*N-N+k%3-1,r+k/3-1);}}main(){for(p=s;
gets(p);p+=N,n++){x=strlen(p)-1;w=x>w?x:w;}for(p=s,e=d[N];p<s+N;p++)
{for(i=1,z=p;z<e;z+=N)c=*z,c==0?*z=c=S:0,i?c==S?*z=O:c==U?*z=D:0:0,(
c=='/'&&z[1]!=U)||(c=='\\'&&z[-1]!=D)||c==U?i=1-i:0;}p=s;e=s+w;g(1);
p=s+w;e=s;g(-1);for(p=s;p<s+w;p++){for(z=p;*z==S;z+=N);f(z,1);}for(i
=0;i<n;i++)printf("%.*s\n",w+1,d[i]);}
Ruby, 794 759 769 752 715 692 663 655 626 616
Additional test cases:
http://pastie.org/708281 and
http://pastie.org/708288 and
http://pastie.org/708310
Compressed except for indent:
def g i,j,&f
t=[-1,0,1]
t.each{|r|next if#w[i][j,1]=='_'&&r>0
t.each{|c|a=i+r
b=j+c
if a>=0&&b>=0&&a<#r&&b<#c
#t[a]||=[]
if r!=0&&c!=0
k=#w[a][j,1]
l=#w[i][b,1]
next if/[\/\\]/=~k+l&&((k!=l)||((r<=>0)==(c<=>0)?k!='\\': k!='/'))
end
e=#w[a][b,1]
z,#t[a][b]=#t[a][b],1
return 1if !z&&(e==' '||r>=0&&e=='_')&&yield(a,b,f)
end}}
nil
end
w=$stdin.readlines
#c=w.map{|e|e.size}.max-1
#w=w=w.map{|e|e.chomp.ljust#c}
z=w.map{|e|e.dup}
#r=w.size
#r.times{|r|#m=r
#c.times{|c|e=w[r][c,1]
z[r][c]='x'if(e==' '||e=='_')&&(#t=[]
!g(r,c){|u,v,f|u>=#m and v==0||v==#c-1||g(u,v,&f)})&&(#t=[]
g(r,c){|u,v,f|u==0||g(u,v,&f)})}}
puts z
Python, 702 805 794 778 758 754 710 651
Handles DigitalRoss's test cases, as well as large test cases such as http://pastie.org/708764.
Example run
$ python runningwater.py < test4.txt
____________________________
/
_ \ __
/ \xxxxx/ / \
___ _____/ /xxx/ / \
____________ / \xxxxx/ ____/xxx/ __ /xxxxxx\
\xxx/ /xxxxx\__ \xxxxxx/ /xx\___/xxxxxxx/
___/xxxxxxxxx\____ /xxxxxxxxxxxxxx/
/xxxxx/ \xxxxx\__/x/ \xxxxxxx/
/xxxxx/ \xxxxxxxx/ \xxxxx/
\xxxxx\ _________ \xxx/
\xxx\ /xxxxxxxxx\ /xx/
\x\ \x\ /\ \x\ /xx/
__________ \x\ \x\_/x/ /x/ /xx/
/xxxxxxxxxx\ \x\ \xxx/ /x/ /xx/
/xxxxxxxxxxxx\ \x\ \x/ /x/ /xx/
\xxxxxxxxxxxxx\ \x\ /x/ /xx/
\xxxxxxx\ \x\_/x/ /xx/
____/xxx/ \xx\ \xxx/ /xx/
\xxxxxx/ \xx\___________________/xx/
\xx/ \xxxxxxxxxxxxxxxxxxxxxxx/
Code
import sys
q=sys.stdin.readlines()
e=enumerate
s=type
k=int
o=[]
t=[0]*max(map(len,q))
n=1
L=[]
l={}
for p,d in e(q):
w=a=0;o+=[[]]
for i,c in e(d):
T=t[i];C=[[c,T]];D=d[i+1:];b=0;o[-1]+=C;L+=C
if c in'_ ':
if('/'in D or '\\'in D)*(T%2-1)*w*p:
for j in range(max(i-1,0),min(i+2,len(o[p-1]))):R=o[p-1][j][0];b=R*(k==s(R))or b
for x in L:x[0]=b*(x[0]==a)or x[0]
a=C[0][0]=b or a or n
elif c in'\\/':w=1;a=0;n+=1
D=d[i-1]+c;t[i-1]+=(D=='/_');t[i]+=(c in'_/\\')+(D=='_\\')
for i,a in e(o):
for c,r in a:
if(r==0)*(s(c)==k):l[c]=1
for j,(c,r)in e(a):
if(c in l)-1:a[j]=q[i][j],0
print''.join((k==s(x))*'x'or x for x,r in a),
Perl, 534 545 550 566 569 567 578 594 596
sub i{$a=1;$a^=substr(x.$l[$_],$_[0],3)=~/^(.[_y]|.\/[^_]|[^_]\\)/for 0..$r-1;
$a}sub f{$c=$e-$s;$_=$l[$r];$f=s/(.{$s})(.{0,$c})/$1<$2>/;(/[ _x]>/&i$e-1and$f=
/>[ _xy]*[\\\/]/,$e=$+[0]-2)or/[ _]*>/,$e=$-[0]-1;(/<[ _x]/&i$s and$f&=
/[\\\/][ _xy]*</,$s=$-[0])or/<[ _]*/,$s=$+[0]-1;$f&$s<$e&&substr($l[$r],$s,$e-$s
)=~s!([\\/][ _xy]*)([\\/][ _]*)!($t=$1)=~y/ _/xy/,$t.$2!eg,$r--&&&f}$q=#l=<>;
while($q--){i$-[0]+1and substr($l[$r--],$-[1],length$1)=~y/_y/x/,$s=$-[0],$e=
$+[0],$q&&f while$l[$r=$q]=~m~\\/|[\\/]([_y]+)[\\/]~g}y/y/x/,print for#l
This handles all the test cases that I've seen. Newlines are optional and are only there for formatting.
Call it as e.g. perl water.pl test.txt.
Here's another funny edge case (for my algorithm anyway) not in any of the previous examples:
__ _
\__ /
/_/
The verbose version I'd put up earlier still fails on that.