简体   繁体   English

有人可以帮助我理解这两段代码[递归]吗?

[英]Can someone help me understand these 2 pieces of code [Recursion]?

I'm having a hard time trying to understand what is going on in this code. 我很难理解这段代码中发生的事情。 Out of the 14 questions we had for homework, these were the only 2 that I got stuck on and just put down the answer without knowing how they got to the answer. 在针对作业的14个问题中,这是我唯一遇到的两个问题,只是在不知道答案如何的情况下给出答案。 Any help would be appreciated, thank you. 任何帮助,将不胜感激,谢谢。

Here is #1: 这是#1:

public void printDollarSign(int k)
{
        int j;
        if (k>0)
        {
              for (j=1; j<= k; j++)
                  System.out.print("$");
              System.out.println();
              printDollarSign(k-1);
        }
}

What will be the output if the call is: printDollarSign(5); 如果调用是,输出将是什么:printDollarSign(5); ?

Answer is: 答案是:

$$$$$ $$$$$

$$$$ $$$$

$$$ $$$

$$ $$

$ $

Here is #2: 这是#2:

public void bbb(String s, int p)
{
    if (p>= 0)
    { 
        bbb(s,p-1);
        System.out.print(s.charAt(p)); 
    }
}

What will the output be if the call is: bbb("January" , 4); 如果调用是,输出将是什么:bbb(“ January”,4); ?

Answer is: 答案是:

Janua 亚努阿

Explanation for printDollarSign : printDollarSign的说明:

  • Here you have created a recursive function. 在这里,您创建了一个递归函数。
  • Every recursive function has a base condition.In your case its if (k>0). 每个递归函数都有一个基本条件,在您的情况下是if(k> 0)。
  • Every recursive call decrements the value of k by 1.Hence for each recursive call ,the number of times your for loop runs is reduced by 1. 每个递归调用都会将k的值递减1.因此,对于每个递归调用,for循环运行的次数将减少1。

For the First call: 对于首次通话:

  1. Suppose k = 5 ; 假设k = 5;
  2. Function call printDollarSign(5); 函数调用printDollarSign(5);
  3. Check if(k > 0 ) ie 5 > 0 ; 检查是否(k> 0)即5> 0;
  4. For loop runs for 5 times and prints 5 "$" signs; For循环运行5次并打印5个“ $”符号;
  5. A println prints a line break; println打印换行符;
  6. Recursive call printDollarSign(4); 递归调用printDollarSign(4);

printDollarSign(k) first prints k number of $'s, then prints a newline and then calls printDollarSign(k-1) first to print k-1 number of $'s, then to print a newline and then to call printDollarSign(k-1-1)... this continues until k=0. printDollarSign(k)首先打印k个$,然后打印换行,然后调用printDollarSign(k-1)首先打印k-1个$,然后打印换行,然后调用printDollarSign(k -1-1)...一直持续到k = 0。 When k=0, printDollarSign(0) prints nothing. 当k = 0时,printDollarSign(0)不打印任何内容。

Your first one, is creating a function with a specific parameter of an int, in this case "k". 您的第一个方法是创建一个带有int特定参数的函数,在本例中为“ k”。

  • It is then setting an int called j via "int k;" 然后通过“ int k;”设置一个称为j的int。
  • It is then checking if k is greater than 0 然后检查k是否大于0
  • After checking it is looping through k (where j = 1 and j < k) and printing out a "$" sign 检查后,它遍历k(其中j = 1且j <k)并打印出“ $”符号
  • It will produce "$$$$$".."$$$$".. etc.. till k < 0 它将产生“ $$$$$” ..“ $$$$” ..等,直到k <0
  • Then write a new line, then call the function again minusing 1 from k 然后编写新行,然后再次调用该函数,将k减1

Code: 码:

public void printDollarSign(int k){ //Define function
        int j;//Define j as an int
        if (k>0){//Check if k is greater than 0
             for (j=1; j<= k; j++)//Loop through k where j = 1
                 System.out.print("$");//Print $ by the amount of k
             System.out.println();//Print a new line
             printDollarSign(k-1);//Re run the function
        }
}

Your second question is creating a function with two parameters of string and int "s" and "p" 您的第二个问题是创建一个带有字符串和int“ s”和“ p”两个参数的函数

  • Its checking if p is greater than 0 它检查p是否大于0
  • Then calling the function inside itself minusing 1 from p (p-1) 然后在内部调用该函数,并减去p(p-1)中的1
  • Its then printing out a character from your string based on p 然后根据p从字符串中打印出一个字符

