finding minimal sum in array greater than given constraint
Hi all. I have problem finding minimal sum in a given array of elements that is greater than given value. for example:
1 2 3 4 5
|
void main()
{
double array[] = {5.8,1.2,3.4,0.6,4.1};
double constraint = 4.5;//Given result should be 1.2 + 3.4 = 4.6
}
| |
Main problem is that array is generally dynamic.
Thanks in advance!
Post your code, so that we can see what is the problem. No one is going to write the code for you.
Main problem is that array is generally dynamic. |
You should still know its length. BTW the array in line 3 is not dynamic.
here's the code
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
#include "stdafx.h"
#include <iostream>
using namespace std;
#include<stdlib.h>
#include<time.h>
double MinimalSum(const double* arr, const int length, double constraint);
int _tmain(int argc, _TCHAR* argv[])
{
int myLength = 5;
double* myArray = new double[myLength];
myArray[0] = 1.2;
myArray[1] = 0.6;
myArray[2] = 3.7;
myArray[3] = 4.1;
myArray[4] = 6.2;
cout << "Minimal sum is " << MinimalSum(myArray,myLength,8.1) << endl;
return 0;
}
double MinimalSum(const double* arr, const int length, double constraint)
{
double sum = 0.0;
double tempSum = 0.0;
for(int i = 0; i < length; i++)
{
tempSum = arr[i];
int firstIndex = i;
for (int j = 0; j < length; j++)
{
if (j == firstIndex)
continue;
if(tempSum >= constraint)
{
if(sum == 0.0 || tempSum < sum)
{
sum = tempSum;
tempSum = 0.0;
j = 0;
}
}
tempSum += arr[j];
}
}
return sum;
}
| |
it seams to me that numbers of loops depends of numbers of array elements
Last edited on
Topic archived. No new replies allowed.