Bagaimana membina intuisi untuk berulang

Dan bagaimana menggunakannya untuk menyelesaikan masalah

Rekursi adalah salah satu topik paling menakutkan yang dihadapi oleh pelajar dalam pengaturcaraan. Sukar untuk difahami kerana otak manusia tidak mampu melakukan rekursi - tetapi komputer. Inilah sebabnya mengapa rekursi adalah alat yang sangat baik untuk pengaturcara, tetapi ini juga bermaksud bahawa belajar menggunakannya sangat sukar. Saya ingin menolong anda membina intuisi untuk berulang sehingga anda dapat menggunakannya untuk menyelesaikan masalah.

Saya adalah pembantu mengajar untuk kursus sains komputer pengantar di universiti saya. Saya telah menjelaskan rekursi dengan cara yang sama berpuluh kali minggu ini. Penjelasan saya nampaknya banyak membantu pelajar. Artikel ini mempunyai penjelasan paling umum di bahagian atas, dan penjelasan paling khusus di bahagian bawah. Dengan cara ini, anda boleh memulakannya pada awal dan berhenti sebaik sahaja anda merasakan pengulangan cukup baik. Saya telah memberikan beberapa contoh di Java, dan cukup sederhana sehingga sesiapa sahaja yang mempunyai pengalaman pengaturcaraan dapat menafsirkannya.

Apakah rekursi?

Untuk memahami pengulangan, mari kita mundur dari pengaturcaraan. Mari mulakan dengan menetapkan definisi umum untuk istilah tersebut. Sesuatu bersifat rekursif jika ditentukan oleh definisinya sendiri hingga tahap tertentu. Itu mungkin tidak banyak membantu anda memahami pengulangan, jadi mari kita lihat definisi matematik. Anda biasa dengan fungsi - satu nombor masuk, nombor lain keluar. Mereka kelihatan seperti ini:

f (x) = 2x

Mari ubah idea ini sedikit dan sebaliknya fikirkan urutan. Urutan mengambil nombor bulat, dan nombor bulat keluar.

A (n) = 2n

Urutan dapat dianggap sebagai fungsi dengan input dan output yang hanya terbatas pada bilangan bulat positif. Secara amnya, urutan bermula dengan 1. Ini bermaksud bahawa A (0) adalah 1. Urutan di atas adalah seperti berikut:

A (n) = 1, 2, 4, 6, 8, 10,… di mana n = 0, 1, 2, 3, 4, 5,…

Sekarang, pertimbangkan urutan berikut:

A (n) = 2 x A (n-1)

Urutan ini ditakrifkan secara rekursif. Dengan kata lain, nilai setiap elemen tertentu bergantung pada nilai elemen lain. Urutan ini kelihatan seperti ini:

A (n) = 1, 2, 4, 8, 16,… di mana n = 0, 1, 2, 3, 4,…

Mana-mana elemen ditakrifkan sebagai 2 kali daripada elemen sebelumnya.

  • Elemen n = 4, 16, ditakrifkan sebagai 2 kali daripada elemen sebelumnya.
  • Elemen n = 3, 8, ditakrifkan sebagai 2 kali daripada elemen sebelumnya.
  • Elemen n = 2, 4, ditakrifkan sebagai 2 kali daripada elemen sebelumnya.
  • Elemen n = 1, 2, ditakrifkan sebagai 2 kali daripada elemen sebelumnya.
  • Elemen n = 0, 1, ditakrifkan sebagai…

Elemen n = 0 tidak dapat ditentukan secara rekursif. Tidak ada unsur sebelumnya. Kami menyebutnya sebagai kes asas , dan ini adalah akibat yang mustahak dari definisi berulang. Mereka mesti dinyatakan secara jelas dalam kod anda . Kami dapat menggambarkan urutan rekursif ini di Java seperti:

public int A(int n){ if (n == 0) return 1; return 2 * A(n - 1);}

Anda harus membiasakan diri dengan anatomi kaedah rekursif. Perhatikan kes asas: jika n adalah 0, elemen didefinisikan sebagai 1. Jika tidak, elemen tersebut ditakrifkan sebagai 2 kali ganda dari elemen sebelumnya. Kita mesti memanggil kaedah secara rekursif untuk mendapatkan nilai elemen sebelumnya, dan kemudian mengalikannya dengan 2. Semua kaedah rekursif akan mempunyai dua komponen berikut:

  • Kes asas, yang mengembalikan nilai yang ditentukan dengan baik.
  • Kes berulang, yang mengembalikan nilai yang ditentukan secara rekursif.

