Skip to content

Instantly share code, notes, and snippets.

@nimi0112
Created October 4, 2022 08:48
Show Gist options
  • Save nimi0112/e6d0fcec2d1281a3e1366e99531f3a50 to your computer and use it in GitHub Desktop.
Save nimi0112/e6d0fcec2d1281a3e1366e99531f3a50 to your computer and use it in GitHub Desktop.
void main() {
int bagCapacityInKg = 10;
final input = <Pair<int, int>>[
Pair<int, int>(2, 1000),
Pair<int, int>(4, 8000),
Pair<int, int>(3, 6000),
Pair<int, int>(3, 18000),
Pair<int, int>(12, 12000),
];
final filteredInput =
input.where((element) => element.first <= bagCapacityInKg).toList();
filteredInput.sort((a, b) => math.max(a.second, b.second));
int currentWeight = 0;
int currentValue = 0;
for (var i = 0; i < filteredInput.length; i++) {
final tempWeight = currentWeight + filteredInput[i].first;
if (currentWeight < tempWeight && tempWeight < bagCapacityInKg) {
currentWeight = tempWeight;
currentValue += filteredInput[i].second;
print("adding ${filteredInput[i].first}");
}
}
print('max weight is $currentWeight');
print('max value is $currentValue');
}
class Pair<Type1, Type2> {
final Type1 first;
final Type2 second;
Pair(this.first, this.second);
Pair<Type1, Type2> copyWith({
Type1? first,
Type2? second,
}) {
return Pair<Type1, Type2>(
first ?? this.first,
second ?? this.second,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment