Embercode
✕
Greedy AlgorithmsQuick quiz

Greedy bug hunt

8 questions. Covers Debugging lab: greedy bugs.

Questions 1 to 5 of 8

  1. 1. The function should return the most units a truck can carry. The input is five boxes of type A (3 units each) and one box of type B (10 units each), with a truck size of 5. It returns 15 instead of 22. What is the bug? ``cpp int maxUnits(std::vector<BoxType> types, int truckSize) { std::ranges::sort(types, std::greater{}, &BoxType::boxes); int total = 0; for (const BoxType& t : types) { int take = std::min(t.boxes, truckSize); total += take * t.unitsPerBox; truckSize -= take; } return total; } ``
  2. 2. What does this program print? ``cpp #include <cstddef> #include <iostream> #include <vector> std::size_t cheapest_buggy(const std::vector<int>& prices) { std::size_t best = 0; for (std::size_t i = 1; i < prices.size(); ++i) { if (prices[i] <= prices[best]) best = i; } return best; } std::size_t cheapest_fixed(const std::vector<int>& prices) { std::size_t best = 0; for (std::size_t i = 1; i < prices.size(); ++i) { if (prices[i] < prices[best]) best = i; } return best; } int main() { std::vector<int> prices = {6, 3, 9, 3, 3}; std::cout << "buggy " << cheapest_buggy(prices) << " fixed " << cheapest_fixed(prices) << '\n'; } ``
  3. 3. The comment says this function returns the earliest index when prices tie. For prices 4, 2, 7, 2, 9 it returns 3. What is the bug? ``cpp std::size_t cheapest(const std::vector<int>& prices) { std::size_t best = 0; for (std::size_t i = 1; i < prices.size(); ++i) { if (prices[i] <= prices[best]) best = i; } return best; } ``
  4. 4. Which test input is best at exposing the tie bug in cheapest?
  5. 5. The problem says a pair fits when the total is at most the limit. For people of weight 1 and 2 with limit 3, it returns 2 boats instead of 1. What is the bug? ``cpp int boats(std::vector<int> people, int limit) { std::ranges::sort(people); int lo = 0; int hi = static_cast<int>(people.size()) - 1; int count = 0; while (lo <= hi) { if (people[lo] + people[hi] < limit) ++lo; --hi; ++count; } return count; } ``

5 question(s) left on this page.