diff --git a/cpp/.clang-format b/cpp/.clang-format new file mode 100644 index 0000000..501c439 --- /dev/null +++ b/cpp/.clang-format @@ -0,0 +1,235 @@ +--- +Language: Cpp +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseColons: false +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterExternBlock: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAfterAttributes: Never +BreakAfterJavaFieldAnnotations: false +BreakArrays: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Attach +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: false +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: None +IndentRequiresClause: true +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +KeepEmptyLinesAtEOF: false +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PackConstructorInitializers: BinPack +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +PPIndentWidth: -1 +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE +... + diff --git a/cpp/assign-cookies.cpp b/cpp/assign-cookies.cpp index cb8a89e..d5656cb 100644 --- a/cpp/assign-cookies.cpp +++ b/cpp/assign-cookies.cpp @@ -2,7 +2,7 @@ #include class Solution { -public: + public: int findContentChildren(std::vector g, std::vector s) { std::sort(g.begin(), g.end()); std::sort(s.begin(), s.end()); @@ -18,4 +18,3 @@ public: return content; } }; - diff --git a/cpp/boats-to-save-people.cpp b/cpp/boats-to-save-people.cpp index 7e6905c..3aceb74 100644 --- a/cpp/boats-to-save-people.cpp +++ b/cpp/boats-to-save-people.cpp @@ -2,9 +2,8 @@ #include class Solution { -public: - int numRescueBoats(std::vector people, int limit) - { + public: + int numRescueBoats(std::vector people, int limit) { std::sort(people.begin(), people.end()); int counter = 0; diff --git a/cpp/calculate-money-in-leetcode-bank.cpp b/cpp/calculate-money-in-leetcode-bank.cpp index b799b41..c9c87f6 100644 --- a/cpp/calculate-money-in-leetcode-bank.cpp +++ b/cpp/calculate-money-in-leetcode-bank.cpp @@ -1,5 +1,5 @@ class Solution { -public: + public: int totalMoney(int n) { auto monday = 1; diff --git a/cpp/can-place-flowers.cpp b/cpp/can-place-flowers.cpp index 31df119..4a63f31 100644 --- a/cpp/can-place-flowers.cpp +++ b/cpp/can-place-flowers.cpp @@ -4,9 +4,8 @@ using std::vector; class Solution { -public: - bool canPlaceFlowers(vector& flowerbed, int n) - { + public: + bool canPlaceFlowers(vector &flowerbed, int n) { int count = 0; int left = 0, right; @@ -25,21 +24,20 @@ public: } }; -int main() -{ +int main() { Solution s; - std::vector flowers { 1, 0, 0, 0, 1 }; + std::vector flowers{1, 0, 0, 0, 1}; assert(s.canPlaceFlowers(flowers, 1)); assert(!s.canPlaceFlowers(flowers, 2)); - flowers = { 1, 0, 0, 0, 0, 1 }; + flowers = {1, 0, 0, 0, 0, 1}; assert(!s.canPlaceFlowers(flowers, 2)); - flowers = { 1, 0, 0, 0, 1, 0, 0 }; + flowers = {1, 0, 0, 0, 1, 0, 0}; assert(s.canPlaceFlowers(flowers, 2)); - flowers = { 0, 0, 1, 0, 0 }; + flowers = {0, 0, 1, 0, 0}; assert(s.canPlaceFlowers(flowers, 1)); return 0; diff --git a/cpp/concatenation-of-consecutive-binary-numbers.cpp b/cpp/concatenation-of-consecutive-binary-numbers.cpp index 999a72d..4d46277 100644 --- a/cpp/concatenation-of-consecutive-binary-numbers.cpp +++ b/cpp/concatenation-of-consecutive-binary-numbers.cpp @@ -3,9 +3,8 @@ class Solution { static const int MOD = 1000000007; -public: - int concatenatedBinary(int n) - { + public: + int concatenatedBinary(int n) { long joined_number = 0; int padding = 1; @@ -21,8 +20,7 @@ public: } }; -int main() -{ +int main() { Solution s; assert(s.concatenatedBinary(1) == 1); diff --git a/cpp/convert-an-array-into-a-2d-array-with-conditions.cpp b/cpp/convert-an-array-into-a-2d-array-with-conditions.cpp index 62d6bd8..aa868be 100644 --- a/cpp/convert-an-array-into-a-2d-array-with-conditions.cpp +++ b/cpp/convert-an-array-into-a-2d-array-with-conditions.cpp @@ -2,8 +2,8 @@ #include class Solution { -public: - std::vector> findMatrix(const std::vector& nums) { + public: + std::vector> findMatrix(const std::vector &nums) { // count the numbers std::map freqs; for (auto x : nums) { @@ -17,7 +17,7 @@ public: elements_left = false; std::vector row; - for (auto& [num, count] : freqs) { + for (auto &[num, count] : freqs) { if (count <= 0) { continue; } @@ -32,4 +32,3 @@ public: return matrix; } }; - diff --git a/cpp/count-good-nodes-in-binary-tree.cpp b/cpp/count-good-nodes-in-binary-tree.cpp index 9905933..1299961 100644 --- a/cpp/count-good-nodes-in-binary-tree.cpp +++ b/cpp/count-good-nodes-in-binary-tree.cpp @@ -6,23 +6,21 @@ * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), + * right(right) {} * }; */ class Solution { - int goodNodes(TreeNode* root, int m) - { + int goodNodes(TreeNode *root, int m) { if (root == nullptr) { return 0; } int new_max = std::max(m, root->val); - return (root->val >= m) + goodNodes(root->left, new_max) + goodNodes(root->right, new_max); + return (root->val >= m) + goodNodes(root->left, new_max) + + goodNodes(root->right, new_max); } -public: - int goodNodes(TreeNode* root) - { - return goodNodes(root, INT_MIN); - } + public: + int goodNodes(TreeNode *root) { return goodNodes(root, INT_MIN); } }; diff --git a/cpp/count-negative-numbers-in-a-sorted-matrix.cpp b/cpp/count-negative-numbers-in-a-sorted-matrix.cpp index 7d26583..f3d24d4 100644 --- a/cpp/count-negative-numbers-in-a-sorted-matrix.cpp +++ b/cpp/count-negative-numbers-in-a-sorted-matrix.cpp @@ -3,14 +3,14 @@ #include class Solution { -public: - int countNegatives(const std::vector>& grid) - { + public: + int countNegatives(const std::vector> &grid) { auto last = 0; auto negatives = 0; - for (const auto& row : grid) { - auto first_positive = std::lower_bound(row.crbegin() + last, row.crend(), 0); + for (const auto &row : grid) { + auto first_positive = + std::lower_bound(row.crbegin() + last, row.crend(), 0); auto i = first_positive - row.crbegin(); negatives += i; @@ -20,11 +20,13 @@ public: } }; -int main() -{ +int main() { Solution s; - assert((s.countNegatives(std::vector { std::vector { 4, 3, 2, -1 }, std::vector { 3, 2, 1, -1 }, std::vector { 1, 1, -1, -2 }, std::vector { -1, -1, -2, -3 } }) == 8)); - assert((s.countNegatives(std::vector { std::vector { 3, 2 }, std::vector { 1, 0 } }) == 0)); + assert((s.countNegatives(std::vector{ + std::vector{4, 3, 2, -1}, std::vector{3, 2, 1, -1}, + std::vector{1, 1, -1, -2}, std::vector{-1, -1, -2, -3}}) == 8)); + assert((s.countNegatives( + std::vector{std::vector{3, 2}, std::vector{1, 0}}) == 0)); return 0; } diff --git a/cpp/count-ways-to-build-good-strings.cpp b/cpp/count-ways-to-build-good-strings.cpp index 2c33e30..74cec4b 100644 --- a/cpp/count-ways-to-build-good-strings.cpp +++ b/cpp/count-ways-to-build-good-strings.cpp @@ -2,43 +2,43 @@ #include class Solution { - constexpr static int MOD = 1000000007; + constexpr static int MOD = 1000000007; - static void add_with_mod(std::vector& good, std::size_t i, int value) { - good[i] = (good[i] + value) % MOD; - } - - public: - int countGoodStrings(int low, int high, int zero, int one) { - assert(low <= high); - - std::vector good(high + 1, 0); - good[0] = 1; - - for (int length = 1; length <= high; ++length) { - if (length >= zero) { - add_with_mod(good, length, good[length - zero]); - } - - if (length >= one) { - add_with_mod(good, length, good[length - one]); - } + static void add_with_mod(std::vector &good, std::size_t i, int value) { + good[i] = (good[i] + value) % MOD; } - int total = 0; - for (int i = low; i <= high; ++i) { - total = (total + good[i]) % MOD; - } + public: + int countGoodStrings(int low, int high, int zero, int one) { + assert(low <= high); - return total; - } + std::vector good(high + 1, 0); + good[0] = 1; + + for (int length = 1; length <= high; ++length) { + if (length >= zero) { + add_with_mod(good, length, good[length - zero]); + } + + if (length >= one) { + add_with_mod(good, length, good[length - one]); + } + } + + int total = 0; + for (int i = low; i <= high; ++i) { + total = (total + good[i]) % MOD; + } + + return total; + } }; int main() { - Solution s; + Solution s; - assert(s.countGoodStrings(3, 3, 1, 1) == 8); - assert(s.countGoodStrings(2, 3, 1, 2) == 5); + assert(s.countGoodStrings(3, 3, 1, 1) == 8); + assert(s.countGoodStrings(2, 3, 1, 2) == 5); - return 0; + return 0; } diff --git a/cpp/design-parking-system.cpp b/cpp/design-parking-system.cpp index 0f12713..288415b 100644 --- a/cpp/design-parking-system.cpp +++ b/cpp/design-parking-system.cpp @@ -5,8 +5,7 @@ class ParkingSystem { int medium; int small; - int& get(int carType) - { + int &get(int carType) { switch (carType) { case 1: return big; @@ -19,17 +18,12 @@ class ParkingSystem { } } -public: + public: ParkingSystem(int big, int medium, int small) - : big(big) - , medium(medium) - , small(small) - { - } + : big(big), medium(medium), small(small) {} - bool addCar(int carType) - { - auto& space = get(carType); + bool addCar(int carType) { + auto &space = get(carType); if (space <= 0) { return false; } diff --git a/cpp/determine-if-two-strings-are-close.cpp b/cpp/determine-if-two-strings-are-close.cpp index b9dbb2f..75cc5f4 100644 --- a/cpp/determine-if-two-strings-are-close.cpp +++ b/cpp/determine-if-two-strings-are-close.cpp @@ -5,9 +5,8 @@ class Solution { using freq_t = std::array; - freq_t freqs(const std::string& word) - { - freq_t f { 0 }; + freq_t freqs(const std::string &word) { + freq_t f{0}; for (auto c : word) { f[c - 'a']++; @@ -16,8 +15,7 @@ class Solution { return f; } - int mask(const freq_t& f) - { + int mask(const freq_t &f) { int m = 0; for (auto c : f) { @@ -27,9 +25,8 @@ class Solution { return m; } -public: - bool closeStrings(std::string word1, std::string word2) - { + public: + bool closeStrings(std::string word1, std::string word2) { auto f1 = freqs(word1); auto m1 = mask(f1); std::sort(f1.begin(), f1.end()); diff --git a/cpp/find-smallest-letter-greater-than-target.cpp b/cpp/find-smallest-letter-greater-than-target.cpp index e46a482..641b38d 100644 --- a/cpp/find-smallest-letter-greater-than-target.cpp +++ b/cpp/find-smallest-letter-greater-than-target.cpp @@ -3,21 +3,19 @@ #include class Solution { -public: - char nextGreatestLetter(const std::vector& letters, char target) - { + public: + char nextGreatestLetter(const std::vector &letters, char target) { auto it = std::lower_bound(letters.begin(), letters.end(), target + 1); return it == letters.end() ? letters.front() : *it; } }; -int main() -{ +int main() { Solution s; - assert((s.nextGreatestLetter(std::vector { 'c', 'f', 'j' }, 'a') == 'c')); - assert((s.nextGreatestLetter(std::vector { 'c', 'f', 'j' }, 'c') == 'f')); - assert((s.nextGreatestLetter(std::vector { 'x', 'x', 'y', 'y' }, 'z') == 'x')); + assert((s.nextGreatestLetter(std::vector{'c', 'f', 'j'}, 'a') == 'c')); + assert((s.nextGreatestLetter(std::vector{'c', 'f', 'j'}, 'c') == 'f')); + assert((s.nextGreatestLetter(std::vector{'x', 'x', 'y', 'y'}, 'z') == 'x')); return 0; } diff --git a/cpp/knight-dialer.cpp b/cpp/knight-dialer.cpp index b305d48..5c0791c 100644 --- a/cpp/knight-dialer.cpp +++ b/cpp/knight-dialer.cpp @@ -20,7 +20,7 @@ class Solution { static int add(int x, int y) { return (x + y) % 1000000007; } - static int get(const std::vector& dp, int it, int idx) { + static int get(const std::vector &dp, int it, int idx) { if (it < 0 || it >= static_cast(dp.size())) { return 0; } @@ -32,7 +32,7 @@ class Solution { return dp[it][idx]; } - static void dpIteration(std::vector& dp, int it) { + static void dpIteration(std::vector &dp, int it) { for (int i = 0; i < 12; ++i) { if (!isValidMove(i)) { continue; @@ -59,7 +59,7 @@ class Solution { } } - public: + public: int knightDialer(int n) { std::vector dp(n); diff --git a/cpp/kth-smallest-element-in-a-sorted-matrix.cpp b/cpp/kth-smallest-element-in-a-sorted-matrix.cpp index 42aceed..ca756ad 100644 --- a/cpp/kth-smallest-element-in-a-sorted-matrix.cpp +++ b/cpp/kth-smallest-element-in-a-sorted-matrix.cpp @@ -6,9 +6,8 @@ using namespace std; class Solution { -public: - int kthSmallest(vector>& matrix, int k) - { + public: + int kthSmallest(vector> &matrix, int k) { int low = matrix.front().front(); int high = matrix.back().back(); @@ -16,7 +15,7 @@ public: int mid = low + (high - low) / 2; int rank = 0; - for (const auto& row : matrix) { + for (const auto &row : matrix) { rank += upper_bound(row.begin(), row.end(), mid) - row.begin(); } @@ -31,22 +30,17 @@ public: } }; -int main() -{ +int main() { Solution s; vector> m; int k; - m = { - { 1, 5, 9 }, - { 10, 11, 13 }, - { 12, 13, 15 } - }; + m = {{1, 5, 9}, {10, 11, 13}, {12, 13, 15}}; k = 8; assert(s.kthSmallest(m, k) == 13); - m = { { -5 } }; + m = {{-5}}; k = 1; assert(s.kthSmallest(m, k) == -5); } diff --git a/cpp/largest-odd-number-in-string.cpp b/cpp/largest-odd-number-in-string.cpp index feeefef..09649d8 100644 --- a/cpp/largest-odd-number-in-string.cpp +++ b/cpp/largest-odd-number-in-string.cpp @@ -1,8 +1,8 @@ #include class Solution { -public: - std::string largestOddNumber(const std::string& num) { + public: + std::string largestOddNumber(const std::string &num) { auto i = num.find_last_of("13579"); if (i == std::string::npos) { return ""; diff --git a/cpp/matrix-diagonal-sum.cpp b/cpp/matrix-diagonal-sum.cpp index 5433d8c..eb6b1b6 100644 --- a/cpp/matrix-diagonal-sum.cpp +++ b/cpp/matrix-diagonal-sum.cpp @@ -2,45 +2,47 @@ #include class Solution { - struct indices { - int x; - int y; + struct indices { + int x; + int y; - bool operator==(const indices& other) const = default; - indices& operator+=(const indices& other) { - x += other.x; - y += other.y; - return *this; + bool operator==(const indices &other) const = default; + indices &operator+=(const indices &other) { + x += other.x; + y += other.y; + return *this; + } + + int operator[](const std::vector> &mat) const { + return mat[y][x]; + } + }; + + public: + int diagonalSum(const std::vector> &mat) { + int sum = 0; + + indices down{0, 0}, up{0, static_cast(mat.size()) - 1}; + indices d_down{1, 1}, d_up{1, -1}; + for (std::size_t i = 0; i < mat.size(); + ++i, down += d_down, up += d_up) { + sum += down[mat]; + if (down != up) { + sum += up[mat]; + } + } + + return sum; } - - int operator[](const std::vector>& mat) const { - return mat[y][x]; - } - }; - - public: - int diagonalSum(const std::vector>& mat) { - int sum = 0; - - indices down{0, 0}, up{0, static_cast(mat.size()) - 1}; - indices d_down{1, 1}, d_up{1, -1}; - for (std::size_t i = 0; i < mat.size(); ++i, down += d_down, up += d_up) { - sum += down[mat]; - if (down != up) { - sum += up[mat]; - } - } - - return sum; - } }; int main() { - Solution s; + Solution s; - assert((s.diagonalSum({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}) == 25)); - assert((s.diagonalSum( - {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}}) == 8)); - assert((s.diagonalSum({{5}}) == 5)); - return 0; + assert((s.diagonalSum({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}) == 25)); + assert( + (s.diagonalSum( + {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}}) == 8)); + assert((s.diagonalSum({{5}}) == 5)); + return 0; } diff --git a/cpp/max-sum-of-rectangle-no-larger-than-k.cpp b/cpp/max-sum-of-rectangle-no-larger-than-k.cpp index 80920db..7b582f4 100644 --- a/cpp/max-sum-of-rectangle-no-larger-than-k.cpp +++ b/cpp/max-sum-of-rectangle-no-larger-than-k.cpp @@ -2,15 +2,14 @@ #include class Solution { - void row_partial_sums(const std::vector>& matrix, std::size_t y, std::vector& partial) const - { + void row_partial_sums(const std::vector> &matrix, + std::size_t y, std::vector &partial) const { for (std::size_t x = 0; x < partial.size(); x++) { partial[x] += matrix[y][x]; } } - int find(std::vector& partial_sums, int k) const - { + int find(std::vector &partial_sums, int k) const { int max_sum = INT_MIN; std::set prefixes; @@ -31,9 +30,9 @@ class Solution { return max_sum; } -public: - int maxSumSubmatrix(const std::vector>& matrix, int k) const - { + public: + int maxSumSubmatrix(const std::vector> &matrix, + int k) const { std::size_t rows = matrix.size(); std::size_t cols = matrix.front().size(); diff --git a/cpp/maximum-value-at-a-given-index-in-a-bounded-array.cpp b/cpp/maximum-value-at-a-given-index-in-a-bounded-array.cpp index f2c4cda..b787ace 100644 --- a/cpp/maximum-value-at-a-given-index-in-a-bounded-array.cpp +++ b/cpp/maximum-value-at-a-given-index-in-a-bounded-array.cpp @@ -1,8 +1,7 @@ #include namespace { -long sum(long index, long value, long n) -{ +long sum(long index, long value, long n) { long count = 0; if (value > index) { @@ -19,12 +18,11 @@ long sum(long index, long value, long n) return count - value; } -} +} // namespace class Solution { -public: - int maxValue(int n, int index, int maxSum) - { + public: + int maxValue(int n, int index, int maxSum) { int left = 1, right = maxSum; while (left < right) { @@ -40,8 +38,7 @@ public: } }; -int main() -{ +int main() { Solution s; assert(s.maxValue(4, 2, 6) == 2); diff --git a/cpp/merge-strings-alternately.cpp b/cpp/merge-strings-alternately.cpp index 0954ab1..612a255 100644 --- a/cpp/merge-strings-alternately.cpp +++ b/cpp/merge-strings-alternately.cpp @@ -2,9 +2,9 @@ #include class Solution { -public: - std::string mergeAlternately(const std::string& word1, const std::string& word2) - { + public: + std::string mergeAlternately(const std::string &word1, + const std::string &word2) { std::string result; auto l = word1.begin(); @@ -27,8 +27,7 @@ public: } }; -int main() -{ +int main() { Solution s; assert(s.mergeAlternately("abc", "pqr") == "apbqcr"); diff --git a/cpp/middle-of-the-linked-list.cpp b/cpp/middle-of-the-linked-list.cpp index 897e7ea..1e41094 100644 --- a/cpp/middle-of-the-linked-list.cpp +++ b/cpp/middle-of-the-linked-list.cpp @@ -9,9 +9,8 @@ * }; */ class Solution { -public: - ListNode* middleNode(ListNode* head) - { + public: + ListNode *middleNode(ListNode *head) { auto slow = head; auto fast = head ? head->next : nullptr; diff --git a/cpp/minimum-flips-to-make-a-or-b-equal-to-c.cpp b/cpp/minimum-flips-to-make-a-or-b-equal-to-c.cpp index 02c9187..971fef2 100644 --- a/cpp/minimum-flips-to-make-a-or-b-equal-to-c.cpp +++ b/cpp/minimum-flips-to-make-a-or-b-equal-to-c.cpp @@ -2,13 +2,12 @@ #include class Solution { -public: - int minFlips(int a, int b, int c) - { + public: + int minFlips(int a, int b, int c) { auto flips = 0; for (; (a | b) != c; a >>= 1, b >>= 1, c >>= 1) { - auto [aa, bb, cc] = std::tuple { a & 1, b & 1, c & 1 }; + auto [aa, bb, cc] = std::tuple{a & 1, b & 1, c & 1}; if ((aa | bb) == cc) { continue; @@ -25,8 +24,7 @@ public: } }; -int main() -{ +int main() { Solution s; assert(s.minFlips(2, 6, 5) == 3); diff --git a/cpp/mirror-reflection.cpp b/cpp/mirror-reflection.cpp index 2cc82ea..7c163c8 100644 --- a/cpp/mirror-reflection.cpp +++ b/cpp/mirror-reflection.cpp @@ -1,7 +1,6 @@ class Solution { -public: - int mirrorReflection(int p, int q) - { + public: + int mirrorReflection(int p, int q) { auto lcm = p * q / std::gcd(p, q); auto x = lcm / p; auto y = lcm / q; diff --git a/cpp/my-calendar-i.cpp b/cpp/my-calendar-i.cpp index b6a2f65..9148eb1 100644 --- a/cpp/my-calendar-i.cpp +++ b/cpp/my-calendar-i.cpp @@ -8,25 +8,20 @@ struct range_t { int start; int end; - range_t(int start, int end) - : start(start) - , end(end) - { - } + range_t(int start, int end) : start(start), end(end) {} bool has(int x) const { return x > start && x < end; } - bool operator>(const range_t& other) const { return start > other.start; } + bool operator>(const range_t &other) const { return start > other.start; } - bool operator==(const range_t& other) const - { + bool operator==(const range_t &other) const { return start == other.start && end == other.end; } }; -bool overlaps(const range_t& a, const range_t& b) -{ - return a == b || a.has(b.start) || a.has(b.end) || b.has(a.start) || b.has(a.end); +bool overlaps(const range_t &a, const range_t &b) { + return a == b || a.has(b.start) || a.has(b.end) || b.has(a.start) || + b.has(a.end); } } // namespace @@ -34,11 +29,10 @@ bool overlaps(const range_t& a, const range_t& b) class MyCalendar { std::vector entries; -public: + public: MyCalendar() = default; - bool book(int start, int end) - { + bool book(int start, int end) { entries.emplace_back(start, end); auto it = entries.end(); @@ -69,15 +63,14 @@ public: * bool param_1 = obj->book(start,end); */ -static void test_case_1() -{ +static void test_case_1() { std::cout << "=== TEST CASE 1 ===\n"; - std::vector entries { { 47, 50 }, { 33, 41 }, { 39, 45 }, { 33, 42 }, - { 25, 32 }, { 26, 35 }, { 19, 25 }, { 3, 8 }, - { 8, 13 }, { 18, 27 } }; - std::vector expected { true, true, false, false, true, - false, true, true, true, false }; + std::vector entries{{47, 50}, {33, 41}, {39, 45}, {33, 42}, + {25, 32}, {26, 35}, {19, 25}, {3, 8}, + {8, 13}, {18, 27}}; + std::vector expected{true, true, false, false, true, + false, true, true, true, false}; MyCalendar c; for (auto i = 0; i < entries.size(); i++) { @@ -90,12 +83,12 @@ static void test_case_1() } } -static void test_case_2() -{ +static void test_case_2() { std::cout << "=== TEST CASE 2 ===\n"; - std::vector entries { { 37, 50 }, { 33, 50 }, { 4, 17 }, { 35, 48 }, { 8, 25 } }; - std::vector expected { true, false, true, false, false }; + std::vector entries{ + {37, 50}, {33, 50}, {4, 17}, {35, 48}, {8, 25}}; + std::vector expected{true, false, true, false, false}; MyCalendar c; for (auto i = 0; i < entries.size(); i++) { @@ -108,22 +101,19 @@ static void test_case_2() } } -static void test_case_3() -{ +static void test_case_3() { std::cout << "=== TEST CASE 3 ===\n"; - std::vector entries { - { 20, 29 }, { 13, 22 }, { 44, 50 }, { 1, 7 }, { 2, 10 }, { 14, 20 }, - { 19, 25 }, { 36, 42 }, { 45, 50 }, { 47, 50 }, { 39, 45 }, { 44, 50 }, - { 16, 25 }, { 45, 50 }, { 45, 50 }, { 12, 20 }, { 21, 29 }, { 11, 20 }, - { 12, 17 }, { 34, 40 }, { 10, 18 }, { 38, 44 }, { 23, 32 }, { 38, 44 }, - { 15, 20 }, { 27, 33 }, { 34, 42 }, { 44, 50 }, { 35, 40 }, { 24, 31 } - }; - std::vector expected { - true, false, true, true, false, true, false, true, false, false, + std::vector entries{ + {20, 29}, {13, 22}, {44, 50}, {1, 7}, {2, 10}, {14, 20}, + {19, 25}, {36, 42}, {45, 50}, {47, 50}, {39, 45}, {44, 50}, + {16, 25}, {45, 50}, {45, 50}, {12, 20}, {21, 29}, {11, 20}, + {12, 17}, {34, 40}, {10, 18}, {38, 44}, {23, 32}, {38, 44}, + {15, 20}, {27, 33}, {34, 42}, {44, 50}, {35, 40}, {24, 31}}; + std::vector expected{ + true, false, true, true, false, true, false, true, false, false, false, false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, false - }; + false, false, false, false, false, false, false, false, false, false}; MyCalendar c; for (auto i = 0; i < entries.size(); i++) { @@ -136,8 +126,7 @@ static void test_case_3() } } -int main() -{ +int main() { MyCalendar c; assert(c.book(10, 20)); assert(!c.book(15, 25)); diff --git a/cpp/n-ary-tree-level-order-traversal.cpp b/cpp/n-ary-tree-level-order-traversal.cpp index 68d870e..9fced78 100644 --- a/cpp/n-ary-tree-level-order-traversal.cpp +++ b/cpp/n-ary-tree-level-order-traversal.cpp @@ -21,8 +21,7 @@ public: */ class Solution { - void levelOrder(vector>& traversal, Node* root, int level) - { + void levelOrder(vector> &traversal, Node *root, int level) { if (root == nullptr) { return; } @@ -37,9 +36,8 @@ class Solution { } } -public: - vector> levelOrder(Node* root) - { + public: + vector> levelOrder(Node *root) { vector> result; levelOrder(result, root, 0); return result; diff --git a/cpp/n-ary-tree-preorder-traversal.cpp b/cpp/n-ary-tree-preorder-traversal.cpp index ee66ae8..a747b53 100644 --- a/cpp/n-ary-tree-preorder-traversal.cpp +++ b/cpp/n-ary-tree-preorder-traversal.cpp @@ -21,8 +21,7 @@ public: */ class Solution { - void preorder(vector& traversal, Node* root) - { + void preorder(vector &traversal, Node *root) { if (root == nullptr) { return; } @@ -33,9 +32,8 @@ class Solution { } } -public: - vector preorder(Node* root) - { + public: + vector preorder(Node *root) { vector result; preorder(result, root); return result; diff --git a/cpp/number-of-laser-beams-in-a-bank.cpp b/cpp/number-of-laser-beams-in-a-bank.cpp index c9bebc2..488232f 100644 --- a/cpp/number-of-laser-beams-in-a-bank.cpp +++ b/cpp/number-of-laser-beams-in-a-bank.cpp @@ -3,13 +3,14 @@ #include class Solution { -public: - int numberOfBeams(const std::vector& bank) { + public: + int numberOfBeams(const std::vector &bank) { int beams = 0; int last_row = 0; - for (const auto& row : bank) { - if (auto current_row = std::count(row.begin(), row.end(), '1'); current_row != 0) { + for (const auto &row : bank) { + if (auto current_row = std::count(row.begin(), row.end(), '1'); + current_row != 0) { beams += last_row * current_row; last_row = current_row; } @@ -18,4 +19,3 @@ public: return beams; } }; - diff --git a/cpp/number-of-matching-subsequences.cpp b/cpp/number-of-matching-subsequences.cpp index 50e70eb..2330124 100644 --- a/cpp/number-of-matching-subsequences.cpp +++ b/cpp/number-of-matching-subsequences.cpp @@ -1,6 +1,5 @@ class Solution { - bool matches(const string& s, const string& word) const - { + bool matches(const string &s, const string &word) const { auto s_i = 0; for (auto i = 0; s_i < s.size() && i < word.size(); i++) { @@ -12,23 +11,23 @@ class Solution { return s_i == s.size(); } - map preprocess(const vector& words) const - { + map preprocess(const vector &words) const { map histogram; - for (auto& w : words) { + for (auto &w : words) { histogram[w]++; } return histogram; } -public: - int numMatchingSubseq(string s, vector& words) - { + public: + int numMatchingSubseq(string s, vector &words) { auto histogram = preprocess(words); - return accumulate(histogram.begin(), histogram.end(), 0, [&](int acc, const auto& pair) { - return acc + (matches(pair.first, s) ? pair.second : 0); - }); + return accumulate(histogram.begin(), histogram.end(), 0, + [&](int acc, const auto &pair) { + return acc + + (matches(pair.first, s) ? pair.second : 0); + }); } }; diff --git a/cpp/numbers-with-same-consecutive-differences.cpp b/cpp/numbers-with-same-consecutive-differences.cpp index dfdb7b4..98cc6e7 100644 --- a/cpp/numbers-with-same-consecutive-differences.cpp +++ b/cpp/numbers-with-same-consecutive-differences.cpp @@ -2,8 +2,7 @@ namespace { -void nums_same_consec_diff(int n, int k, std::vector& nums, int number) -{ +void nums_same_consec_diff(int n, int k, std::vector &nums, int number) { if (n == 0) { nums.push_back(number); return; @@ -17,12 +16,11 @@ void nums_same_consec_diff(int n, int k, std::vector& nums, int number) } } -} +} // namespace class Solution { -public: - std::vector numsSameConsecDiff(int n, int k) - { + public: + std::vector numsSameConsecDiff(int n, int k) { std::vector nums; for (int d = 1; d < 10; d++) { @@ -37,36 +35,32 @@ public: #include -TEST(examples, first) -{ +TEST(examples, first) { Solution s; - ASSERT_EQ(s.numsSameConsecDiff(3, 7), (std::vector { 181, 292, 707, 818, 929 })); + ASSERT_EQ(s.numsSameConsecDiff(3, 7), + (std::vector{181, 292, 707, 818, 929})); } -TEST(examples, second) -{ +TEST(examples, second) { Solution s; ASSERT_EQ(s.numsSameConsecDiff(2, 1), - (std::vector { 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78, - 87, 89, 98 })); + (std::vector{10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, + 78, 87, 89, 98})); } -TEST(same, two) -{ +TEST(same, two) { Solution s; ASSERT_EQ(s.numsSameConsecDiff(2, 0), - (std::vector { 11, 22, 33, 44, 55, 66, 77, 88, 99 })); + (std::vector{11, 22, 33, 44, 55, 66, 77, 88, 99})); } -TEST(same, three) -{ +TEST(same, three) { Solution s; ASSERT_EQ(s.numsSameConsecDiff(3, 0), - (std::vector { 111, 222, 333, 444, 555, 666, 777, 888, 999 })); + (std::vector{111, 222, 333, 444, 555, 666, 777, 888, 999})); } -int main(int argc, char** argv) -{ +int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } diff --git a/cpp/out-of-boundary-paths.cpp b/cpp/out-of-boundary-paths.cpp index d731fd8..f6db2e4 100644 --- a/cpp/out-of-boundary-paths.cpp +++ b/cpp/out-of-boundary-paths.cpp @@ -1,5 +1,5 @@ class Solution { -private: + private: const static unsigned CAP = 1000000007; class dp { @@ -9,9 +9,7 @@ private: std::vector>> paths; - int - dfs(int y, int x, int moves) - { + int dfs(int y, int x, int moves) { if (y < 0 || y >= rows || x < 0 || x >= cols) { // BASE: we got out of the bounds return 1; @@ -28,8 +26,8 @@ private: } int options = 0; - for (auto& [dx, dy] : std::vector> { - { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }) { + for (auto &[dx, dy] : std::vector>{ + {0, 1}, {1, 0}, {0, -1}, {-1, 0}}) { options = (options + dfs(y + dy, x + dx, moves - 1)) % CAP; } paths[y][x][moves] = options; @@ -37,26 +35,17 @@ private: return options; } - public: + public: dp(int rows, int cols, int maxMove) - : rows(rows) - , cols(cols) - , maxMove(maxMove) - , paths(rows, std::vector>(cols)) - { - } + : rows(rows), cols(cols), maxMove(maxMove), + paths(rows, std::vector>(cols)) {} - int - get(int row, int col) - { - return dfs(row, col, maxMove); - } + int get(int row, int col) { return dfs(row, col, maxMove); } }; -public: - int - findPaths(int m, int n, int maxMove, int startRow, int startColumn) const - { + public: + int findPaths(int m, int n, int maxMove, int startRow, + int startColumn) const { return dp(m, n, maxMove).get(startRow, startColumn); } }; diff --git a/cpp/palindrome-linked-list.cpp b/cpp/palindrome-linked-list.cpp index c6ba84a..bd75a5c 100644 --- a/cpp/palindrome-linked-list.cpp +++ b/cpp/palindrome-linked-list.cpp @@ -14,42 +14,24 @@ struct ListNode { int val; - ListNode* next; - ListNode() - : val(0) - , next(nullptr) - { - } - ListNode(int x) - : val(x) - , next(nullptr) - { - } - ListNode(int x, ListNode* next) - : val(x) - , next(next) - { - } + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} }; namespace { struct middle_t { - ListNode* node; + ListNode *node; std::size_t size; - middle_t(ListNode* node, std::size_t size) - : node(node) - , size(size) - { - } + middle_t(ListNode *node, std::size_t size) : node(node), size(size) {} }; -middle_t -find_middle(ListNode* head) -{ - ListNode* slow = head; - ListNode* fast = head->next; +middle_t find_middle(ListNode *head) { + ListNode *slow = head; + ListNode *fast = head->next; std::size_t size; for (size = 0; fast != nullptr && fast->next != nullptr; size++) { @@ -57,15 +39,15 @@ find_middle(ListNode* head) fast = fast->next->next; } - return { slow, size }; + return {slow, size}; } -ListNode* reverse_list(ListNode* tail) -{ - ListNode* previous = nullptr; - ListNode* next = nullptr; +ListNode *reverse_list(ListNode *tail) { + ListNode *previous = nullptr; + ListNode *next = nullptr; - for (ListNode* current = tail; current != nullptr; previous = current, current = next) { + for (ListNode *current = tail; current != nullptr; + previous = current, current = next) { next = current->next; current->next = previous; } @@ -73,8 +55,7 @@ ListNode* reverse_list(ListNode* tail) return previous; } -bool compare_lists(ListNode* left, ListNode* right, std::size_t size) -{ +bool compare_lists(ListNode *left, ListNode *right, std::size_t size) { for (auto i = 0u; i < size + 1; i++) { if (left->val != right->val) { return false; @@ -89,9 +70,8 @@ bool compare_lists(ListNode* left, ListNode* right, std::size_t size) } // namespace class Solution { -public: - bool isPalindrome(ListNode* head) - { + public: + bool isPalindrome(ListNode *head) { // find middle of the linked list auto mid = find_middle(head); @@ -106,11 +86,9 @@ public: #pragma region Testing utilities namespace { -ListNode* -construct_list(const std::vector& values) -{ - ListNode* head = new ListNode(values.front()); - ListNode* tail = head; +ListNode *construct_list(const std::vector &values) { + ListNode *head = new ListNode(values.front()); + ListNode *tail = head; for (std::size_t i = 1; i < values.size(); i++) { tail->next = new ListNode(values[i]); @@ -120,8 +98,7 @@ construct_list(const std::vector& values) return head; } -void destroy_list(ListNode* linked_list) -{ +void destroy_list(ListNode *linked_list) { if (linked_list == nullptr) { return; } @@ -129,8 +106,7 @@ void destroy_list(ListNode* linked_list) delete linked_list; } -bool test_find_middle(const std::vector& values, int mid_value) -{ +bool test_find_middle(const std::vector &values, int mid_value) { auto linked_list = construct_list(values); auto mid = find_middle(linked_list); @@ -140,8 +116,7 @@ bool test_find_middle(const std::vector& values, int mid_value) return result; } -bool test_isPalindrome(const std::vector& values) -{ +bool test_isPalindrome(const std::vector &values) { auto linked_list = construct_list(values); Solution s; @@ -154,19 +129,18 @@ bool test_isPalindrome(const std::vector& values) } // namespace #pragma endregion // Testing utilities -int main() -{ +int main() { // find_middle tests - assert(test_find_middle(std::vector { 1, 2, 2, 1 }, 2)); - assert(test_find_middle(std::vector { 1, 2, 3, 2, 1 }, 3)); - assert(test_find_middle(std::vector { 1, 2 }, 1)); - assert(test_find_middle(std::vector { 1 }, 1)); + assert(test_find_middle(std::vector{1, 2, 2, 1}, 2)); + assert(test_find_middle(std::vector{1, 2, 3, 2, 1}, 3)); + assert(test_find_middle(std::vector{1, 2}, 1)); + assert(test_find_middle(std::vector{1}, 1)); // isPalindrome tests - assert(test_isPalindrome(std::vector { 1, 2, 2, 1 })); - assert(test_isPalindrome(std::vector { 1, 2, 3, 2, 1 })); - assert(!test_isPalindrome(std::vector { 1, 2 })); - assert(test_isPalindrome(std::vector { 1 })); + assert(test_isPalindrome(std::vector{1, 2, 2, 1})); + assert(test_isPalindrome(std::vector{1, 2, 3, 2, 1})); + assert(!test_isPalindrome(std::vector{1, 2})); + assert(test_isPalindrome(std::vector{1})); return 0; } diff --git a/cpp/partition-list.cpp b/cpp/partition-list.cpp index e6cdc51..cfea36a 100644 --- a/cpp/partition-list.cpp +++ b/cpp/partition-list.cpp @@ -9,22 +9,20 @@ * }; */ class Solution { - ListNode* update_tail(ListNode* tail, ListNode* node) const - { + ListNode *update_tail(ListNode *tail, ListNode *node) const { if (tail != nullptr) { tail->next = node; } return node; } -public: - ListNode* partition(ListNode* head, int x) - { - ListNode* left_head = nullptr; - ListNode* right_head = nullptr; + public: + ListNode *partition(ListNode *head, int x) { + ListNode *left_head = nullptr; + ListNode *right_head = nullptr; - ListNode* left_tail = nullptr; - ListNode* right_tail = nullptr; + ListNode *left_tail = nullptr; + ListNode *right_tail = nullptr; while (head != nullptr) { auto next_head = head->next; diff --git a/cpp/pascals-triangle-ii.cpp b/cpp/pascals-triangle-ii.cpp index f4f5db4..fc55fd8 100644 --- a/cpp/pascals-triangle-ii.cpp +++ b/cpp/pascals-triangle-ii.cpp @@ -1,13 +1,12 @@ class Solution { -public: - vector getRow(int rowIndex) - { + public: + vector getRow(int rowIndex) { vector result; result.push_back(1); for (auto k = 0; k < rowIndex; k++) { - auto next = static_cast( - static_cast(result.back()) * (rowIndex - k) / (k + 1)); + auto next = static_cast(static_cast(result.back()) * + (rowIndex - k) / (k + 1)); result.push_back(next); } diff --git a/cpp/pascals-triangle.cpp b/cpp/pascals-triangle.cpp index 61ad1da..1c38a84 100644 --- a/cpp/pascals-triangle.cpp +++ b/cpp/pascals-triangle.cpp @@ -1,22 +1,20 @@ class Solution { - int getN(const vector& previousRow, int n) - { + int getN(const vector &previousRow, int n) { if (n == 0 || n == previousRow.size()) { return 1; } return previousRow[n - 1] + previousRow[n]; } -public: - vector> generate(int numRows) - { + public: + vector> generate(int numRows) { if (numRows <= 0) { return {}; } - vector> result { vector { 1 } }; + vector> result{vector{1}}; for (auto i = 2; i <= numRows; i++) { - auto& previous = result.back(); + auto &previous = result.back(); vector current; for (auto j = 0; j < i; j++) { diff --git a/cpp/ransom-note.cpp b/cpp/ransom-note.cpp index cdc7b79..a323935 100644 --- a/cpp/ransom-note.cpp +++ b/cpp/ransom-note.cpp @@ -4,8 +4,7 @@ namespace { -std::map build_freqs(const std::string& input) -{ +std::map build_freqs(const std::string &input) { std::map freqs; for (auto c : input) { @@ -15,8 +14,7 @@ std::map build_freqs(const std::string& input) return freqs; } -bool subtract(std::map available, const std::string& message) -{ +bool subtract(std::map available, const std::string &message) { for (auto c : message) { available[c]--; @@ -28,19 +26,18 @@ bool subtract(std::map available, const std::string& message) return true; } -} +} // namespace class Solution { -public: - bool canConstruct(const std::string& ransomNote, const std::string& magazine) - { + public: + bool canConstruct(const std::string &ransomNote, + const std::string &magazine) { auto available = build_freqs(magazine); return subtract(available, ransomNote); } }; -int main() -{ +int main() { Solution s; assert(!s.canConstruct("a", "b")); diff --git a/cpp/removing-stars-from-a-string.cpp b/cpp/removing-stars-from-a-string.cpp index cb659ff..245ec84 100644 --- a/cpp/removing-stars-from-a-string.cpp +++ b/cpp/removing-stars-from-a-string.cpp @@ -2,9 +2,8 @@ #include class Solution { -public: - std::string removeStars(const std::string& s) - { + public: + std::string removeStars(const std::string &s) { std::vector without_stars; for (auto c : s) { @@ -15,6 +14,6 @@ public: } } - return std::string { without_stars.begin(), without_stars.end() }; + return std::string{without_stars.begin(), without_stars.end()}; } }; diff --git a/cpp/reordered-power-of-2.cpp b/cpp/reordered-power-of-2.cpp index 3734223..a4b41c1 100644 --- a/cpp/reordered-power-of-2.cpp +++ b/cpp/reordered-power-of-2.cpp @@ -4,10 +4,7 @@ namespace { -bool is_power_of_2(int n) -{ - return (n & (n - 1)) == 0; -} +bool is_power_of_2(int n) { return (n & (n - 1)) == 0; } class permutations { using values_t = typename std::vector; @@ -16,46 +13,38 @@ class permutations { values_t elements; bool last; - public: + public: p_iter(values_t elements, bool last = false) - : elements(elements) - , last(last) - { - } + : elements(elements), last(last) {} - const values_t& operator*() const { return elements; } + const values_t &operator*() const { return elements; } - p_iter& operator++() - { + p_iter &operator++() { if (!std::next_permutation(elements.begin(), elements.end())) { last = true; } return *this; } - bool operator==(const p_iter& other) const - { + bool operator==(const p_iter &other) const { return last == other.last && elements == other.elements; } - bool operator!=(const p_iter& other) const { return !(*this == other); } + bool operator!=(const p_iter &other) const { return !(*this == other); } }; values_t elements; -public: - permutations(const values_t& input_ints) - : elements(input_ints) - { + public: + permutations(const values_t &input_ints) : elements(input_ints) { std::sort(elements.begin(), elements.end()); } - p_iter begin() const { return { elements, elements.empty() }; } - p_iter end() const { return { elements, true }; } + p_iter begin() const { return {elements, elements.empty()}; } + p_iter end() const { return {elements, true}; } }; -std::vector to_vector(int n) -{ +std::vector to_vector(int n) { if (n == 0) { return std::vector(1, 0); } @@ -70,8 +59,7 @@ std::vector to_vector(int n) return digits; } -int to_number(const std::vector digits) -{ +int to_number(const std::vector digits) { int number = 0; for (auto digit : digits) { @@ -81,13 +69,12 @@ int to_number(const std::vector digits) return number; } -} +} // namespace class Solution { -public: - bool reorderedPowerOf2(int n) - { - for (const auto& permutation : permutations(to_vector(n))) { + public: + bool reorderedPowerOf2(int n) { + for (const auto &permutation : permutations(to_vector(n))) { if (permutation.front() == 0) { continue; } @@ -101,8 +88,7 @@ public: } }; -int main() -{ +int main() { Solution s; assert(s.reorderedPowerOf2(1)); diff --git a/cpp/rotate-image.cpp b/cpp/rotate-image.cpp index 324b6ff..d25b533 100644 --- a/cpp/rotate-image.cpp +++ b/cpp/rotate-image.cpp @@ -2,16 +2,15 @@ #include class Solution { -public: - void rotate(std::vector>& matrix) - { + public: + void rotate(std::vector> &matrix) { for (std::size_t i = 0; i < matrix.size(); i++) { for (std::size_t j = i; j < matrix.size(); j++) { std::swap(matrix[i][j], matrix[j][i]); } } - for (auto& row : matrix) { + for (auto &row : matrix) { std::reverse(row.begin(), row.end()); } } diff --git a/cpp/same-tree.cpp b/cpp/same-tree.cpp index 8ec70c0..18210fb 100644 --- a/cpp/same-tree.cpp +++ b/cpp/same-tree.cpp @@ -6,13 +6,13 @@ * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), + * right(right) {} * }; */ class Solution { -public: - bool isSameTree(TreeNode* p, TreeNode* q) - { + public: + bool isSameTree(TreeNode *p, TreeNode *q) { if (p == nullptr && q == nullptr) { return true; } diff --git a/cpp/snapshot-array.cpp b/cpp/snapshot-array.cpp index f0e2962..16bd0df 100644 --- a/cpp/snapshot-array.cpp +++ b/cpp/snapshot-array.cpp @@ -7,24 +7,14 @@ class SnapshotArray { int snap_id = 0; std::vector> arr; -public: - SnapshotArray(int length) - : arr(length, std::map { { 0, 0 } }) - { - } + public: + SnapshotArray(int length) : arr(length, std::map{{0, 0}}) {} - void set(int index, int val) - { - arr[index][snap_id] = val; - } + void set(int index, int val) { arr[index][snap_id] = val; } - int snap() - { - return snap_id++; - } + int snap() { return snap_id++; } - int get(int index, int snap_id) - { + int get(int index, int snap_id) { auto it = std::prev(arr[index].lower_bound(snap_id + 1)); return it == arr[index].end() ? 0 : it->second; } @@ -38,8 +28,7 @@ public: * int param_3 = obj->get(index,snap_id); */ -int main() -{ +int main() { SnapshotArray arr(3); arr.set(0, 5); assert(arr.snap() == 0); diff --git a/cpp/sort-the-matrix-diagonally.cpp b/cpp/sort-the-matrix-diagonally.cpp index 9ad363d..c3a80c4 100644 --- a/cpp/sort-the-matrix-diagonally.cpp +++ b/cpp/sort-the-matrix-diagonally.cpp @@ -7,10 +7,8 @@ namespace { -template -void print_matrix(const std::vector>& m) -{ - for (const auto& row : m) { +template void print_matrix(const std::vector> &m) { + for (const auto &row : m) { for (auto x : row) { std::cout << x << " "; } @@ -21,48 +19,41 @@ void print_matrix(const std::vector>& m) std::cout << "\n"; } -template -class diagonal { - std::vector>& matrix; +template class diagonal { + std::vector> &matrix; std::size_t x; std::size_t y; class diagonal_iter { - std::vector>& m; + std::vector> &m; std::size_t x; std::size_t y; - public: + public: using difference_type = std::ptrdiff_t; using value_type = T; - using pointer = T*; - using reference = T&; + using pointer = T *; + using reference = T &; using iterator_category = std::random_access_iterator_tag; - diagonal_iter(std::vector>& matrix, - std::size_t x, - std::size_t y) - : m(matrix) - , x(x) - , y(y) - { - } + diagonal_iter(std::vector> &matrix, std::size_t x, + std::size_t y) + : m(matrix), x(x), y(y) {} - bool operator!=(const diagonal_iter& rhs) const - { + bool operator!=(const diagonal_iter &rhs) const { return m != rhs.m || x != rhs.x || y != rhs.y; } - bool operator==(const diagonal_iter& rhs) const { return !(*this != rhs); } + bool operator==(const diagonal_iter &rhs) const { + return !(*this != rhs); + } - diagonal_iter& operator++() - { + diagonal_iter &operator++() { x++; y++; return *this; } - diagonal_iter operator--() - { + diagonal_iter operator--() { x--; y--; return *this; @@ -70,21 +61,18 @@ class diagonal { reference operator*() const { return m[y][x]; } - diagonal_iter operator-(difference_type n) const - { - return diagonal_iter { m, x - n, y - n }; + diagonal_iter operator-(difference_type n) const { + return diagonal_iter{m, x - n, y - n}; } - int operator-(const diagonal_iter& rhs) const { return x - rhs.x; } + int operator-(const diagonal_iter &rhs) const { return x - rhs.x; } - diagonal_iter operator+(difference_type n) const - { - return diagonal_iter { m, x + n, y + n }; + diagonal_iter operator+(difference_type n) const { + return diagonal_iter{m, x + n, y + n}; } - bool operator<(const diagonal_iter& rhs) const { return x < rhs.x; } + bool operator<(const diagonal_iter &rhs) const { return x < rhs.x; } - diagonal_iter& operator=(const diagonal_iter& rhs) - { + diagonal_iter &operator=(const diagonal_iter &rhs) { if (this != &rhs) // not a self-assignment { this->m = rhs.m; @@ -95,53 +83,40 @@ class diagonal { } }; -public: - diagonal(std::vector>& matrix, std::size_t x, std::size_t y) - : matrix(matrix) - , x(x) - , y(y) - { - } + public: + diagonal(std::vector> &matrix, std::size_t x, std::size_t y) + : matrix(matrix), x(x), y(y) {} - diagonal_iter begin() const { return diagonal_iter { matrix, x, y }; } + diagonal_iter begin() const { return diagonal_iter{matrix, x, y}; } - diagonal_iter end() const - { + diagonal_iter end() const { auto max_x = matrix[y].size(); auto max_y = matrix.size(); auto steps = std::min(max_x - x, max_y - y); - return diagonal_iter { matrix, x + steps, y + steps }; + return diagonal_iter{matrix, x + steps, y + steps}; } }; -template -class diagonals { - std::vector>& _matrix; +template class diagonals { + std::vector> &_matrix; class diagonals_iter { - std::vector>& m; + std::vector> &m; std::size_t x; std::size_t y; - public: - diagonals_iter(std::vector>& matrix, - std::size_t x, - std::size_t y) - : m(matrix) - , x(x) - , y(y) - { - } + public: + diagonals_iter(std::vector> &matrix, std::size_t x, + std::size_t y) + : m(matrix), x(x), y(y) {} - bool operator!=(const diagonals_iter& rhs) const - { + bool operator!=(const diagonals_iter &rhs) const { return m != rhs.m || x != rhs.x || y != rhs.y; } - diagonals_iter& operator++() - { + diagonals_iter &operator++() { if (y != 0) { // iterating through diagonals down the first column y++; @@ -159,24 +134,21 @@ class diagonals { return *this; } - diagonal operator*() const { return diagonal { m, x, y }; } + diagonal operator*() const { return diagonal{m, x, y}; } }; -public: - diagonals(std::vector>& matrix) - : _matrix(matrix) - { - } - diagonals_iter begin() { return diagonals_iter { _matrix, 0, 0 }; } - diagonals_iter end() { return diagonals_iter { _matrix, 0, _matrix.size() }; } + public: + diagonals(std::vector> &matrix) : _matrix(matrix) {} + diagonals_iter begin() { return diagonals_iter{_matrix, 0, 0}; } + diagonals_iter end() { return diagonals_iter{_matrix, 0, _matrix.size()}; } }; } // namespace class Solution { -public: - std::vector> diagonalSort(std::vector> mat) - { + public: + std::vector> + diagonalSort(std::vector> mat) { for (auto d : diagonals(mat)) { std::sort(d.begin(), d.end()); } @@ -185,44 +157,38 @@ public: } }; -static void -test_case_1() -{ +static void test_case_1() { // Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] // Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]] Solution s; - assert((s.diagonalSort(std::vector { std::vector { 3, 3, 1, 1 }, - std::vector { 2, 2, 1, 2 }, - std::vector { 1, 1, 1, 2 } }) - == std::vector { std::vector { 1, 1, 1, 1 }, - std::vector { 1, 2, 2, 2 }, - std::vector { 1, 2, 3, 3 } })); + assert((s.diagonalSort(std::vector{std::vector{3, 3, 1, 1}, + std::vector{2, 2, 1, 2}, + std::vector{1, 1, 1, 2}}) == + std::vector{std::vector{1, 1, 1, 1}, std::vector{1, 2, 2, 2}, + std::vector{1, 2, 3, 3}})); } -static void -test_case_2() -{ +static void test_case_2() { // Input: mat = // [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]] // Output: // [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]] Solution s; - assert((s.diagonalSort(std::vector { std::vector { 11, 25, 66, 1, 69, 7 }, - std::vector { 23, 55, 17, 45, 15, 52 }, - std::vector { 75, 31, 36, 44, 58, 8 }, - std::vector { 22, 27, 33, 25, 68, 4 }, - std::vector { 84, 28, 14, 11, 5, 50 } }) - == std::vector { std::vector { 5, 17, 4, 1, 52, 7 }, - std::vector { 11, 11, 25, 45, 8, 69 }, - std::vector { 14, 23, 25, 44, 58, 15 }, - std::vector { 22, 27, 31, 36, 50, 66 }, - std::vector { 84, 28, 75, 33, 55, 68 } })); + assert((s.diagonalSort(std::vector{std::vector{11, 25, 66, 1, 69, 7}, + std::vector{23, 55, 17, 45, 15, 52}, + std::vector{75, 31, 36, 44, 58, 8}, + std::vector{22, 27, 33, 25, 68, 4}, + std::vector{84, 28, 14, 11, 5, 50}}) == + std::vector{std::vector{5, 17, 4, 1, 52, 7}, + std::vector{11, 11, 25, 45, 8, 69}, + std::vector{14, 23, 25, 44, 58, 15}, + std::vector{22, 27, 31, 36, 50, 66}, + std::vector{84, 28, 75, 33, 55, 68}})); } -int main() -{ +int main() { test_case_1(); test_case_2(); diff --git a/cpp/spiral-matrix-ii.cpp b/cpp/spiral-matrix-ii.cpp index c76e42b..ab93a1f 100644 --- a/cpp/spiral-matrix-ii.cpp +++ b/cpp/spiral-matrix-ii.cpp @@ -3,100 +3,103 @@ #include class Solution { - struct indices { - int x; - int y; + struct indices { + int x; + int y; - bool operator==(const indices& other) const = default; - indices& operator+=(const indices& other) { - x += other.x; - y += other.y; - return *this; - } - - friend indices operator+(indices left, const indices& right) { - return left += right; - } - - int& operator[](std::vector>& mat) const { - return mat[y][x]; - } - }; - - struct spiral_indices { - spiral_indices(const std::vector>& matrix) - : x_bounds{-1, static_cast(matrix.size() ? matrix[0].size() : 0)}, - y_bounds{-1, static_cast(matrix.size())} {} - - bool done() const { return !in_bounds(idx); } - - spiral_indices& operator++() { - // update bounds and change the direction if cannot move - if (!in_bounds(idx + d)) { - // change the direction - d = {-d.y, d.x}; - - // get the magnitude of the vector - auto flat_d = d.x + d.y; - - // decide whether we're moving x or y bounds - auto& bounds = d.x ? x_bounds : y_bounds; - if (flat_d > 0) { - bounds.x++; - } else { - bounds.y--; + bool operator==(const indices &other) const = default; + indices &operator+=(const indices &other) { + x += other.x; + y += other.y; + return *this; } - } - idx += d; + friend indices operator+(indices left, const indices &right) { + return left += right; + } - return *this; + int &operator[](std::vector> &mat) const { + return mat[y][x]; + } + }; + + struct spiral_indices { + spiral_indices(const std::vector> &matrix) + : x_bounds{-1, + static_cast(matrix.size() ? matrix[0].size() : 0)}, + y_bounds{-1, static_cast(matrix.size())} {} + + bool done() const { return !in_bounds(idx); } + + spiral_indices &operator++() { + // update bounds and change the direction if cannot move + if (!in_bounds(idx + d)) { + // change the direction + d = {-d.y, d.x}; + + // get the magnitude of the vector + auto flat_d = d.x + d.y; + + // decide whether we're moving x or y bounds + auto &bounds = d.x ? x_bounds : y_bounds; + if (flat_d > 0) { + bounds.x++; + } else { + bounds.y--; + } + } + + idx += d; + + return *this; + } + + int &operator[](std::vector> &mat) const { + return idx[mat]; + } + + private: + indices idx{0, 0}; + indices d{1, 0}; + indices x_bounds, y_bounds; + + bool in_bounds(const indices &idx) const { + return (x_bounds.x < idx.x && idx.x < x_bounds.y) && + (y_bounds.x < idx.y && idx.y < y_bounds.y); + } + }; + + public: + std::vector> generateMatrix(int n) { + auto length = static_cast(n); + std::vector> spiral{length, + std::vector(length, 0)}; + + int i = 1; + for (spiral_indices idx{spiral}; !idx.done(); ++idx) { + idx[spiral] = i++; + } + + return spiral; } - - int& operator[](std::vector>& mat) const { - return idx[mat]; - } - - private: - indices idx{0, 0}; - indices d{1, 0}; - indices x_bounds, y_bounds; - - bool in_bounds(const indices& idx) const { - return (x_bounds.x < idx.x && idx.x < x_bounds.y) && - (y_bounds.x < idx.y && idx.y < y_bounds.y); - } - }; - - public: - std::vector> generateMatrix(int n) { - auto length = static_cast(n); - std::vector> spiral{length, std::vector(length, 0)}; - - int i = 1; - for (spiral_indices idx{spiral}; !idx.done(); ++idx) { - idx[spiral] = i++; - } - - return spiral; - } }; int main() { - Solution s; + Solution s; - assert((s.generateMatrix(0) == std::vector>{})); - assert((s.generateMatrix(1) == std::vector>{{1}})); - assert( - (s.generateMatrix(2) == std::vector>{{1, 2}, {4, 3}})); + assert((s.generateMatrix(0) == std::vector>{})); + assert((s.generateMatrix(1) == std::vector>{{1}})); + assert( + (s.generateMatrix(2) == std::vector>{{1, 2}, {4, 3}})); - for (auto&& row : s.generateMatrix(3)) { - for (auto x : row) std::cout << x << " "; - std::cout << "\n"; - } + for (auto &&row : s.generateMatrix(3)) { + for (auto x : row) + std::cout << x << " "; + std::cout << "\n"; + } - assert((s.generateMatrix(3) == - std::vector>{{1, 2, 3}, {8, 9, 4}, {7, 6, 5}})); + assert((s.generateMatrix(3) == + std::vector>{{1, 2, 3}, {8, 9, 4}, {7, 6, 5}})); - return 0; + return 0; } diff --git a/cpp/spiral-matrix.cpp b/cpp/spiral-matrix.cpp index 8c4451e..e72d437 100644 --- a/cpp/spiral-matrix.cpp +++ b/cpp/spiral-matrix.cpp @@ -2,90 +2,90 @@ #include class Solution { - struct indices { - int x; - int y; + struct indices { + int x; + int y; - bool operator==(const indices& other) const = default; - indices& operator+=(const indices& other) { - x += other.x; - y += other.y; - return *this; - } - - friend indices operator+(indices left, const indices& right) { - return left += right; - } - - int operator[](const std::vector>& mat) const { - return mat[y][x]; - } - }; - - struct spiral_indices { - spiral_indices(const std::vector>& matrix) - : x_bounds{-1, static_cast(matrix[0].size())}, - y_bounds{-1, static_cast(matrix.size())} {} - - bool done() const { return !in_bounds(idx); } - - spiral_indices& operator++() { - // update bounds and change the direction if cannot move - if (!in_bounds(idx + d)) { - // change the direction - d = {-d.y, d.x}; - - // get the magnitude of the vector - auto flat_d = d.x + d.y; - - // decide whether we're moving x or y bounds - auto& bounds = d.x ? x_bounds : y_bounds; - if (flat_d > 0) { - bounds.x++; - } else { - bounds.y--; + bool operator==(const indices &other) const = default; + indices &operator+=(const indices &other) { + x += other.x; + y += other.y; + return *this; } - } - idx += d; + friend indices operator+(indices left, const indices &right) { + return left += right; + } - return *this; + int operator[](const std::vector> &mat) const { + return mat[y][x]; + } + }; + + struct spiral_indices { + spiral_indices(const std::vector> &matrix) + : x_bounds{-1, static_cast(matrix[0].size())}, + y_bounds{-1, static_cast(matrix.size())} {} + + bool done() const { return !in_bounds(idx); } + + spiral_indices &operator++() { + // update bounds and change the direction if cannot move + if (!in_bounds(idx + d)) { + // change the direction + d = {-d.y, d.x}; + + // get the magnitude of the vector + auto flat_d = d.x + d.y; + + // decide whether we're moving x or y bounds + auto &bounds = d.x ? x_bounds : y_bounds; + if (flat_d > 0) { + bounds.x++; + } else { + bounds.y--; + } + } + + idx += d; + + return *this; + } + + int operator[](const std::vector> &mat) const { + return idx[mat]; + } + + private: + indices idx{0, 0}; + indices d{1, 0}; + indices x_bounds, y_bounds; + + bool in_bounds(const indices &idx) const { + return (x_bounds.x < idx.x && idx.x < x_bounds.y) && + (y_bounds.x < idx.y && idx.y < y_bounds.y); + } + }; + + public: + std::vector spiralOrder(const std::vector> &matrix) { + std::vector spiral; + + for (spiral_indices idx{matrix}; !idx.done(); ++idx) { + spiral.push_back(idx[matrix]); + } + + return spiral; } - - int operator[](const std::vector>& mat) const { - return idx[mat]; - } - - private: - indices idx{0, 0}; - indices d{1, 0}; - indices x_bounds, y_bounds; - - bool in_bounds(const indices& idx) const { - return (x_bounds.x < idx.x && idx.x < x_bounds.y) && - (y_bounds.x < idx.y && idx.y < y_bounds.y); - } - }; - - public: - std::vector spiralOrder(const std::vector>& matrix) { - std::vector spiral; - - for (spiral_indices idx{matrix}; !idx.done(); ++idx) { - spiral.push_back(idx[matrix]); - } - - return spiral; - } }; int main() { - Solution s; + Solution s; - assert((s.spiralOrder({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}) == - std::vector{1, 2, 3, 6, 9, 8, 7, 4, 5})); - assert((s.spiralOrder({{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}) == - std::vector{1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7})); + assert((s.spiralOrder({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}) == + std::vector{1, 2, 3, 6, 9, 8, 7, 4, 5})); + assert((s.spiralOrder({{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}) == + std::vector{1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7})); - return 0; + return 0; } diff --git a/cpp/sum-of-absolute-differences-in-a-sorted-array.cpp b/cpp/sum-of-absolute-differences-in-a-sorted-array.cpp index 7d7e49b..2203608 100644 --- a/cpp/sum-of-absolute-differences-in-a-sorted-array.cpp +++ b/cpp/sum-of-absolute-differences-in-a-sorted-array.cpp @@ -4,8 +4,8 @@ #include class Solution { - public: - std::vector getSumAbsoluteDifferences(const std::vector& nums) { + public: + std::vector getSumAbsoluteDifferences(const std::vector &nums) { auto total = std::accumulate(nums.begin(), nums.end(), 0); auto left = 0; diff --git a/cpp/unique-paths.cpp b/cpp/unique-paths.cpp index 31c2358..b606bc6 100644 --- a/cpp/unique-paths.cpp +++ b/cpp/unique-paths.cpp @@ -1,15 +1,13 @@ class Solution { - int right(const std::vector& row, int size, int idx) const - { + int right(const std::vector &row, int size, int idx) const { if (idx >= size) { return 0; } return row[idx]; } -public: - int uniquePaths(int m, int n) - { + public: + int uniquePaths(int m, int n) { std::vector bottom(n, 1); for (int y = m - 2; y >= 0; y--) { diff --git a/cpp/utf-8-validation.cpp b/cpp/utf-8-validation.cpp index 6097c91..c613ab7 100644 --- a/cpp/utf-8-validation.cpp +++ b/cpp/utf-8-validation.cpp @@ -10,27 +10,16 @@ namespace { class todo : public std::exception { std::string cause; -public: - todo() - : cause("Not yet implemented!") - { - } + public: + todo() : cause("Not yet implemented!") {} - todo(std::string&& excuse) - : cause("Not yet implemented: " + excuse) - { - } + todo(std::string &&excuse) : cause("Not yet implemented: " + excuse) {} - virtual const char* what() const throw() - { - return cause.c_str(); - } + virtual const char *what() const throw() { return cause.c_str(); } }; auto expected_size(int first) -> std::optional { - static constexpr std::array HEADERS = { - 0, 6, 14, 30 - }; + static constexpr std::array HEADERS = {0, 6, 14, 30}; for (auto i = 0; i < 4; i++) { auto mask_length = 1 + i + (i > 0); @@ -44,14 +33,13 @@ auto expected_size(int first) -> std::optional { return {}; } -} +} // namespace class Solution { static constexpr int CONTINUATION_BYTE = 2; -public: - auto validUtf8(const std::vector& data) -> bool - { + public: + auto validUtf8(const std::vector &data) -> bool { for (auto i = 0; i < data.size();) { auto expected_length = expected_size(data[i]); if (!expected_length.has_value()) { @@ -60,7 +48,8 @@ public: } if (i + *expected_length > data.size()) { - // std::cout << "unexpected length of size " << data.size() << " ≠ " << *expected_length << "\n"; + // std::cout << "unexpected length of size " << data.size() << " + // ≠ " << *expected_length << "\n"; return false; } @@ -89,31 +78,27 @@ public: #include -TEST(examples, valid) -{ +TEST(examples, valid) { Solution s; - ASSERT_TRUE(s.validUtf8(std::vector { 197, 130, 1 })); + ASSERT_TRUE(s.validUtf8(std::vector{197, 130, 1})); } -TEST(examples, invalid) -{ +TEST(examples, invalid) { Solution s; - ASSERT_FALSE(s.validUtf8(std::vector { 235, 140, 4 })); + ASSERT_FALSE(s.validUtf8(std::vector{235, 140, 4})); } -TEST(valid, ascii_byte) -{ +TEST(valid, ascii_byte) { Solution s; - ASSERT_TRUE(s.validUtf8(std::vector { 64 })); + ASSERT_TRUE(s.validUtf8(std::vector{64})); } TEST(invalid, just_one_byte) { Solution s; - ASSERT_FALSE(s.validUtf8(std::vector {2 << 7})); + ASSERT_FALSE(s.validUtf8(std::vector{2 << 7})); } -int main(int argc, char** argv) -{ +int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } diff --git a/cpp/valid-anagram.cpp b/cpp/valid-anagram.cpp index 7836466..a6a729c 100644 --- a/cpp/valid-anagram.cpp +++ b/cpp/valid-anagram.cpp @@ -3,8 +3,8 @@ #include class Solution { -public: - bool isAnagram(const std::string& s, const std::string& t) { + public: + bool isAnagram(const std::string &s, const std::string &t) { std::array counter{}; for (char c : s) { @@ -19,8 +19,7 @@ public: } } - return std::all_of(counter.begin(), counter.end(), [](auto c) { - return c == 0; - }); + return std::all_of(counter.begin(), counter.end(), + [](auto c) { return c == 0; }); } }; diff --git a/cpp/valid-parentheses.cpp b/cpp/valid-parentheses.cpp index 3b8e767..5fdf62f 100644 --- a/cpp/valid-parentheses.cpp +++ b/cpp/valid-parentheses.cpp @@ -2,9 +2,8 @@ #include class Solution { -public: - bool isValid(const std::string& s) - { + public: + bool isValid(const std::string &s) { std::vector st; for (auto c : s) { diff --git a/cpp/vertical-order-traversal-of-a-binary-tree.cpp b/cpp/vertical-order-traversal-of-a-binary-tree.cpp index 6cd1ecc..46dcb74 100644 --- a/cpp/vertical-order-traversal-of-a-binary-tree.cpp +++ b/cpp/vertical-order-traversal-of-a-binary-tree.cpp @@ -5,54 +5,30 @@ // Definition for a binary tree node. struct TreeNode { int val; - TreeNode* left; - TreeNode* right; - TreeNode() - : val(0) - , left(nullptr) - , right(nullptr) - { - } - TreeNode(int x) - : val(x) - , left(nullptr) - , right(nullptr) - { - } - TreeNode(int x, TreeNode* left, TreeNode* right) - : val(x) - , left(left) - , right(right) - { - } + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) + : val(x), left(left), right(right) {} }; namespace { struct TreeNodeHandle { - TreeNode* node; + TreeNode *node; int x; int y; - TreeNodeHandle(TreeNode* node, int x, int y) - : node(node) - , x(x) - , y(y) - { - } + TreeNodeHandle(TreeNode *node, int x, int y) : node(node), x(x), y(y) {} - bool operator==(const TreeNodeHandle& rhs) const - { + bool operator==(const TreeNodeHandle &rhs) const { return node == rhs.node && x == rhs.x && y == rhs.y; } - int value() const - { - return node->val; - } + int value() const { return node->val; } - bool operator<(const TreeNodeHandle& rhs) const - { + bool operator<(const TreeNodeHandle &rhs) const { if (y != rhs.y) { return y < rhs.y; } @@ -66,75 +42,62 @@ struct TreeNodeHandle { }; class verticals { - TreeNode* root; + TreeNode *root; class verticals_iter { std::deque queue; - void advance() - { - auto& n = queue.front(); + void advance() { + auto &n = queue.front(); if (n.node->left != nullptr) { queue.push_back(TreeNodeHandle(n.node->left, n.x - 1, n.y + 1)); } if (n.node->right != nullptr) { - queue.push_back(TreeNodeHandle(n.node->right, n.x + 1, n.y + 1)); + queue.push_back( + TreeNodeHandle(n.node->right, n.x + 1, n.y + 1)); } } - public: - verticals_iter(std::deque queue) - : queue(queue) - { + public: + verticals_iter(std::deque queue) : queue(queue) { if (queue.front().node == nullptr) { queue.pop_front(); } } - bool operator!=(const verticals_iter& other) const - { + bool operator!=(const verticals_iter &other) const { return queue != other.queue; } - verticals_iter operator++() - { + verticals_iter operator++() { advance(); queue.pop_front(); return *this; } - TreeNodeHandle& operator*() - { - return queue.front(); - } + TreeNodeHandle &operator*() { return queue.front(); } }; -public: - verticals(TreeNode* root) - : root(root) - { + public: + verticals(TreeNode *root) : root(root) {} + + verticals_iter begin() const { + return verticals_iter(std::deque{TreeNodeHandle(root, 0, 0)}); } - verticals_iter begin() const - { - return verticals_iter(std::deque { TreeNodeHandle(root, 0, 0) }); - } - - verticals_iter end() const - { + verticals_iter end() const { std::deque q; return verticals_iter(q); } }; -} +} // namespace class Solution { -public: - std::vector> verticalTraversal(TreeNode* root) - { + public: + std::vector> verticalTraversal(TreeNode *root) { std::map> traversals; int min_x = 0; @@ -150,13 +113,13 @@ public: std::vector> result; for (int x = min_x; x <= max_x; x++) { - auto& v = traversals[x]; + auto &v = traversals[x]; if (v.size()) { std::sort(v.begin(), v.end()); - result.push_back(std::vector {}); + result.push_back(std::vector{}); - for (auto& n : v) { + for (auto &n : v) { result.back().push_back(n.value()); } } @@ -172,8 +135,7 @@ public: namespace _tests { -TreeNode* construct_tree(const std::vector& values, std::size_t i = 0) -{ +TreeNode *construct_tree(const std::vector &values, std::size_t i = 0) { if (i >= values.size() || values[i] == -1) { return nullptr; } @@ -185,8 +147,7 @@ TreeNode* construct_tree(const std::vector& values, std::size_t i = 0) return tree; } -void destruct_tree(TreeNode* ptr) -{ +void destruct_tree(TreeNode *ptr) { if (ptr == nullptr) { return; } @@ -196,46 +157,49 @@ void destruct_tree(TreeNode* ptr) delete ptr; } -} +} // namespace _tests -TEST(examples, first) -{ +TEST(examples, first) { Solution s; - auto t = _tests::construct_tree(std::vector { 3, 9, 20, -1, -1, 15, 7 }); - EXPECT_EQ(s.verticalTraversal(t), (std::vector { std::vector { 9 }, std::vector { 3, 15 }, std::vector { 20 }, std::vector { 7 } })); + auto t = _tests::construct_tree(std::vector{3, 9, 20, -1, -1, 15, 7}); + EXPECT_EQ(s.verticalTraversal(t), + (std::vector{std::vector{9}, std::vector{3, 15}, std::vector{20}, + std::vector{7}})); _tests::destruct_tree(t); } -TEST(examples, second) -{ +TEST(examples, second) { Solution s; - auto t = _tests::construct_tree(std::vector { 1, 2, 3, 4, 5, 6, 7 }); - EXPECT_EQ(s.verticalTraversal(t), (std::vector { std::vector { 4 }, std::vector { 2 }, std::vector { 1, 5, 6 }, std::vector { 3 }, std::vector { 7 } })); + auto t = _tests::construct_tree(std::vector{1, 2, 3, 4, 5, 6, 7}); + EXPECT_EQ(s.verticalTraversal(t), + (std::vector{std::vector{4}, std::vector{2}, std::vector{1, 5, 6}, + std::vector{3}, std::vector{7}})); _tests::destruct_tree(t); } -TEST(examples, third) -{ +TEST(examples, third) { Solution s; - auto t = _tests::construct_tree(std::vector { 1, 2, 3, 4, 6, 5, 7 }); - EXPECT_EQ(s.verticalTraversal(t), (std::vector { std::vector { 4 }, std::vector { 2 }, std::vector { 1, 5, 6 }, std::vector { 3 }, std::vector { 7 } })); + auto t = _tests::construct_tree(std::vector{1, 2, 3, 4, 6, 5, 7}); + EXPECT_EQ(s.verticalTraversal(t), + (std::vector{std::vector{4}, std::vector{2}, std::vector{1, 5, 6}, + std::vector{3}, std::vector{7}})); _tests::destruct_tree(t); } -TEST(submission, first) -{ +TEST(submission, first) { Solution s; - auto t = _tests::construct_tree(std::vector { 3, 1, 4, 0, 2, 2 }); - EXPECT_EQ(s.verticalTraversal(t), (std::vector { std::vector { 0 }, std::vector { 1 }, std::vector { 3, 2, 2 }, std::vector { 4 } })); + auto t = _tests::construct_tree(std::vector{3, 1, 4, 0, 2, 2}); + EXPECT_EQ(s.verticalTraversal(t), + (std::vector{std::vector{0}, std::vector{1}, std::vector{3, 2, 2}, + std::vector{4}})); _tests::destruct_tree(t); } -int main(int argc, char** argv) -{ +int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } diff --git a/cpp/widest-vertical-area-between-two-points-containing-no-points.cpp b/cpp/widest-vertical-area-between-two-points-containing-no-points.cpp index 8641575..3cadfd6 100644 --- a/cpp/widest-vertical-area-between-two-points-containing-no-points.cpp +++ b/cpp/widest-vertical-area-between-two-points-containing-no-points.cpp @@ -2,10 +2,10 @@ #include class Solution { -public: - int maxWidthOfVerticalArea(const std::vector>& points) { + public: + int maxWidthOfVerticalArea(const std::vector> &points) { std::set seen; - for (const auto& point : points) { + for (const auto &point : points) { seen.insert(point[0]); }