Code: 码:

public void bbb(String s, int p){//Define Function
    if (p>= 0){ //Check if p is greater than 0
        bbb(s,p-1);//Rerun function
        System.out.print(s.charAt(p));//Print character of string based on p
    }
}

Add code comments for explanation: 添加代码注释以进行解释:

1# 1号

public void printDollarSign(int k)
    {
        // temporary variable j, it will be always initialized to 1 inside the for loop.
        int j;
        // only executed to be true if k is more than 0, that means if K is initially 5
        // then it only works for 5,4,3,2,1  and not for 0.
        if (k>0)
        {
            // always starts with 1 and goes to the value of k, that means if K is currently 5
            // then it will print 5 dollars, if 4 then 4 dollars and so on
            for (j=1; j<= k; j++)
                System.out.print("$");
            // a new line will be added once dollars are printed.
            System.out.println();
            // this will again call the same function and decrements the value of k, so next time 
            // k will have the value one less then the previous one, if this has printed 5 dollars 
            // in last iteration next time it will print 4 dollars and so on
            printDollarSign(k-1);
        }
    }

2# 2号

public void bbb(String s, int p)
    {
        // only print a character if p has a value grater than 0. in you case , p has a value 4 that
        // mean only 4 characters will be printed at max
        if (p>= 0)
        { 
            // recuresively call same method by decrementing p, so it will be
            // [bbb(s,3) prints 'a']-> [bbb(s,3) prints 'u']-> bbb(s,2) [prints 'n']-> [bbb(s, 1) prints 'a']> [bbb(s, 0) prints 'J']
            // last character will be printed first
            bbb(s,p-1);
            // prints the character at p location
            System.out.print(s.charAt(p)); 
        }
    }

Explanation for bbb : bbb的解释:

  • It's an application of recursion to extract a substring from the given string. 递归的一种应用是从给定的字符串中提取子字符串。
  • Base condition if (p>= 0). 基本条件是否(p> = 0)。
  • You should be aware about the fact that for each and every recursion call the value of "P" is stored in the stack. 您应该意识到以下事实:对于每个递归调用,“ P”的值都存储在堆栈中。
  • As you know stack is a Last In First Out(LIFO) data structure , the last value inserted into the stack will be popped out first. 如您所知,堆栈是一个后进先出(LIFO)数据结构,插入堆栈中的最后一个值将首先弹出。

Execution: 执行:

  1. bbb("January" , 4); bbb(“ January”,4); --> Stack contains : [4] ->堆栈包含: [4]
  2. bbb("January" , 3); bbb(“ January”,3); --> Stack contains : [3 4] ->堆栈包含: [3 4]
  3. bbb("January" , 2); bbb(“ January”,2); --> Stack contains : [2 3 4] ->堆栈包含: [2 3 4]
  4. bbb("January" , 1); bbb(“ January”,1); --> Stack contains : [1 2 3 4] ->堆栈包含: [1 2 3 4]
  5. bbb("January" , 0); bbb(“ January”,0); --> Stack contains : [0 1 2 3 4] ->堆栈包含: [0 1 2 3 4]

Now pop out each element and print the char at that position 现在弹出每个元素并在该位置打印字符

  1. After 0 -> J 在0之后-> J
  2. After 1 -> Ja 1之后-> Ja
  3. After 2 -> Jan 2点后-> 1月
  4. After 3 -> Janu 3之后-> Janu
  5. After 4 -> Janua 4点后-> Janua
if you provide a string s as 'January', the way it stores is like this:
0th position = J, 
1th position = a,
2th position = n,
3th position = u,
4th position = a,
5th position = r,
6th position = y,
Just like an array of characters. 
When you provide p=4, you are setting the closing criteria for the condition    check. 

function bbb('January', 4){
if(4>=0){
bbb('January', 3); ....

function bbb('January', 3){
if(3>=0){
bbb('January', 2); ....

function bbb('January', 2){
if(2>=0){
bbb('January', 1); ....

function bbb('January', 1){
if(1>=0){
bbb('January', 0); ....

function bbb('January', 0){
if(0>=0){
bbb('January', -1); ....

function bbb('January', -1){
if(-1>=0){ Here condition check fails.. hence char at(-1) doec not print

return goes back to print of previous call and prints J as p=0, we have J
the p=1: a
p=2: n
p=3: u
p=4: a

and function finishes... 功能完成...

Kindly let me know if the explanation was helpful 请让我知道说明是否有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM