logo CodeStepByStep logo

mirrorSequence

Language/Type: JavaScript recursion

Write a recursive function named mirrorSequence that accepts an integer parameter n and returns a (string) sequence of n numbers as in the table below. For odd numbers the sequence has a single 1 in the middle, while for even values it has two 1s in the middle. Throw an exception with the message "argument must be greater than 0" if passed a value less than 1.

Note: Because JavaScript integers are number types, dividing two integers which do not divide evenly returns the decimal value of the result instead of an integer (for example, 1 / 2 results in 0.5, not 0). Use parseInt(a / b) to parse the result into an integer if needed to solve this problem.

Call Return
mirrorSequence(1) 1
mirrorSequence(2) 1 1
mirrorSequence(3) 2 1 2
mirrorSequence(4) 2 1 1 2
mirrorSequence(5) 3 2 1 2 3
mirrorSequence(6) 3 2 1 1 2 3
mirrorSequence(7) 4 3 2 1 2 3 4
mirrorSequence(8) 4 3 2 1 1 2 3 4
mirrorSequence(9) 5 4 3 2 1 2 3 4 5
mirrorSequence(10) 5 4 3 2 1 1 2 3 4 5
Function: Write a JavaScript function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.