So in this problem, we start out with n
number of people with big heads and happy smiles.
And after every hexamester, each one of
our happy udacians goes out and asks
spread number of their friends
to also take the course.
This process continues as long as the
number of udacians is less than the target.
With a little bit of math, you can solve
this pretty straightforward,
and you might have done it in
middle school or high school,
but we're going to use recursion
to solve this problem very easily.
Remember what we're looking for is the
number of hexamesters this process goes through
until we reach the target.
I saw on the forms a couple of people
were trying to use global variables
that counted recursive calls,
but really that kind of defeats the purpose in
the power that we can use in the recursion.
I'm going to show you how to do that right now.
So our base case says that if we've met our
target, then we don't need any time to spread
in order to reach the target because
we're already there.
Now here I have a + 1 because we're
going to say that we're doing 1 iteration
of the udacian spreading process.
Now for the recursive call.
The first thing we need is n.
Well, n is going to be the same thing as last
time + how many new people we've gotten,
which is spread x n.
A more succinct way of writing this would
be simply (n x (1 + spread).
The spreading rate doesn't change,
so we're going to leave that alone.
Our target doesn't change.
And that's it. We're done.
この問題では頭の大きいスマイルさんの
数nから取り掛かります
すべての学期後 幸せなUDACITY受講生の
1人1人がたくさんの友人に
コースを受講するよう勧めてくれます
この工程はUDACITY受講生の数が
目標に達しない限り続きます
数学を少し使ってこのとても簡単な問題を
解くことができます
この計算は中学校や高校で
学習したことがあると思います
この問題をとても簡単に解くために再帰を使用します
目標に達するまでこの工程を続ける学期数を
探していることを忘れないでください
再帰呼び出しを数えるグローバル変数を
使おうとしている人がいました
しかしそれは再帰で使用できる累乗の演算目的を
ダメにしてしまいます
それをどのように行うのかお見せします
私たちの基本ケースではもし目標に達したら
すでに到達しているので達するための時間が
必要なくなると示されます
ここに+1があります
これは工程を広めUDACITY受講生の反復を
1回行おうとしているためです
再帰呼び出しでまず最初に必要なのはnです
nは前回にいた数でそれに獲得した新しい人の数
n*spreadを足します
これを簡潔な方法で書くと
シンプルにn*(1+spread)となります
spread率は変わりません
それをこのままにしておきます
目標は変わりません
これだけで終わります
在這問題中,一開始有 n 個人,有大頭和快樂的笑容
之後每個學期 (hexamester),
每一個快樂的 udacian 走出去並要求
向他們的朋友宣傳選修這個課程
只要 udacians 的數目小於目標值,就繼續這個過程
運用一點數學,你可以相當簡單地解決這個問題
你可能在國中或高中做過這種問題
不過,我們使用遞迴,很容易地就能解決這個問題
記住我們尋找的答案是,
這個過程要經歷多少個學期 (hexamesters)
才能達到目標值
我看到在論壇中,
一些人試圖使用全域變數 (global variable)
來數遞迴呼叫 (recursive calls) 的次數
但實際上,這麼做會破壞我們使用遞迴力量的目的
我現在要向你展示,如何運用遞迴
基本情況說,如果已經符合了目標值,
我們不再需要為了達到目標
再花任何時間做傳播,因為我們已經達成目標了
現在這裡,有個 +1,
因為我們要說,我們進行了 udacian 傳播過程
的一次運算
現在處理遞迴呼叫
首先我們需要的是 n
嗯,n 是同樣的事情,是上次的值加上得到的新人數
也就是 spread 乘以 n
更簡潔的寫法是 n x (1 + spread)
傳播率 (spreading rate) 不會改變,所以我們不更動它
我們的目標值不會改變
就這樣了,我們完成了