diff --git a/leetcode/2418.cpp b/leetcode/2418.cpp new file mode 100644 index 0000000..85ae902 --- /dev/null +++ b/leetcode/2418.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include + +#include + +using std::string; +using std::vector; + +vector sort_strings_by_ints(vector strings, vector ints) { + vector indices(ints.size()); + std::iota(indices.begin(), indices.end(), 0); + std::ranges::stable_sort(indices, + [&ints](int a, int b) { + return ints[a] > ints[b]; }); + vector result(strings.size()); + for (int i = 0; i < static_cast(strings.size()); i++) + result[i] = strings[indices[i]]; + return result; } + +TEST(sort_strings_by_ints, a) { + EXPECT_EQ((vector{"foo", "bar", "baz"}), + sort_strings_by_ints({"bar", "foo", "baz"}, {1, 3, 1})); } + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); } diff --git a/leetcode/885.cpp b/leetcode/885.cpp new file mode 100644 index 0000000..7352133 --- /dev/null +++ b/leetcode/885.cpp @@ -0,0 +1,36 @@ +#include +#include +#include + +#include + +using std::map; +using std::pair; +using std::vector; + +const map next{{'E', 'S'}, {'S', 'W'}, {'W', 'N'}, {'N', 'E'}}; + +const map> deltas{{'E', {0, +1}}, {'S', {+1, 0}}, {'W', {0, -1}}, {'N', {-1, 0}}}; + +vector> spiral_matrix_iii(int rows, int cols, int rStart, int cStart) { + vector> ans{{rStart, cStart}}; + int r = rStart, c = cStart; + int step = 1, i = 0; + char dir = 'E'; + while (ans.size() < static_cast(rows) * cols) { + const auto& [dr, dc] = deltas.at(dir); + for (int i = 0; i < step; i++) { + r += dr; + c += dc; + if (0 <= r and r < rows and 0 <= c and c < cols) ans.push_back({r, c}); } + i++; + if (!(i % 2)) step++; + dir = next.at(dir); } + return ans; } + +TEST(spiral_matrix_iii, oversimple) { + EXPECT_EQ((vector>{{0, 0}, {0, 1}, {0, 2}, {0, 3}}), spiral_matrix_iii(1, 4, 0, 0)); } + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); }