2013-03-22 47 views
-1

我的主要問題是,我似乎無法理解如何解決紙上的問題,更別說理解代碼,或寫我自己的。下面是我正在閱讀的一本書Eloquent JavaScript的摘錄。Javascript代碼需要的解釋(遞歸示例)

考慮一下這個難題:從數字1開始,反覆添加5或乘以3,可以產生無限量的新數字。你如何編寫一個函數,給定一個數字,試圖找出產生該數字的一系列加法和乘法?

¶例如,可以通過首先將1乘以3,然後再加5兩次來達到數字13。數字15根本無法達到。

¶下面是解:

function findSequence(goal) { 
    function find(start, history) { 
    if (start == goal) 
     return history; 
    else if (start > goal) 
     return null; 
    else 
     return find(start + 5, "(" + history + " + 5)") || 
       find(start * 3, "(" + history + " * 3)"); 
    } 
    return find(1, "1"); 
} 

print(findSequence(24)); 
+1

那麼,什麼是你的問題? – musefan 2013-03-22 14:02:37

+1

@musefan我想他想解釋的代碼 – 2013-03-22 14:03:51

+0

@Harikrishnan:是的......那不會發生 – musefan 2013-03-22 14:04:29

回答

1
function findSequence(goal) { 

    // define a function that has a 'start' number (current total), 
    // and a string that is the history of what we've done so far 
    // (and note that for this function, the 'goal' parameter above is in scope). 
    function find(start, history) { 
    // if we've reached the goal, return the string that says how we got there 
    if (start == goal) 
     return history; 
    // if we've overshot, return null 
    else if (start > goal) 
     return null; 
    else 
     // call this same function (recursion) with two different possibile ways of 
     // getting closer to the goal - one adding 5 and one multiplying by 3... 
     // the or ('||') operator will return the first of the two that is not null 
     return find(start + 5, "(" + history + " + 5)") || 
       find(start * 3, "(" + history + " * 3)"); 
    } 
    // start at 1 
    return find(1, "1"); 
} 
+0

謝謝你sje397。我會研究你的意見。 – DEdesigns57 2013-03-22 14:09:59

+0

那麼你認爲這是一個可以接受的問題呢?也許不太具體?你認爲「從Eloquent JavaScript書中解釋findSequence函數」是一個常用的搜索術語嗎? – musefan 2013-03-22 14:10:25

+0

@musefan是的,沒關係......可以在問題標題中使用「遞歸」這個詞。 – sje397 2013-03-22 14:11:15