problem

Problem: A vector of integers is given. Program should Reduce the vector of integers by cumulatively applying a function to every two digits, starting from the beginning and return final result.

For example: vector A = 1,2,3,4,5
Program calculates ((((1+2)+3)+4)+5) and returns final result

where + is a "function". It should work for any function.

Any ideas??
Use a loop and call the function in it. The first time pass the first two elements of the vector, in the other iterations pass the old result and the next element
Bazzy, in that case, I will need to call the function twice (first with the first two values and the second time inside the loop, with the old result and the third value and so on), which kind of makes me think it as not the best solution.

I have posted recursive solution. I have a feeling this can be solved using something from <algorithm> header or using boost::bind (not very knowledgeable, would like to find out though).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
int Reduce(const vector<int>& vec, int(*myFunc)(int, const vector<int>&))
{
	int num = myFunc(vec.size()-1, vec);
	return num;
}

int plus(int n, const vector<int>& vec)
{
	if(n == 1)
	  return (vec[n] + vec[n-1]);

	int num = vec[n] + (plus(n-1, vec));
	return num;
}

int multiply();

int main()
{
	vector<int> vec;
	vec.push_back(1);
	vec.push_back(2);
	vec.push_back(3);
	vec.push_back(4);

	int num = Reduce(vec, &plus);
	cout << "Reduced value is: " << num << endl;

	return 0;
}


Would certainly like to know about other solutions. Thanks!
Last edited on
I will need to call the function twice (first with the first two values and the second time inside the loop, with the old result and the third value and so on)

Not true, you need to put the first element as the starting result
pseudocode:
1
2
3
result = first element of the fector
from the second to the last element of the vector
   result = function ( result, element )
Thank you!
Topic archived. No new replies allowed.