Created
November 18, 2017 20:31
-
-
Save tatarurzvn/58ba6cfdda7b1c84420dfa7afc698f59 to your computer and use it in GitHub Desktop.
Greedy exercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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