Skip to content

Commit

Permalink
Leetcode (#31)
Browse files Browse the repository at this point in the history
* Add leetcode problem of the day

* Add leetcode problem of the day
  • Loading branch information
iglesias authored Aug 8, 2024
1 parent e1ae694 commit d098ec1
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
28 changes: 28 additions & 0 deletions leetcode/2418.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#include <algorithm>
#include <numeric>
#include <string>
#include <vector>

#include <gtest/gtest.h>

using std::string;
using std::vector;

vector<string> sort_strings_by_ints(vector<string> strings, vector<int> ints) {
vector<int> 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<string> result(strings.size());
for (int i = 0; i < static_cast<int>(strings.size()); i++)
result[i] = strings[indices[i]];
return result; }

TEST(sort_strings_by_ints, a) {
EXPECT_EQ((vector<string>{"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(); }
36 changes: 36 additions & 0 deletions leetcode/885.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#include <map>
#include <utility>
#include <vector>

#include <gtest/gtest.h>

using std::map;
using std::pair;
using std::vector;

const map<char, char> next{{'E', 'S'}, {'S', 'W'}, {'W', 'N'}, {'N', 'E'}};

const map<char, pair<int, int>> deltas{{'E', {0, +1}}, {'S', {+1, 0}}, {'W', {0, -1}}, {'N', {-1, 0}}};

vector<vector<int>> spiral_matrix_iii(int rows, int cols, int rStart, int cStart) {
vector<vector<int>> ans{{rStart, cStart}};
int r = rStart, c = cStart;
int step = 1, i = 0;
char dir = 'E';
while (ans.size() < static_cast<uint64_t>(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<vector<int>>{{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(); }

0 comments on commit d098ec1

Please sign in to comment.