Posts

Showing posts with the label recursion

Remove Consecutive Duplicates Recursively giving infinite recursion

Remove Consecutive Duplicates Recursively giving infinite recursion Not a homework question. I am self learning. I have to remove consecutive characters in a string by recursion. However the program I made is not working for inputs containing duplicates. It is goining in infinite recursion and hence gives segmentation fault. However it is working for inputs which doesn't have consecutive duplicates in them. I have tried debugging in Eclipse Ide but things get weird when I debug. (I know how to debug) but I can't figure out the things are different when I debug and when I run. I will give you example after my code. #include <iostream> #include <cstring> using namespace std; void removeConsecutiveDuplicates(char *input) { int l = strlen(input); if(l == 0) { return; } if(input[0] != input[1]) { removeConsecutiveDuplicates(input+1); return; } int i = 1; for(; input[i] != ''; ++i) { input[i-1] = input[i]; ...

Recursively calculate the sum of an Array of integers in JavaScript

Recursively calculate the sum of an Array of integers in JavaScript I wanted to write a JavaScript program to compute the sum of an array of integers Recursively . Expected Results Input : [1, 2, 3, 4, 5, 6] Output : 21 I achieved the above results with this code: function calculateSum(array) { if (array instanceof Array){ if (!array.some(isNaN)) { var total = 0; array.forEach(function (value) { total += value; }); return total; } return "Provide an Array with only Numeric Values"; } return "Please provide an Array"; } But I'm looking for a solution that uses Recursion . EDIT : I started doing the above exercise to practice Recursion . I was having a hard time figuring that out. So, That's why I posted this. I'd be glad if you understood. Thanks in advance. What have you tried? What specifically do you need help with? ...