打印山脉算法 [英] Printing mountain ranges algorithm

查看:213
本文介绍了打印山脉算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  / \ 
/ \
/ \



/ \ / \\ \\
/ \

/ \
/ \ / \

/ \
/ \ / \

$ b $ \\ / \ / \

对于n = 3对的起伏,我有5种可能的方式来绘制这些山脉(我不应该低于x = 0轴)。当我在浏览器的控制台中打印这些输出时,我有以下长的JavaScript代码工作正常。但是,当我尝试输出为HTML的起伏不正确对齐。这是我的代码:

 < html> 


< script>
F = n =>对于(i = 1; i <1< m; i + = 2)
{
o = [],
= n + n

L = 0;
p = 1; (i& j)
{$($)


q = o [nl] || []
q [p] = 1;
o [n-1] = q
++ l;
}
else
{
--l;
if(l <0)continue outer;
q = o [n-1] || []
q [p] = 0;
$ n


if(l == 0)
{

console.log(o.join ('\ n')。replace(/,\ d?/ g,r =>'\\ /'[r [1]] ||'')); //在上面显示的控制台中工作良好。
document.write(o.join('< br>')。replace(/,\d?/ g,r =>'\\ /'[r [1]] || ''))//不要显示它们。





F(3);

< / script>

< / html>

它会像这样打印出来:

 / \ 
/ \
/ \

/ \ / \
/ \




$ \\ b $ b $ \\ b

/ \ / \ / \

有人知道我可以如何正确地输出它们吗? / p>

解决方案

你的问题是你正在使用''空格作为litteral空间。最好使用& nbsp; 作为

document.write(o.join('< br>')。replace(/,\ d?/ g,r =>'\\ /'[r [1]] ||'& amp另一件事,使用一个固定宽度的字体和适当的 line-height



获得更好的结果。



JSFiddle例子


  /\
 /  \
/    \



 /\/\
/    \ 

   /\  
/\/  \

 /\
/  \/\


/\/\/\

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 ?

解决方案

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

这篇关于打印山脉算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