Generating a sequence of squares with alternating signs.
In this assignment, you’ll implement and test a method that constructs and returns an array containing values that follow a very specific sequence: $(0, -1, 4, -9, 16, \ldots)$. As you can see, the magnitude of each value is the next perfect square in the sequence ($0 = 0^2, 1 = 1^2, 4 = 2^2, 9 = 3^2, 16 = 4^2$, etc.), but the signs alternate between positive and negative.
In the edu.cnm.deepdive.Generator
class, the oscillatingSquares
method is declared with the following signature, return type, and modifiers:
public static int[] oscillatingSquares(int length)
The implementation must not change the modifiers, return type, method name, parameter types/number/order, or possible exceptions shown above. For more method declaration details, see the Javadoc documentation.
The returned array must contain exactly length
elements.
The value of the element at index position n
must be equal to (-1)nn2.
For example,
Generator.oscillatingSquares(5);
would return
{0, -1, 4, -9, 16}
You may find it useful to create one or more additional static
methods as “helpers”; the problem can be solved without doing so, however.
Don’t hesitate to declare any constants (static final
fields) that you feel might simplify or clarify your code.
The method to be completed includes a TODO
comment to that effect.
These cases will be used to unit test the implementation:
length |
Expected return value of Generator.oscillatingSquares(length) |
---|---|
0 |
{} |
1 |
{0} |
5 |
{0, -1, 4, -9, 16} |
7 |
{0, -1, 4, -9, 16, -25, 36} |
10 |
{0, -1, 4, -9, 16, -25, 36, -49, 64, -81} |