当对象只有最终字段时,如何编写递归方法来生成算术序列?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了当对象只有最终字段时,如何编写递归方法来生成算术序列?相关的知识,希望对你有一定的参考价值。
所以我正在完成我的第一个CS类,所以我的经验肯定是在低端,但是对于一个赋值,我必须创建一个方法来生成并返回算术序列中索引n的数量,并带有起始值init和常见差异差异
这根本不容易使用递归,但需要递归。我也仅限于可以使用的字段,方法和方法签名。
我也了解如何使用下面的代码制作此方法。
public class ArithmeticNumberGenerator implements NumberGenerator {
private int init; // first term in the sequence
private final int diff; // common difference
/**
* Constructs an arithmetic number generator with given
* start value init and common difference diff
* @param init start value
* @param diff common difference
* @throws IllegalArgumentException if any of the input arguments
* is illegal
*/
public ArithmeticNumberGenerator(int init, int diff) throws
IllegalArgumentException {
if (init < 0 || diff < 0)
throw new IllegalArgumentException("Cannot use negative numbers.");
else {
this.init = init;
this.diff = diff;
}
}
@Override
public int generateNumber(int n) {
// Time Complexity: O(?)
// This method generates the number of index n
// in an arithmetic sequence recursively
if (n == 0)
return init;
else {
init = init + diff;
return generateNumber(n - 1);
}
}
}
但是,对于赋值,“init”字段应该是final,并且在这种情况下我无法弄清楚如何实现此方法。任何帮助将不胜感激。
答案
如果我正确理解了问题,你必须使用递归,并且上面的所有方法签名都是固定的,并且init
必须是最终的。以下遵守这些规则。
public static class ArithmeticNumberGenerator implements NumberGenerator {
private final int init; // first term in the sequence
private final int diff; // common difference
/**
* Constructs an arithmetic number generator with given start value init
* and common difference diff
*
* @param init
* start value
* @param diff
* common difference
* @throws IllegalArgumentException
* if any of the input arguments is illegal
*/
public ArithmeticNumberGenerator(int init, int diff) throws IllegalArgumentException {
if (init < 0 || diff < 0)
throw new IllegalArgumentException("Cannot use negative numbers.");
else {
this.init = init;
this.diff = diff;
}
}
@Override
public int generateNumber(int n) {
// Time Complexity: O(?)
// This method generates the number of index n
// in an arithmetic sequence recursively
if (n == 0)
return init;
else {
ArithmeticNumberGenerator g = new ArithmeticNumberGenerator(init+diff, diff);
return g.generateNumber(n - 1);
}
}
}
以上是关于当对象只有最终字段时,如何编写递归方法来生成算术序列?的主要内容,如果未能解决你的问题,请参考以下文章