Recursion: base case and recursive case · רקורסיה: מקרה בסיס ומקרה רקורסיבי
A method that calls itself
- Recursion is when a method calls itself to solve a smaller piece of the same problem.
- On the AP CSA exam you mostly trace recursion (follow the calls by hand). Writing small recursive methods helps you trace well.
- Every recursive method needs two parts: a base case and a recursive case.
שיטה הקוראת לעצמה
- רקורסיה היא כאשר שיטה קוראת לעצמה כדי לפתור חלק קטן יותר מאותו בעיה.
- במבחן AP CSA אתה בעיקר מעקב אחר רקורסיה (עוקב אחר הקריאות ביד). כתיבת שיטות רקורסיביות קטנות עוזרת לך לעקוב היטב.
- לכל שיטה רקורסיבית יש שני חלקים: מקרה בסיס ומקרה רקורסיבי.
Base case and recursive case
- Base case: the simplest input, where you return an answer without calling yourself. This stops the recursion.
- Recursive case: you call the same method with a smaller input, then build the answer.
- Without a base case, the method calls forever and crashes (a stack overflow).
מקרה בסיסי ומקרה רקורסיבי
- מקרה בסיס: הקלט הפשוט ביותר, שבו מחזיר תשובה ללא קריאה לעצמך. זה מעצור את הרקורסיה.
- מקרה רקורסיבי: אתה קורא לאותה שיטה עם קלט קטן יותר, ואז בונה את התשובה.
- ללא מקרה בסיס, השיטה קוראת לנצח ומגרושה (פלישת סטק).
Example: factorial
factorial(n)meansn * (n-1) * ... * 1. For examplefactorial(4) = 24.- Base case:
factorial(1)is1. - Recursive case:
factorial(n)isn * factorial(n - 1).
דוגמה: פקטוריאל
factorial(n)פירושוn * (n-1) * ... * 1. לדוגמהfactorial(4) = 24.- מקרה בסיס:
factorial(1)הוא1. - מקרה רקורסיבי:
factorial(n)הואn * factorial(n - 1).
public class Recursion {
public static int factorial(int n) {
if (n <= 1) { // base case
return 1;
}
return n * factorial(n - 1); // recursive case
}
}
How the calls unwind
- Each call waits for the smaller call to finish. Then it multiplies and returns.
- Trace
factorial(3). Calls go down, then answers come back up.
כיצד השיחות נפתחות
- כל שיחה ממתין לשיחה הקטנה יותר להסתיים. לאחר מכן היא מכפילה ומחזירה תוצאה.
- מעקב אחר
factorial(3). השיחות יורדות, ואז התשובות חוזרות למעלה.
factorial(3) = 3 * factorial(2) <- waits
factorial(2) = 2 * factorial(1) <- waits
factorial(1) = 1 <- base case, returns 1
factorial(2) = 2 * 1 = 2 <- returns 2
factorial(3) = 3 * 2 = 6 <- returns 6
Example: sum to n
sumTo(n)adds1 + 2 + ... + n. For examplesumTo(4) = 10.- Base case:
sumTo(0)is0(nothing to add). - Recursive case:
sumTo(n)isn + sumTo(n - 1).
דוגמה: סכום עד n
sumTo(n)מוסיף1 + 2 + ... + n. לדוגמהsumTo(4) = 10.- מקרה בסיסי:
sumTo(0)הוא0(אין מה להוסיף). - מקרה רקורסיבי:
sumTo(n)הואn + sumTo(n - 1).
public class Recursion {
public static int sumTo(int n) {
if (n <= 0) { // base case
return 0;
}
return n + sumTo(n - 1); // recursive case
}
}
Recursion over an array
- We can also recurse with an index that moves toward the end.
- Base case: when the index is past the last spot, return
0. - Recursive case: add
a[i]to the sum of the rest,arraySum(a, i + 1).
ריקורסיה על מערך
- ניתן לבצע ריקורסיה גם באמצעות מדד הנע לעבר הסוף.
- מקרה בסיסי: כאשר המדד מעבר לנקודה האחרונה, החזר
0. - מקרה רקורסיבי: הוספת
a[i]לסכום השארית,arraySum(a, i + 1).
- To sum the whole array you start at index
0:arraySum(a, 0). - Each call handles one value and trusts the next call for the rest.
public class Recursion {
public static int arraySum(int[] a, int i) {
if (i >= a.length) { // base case: past the end
return 0;
}
return a[i] + arraySum(a, i + 1);
}
}
- כדי לחשב את סכום כל המערך מתחילים במדד
0:arraySum(a, 0). - כל שיחה מטפלת בערך אחד ומתקבלת על היכולת של השיחה הבאה לטפל בשאר.
Common mistakes
- Recursion needs a base case, or it throws StackOverflowError.
- Each call must move closer to the base case.
טעויות נפוצות
- ריקורסיה דורשת מקרה בסיסי, או שתופיע שגיאת StackOverflowError.
- כל שיחה חייבת לקרב למקרה הבסיסי.
Now you try
- Each task gives you a method skeleton with a TODO. Write the base case and the recursive case.
- A hidden Harness calls your method with several values and checks the result.
- Press Run to compile, then Check answer.
כעת תנסו בעצמכם
- כל משימה מספקת לך תבנית מטהוד עם TODO. כתוב את המקרה הבסיסי וגם את המקרה הרקורסיבי.
- Harness נסתר קורא למטהוד שלך עם ערכים שונים ובוחן את התוצאה.
- לחץ על Run להתקפלה, ולאחר מכן לחץ על Check answer.
Recursion: base + recursive case · רקורסיה: מקרה בסיס + מקרה רקורסיבי
Calls split until a base case, then answers return up. · קריאות מתפצלות עד מקרה בסיס, ולאחר מכן התשובות חוזרות למעלה.
Complete factorial(int n) so it returns n * (n-1) * ... * 1 using recursion. Use a base case for n <= 1. The checker tests several values. · השלם את factorial(int n) כך שיתחזיר n * (n-1) * ... * 1 באמצעות רקורסיה. השתמש במקרה בסיסי עבור n <= 1. הבוחן בודק מספר ערכים.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Complete sumTo(int n) so it returns 1 + 2 + ... + n using recursion. Use a base case for n <= 0. The checker tests several values. · השלם את sumTo(int n) כך שיתחזיר 1 + 2 + ... + n באמצעות רקורסיה. השתמש במקרה בסיסי עבור n <= 0. הבוחן בודק מספר ערכים.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Complete arraySum(int[] a, int i) so it returns the sum of a[i] to the end, using recursion. Base case: when i is past the last spot, return 0. The checker tests several arrays. · השלם את arraySum(int[] a, int i) כך שיתחזיר את הסכום של a[i] עד הסוף, באמצעות רקורסיה. מקרה בסיסי: כאשר i עובר את המיקום האחרון, החזר 0. הבוחן בודק מספר מערכים.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.