Mari kita buat contoh lain, teruskan dengan konteks matematik. Urutan Fibonacci sering digunakan untuk menggambarkan pengulangan. Mana-mana unsur urutan Fibonacci adalah jumlah dari dua unsur sebelumnya. Ia seperti ini:

F (n) = 1, 1, 2, 3, 5, 8,… di mana n = 0, 1, 2, 3, 4, 5,…

  • N = 5, elemen, 8, ditakrifkan sebagai jumlah unsur n = 4 dan unsur n = 3…

Pada ketika ini, anda harus ragu-ragu. Dalam contoh sebelumnya, setiap elemen hanya bergantung pada satu elemen lain, kini setiap elemen bergantung pada dua elemen lain. Ini menyukarkan perkara.

  • Elemen n = 4, 5, ditakrifkan sebagai jumlah unsur n = 3 dan unsur n = 2.
  • Elemen n = 3, 3, ditakrifkan sebagai jumlah unsur n = 2 dan unsur n = 1.
  • Elemen n = 2, 2, ditakrifkan sebagai jumlah unsur n = 1 dan unsur n = 0.
  • Unsur n = 1, 1, ditakrifkan sebagai jumlah unsur n = 0 dan…

Elemen n = 1 tidak dapat ditentukan secara rekursif. Elemen n = 0 juga tidak. Unsur-unsur ini tidak dapat didefinisikan secara rekursif kerana definisi rekursif memerlukan dua elemen sebelumnya. Unsur n = 0 tidak mempunyai unsur sebelumnya, dan elemen n = 1 hanya mempunyai satu elemen sebelumnya. Ini bermaksud bahawa terdapat dua kes asas. Sebelum menulis sebarang kod, saya akan menuliskan seperti ini:

Unsur n = 0 ditakrifkan sebagai 1. Elemen n = 1 ditakrifkan sebagai 1.

Elemen n ditakrifkan sebagai jumlah unsur n-1 dan unsur n-2.

Sekarang kita mempunyai idea bagaimana tugas ini ditakrifkan secara rekursif, dan kita dapat meneruskan dan menulis beberapa kod. Tidak pernahmula menulis kod tanpa terlebih dahulu mempunyai pemahaman semula jadi mengenai tugas.

