🔒 Locked
accumulate
Advertisement
Original Post
Accumulate adds up array elements (sequence elements, really). The first two parameters should be pointers to the beginning and to one-past-the end of the array, respectively (or begin() and end() of a container, or delimiting the range you want to add up).
int array[5] = { 1, 10, 100, 1000, 10000 };int sum = 0;accumulate(array, array+5, sum, plus<int>());// sum == 11111
From N1 to N2 seems pretty easy...
say we pick 5 and 18, if you match pairs you get 5 + 18, 6 + 17, 7 + 16, 8 + 15, 9 + 14, 10 + 13, 11 + 12, which means (N2 - N1 + 1 ) / 2 pairs... each pairs equals N1 + N2. Now, this is only if N2 - N1 + 1 is even, if its odd, you need to add the middle, say 5 and 9... 5 + 9, 6 + 8 and now 7... its (N2 + N1) / 2
there might be gazillions of ways to optimize it, but anyway
which outputs 45, 1 and 6. Since its counting FROM -> TO, 1,1 returns 1, not sure if its your desired behavior.
Hope this helps
Eric
say we pick 5 and 18, if you match pairs you get 5 + 18, 6 + 17, 7 + 16, 8 + 15, 9 + 14, 10 + 13, 11 + 12, which means (N2 - N1 + 1 ) / 2 pairs... each pairs equals N1 + N2. Now, this is only if N2 - N1 + 1 is even, if its odd, you need to add the middle, say 5 and 9... 5 + 9, 6 + 8 and now 7... its (N2 + N1) / 2
there might be gazillions of ways to optimize it, but anyway
#include <iostream>int accumulate(int in_from, int in_to){ const int inner = in_to - in_from + 1; const int pairs = inner / 2; const bool isOdd = inner % 2 ? true : false; const int pairValue = in_to + in_from; return ((pairs * pairValue) + (isOdd ? (pairValue / 2) : 0));}int main(int ac, char *av[]){ std::cout << "accumulate " << accumulate(5, 10) << std::endl; std::cout << "accumulate " << accumulate(1, 1) << std::endl; std::cout << "accumulate " << accumulate(1,3) << std::endl; return 0;}which outputs 45, 1 and 6. Since its counting FROM -> TO, 1,1 returns 1, not sure if its your desired behavior.
Hope this helps
Eric
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement