2012-04-03 30 views
0

有人可以直觀地解釋這裏發生了什麼。另一個遞歸JavaScript函數

var stack = []; 

function countDown(int) { 
    stack.push(int); 
    if (int === 1) { 
     return 1; 
    } 
    return countDown(int - 1); 
} 

function multiplyEach() { 
    // Remove the last value of the stack 
    // and assign it to the variable int 
    int = stack.pop(); 
    x = stack.length; 
    // Base case 
    if (x === 0) { 
     return int; 
    } 
    // Recursive case 
    else { 
     stack[x - 1] = int * stack[x - 1]; 
     return multiplyEach(); 
    } 
} 

//調用函數

countDown(7); 

//然後打印出來()

console.log(multiplyEach()); 

我有幾分明白,就是它的堆疊建立並乘以multiplyEach返回的值一切都在一起,但我無法想象它。

然後:

Stack[x-1] is getting me 
+0

這個問題看起來不完整。你做完了嗎? – kojiro 2012-04-03 12:40:16

+0

良好的格式是開始理解代碼的好方法 – 2012-04-03 12:41:00

+0

我在試圖瞭解的手機上。格式不完美。這就是我的全部答案。問題已完成 – Sam 2012-04-03 12:48:48

回答

1

這是一個兩部分算法。

首先countDown(n)填充陣列stack與來自n值下降到1,所以stack = [n, n-1, n-2, ..., 3, 2, 1]countDown的返回值從不使用,因此可以忽略return語句。唯一重要的是它按照說明填充stack數組。

其次,multiplyEach反覆取堆的最後一個元素,將其刪除,與陣列中的下一個最後一個元素相乘:

[n, n-1, n-2, ..., 6, 5, 4, 3, 2, 1] 
[n, n-1, n-2, ..., 6, 5, 4, 3, 2] 
[n, n-1, n-2, ..., 6, 5, 4, 6] 
[n, n-1, n-2, ..., 6, 5, 24] 
[n, n-1, n-2, ..., 6, 120] 
... 
[n!] 

換句話說,該算法計算數的階乘n給予countDown

0

int被設置爲最後一個數組元素的值併除去從陣列,x被設定爲後pop長度stack陣列的,所以stack[x-1]是獲取「新」數組的最後一個元素。如果數組中還有東西,它將乘以int和新的最後一個元素(先前是倒數第二個元素),並將其存儲爲數組的最後一個元素。然後再次調用該過程,直到數組爲空並且所有數字相乘。

1
function countDown(int) { 
    stack.push(int); 
    if (int === 1) { 
    return 1; 
    } 
    return countDown(int - 1); 
} 

這個函數是整型值遞歸地增加了堆棧變量,當函數最終返回堆棧包含數字從int到1

詳細這裏是如何此功能工作

1-推INT到堆棧 2-如果int是等於1返回 3-否則調用COUNTDOWN(INT-1)

函數將遞歸調用自身,並保持推動INT到t他直到堆棧變爲1,所以最後的堆棧變量包含範圍[int, int-1, int-2, ... 1]。下列行示出了堆​​疊陣列的狀態的功能倒計時每次迭代

[int] 
[int, int-1] 
[int, int-1, int-2] 
[int, int-1, int-2, int-3] 
[int, int-1, int-2, int-3, int-4] 
.... 
[int, int-1, int-2, int-3, int-4,......1] 

該數組然後由multipyEach功能

function multiplyEach() { 
    // Remove the last value of the stack and assign it to the variable int 
    int = stack.pop(); x = stack.length; 
    // Base case 
    if (x===0) { 
    return int; 
    } 
// Recursive case 
    else { 
    stack[x - 1] = int * stack[x - 1]; 
    return multiplyEach(); 
    } 
} 

該函數從陣列中移除的最後一個元件和後將它乘以數組中的前一個數字並將其存儲在該先前的位置(stack[x - 1] = int * stack[x - 1];)。同樣,這個函數會一直調用它自己,直到數組的大小變爲0,這將導致int內部的數字是它的階乘。下面是每次迭代後數組的狀態multiplyEach

[int, int-1, int-2, int-3, .... 4, 3, 2, 1] 
[int, int-1, int-2, int-3, .... 4, 3, 2] 
[int, int-1, int-2, int-3, .... 4, 6] 
[int, int-1, int-2, int-3, .... 24] 
. 
. 
[int!]