英文:
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>
<b> **I can not use global variables, helper methods or any loops**<br/>
<b> **Not interested in answer, but guidance would be great.**<br/>
Currently console is printing:
### compcompcompcomputingtingtingting ###
but it needs to be:
> <b>computing<br/>
<b>compcomputingting<br/>
<b>compcompcomputingtingting<br/>
<b>compcompcompcomputingtingting<br/>
public static String madComputing(int n) {
if (n < 0)
return "Must be postive integer";// printing to present error instead getting error in console
if (n > 1000)// avoid overflow
return "Cannot be greater than 1000";
if (n > 0) {
//System.out.print("computing");
return "comp" + madComputing(n - 1) + "ting" ;
} else
return "u";
}
</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'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'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't just show the final string but also the increments in between.
So in each recursive call, you'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 'comp's before 'u' and the 'tings' after. So you can pass an a 'before' and 'after' string parameters (which will be empty strings on the first call) that hold the string of 'comp's and 'ting's so far.
Then on each call, you just need to add a 'comp' to the before string, a 'ting' to the after string, print the whole thing with a 'u' in the middle (before + 'u' + 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's a little more complex:
1. The base case needs to be "computing" instead of "u"
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 + '\n' + 'comp' + last_line + 'ting'``
Explanation:
The change of base case is because you want to print "computing" when n=1 and not just "u".
And the way to thing about the rest is that on each stage, you're taking the last line from the result so far and adding a 'comp' to the front and a 'ting' to the end, then attaching this to the result.
So the base case is 'computing'. Then for n=2, we get the recursive result for n-1 (which is 1) which will give us 'computing'. The last line from this result is the only line (i.e. 'computing'). Then we add a 'comp' and a 'ting' and attach it to the whole result giving us "computing\ncompcomputingting".
For n=3, the recc_result is "computing\ncompcomputingting" from which we take the last line ("compcomputingting") and then add a comp and ting making "compcompcomputingtingting" and attach it to the whole result giving "computing\ncompcomputingting\ncompcompcomputingtingting"
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 < 0) {
return "Must be postive integer";
}
if (n > 1000) {
return "Cannot be greater than 1000";
}
if (n > 0) {
System.out.println(acc);
acc = "comp" + acc + "ting";
return madComputing(n - 1, acc);
} else {
return "";
}
}
Or if you can not add an accumulator:
public static String madComputing(int n) {
if (n < 0) {
return "Must be postive integer";
}
if (n > 1000) {
return "Cannot be greater than 1000";
}
if (n >= 0) {
String value = "comp" + (n == 0 ? "u" : madComputing(n - 1))+ "ting";
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 = "";
String half = "";
if (n < 0)
return "Has to be positive";
if (n > 1000)
return "Stackoverflow for values greater than 999";
if (n > 1) {// anything larger than 1
res = "" + madComputing(n - 1);// assign the recursive call to var res to split and access it's substring
// System.out.println(res); if you leave this in, it will print at each level
half = res.substring(res.lastIndexOf("\n") + 1);// get the last indexed value
return "comp" + half + "ting";// use half to complete my method which will print for any n less than 1000
} else {
return "computing";// this is the base case when n == 1
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论