Kodewick
Jetzt lernen →
Mini-Aufgabe←→0 / 60

Den Rucksack packen

#027Mini-Aufgabetotal + weights[i] <= limit7 Min.

Für einen Campingausflug kann der Rucksack höchstens limit Kilo tragen. items[i] wiegt weights[i] Kilo. Geh sie der Reihe nach durch: Passt es noch, pack es ein; würde es zu schwer, lass es aus. Schreib pack(items, weights, limit), das zurückgibt, was eingepackt wurde.

Beispiele
pack({"tent", "stove", "book"}, {5, 3, 1}, 8)→['tent', 'stove']
pack({"tent", "stove", "book"}, {5, 4, 1}, 8)→['tent', 'book']
Die Funktionvector<string> pack(const vector<string> &items, const vector<int> &weights, int limit)
main.cpp
#include <string>
#include <vector>
using namespace std;

vector<string> pack(const vector<string> &items, const vector<int> &weights, int limit) {
    vector<string> bag;
    int total = 0;
    for (int i = 0; i < items.size(); i++) {
        // dein Code hier: passt das hier noch unter limit, steck es in bag und zähl es zu total dazu
    }
    return bag;
}
Strg + Enter führt den Code auch aus
Ergebnis

Ausführen testet die Beispiele. Wenn sie passen, drück auf Abgeben.