public int F(int n) if (n == 0 

Tumpuan Panggilan

Sebagai pengaturcara, kami ingin mempunyai intuisi untuk berulang supaya kami dapat menggunakannya untuk melakukan sesuatu. Untuk melakukannya dengan berkesan, kita mesti memahami bagaimana komputer memproses pengulangan.

Terdapat struktur data yang digunakan komputer untuk melacak panggilan kaedah yang disebut timbunan panggilan . Setiap panggilan kaedah membuat pemboleh ubah tempatan dari parameter kaedah. Komputer perlu menyimpan pemboleh ubah ini semasa kaedah dijalankan. Kemudian, komputer membuang nilai ketika kaedah kembali untuk mengelakkan memori terbuang.

The call stack (and stacks in general) function as you might imagine some sort of real-life stack would. Imagine a stack of papers on your desk — it starts as nothing, and then you add papers one by one. You don’t know anything about any of the papers in the stack except for the paper on top. The only way you can remove papers from the stack is by taking them off the top, one-by-one, in the opposite order that they were added.

This is essentially how the call stack works, except the items in the stack are activation records instead of papers. Activation records are just little pieces of data that store the method name and parameter values.

Without recursion, the call stack is pretty simple. Here’s an example. If you had some code that looked like this…

public static void main(String[] args) System.out.println(myMethod(1));

…The call stack would look like this:

* myMethod(int a)
* main(String[] args)

Here we see two methods under execution, main and myMethod. The important thing to notice is that main cannot be removed from the stack until myMethod is removed from the stack. In other words, main cannot complete until myMethod is called, executed, and returns a value.

This is true for any case of method composition (a method within a method) — so let’s look at recursive example: the A(int n) method we wrote earlier. Your code might look like this:

public static void main(String[] args) System.out.println(A(4));
public static int A(int n){ if (n == 0) return 1; return 2 * A(n - 1);}

When main is called, A is called. When A is called, it calls itself. So the call stack will start building up like so:

* A(4)* main(String[] args)

A(4) calls A(3).

* A(3)* A(4)* main(String[] args)

Now, it’s important to note that A(4) cannot be removed from the call stack until A(3) is removed from the call stack first. This makes sense, because the value of A(4) depends on the value of A(3). The recursion carries on…

* A(0)* A(1)* A(2)* A(3)* A(4)* main(String[] args)

When A(0) is called, we have reached a base case. This means that the recursion is completed, and instead of making a recursive call, a value is returned. A(0) comes off the stack, and the rest of the calls are then able to come off the stack in succession until A(4) is finally able to return its value to main.

Here’s the intuition: the return value of any method call depends on the return value of another method call. Therefore, all the method calls must be stored in memory until a base case is reached. When the base case is reached, the values start becoming well-defined instead of recursively defined. For example, A(1) is recursively defined until it knows the definition of the base case, 1. Then, it is well-defined as 2 times 1.

When we are trying to solve problems with recursion, it is often more effective to think about the order in which values are returned. This is the opposite of the order in which calls are made. This order is more useful because it consists of well-defined values, instead of recursively defined values.

For this example, it is more useful to consider that A(0) returns 1, and then A(1) returns 2 times 1, and then A(2) returns 2 times A(1), and so on. However, when we are writing our code, it can easier to frame it in the reverse order (the order that the calls are made). This is another reason that I find it helpful to write the base case and the recursive case down before writing any code.

Helper Methods and Recursion vs. Loops

We are programmers, not mathematicians, so recursion is simply a tool. In fact, recursion is a relatively simple tool. It’s very similar to loops in that both loops and recursion induce repetition in the program.

You may have heard that any repetitive task can be done using either a while loop or a for loop. Some tasks lend themselves better to while loops and other tasks lend themselves better to for loops.

The same is true with this new tool, recursion. Any repetitive task can be accomplished with either a loop or recursion, but some tasks lend themselves better to loops and others lend themselves better to recursion.

When we use loops, it is sometimes necessary to make use of a local variable to “keep track” of a calculation. Here’s an example.

public double sum (double[] a){ double sum = 0.0; for (int i = 0; i < a.length; i++) sum += a[i]; return sum;
}

This method takes an array of doubles as a parameter and returns the sum of that array. It uses a local variable, sum, to keep track of the working sum. When the loop is completed, sum will hold the actual sum of all values in the array, and that value is returned. This method actually has two other local variables that are less obvious. There is the double array a, whose scope is the method, and the iterator i (keeps track of the index), whose scope is the for loop.

What if we wanted to accomplish this same task using recursion?

public double recursiveSum(double[] a) # recursively calculate sum

This task is repetitive, so it is possible to do it using recursion, though it is probably more elegantly accomplished using a loop. We just need to create a few local variables to keep track of the working sum and the index, right?

Alas, this is impossible. Local variables only exist in the context of a single method call, and recursion makes use of repeated method calls to accomplish a repetitive task. This means that local variables are pretty much useless when we are using recursion. If you are writing a recursive method and you feel as though you need a local variable, you probably need a helper method.

A helper method is a recursive method that makes use of additional parameters to keep track of values. For recursiveSum, our helper method might look like this:

public double recursiveSum(double[] a, double sum, int index){ if (index == a.length) return sum; sum += a[index]; return recursiveSum(a, sum, index + 1);}

This method builds the sum by passing the working value to a new method call with the next index. When there are no more values in the array, the working sum is the actual sum.

Now we have two methods. The “starter method,” and the helper method.

public double recursiveSum(double[] a) # recursively calculate sum
public double recursiveSum(double[] a, double sum, int index){ if (index == a.length) return sum; sum += a[index]; return recursiveSum(a, sum, index + 1);}

The term “helper method” is actually a bit of a misnomer. It turns out that the helper method does all the work, and the other method is just a starter. It simply calls the helper method with the initial values that start the recursion.

public double recursiveSum(double[] a) return recursiveSum(a, 0.0, 0);
public double recursiveSum(double[] a, double sum, int index){ if (index == a.length) return sum; sum += a[index]; return recursiveSum(a, sum, index + 1);}

Note that the values used in the starter call to the helper method are the same values used to initialize the local variables in the loop example. We initialize the variable used to keep track of the sum to 0.0, and we initialize the variable used to keep track of the index to 0.

Earlier, I said that local variables are useless in the context of recursion. This isn’t completely true, because the method parameters are indeed local variables. They work for recursion because new ones are created every time the method is called. When the recursion is executed, there are many method calls being stored in the call stack, and as a result there are many copies of the local variables.

You might ask, “If the helper method does all the work, why do we even need the starter method? Why don’t we just call the helper method with the initial values, and then you only need to write one method?”

Well, remember that we were trying to replace the method that used a for loop. That method was simple. It took an array as a parameter and returned the sum of the array as a double. If we replaced this method with one that took three parameters, we would have to remember to call it with the proper starting values. If someone else wanted to use your method, it would be impossible if he or she didn’t know the starting values.

For these reasons, it makes sense to add another method that takes care of these starting values for us.

Wrapping up

Recursion is a pretty challenging concept, but you made it all the way to the end of my explanation. I hope you understand the magic a little better. I now officially grant you the title of “Grand-Wizard of Recursion.” Congratulations!