递归的Java函数,用于重复单词“computing”的开头和结尾。

huangapple go评论151阅读模式
英文:

Recursive java function to repeat the beginning and end of the word "computing"

问题

public static String madComputing(int n) {
    if (n < 0)
        return "必须是正整数"; // 打印以表示错误,而不是在控制台中获取错误
    if (n > 1000) // 避免溢出
        return "不能大于1000";

    if (n > 0) {
        // System.out.print("computing");
        return "comp" + madComputing(n - 1) + "ting";
    } else
        return "u";
}

<b> 我不能使用全局变量、辅助方法或任何循环<br/>
<b> 对答案不感兴趣,但指导将会很好。<br/>

当前控制台输出:

compcompcompcomputingtingtingting

但应为:

> <b>computing<br/>
<b>compcomputingting<br/>
<b>compcompcomputingtingting<br/>
<b>compcompcompcomputingtingting<br/>


<details>
<summary>英文:</summary>
&lt;b&gt; **I can not use global variables, helper methods or any loops**&lt;br/&gt;
&lt;b&gt; **Not interested in answer, but guidance would be great.**&lt;br/&gt;
Currently console is printing:
### compcompcompcomputingtingtingting ###
but it needs to be:
&gt; &lt;b&gt;computing&lt;br/&gt;
&lt;b&gt;compcomputingting&lt;br/&gt;
&lt;b&gt;compcompcomputingtingting&lt;br/&gt;
&lt;b&gt;compcompcompcomputingtingting&lt;br/&gt;
public static String madComputing(int n) {
if (n &lt; 0)
return &quot;Must be postive integer&quot;;// printing to present error instead getting error in console
if (n &gt; 1000)// avoid overflow
return &quot;Cannot be greater than 1000&quot;;
if (n &gt; 0) {
//System.out.print(&quot;computing&quot;);
return &quot;comp&quot; + madComputing(n - 1) + &quot;ting&quot; ;
} else
return &quot;u&quot;;
}
</details>
# 答案1
**得分**: 1
我会尽量为您解释,而不是给您快速答案。看起来您的基本情况都正确,您的问题可以通过一些小的调整来解决:
我认为您代码的主要问题在于您没有在每次递归调用时打印/创建新的输出 - 每次递归调用都只是将内容追加到同一个字符串中。您可以从中看出,您需要在每次递归调用时打印一些内容,因为您理想的输出不仅显示最终字符串,还显示了中间的增量。
因此,在每次递归调用中,您将打印到目前为止的结果,然后将该中间结果传递给下一次递归调用。这意味着您的方法需要接受一个参数(或两个参数),它将是到目前为止的结果(累加器)。
现在的问题是,中间结果是什么样的?这将是每个输出之间变化的内容,即在'u'之前的'comp'和在之后的'ting'。因此,您可以传递一个'before'和'after'字符串参数(在第一次调用时将是空字符串),用于保存到目前为止的'comp'和'ting'字符串。
然后在每次调用中,您只需要将'comp'添加到前一个字符串,将'ting'添加到后一个字符串,打印整个字符串,并在中间添加一个'u'(before + 'u' + after),然后将*新的* before 和 after 字符串传递给递归调用。
**在进一步澄清后的编辑:不使用累加器完成此操作**:
如果您需要在没有累加器的情况下完成这个任务,会稍微复杂一些:
1. 基本情况应为"computing"而不是"u"。
2. 对于非基本情况,首先进行递归调用(即使用 n-1 调用该方法)并将其存储为一个字符串(称为``recc_result``)。
3. 将递归结果按换行符`\n`拆分,并从中获取最后一行。可以使用 ``recc_result.split()`` 来完成,然后取数组的最后一个元素。将其称为``last_line``。
4. 最后,返回 ``recc_result + '\n' + 'comp' + last_line + 'ting'``。
解释:
更改基本情况是因为当 n=1 时,您想要打印"computing"而不仅仅是"u"。
其余部分的思路是,在每个阶段,您都从到目前为止的结果中获取最后一行,然后在前面添加一个'comp',在末尾添加一个'ting',然后将其连接到结果中。
因此,基本情况是'computing'。然后对于 n=2,我们获取 n-1(即1)的递归结果,它将给我们'computing'。从这个结果中获取最后一行是唯一的一行(即'computing')。然后我们添加一个'comp'和一个'ting',将其附加到整个结果,得到"computing\ncompcomputingting"。
对于 n=3,``recc_result`` 是"computing\ncompcomputingting",我们从中获取最后一行("compcomputingting"),然后添加一个'comp'和一个'ting',将其连接到整个结果中,得到"compcompcomputingtingting",然后将其附加到整个结果中,得到"computing\ncompcomputingting\ncompcompcomputingtingting"。
注:``\n`` 表示换行。
<details>
<summary>英文:</summary>
I&#39;ll try to explain this to you rather than give you the quick answer. It looks like you have the base cases all correct and your issue can be fixed with a few small tweaks:
I think the primary problem with your code is that you&#39;re not printing / creating a new output at every recursive call - your recursive calls are simply appending to the same string each time. You can tell you need to print something at each recursive call because your ideal output doesn&#39;t just show the final string but also the increments in between.
So in each recursive call, you&#39;ll print your result so far, and then pass that intermediate result to the next recursive call. This means your method needs to take a parameter (or 2) which will be the result so far (accumulator)
Now the question is, what does the intermediate result look like? This will be the the thing that changes between each output, which is the &#39;comp&#39;s before &#39;u&#39; and the &#39;tings&#39; after. So you can pass an a &#39;before&#39; and &#39;after&#39; string parameters (which will be empty strings on the first call) that hold the string of &#39;comp&#39;s and &#39;ting&#39;s so far. 
Then on each call, you just need to add a &#39;comp&#39; to the before string, a &#39;ting&#39; to the after string, print the whole thing with a &#39;u&#39; in the middle (before + &#39;u&#39; + after) and then pass the *new* before and after strings to the recursive call
**Edit after further clarification: doing it without an accumulator**:
If you need to accomplish this without an accumulator, it&#39;s a little more complex:
1. The base case needs to be &quot;computing&quot; instead of &quot;u&quot;
2. For the non-base case, first make the recursive call (i.e. call the method with n-1) and store it as a string (say ``recc_result``)
3. Split the recursive result by newline `\n` and get the last line out of it. This can be done using ``recc_result.split()`` and then taking the last element of the array. Call this ``last_line``
4. Finally, return the ``recc_result + &#39;\n&#39; + &#39;comp&#39; + last_line + &#39;ting&#39;``
Explanation:
The change of base case is because you want to print &quot;computing&quot; when n=1 and not just &quot;u&quot;.
And the way to thing about the rest is that on each stage, you&#39;re taking the last line from the result so far and adding a &#39;comp&#39; to the front and a &#39;ting&#39; to the end, then attaching this to the result.
So the base case is &#39;computing&#39;. Then for n=2, we get the recursive result for n-1 (which is 1) which will give us &#39;computing&#39;. The last line from this result is the only line (i.e. &#39;computing&#39;). Then we add a &#39;comp&#39; and a &#39;ting&#39; and attach it to the whole result giving us &quot;computing\ncompcomputingting&quot;. 
For n=3, the recc_result is &quot;computing\ncompcomputingting&quot; from which we take the last line (&quot;compcomputingting&quot;) and then add a comp and ting making &quot;compcompcomputingtingting&quot; and attach it to the whole result giving &quot;computing\ncompcomputingting\ncompcompcomputingtingting&quot;
Note: ``\n`` = newline
</details>
# 答案2
**得分**: 0
以下是您要翻译的内容:
你可以添加一个额外的参数作为累加器,并将初始参数设为 "computing"。
对于您的示例情况,调用方式为 madComputing(4, "computing")。
尽管代码看起来很糟糕,但它仍然能够完成任务:
```java
public static String madComputing(int n, String acc) {
if (n < 0) {
return "必须是正整数";
}
if (n > 1000) {
return "不能大于1000"; 
}   
if (n > 0) {
System.out.println(acc);
acc = "comp" + acc + "ting";
return madComputing(n - 1, acc);
} else {
return ""; 
}  
}

或者如果您不能添加一个累加器:

public static String madComputing(int n) {
  if (n < 0) {
      return "必须是正整数";
  }
  if (n > 1000) {
      return "不能大于1000"; 
  }   
  if (n >= 0) {
      String value = "comp" + (n == 0 ? "u" : madComputing(n - 1)) + "ting";
      System.out.println(value);      
      return value;
  } 
  return null;
}
英文:

You can add an extra parameter as the accumulator and give the initial param as "computing".
Call it as madComputing(4, "computing") for your example case.

It looks very bad code wise but it still does the job:

public static String madComputing(int n, String acc) {
if (n &lt; 0) {
return &quot;Must be postive integer&quot;;
}
if (n &gt; 1000) {
return &quot;Cannot be greater than 1000&quot;; 
}   
if (n &gt; 0) {
System.out.println(acc);
acc = &quot;comp&quot; + acc + &quot;ting&quot;;
return madComputing(n - 1, acc);
} else {
return &quot;&quot;; 
}  
}

Or if you can not add an accumulator:

public static String madComputing(int n) {
if (n &lt; 0) {
return &quot;Must be postive integer&quot;;
}
if (n &gt; 1000) {
return &quot;Cannot be greater than 1000&quot;; 
}   
if (n &gt;= 0) {
String value = &quot;comp&quot; + (n == 0 ? &quot;u&quot; : madComputing(n - 1))+ &quot;ting&quot;;
System.out.println(value);      
return value;
} 
return null;
}

答案3

得分: 0

public static String madComputing(int n) {
    String res = "";
    String half = "";
    if (n < 0)
        return "必须是正数";
    if (n > 1000)
        return "对于大于999的值,会导致堆栈溢出";
    if (n > 1) {// 任何大于1的值
        res = "" + madComputing(n - 1);// 将递归调用赋给变量res以拆分并访问其子字符串
        // System.out.println(res); 如果保留这句,将在每个级别打印
        half = res.substring(res.lastIndexOf("\n") + 1);// 获取最后索引的值
        return "comp" + half + "ting";// 使用half完成我的方法,该方法将对任何小于1000的n打印
    } else {
        return "计算";// 当n == 1时,这是基本情况
    }
}
英文:
public static String madComputing(int n) {
String res = &quot;&quot;;
String half = &quot;&quot;;
if (n &lt; 0)
return &quot;Has to be positive&quot;;
if (n &gt; 1000)
return &quot;Stackoverflow for values greater than 999&quot;;
if (n &gt; 1) {// anything larger than 1
res = &quot;&quot; + madComputing(n - 1);// assign the recursive call to var res to split and access it&#39;s substring
// System.out.println(res); if you leave this in, it will print at each level
half = res.substring(res.lastIndexOf(&quot;\n&quot;) + 1);// get the last indexed value
return &quot;comp&quot; + half + &quot;ting&quot;;// use half to complete my method which will print for any n less than 1000
} else {
return &quot;computing&quot;;// this is the base case when n == 1
}
}

huangapple
  • 本文由 发表于 2020年5月30日 07:31:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/62096001.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定