Skip to content

Instantly share code, notes, and snippets.

@tatarurzvn
Created November 18, 2017 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tatarurzvn/58ba6cfdda7b1c84420dfa7afc698f59 to your computer and use it in GitHub Desktop.
Save tatarurzvn/58ba6cfdda7b1c84420dfa7afc698f59 to your computer and use it in GitHub Desktop.
Greedy exercise
#include <stdio.h>
#define MAX_WEIGHT 10
int getValoare(float values[], float weights[], int size)
{
int currentWeight = 0;
int currentValue = 0;
int i = 0;
while (currentWeight < MAX_WEIGHT && i < size)
{
if (currentWeight + weights[i] < MAX_WEIGHT)
{
currentWeight += weights[i];
currentValue += values[i];
}
if (currentWeight + weights[i] >= MAX_WEIGHT)
{
currentValue += (MAX_WEIGHT - currentWeight) * (values[i] / weights[i]);
currentWeight = MAX_WEIGHT;
}
i++;
}
return (currentValue);
}
void sorteaza(float a[], float b[], int size)
{
float aux;
for (int i = 0; i < size; i++)
for (int j = i + 1; j < size; j++)
{
if (a[i] / b[i] < a[j] / b[j])
{
aux = a[i];
a[i] = a[j];
a[j] = aux;
aux = b[i];
b[i] = b[j];
b[j] = aux;
}
}
}
int main()
{
float values[6] = {7, 4, 2, 9, 4, 5};
float weights[6] = {3, 3, 1, 1, 2, 1};
sorteaza(values, weights, 6);
printf("%d", getValoare(values, weights, 6));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment