简体   繁体   English

如何使用递归打印1到5和5到1?

[英]how to print 1 to 5 and 5 to 1 using recursion…?

I wanted to print numbers 5-0 then 0-5 in the order with shortest Lines of code. 我想按最短代码行的顺序打印数字5-0然后是0-5。 Here's what I implemented. 这是我实现的。 However, looking for any other logic with less number of lines of code. 但是,寻找其他更少代码行的逻辑。 Looking forward for your replies please. 请期待您的答复。 Thanks, 谢谢,

            <html>
                <body>  
                    <script>
                    var n;
                    function count(n){
                        console.log(n);
                        if(n>=1){
                            return count(n-1);
                        }
                        else{
                            n=1;
                            count2(n);
                        }
                    }
                    function count2(n){
                        console.log(n);
                        if(n<5){
                            count2(n+1);
                        }
                    }
                    count(5);
                    </script>
                </body>
            </html>

Your recursive attempt could be written like this: 您的递归尝试可以这样写:

 function count(n, limit=-n){ console.log(Math.abs(n)); if (n>limit) count(n-1, limit); } count(5); 

In a non-recursive version it would be: 在非递归版本中,它将是:

 function count(n) { for (let i = -n; i <= n; i++) console.log(Math.abs(i)); } count(5); 

you have no need to use recursion for this. 您无需为此使用递归。 Simply use for loops 只需使用循环

let number = 5
//from 1 to your desired number
for(let i = 1;i<=number;i++){
    console.log(i);
}
//from your desired number to 1 
for(let i = number;i>0;i--){
    console.log(i);
}

Changing the step: 更改步骤:

function ctn(num) {
    let i = -1, n = num++;
    do {
        console.log(n);
        n || (i = 1);
    } while ( (n += i) < num);
}

You can use iteration. 您可以使用迭代。 smallest i can think of 我能想到的最小的

 console.log('forward'); [...'12345'].forEach(e=>console.log(e)); console.log('reverse'); [...'54321'].forEach(e=>console.log(e)); 

It can take any no., any increment (inc) 可以取任何编号,可以任意增加(增量)

 const print = (i=5, flow=1, inc=-1) => { console.log(i); if(i===0 && flow===1){ print(i+1,flow+1, 1); return; } if(i===5 && flow===2){ return; } print(i+inc, flow, inc); } print(); 

Here is a version using generators just for the sake of it! 这是仅出于此目的而使用生成器的版本!

It creates an array from the output and does the console.log all in one go. 它从输出创建一个数组,然后一次完成console.log。

 function* count(n, max = n) { yield n > 0 ? n : -n; if (n > -max) yield* count(n-1, max); } console.log(Array.from(count(5))) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM