Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //main variable for storing solution.
- var ears;
- /**
- * Sets collector variable to 0 and calls the recursion function.
- * @param {number} amountOfBunnies - The amount of bunnies that need to have ears counted.
- * @return {(number | string)} - Return either the solution or error message if parameters were invalid.
- */
- function recursiveCalculateEars(amountOfBunnies) {
- if (typeof amountOfBunnies == 'number'){
- ears = 0;
- return recursion(amountOfBunnies);
- } else {
- return 'Invalid parameters.';
- }
- /**
- * Main recursion function, recalls itself untill i == 0.
- * @param {number} i
- * @return {number} - The total amount of ears counted according to the variable ears.
- */
- function recursion(i){
- if (i > 0){
- ears += 2;
- return recursion(i - 1);
- } else if(i < 0){
- ears -= 2;
- return recursion(i + 1);
- } else if(i == 0){
- return ears;
- }
- }
- }
- /**
- * Iteratively calculates amount of bunny ears using a for loop.
- * @param {number} amountOfBunnies - The amount of bunnies to be calculated.
- * @return {(number | string)} - Return either the solution or error message if parameters were invalid.
- */
- function iterativeCalculateEars(amountOfBunnies){
- if (typeof amountOfBunnies == 'number'){
- ears = 0;
- if (amountOfBunnies > 0){
- for (var i = amountOfBunnies; i > 0; i--){
- ears += 2;
- }
- }else if (amountOfBunnies < 0){
- for (var i = amountOfBunnies; i < 0; i++){
- ears -= 2;
- }
- }
- return ears;
- } else {
- return 'Invalid parameters.'
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement