How to calculate this sequence iteratively?

2019-05-09 23:30发布

问题:

I want calculate this sequence iteratively.

A(0,j)=j+1
A(i,0)=A(i-1,0)
A(i,j)=A(i-1,A(i,j-1))

This is my try

    public function calculsuite1Action($i,$j)
{
    $A = array();
    for ($k = 0; $k <= $i * $i * $i + $j; $k++) {
        $A[0][$k] = $k + 1;
    }
    for ($c = 1; $c <= $i; $c++) {
        for ($k = 0; $k <= $i * $i * $i + $j - $c; $k++) {
            if ($k == 0) {
                $A[$c][$k] = $A[$c - 1][1];
            } else {
                $A[$c][$k] = $A[$c - 1][$A[$c][$k - 1]];
            }
            if ($c == $i && $k == $j) {
                return $A[$i][$j];
            }

        }
    }
}

I'm trying to find a solution using PHP or any other programming language. How can I do that?

回答1:

I have tried looking for a pattern for the first few entries. If I haven´t done any mistakes the sequence is pretty simple. It boils down to

A(i, j) = j+1

Just used this JavaScript program to verify I didn't make any mistakes

for (i = 0; i < 5; i++){
  for (j = 0; j < 5; j++){
    console.log("A("+i+", "+j+") = "+calc(i,j));
  }
}

function calc(i, j){
  if(i==0)
    return j+1;
  else if(j == 0)
    return calc(i-1, 0);
  else
    return calc(i-1, calc(i, j-1));
}



回答2:

Here's a stack implementation. Please see here for an explanation of how I converted the recursion.

JavaScript code:

/**
* A(0,j)=j+1
* A(i,0)=A(i-1,0)
* A(i,j)=A(i-1,A(i,j-1))
***/

// Recursive
function f(i,j){
  if (i == 0) return j+1
  else if (j == 0) return f(i-1,0)
  else return f(i-1,f(i,j-1))
}

// Iterative
function iterative(_i,_j){
  let result = undefined;
  let stack = [[f, [_i, _j]]];

  function g(i){
    let Aij_1 = result;
    stack.push([f, [i-1, Aij_1]]);
  }

  function f(i, j){
    if (!i){
        result = j + 1;
        
    } else if (!j){
        stack.push([f, [i-1, 0]]);
        
    } else {
        stack.push([g, [i]]);
        stack.push([f, [i, j-1]]);
    }
  }

  while (stack.length){
    [func, params] = stack.pop();
    func.apply(func, params);
  }

  return result;
}

for (let i=0; i<11; i++){
  for (let j=0; j<11; j++)
    // Log both iterative and recursive results for comparison
    console.log(
      '(' + i + ', ' + j + ') => ' +
      JSON.stringify([iterative(i,j), f(i,j)])
    );
}