问题
/\
/ \
/ \
/\/\
/ \
/\
/\/ \
/\
/ \/\
/\/\/\
for n=3 pairs of ups and downs I have 5 possible way to draw these mountains.(I should never go below the x=0 axis). I have the following long javascript code which works fine when I print these outputs in the console of the browser.However when I try to output them as html the ups and downs are not correctly aligned. Here is my Code:
<html>
<script>
F=n=> {
m = n+n
outer:
for (i=1; i < 1<<m; i+=2)
{
o=[]
l=0;
p=1;
for (j = 1; j <1<<m; j+=j,p++)
{
if (i&j)
{
q=o[n-l]||[]
q[p]=1;
o[n-l]=q
++l;
}
else
{
--l;
if (l<0) continue outer;
q=o[n-l]||[]
q[p]=0;
o[n-l]=q
}
}
if (l==0)
{
console.log(o.join('\n').replace(/,\d?/g,r=>'\\/'[r[1]]||' ')); // WORKS FINE IN CONSOLE AS SHOWN IN ABOVE.
document.write(o.join('<br>').replace(/,\d?/g,r=>'\\/'[r[1]]||' ') ) // DOESNT PROPERLY SHOW THEM.
}
}
}
F(3);
</script>
</html>
It prints them like that :
/\
/ \
/ \
/\/\
/ \
/\
/\/ \
/\
/ \/\
/\/\/\
Does anybody know how I can properly output them ?
回答1:
Your problem is you are using ' '
spaces as litteral space. HTML doenst like literal spaces all that well.. Best to use
as
document.write(o.join('<br>').replace(/,\d?/g, r => '\\/' [r[1]] || ' '));
One other thing, use a fixed-width font and proper line-height
for better results.
JSFiddle Example
来源:https://stackoverflow.com/questions/41990386/printing-mountain-ranges-algorithm