Printing mountain ranges algorithm

风格不统一 提交于 2019-12-12 03:56:21

问题


  /\
 /  \
/    \



 /\/\
/    \ 

   /\  
/\/  \

 /\
/  \/\


/\/\/\

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 &nbsp; as

document.write(o.join('<br>').replace(/,\d?/g, r => '\\/' [r[1]] || '&nbsp;'));

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!