Advent of Code 2024: A Reflection on Using Q
Finally finished the 24.5 days of the advent of code using q this year https://github.com/jglara/aoc-2024-q, not without help from reddit group. I could not have finished it alone for some of the hardest problems; and I can not say I am proud of my solutions, even more after looking at real experts in q solutions like https://q.kx.com/aoc24/index.html; but I really liked the experience.
Key Takeaways
Q vs. C++
After completing the Advent of Code challenges in Q, I was curious to see how I would fare using C++. Initially, I thought it would be straightforward to translate the Q code to C++, but I found that the C++ solutions were not as elegant.
Compare solutions for Day 1 in both languages:
领英推荐
Q:
/ part 1: sum differences after ordering
d1p1:{ sum abs (asc x[;0]) - (asc x[;1]) }
/ part 2: count each different value in second column and multiply key by value if it appears in column 1
d1p2:{ k: count each group x[;1]; sum x[;0] k x[;0] }
C++:
int day01a(std::vector<int> &c1, std::vector<int> &c2) {
std::ranges::sort(c1);
std::ranges::sort(c2);
auto total = std::ranges::fold_left(
std::views::zip(c1, c2) |
std::views::transform([](const auto &p) {
auto [a,b] = p;
return std::abs(a-b);
}),
0,
std::plus<>{});
return total;
}
int day01b(std::vector<int> &c1, std::vector<int> &c2)
{
std::unordered_map<int, int> m;
std::ranges::for_each(c2, [&m] (const auto &x) {
m[x]++;
});
auto total = std::ranges::fold_left(
c1 | std::views::transform([&m] (auto x) {
return x*m[x];
}),
0,
std::plus<>{});
return total;
}
For learning more about q language this is a good guide: https://www.defconq.tech/docs/studyPlan/kdbDevs
Software Designer at Ericsson
1 个月Thanks for your blog, it is very useful for newcomers to q
KDB/Q Consultant | Blogger | DefconQ | Data Intellect
1 个月Thanks for mentioning my blog post ??