45 -34 8 7 48 -30
45 -34 8 7 48 //max 55 the sum of the two vector is (45 11 -26 15 55 18)
45 -34 8 7 // here I find the 63 the sum of 3 vectr till yet is (45 11 19 -19 63 25)
45 -34 8 // max 45 sum is 45 11 19 26 29 33
45 -34 //max 74 sum is 45 11 19 26 74 -1 we found a max of 74 for a sum of 4 elements
45 <- max 74 no change here…
45 11 19 26 74 44
/*
* test.c
*
* Created on: 15 dc. 2011
* Author: RARVA.Riendf
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define VALUE_NUMBER 5000
int data[VALUE_NUMBER] =
{paste data here};
struct max {
int pos;
int value;
};
struct max findMax(int data[]) {
struct max currentMax;
currentMax.pos = 0;
currentMax.value = data[0];
int i;
for ( i = 0;i < VALUE_NUMBER;i ++) {
if (data[i] >= currentMax.value) {
currentMax.pos = i;
currentMax.value = data[i];
}
}
return currentMax;
}
void switchData(int data[]) {
int i;
for ( i = VALUE_NUMBER - 1;i > 0;i –)
data[i] = data[i - 1];
data[0] = 0;
}
void copyData(int data[], int targetData[]) {
int i;
for (i = 0;i < VALUE_NUMBER;i ++)
targetData[i] = data[i];
}
void sumData(int data[], int data1[]) {
int i;
for (i = 0;i < VALUE_NUMBER;i ++)
data1[i] += data[i];
}
struct max maxof(struct max max1, struct max max2) {
if (max1.value > max2.value)
return max1;
if (max2.value > max1.value)
return max2;
return max1.pos > max2.pos ? max1 : max2;
}
int main() {
struct max currentMax, tempMax;
currentMax = findMax(data);
int nbElements = VALUE_NUMBER;
int currentData[VALUE_NUMBER];
copyData(data, currentData);
int switchedVector[VALUE_NUMBER];
copyData(data, switchedVector);
while (nbElements) {
nbElements –;
switchData(switchedVector);
sumData(switchedVector, currentData); //<- (if data is 1 2 3 it does 1 2 3 + 0 1 2 next loop it will be 1 3 5 + 0 0 1) I know it is possible in binary with the appropriate << and &
tempMax = findMax(currentData); //<- find the highest value and its position, and this can be heavily and easily parallized if needed
currentMax = maxof(tempMax, currentMax); // <- pick the highest one
}
fprintf(stderr, "%d\n\r", currentMax.value);
fprintf(stderr, "%d", currentMax.pos);
fflush(stderr);
fflush(stdout);
return 0;
}
Sorry, it still isn't very clear. :sad:
You're summing data… but why does sum have a second parameter? What does it mean to execute a switch statement on 'data', using the sizeof an int as a parameter?
And this problem is very different from finding the maximum element in an array!
[100 -200 25 25 25 25 25 25]
it should be very clear that the largest element has nothing to do with the solution.
Agreed in the vast majority of cases. Just to quibble, though, sometimes, it is – if your algorithm is accessing data in a way that the hardware architecture doesn't like, you can make your solution go from ok to very bad. (e.g., processor caching, data access speed, etc.)
Unless of course you meant the high-level algorithm, like from a mathematical standpoint, not its implementation, in which case I agree with you unreservedly.