Embercode
✕
Heaps and Priority QueuesQuick quiz

Ugly numbers and comparators

8 questions. Covers Custom comparators and tie-breaking.

Questions 1 to 5 of 8

  1. 1. What does this program print? ``cpp #include <algorithm> #include <cstddef> #include <iostream> #include <vector> int main() { std::vector<long long> ugly{1}; std::size_t i2 = 0, i3 = 0, i5 = 0; while (ugly.size() < 7) { long long a = ugly[i2] * 2, b = ugly[i3] * 3, c = ugly[i5] * 5; long long next = std::min({a, b, c}); ugly.push_back(next); if (next == a) ++i2; if (next == b) ++i3; if (next == c) ++i5; } for (long long v : ugly) std::cout << v << ' '; std::cout << '\n'; } ``
  2. 2. What does this program print? ``cpp #include <iostream> #include <queue> #include <string> #include <vector> using namespace std; struct Job { string name; int priority; int seq; }; struct ByPriorityThenSeq { bool operator()(const Job& a, const Job& b) const { if (a.priority != b.priority) return a.priority < b.priority; return a.seq > b.seq; } }; int main() { priority_queue<Job, vector<Job>, ByPriorityThenSeq> pq; int next = 0; auto push = [&](string name, int p) { pq.push({std::move(name), p, next++}); }; push("A", 2); push("B", 1); push("C", 2); push("D", 3); push("E", 1); push("F", 2); while (!pq.empty()) { cout << pq.top().name << ' '; pq.pop(); } cout << '\n'; } ``
  3. 3. A priority_queue<Item, vector<Item>, BadCompare> uses this comparator. What is the bug? ``cpp struct Item { int key; int id; }; struct BadCompare { bool operator()(const Item& a, const Item& b) const { return a.key <= b.key; } }; ``
  4. 4. This program builds ugly numbers with three pointers, but its output has a repeated value: 1 2 3 4 5 6 6 8. Which line causes it? ``cpp #include <algorithm> #include <cstddef> #include <iostream> #include <vector> int main() { std::vector<long long> ugly{1}; std::size_t i2 = 0, i3 = 0, i5 = 0; while (ugly.size() < 8) { long long a = ugly[i2] * 2, b = ugly[i3] * 3, c = ugly[i5] * 5; long long next = std::min({a, b, c}); ugly.push_back(next); if (next == a) ++i2; else if (next == b) ++i3; if (next == c) ++i5; } for (long long v : ugly) std::cout << v << ' '; std::cout << '\n'; } ``
  5. 5. Why can every ugly number after 1 be built from an earlier one?

5 question(s) left on this page.