Kodewick
Start learning →
Mini challenge←→0 / 60

Pack the bag

#027Mini challengevectorLoops7 min

For a camping trip, the backpack can carry at most limit kilos. items[i] weighs weights[i] kilos. Go through them in order: if it still fits, pack it; if it would be too heavy, skip it. Write pack(items, weights, limit) to return what got packed.

Examples
pack({"tent", "stove", "book"}, {5, 3, 1}, 8)→['tent', 'stove']
pack({"tent", "stove", "book"}, {5, 4, 1}, 8)→['tent', 'book']
The functionvector<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++) {
        // your code here: if this one still fits under limit, put it in bag and add to total
    }
    return bag;
}
Ctrl + Enter runs too
Result

Run tries the examples. When they look right, Submit.