如何在具有越来越多参数的电源循环中使用递归? [英] How to use recursion in a power loop with growing number of parameters?

查看:61
本文介绍了如何在具有越来越多参数的电源循环中使用递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个典型的电源循环问题,我只需要简单而优雅(紧凑) )解决方案......我将用嵌套for循环显示问题/解决方案的样本。假设我需要将这段代码转换为递归:

This is a typical Power Loop problem, and I only need a simple and elegant (compact) solution... I will show fist the sample of problem/solution with nested for loops. Suppose that I need to transform this piece of code into a recursion:

console.log("bits","Binary")
for (let i=0; i<2; i++) {
    show(i)
    for (let j=0; j<2; j++) {
      show(i,j)
      for (let k=0; k<2; k++)
        show(i,j,k) // ... l,m,n,o,p
  } // j
} // i

function show(...args) {
   let code = String( args.reduce( (ac,cur) => ''+ac+cur ) )
   console.log( code.length, code )
}

这个3级样本的14个独特行输出是

The 14-unique-lines output of this 3-level sample is

bits Binary
1 '0'
2 '00'
3 '000'
3 '001'
2 '01'
3 '010'
3 '011'
1 '1'
2 '10'
3 '100'
3 '101'
2 '11'
3 '110'
3 '111'






丑陋和部分解决方案



我试图用as作为参考来解决此解决方案

callManyTimes([2,2,2], show);

function callManyTimes(maxIndices, func) {
    doCallManyTimes(maxIndices, func, [], 0);
}

function doCallManyTimes(maxIndices, func, args, index) {
    if (maxIndices.length == 0) {
        let x = args.slice(0); // cloning
        while(x.length>0) {
          func(x); // why send array[array]?
          x.shift();
        }
    } else {
        var rest = maxIndices.slice(1);
        for (args[index] = 0; args[index] < maxIndices[0]; ++args[index]) {
            doCallManyTimes(rest, func, args, index + 1);
        }
    }
}

function show(...args) {
   if (typeof args[0] == 'object') args=args[0] // workaround... can optimize?
   let code = String( args.reduce( (ac,cur) => ''+ac+cur ) )
   console.log( code.length, code )
}

输出有重复的行,但有一部分行是解决方案...所以,似乎附近,但很丑(没有优雅使用重复堆栈等)。

The output have duplicated lines, but there are a subset of lines that are the solution... So, seems near, but is ugly (no elegant use of the recurrence stack, etc.)

3 '000'
2 '00'
1 '0'
3 '001'
2 '01'
1 '1'
3 '010'
2 '10'
1 '0'
3 '011'
2 '11'
1 '1'
...


推荐答案

您可以使用一个为生成的值采用临时数组的函数。

You could take a function which takes a temporary array for the generated values.

function show(...args) {
    let code = args.join('');
    console.log(code.length, code);
}

function callManyTimes(max, cb, items = []) {
    var i, temp;
    if (items.length === max.length) return;
    for (i = 0; i < max[items.length]; i++) {
        temp = items.concat(i);
        cb(...temp);
        callManyTimes(max, cb, temp);
    }
}

callManyTimes([2, 2, 2], show);

这篇关于如何在具有越来越多参数的电源循环中使用递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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