From ff45f071a3b572a0aec09ad473600ec7d2968848 Mon Sep 17 00:00:00 2001 From: JamesKano0128 Date: Wed, 26 Jun 2024 07:17:12 -0500 Subject: [PATCH] feat: solve medium/longest-common-subsequence --- .gitignore | 6 +- Cargo.lock | 318 ++++++++---------- Cargo.toml | 49 ++- README.md | 193 +++-------- easy/a-very-big-sum/Cargo.toml | 8 + easy/a-very-big-sum/README.md | 1 + easy/a-very-big-sum/src/main.rs | 35 ++ easy/compare-the-triplets/Cargo.toml | 8 + easy/compare-the-triplets/README.md | 1 + easy/compare-the-triplets/src/main.rs | 59 ++++ easy/simple-array-sum/Cargo.toml | 8 + easy/simple-array-sum/README.md | 1 + easy/simple-array-sum/src/main.rs | 34 ++ easy/solve-me-first/Cargo.toml | 8 + easy/solve-me-first/README.md | 1 + easy/solve-me-first/src/main.rs | 20 ++ hard/bead-ornaments/Cargo.toml | 8 + hard/bead-ornaments/README.md | 11 + hard/bead-ornaments/src/main.rs | 65 ++++ hard/matrix-rotation-algo/Cargo.toml | 8 + hard/matrix-rotation-algo/README.md | 1 + hard/matrix-rotation-algo/src/main.rs | 76 +++++ hard/morgan-and-string/Cargo.toml | 8 + hard/morgan-and-string/README.md | 1 + hard/morgan-and-string/src/main.rs | 54 +++ hard/string-similarity/Cargo.toml | 8 + hard/string-similarity/README.md | 1 + hard/string-similarity/src/main.rs | 84 +++++ medium/bear-and-steady-gene/Cargo.toml | 8 + medium/bear-and-steady-gene/README.md | 15 + medium/bear-and-steady-gene/src/main.rs | 81 +++++ medium/bigger-is-greater/Cargo.toml | 8 + medium/bigger-is-greater/README.md | 7 + medium/bigger-is-greater/src/main.rs | 69 ++++ medium/climbing-the-leaderboard/Cargo.toml | 8 + medium/climbing-the-leaderboard/README.md | 1 + medium/climbing-the-leaderboard/src/main.rs | 83 +++++ medium/coin-change/Cargo.toml | 8 + medium/coin-change/README.md | 6 + medium/coin-change/src/main.rs | 55 +++ medium/connected-cell-in-grid/Cargo.toml | 8 + medium/connected-cell-in-grid/README.md | 1 + medium/connected-cell-in-grid/src/main.rs | 78 +++++ medium/extra-long-factorials/Cargo.toml | 8 + medium/extra-long-factorials/README.md | 1 + medium/extra-long-factorials/src/main.rs | 54 +++ medium/gena-playing-hanoi/Cargo.toml | 8 + medium/gena-playing-hanoi/README.md | 5 + medium/gena-playing-hanoi/src/main.rs | 77 +++++ medium/journey-to-moon/Cargo.toml | 8 + medium/journey-to-moon/README.md | 1 + medium/journey-to-moon/src/main.rs | 99 ++++++ medium/larry-array/Cargo.toml | 8 + medium/larry-array/README.md | 4 + medium/larry-array/src/main.rs | 52 +++ medium/longest-common-subsequence/Cargo.toml | 8 + medium/longest-common-subsequence/README.md | 12 + medium/longest-common-subsequence/src/main.rs | 91 +++++ medium/magic-square-forming/Cargo.toml | 8 + medium/magic-square-forming/README.md | 1 + medium/magic-square-forming/src/main.rs | 54 +++ medium/minimum-loss/Cargo.toml | 8 + medium/minimum-loss/README.md | 19 ++ medium/minimum-loss/src/main.rs | 45 +++ medium/non-divisible-subset/Cargo.toml | 8 + medium/non-divisible-subset/README.md | 1 + medium/non-divisible-subset/src/main.rs | 63 ++++ medium/pairs/Cargo.toml | 8 + medium/pairs/README.md | 1 + medium/pairs/src/main.rs | 64 ++++ medium/queens-attack2/Cargo.toml | 8 + medium/queens-attack2/README.md | 1 + medium/queens-attack2/src/main.rs | 110 ++++++ medium/really-special-subtree/Cargo.toml | 8 + medium/really-special-subtree/README.md | 1 + medium/really-special-subtree/src/main.rs | 111 ++++++ medium/red-john-is-back/Cargo.toml | 8 + medium/red-john-is-back/README.md | 1 + medium/red-john-is-back/src/main.rs | 84 +++++ medium/roads-and-libraries/Cargo.toml | 8 + medium/roads-and-libraries/README.md | 6 + medium/roads-and-libraries/src/main.rs | 103 ++++++ medium/sherlock-and-anagrams/Cargo.toml | 8 + medium/sherlock-and-anagrams/README.md | 5 + medium/sherlock-and-anagrams/src/main.rs | 64 ++++ medium/short-palindrome/Cargo.toml | 8 + medium/short-palindrome/README.md | 12 + medium/short-palindrome/src/main.rs | 48 +++ medium/shortest-reach/Cargo.toml | 8 + medium/shortest-reach/README.md | 1 + medium/shortest-reach/src/main.rs | 102 ++++++ medium/snakes-and-ladders/Cargo.toml | 8 + medium/snakes-and-ladders/README.md | 1 + medium/snakes-and-ladders/src/main.rs | 123 +++++++ medium/special-subtree/Cargo.toml | 8 + medium/special-subtree/README.md | 1 + medium/special-subtree/src/main.rs | 107 ++++++ medium/stock-maximize/Cargo.toml | 8 + medium/stock-maximize/README.md | 1 + medium/stock-maximize/src/main.rs | 51 +++ medium/the-time-in-words/Cargo.toml | 8 + medium/the-time-in-words/README.md | 1 + medium/the-time-in-words/src/main.rs | 93 +++++ medium/threed-surface-area/Cargo.toml | 8 + medium/threed-surface-area/README.md | 11 + medium/threed-surface-area/src/main.rs | 83 +++++ 106 files changed, 3101 insertions(+), 343 deletions(-) create mode 100644 easy/a-very-big-sum/Cargo.toml create mode 100644 easy/a-very-big-sum/README.md create mode 100644 easy/a-very-big-sum/src/main.rs create mode 100644 easy/compare-the-triplets/Cargo.toml create mode 100644 easy/compare-the-triplets/README.md create mode 100644 easy/compare-the-triplets/src/main.rs create mode 100644 easy/simple-array-sum/Cargo.toml create mode 100644 easy/simple-array-sum/README.md create mode 100644 easy/simple-array-sum/src/main.rs create mode 100644 easy/solve-me-first/Cargo.toml create mode 100644 easy/solve-me-first/README.md create mode 100644 easy/solve-me-first/src/main.rs create mode 100644 hard/bead-ornaments/Cargo.toml create mode 100644 hard/bead-ornaments/README.md create mode 100644 hard/bead-ornaments/src/main.rs create mode 100644 hard/matrix-rotation-algo/Cargo.toml create mode 100644 hard/matrix-rotation-algo/README.md create mode 100644 hard/matrix-rotation-algo/src/main.rs create mode 100644 hard/morgan-and-string/Cargo.toml create mode 100644 hard/morgan-and-string/README.md create mode 100644 hard/morgan-and-string/src/main.rs create mode 100644 hard/string-similarity/Cargo.toml create mode 100644 hard/string-similarity/README.md create mode 100644 hard/string-similarity/src/main.rs create mode 100644 medium/bear-and-steady-gene/Cargo.toml create mode 100644 medium/bear-and-steady-gene/README.md create mode 100644 medium/bear-and-steady-gene/src/main.rs create mode 100644 medium/bigger-is-greater/Cargo.toml create mode 100644 medium/bigger-is-greater/README.md create mode 100644 medium/bigger-is-greater/src/main.rs create mode 100644 medium/climbing-the-leaderboard/Cargo.toml create mode 100644 medium/climbing-the-leaderboard/README.md create mode 100644 medium/climbing-the-leaderboard/src/main.rs create mode 100644 medium/coin-change/Cargo.toml create mode 100644 medium/coin-change/README.md create mode 100644 medium/coin-change/src/main.rs create mode 100644 medium/connected-cell-in-grid/Cargo.toml create mode 100644 medium/connected-cell-in-grid/README.md create mode 100644 medium/connected-cell-in-grid/src/main.rs create mode 100644 medium/extra-long-factorials/Cargo.toml create mode 100644 medium/extra-long-factorials/README.md create mode 100644 medium/extra-long-factorials/src/main.rs create mode 100644 medium/gena-playing-hanoi/Cargo.toml create mode 100644 medium/gena-playing-hanoi/README.md create mode 100644 medium/gena-playing-hanoi/src/main.rs create mode 100644 medium/journey-to-moon/Cargo.toml create mode 100644 medium/journey-to-moon/README.md create mode 100644 medium/journey-to-moon/src/main.rs create mode 100644 medium/larry-array/Cargo.toml create mode 100644 medium/larry-array/README.md create mode 100644 medium/larry-array/src/main.rs create mode 100644 medium/longest-common-subsequence/Cargo.toml create mode 100644 medium/longest-common-subsequence/README.md create mode 100644 medium/longest-common-subsequence/src/main.rs create mode 100644 medium/magic-square-forming/Cargo.toml create mode 100644 medium/magic-square-forming/README.md create mode 100644 medium/magic-square-forming/src/main.rs create mode 100644 medium/minimum-loss/Cargo.toml create mode 100644 medium/minimum-loss/README.md create mode 100644 medium/minimum-loss/src/main.rs create mode 100644 medium/non-divisible-subset/Cargo.toml create mode 100644 medium/non-divisible-subset/README.md create mode 100644 medium/non-divisible-subset/src/main.rs create mode 100644 medium/pairs/Cargo.toml create mode 100644 medium/pairs/README.md create mode 100644 medium/pairs/src/main.rs create mode 100644 medium/queens-attack2/Cargo.toml create mode 100644 medium/queens-attack2/README.md create mode 100644 medium/queens-attack2/src/main.rs create mode 100644 medium/really-special-subtree/Cargo.toml create mode 100644 medium/really-special-subtree/README.md create mode 100644 medium/really-special-subtree/src/main.rs create mode 100644 medium/red-john-is-back/Cargo.toml create mode 100644 medium/red-john-is-back/README.md create mode 100644 medium/red-john-is-back/src/main.rs create mode 100644 medium/roads-and-libraries/Cargo.toml create mode 100644 medium/roads-and-libraries/README.md create mode 100644 medium/roads-and-libraries/src/main.rs create mode 100644 medium/sherlock-and-anagrams/Cargo.toml create mode 100644 medium/sherlock-and-anagrams/README.md create mode 100644 medium/sherlock-and-anagrams/src/main.rs create mode 100644 medium/short-palindrome/Cargo.toml create mode 100644 medium/short-palindrome/README.md create mode 100644 medium/short-palindrome/src/main.rs create mode 100644 medium/shortest-reach/Cargo.toml create mode 100644 medium/shortest-reach/README.md create mode 100644 medium/shortest-reach/src/main.rs create mode 100644 medium/snakes-and-ladders/Cargo.toml create mode 100644 medium/snakes-and-ladders/README.md create mode 100644 medium/snakes-and-ladders/src/main.rs create mode 100644 medium/special-subtree/Cargo.toml create mode 100644 medium/special-subtree/README.md create mode 100644 medium/special-subtree/src/main.rs create mode 100644 medium/stock-maximize/Cargo.toml create mode 100644 medium/stock-maximize/README.md create mode 100644 medium/stock-maximize/src/main.rs create mode 100644 medium/the-time-in-words/Cargo.toml create mode 100644 medium/the-time-in-words/README.md create mode 100644 medium/the-time-in-words/src/main.rs create mode 100644 medium/threed-surface-area/Cargo.toml create mode 100644 medium/threed-surface-area/README.md create mode 100644 medium/threed-surface-area/src/main.rs diff --git a/.gitignore b/.gitignore index 51065d2..a9d37c5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,2 @@ -.idea -.DS_Store -target/ -.vscode +target +Cargo.lock diff --git a/Cargo.lock b/Cargo.lock index f0a2738..2f6e9e1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3,187 +3,137 @@ version = 3 [[package]] -name = "aho-corasick" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0" -dependencies = [ - "memchr", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "getrandom" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - -[[package]] -name = "libc" -version = "0.2.153" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" - -[[package]] -name = "memchr" -version = "2.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149" - -[[package]] -name = "ppv-lite86" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" - -[[package]] -name = "proc-macro2" -version = "1.0.78" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha", - "rand_core", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom", -] - -[[package]] -name = "regex" -version = "1.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" - -[[package]] -name = "rust-challenges" -version = "0.1.0" -dependencies = [ - "rand", - "regex", - "test-case", -] - -[[package]] -name = "syn" -version = "2.0.52" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b699d15b36d1f02c3e7c69f8ffef53de37aefae075d8488d4ba1a7788d574a07" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "test-case" -version = "3.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb2550dd13afcd286853192af8601920d959b14c401fcece38071d53bf0768a8" -dependencies = [ - "test-case-macros", -] - -[[package]] -name = "test-case-core" -version = "3.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adcb7fd841cd518e279be3d5a3eb0636409487998a4aff22f3de87b81e88384f" -dependencies = [ - "cfg-if", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "test-case-macros" -version = "3.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c89e72a01ed4c579669add59014b9a524d609c0c88c6a585ce37485879f6ffb" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "test-case-core", -] - -[[package]] -name = "unicode-ident" -version = "1.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +name = "a-very-big-sum" +version = "0.1.0" + +[[package]] +name = "bead-ornaments" +version = "0.1.0" + +[[package]] +name = "bear-and-steady-gene" +version = "0.1.0" + +[[package]] +name = "bigger-is-greater" +version = "0.1.0" + +[[package]] +name = "climbing-the-leaderboard" +version = "0.1.0" + +[[package]] +name = "coin-change" +version = "0.1.0" + +[[package]] +name = "compare-the-triplets" +version = "0.1.0" + +[[package]] +name = "connected-cell-in-grid" +version = "0.1.0" + +[[package]] +name = "extra-long-factorials" +version = "0.1.0" + +[[package]] +name = "gena-playing-hanoi" +version = "0.1.0" + +[[package]] +name = "journey-to-moon" +version = "0.1.0" + +[[package]] +name = "larry-array" +version = "0.1.0" + +[[package]] +name = "longest-common-subsequence" +version = "0.1.0" + +[[package]] +name = "magic-square-forming" +version = "0.1.0" + +[[package]] +name = "matrix-rotation-algo" +version = "0.1.0" + +[[package]] +name = "minimum-loss" +version = "0.1.0" + +[[package]] +name = "morgan-and-string" +version = "0.1.0" + +[[package]] +name = "non-divisible-subset" +version = "0.1.0" + +[[package]] +name = "pairs" +version = "0.1.0" + +[[package]] +name = "queens-attack2" +version = "0.1.0" + +[[package]] +name = "really-special-subtree" +version = "0.1.0" + +[[package]] +name = "red-john-is-back" +version = "0.1.0" + +[[package]] +name = "roads-and-libraries" +version = "0.1.0" + +[[package]] +name = "sherlock-and-anagrams" +version = "0.1.0" + +[[package]] +name = "short-palindrome" +version = "0.1.0" + +[[package]] +name = "shortest-reach" +version = "0.1.0" + +[[package]] +name = "simple-array-sum" +version = "0.1.0" + +[[package]] +name = "snakes-and-ladders" +version = "0.1.0" + +[[package]] +name = "solve-me-first" +version = "0.1.0" + +[[package]] +name = "special-subtree" +version = "0.1.0" + +[[package]] +name = "stock-maximize" +version = "0.1.0" + +[[package]] +name = "string-similarity" +version = "0.1.0" + +[[package]] +name = "the-time-in-words" +version = "0.1.0" + +[[package]] +name = "threed-surface-area" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 3e6fe6b..7f29c73 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,14 +1,41 @@ -[package] -name = "rust-challenges" -version = "0.1.0" -authors = ["Justin Sexton "] -edition = "2018" +[workspace] +members = [ + "easy/solve-me-first", + "easy/simple-array-sum", + "easy/compare-the-triplets", + "easy/a-very-big-sum", -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + "medium/magic-square-forming", + "medium/climbing-the-leaderboard", + "medium/extra-long-factorials", + "medium/non-divisible-subset", + "medium/queens-attack2", + "medium/the-time-in-words", + "medium/bigger-is-greater", + "medium/threed-surface-area", + "medium/bear-and-steady-gene", + "medium/minimum-loss", + "medium/connected-cell-in-grid", + "medium/short-palindrome", + "medium/gena-playing-hanoi", + "medium/roads-and-libraries", + "medium/journey-to-moon", + "medium/really-special-subtree", + "medium/snakes-and-ladders", + "medium/shortest-reach", + "medium/special-subtree", + "medium/larry-array", + "medium/sherlock-and-anagrams", + "medium/coin-change", + "medium/pairs", + "medium/red-john-is-back", + "medium/stock-maximize", + "medium/longest-common-subsequence", -[dependencies] -regex = "1" -rand = "0.8.5" + "hard/matrix-rotation-algo", + "hard/morgan-and-string", + "hard/bead-ornaments", + "hard/string-similarity" +] -[dev-dependencies] -test-case = "3.2.1" +resolver = "2" diff --git a/README.md b/README.md index 4164f37..0e3dcdb 100644 --- a/README.md +++ b/README.md @@ -1,144 +1,49 @@ -# Rust Challenges Course - -![](https://github.com/jusexton/rust-challenges/workflows/build/badge.svg) - -Programming challenges written in the Rust programming language - -Visit https://github.com/jusexton/all-challenges if you're interested in seeing programming challenges completed in -other languages. - -## Completed Programming Challenges - -- [Code Wars](#code-wars) -- [r/dailyprogrammer](#rdailyprogrammer) -- [LeetCode](#leetcode) -- [Other](#other) - -### Code Wars - -#### Kata 4 - -- Pyramid Slide (https://www.codewars.com/kata/551f23362ff852e2ab000037) - -#### Kata 5 - -- Sum of Pairs (https://www.codewars.com/kata/54d81488b981293527000c8f) -- Are They Same (https://www.codewars.com/kata/550498447451fbbd7600041c) -- Josephus Survivor (https://www.codewars.com/kata/555624b601231dc7a400017a) -- Perimeter of Squares in Rectangles (https://www.codewars.com/kata/559a28007caad2ac4e000083) -- Diamond (https://www.codewars.com/kata/5503013e34137eeeaa001648) -- Fibonacci Product (https://www.codewars.com/kata/5541f58a944b85ce6d00006a) -- Valid Parentheses (https://www.codewars.com/kata/52774a314c2333f0a7000688) -- Alphanumeric (https://www.codewars.com/kata/526dbd6c8c0eb53254000110) - -#### Kata 6 - -- Add Without Operator (https://www.codewars.com/kata/5a9c35e9ba1bb5c54a0001ac) -- Frequency Sort (https://www.codewars.com/kata/5a8d2bf60025e9163c0000bc) -- Dead Fish Parse (https://www.codewars.com/kata/51e0007c1f9378fa810002a9) -- Pascal Case (https://www.codewars.com/kata/587731fda577b3d1b0001196) -- New Cashier Does Not Know Space or Shift (https://www.codewars.com/kata/5d23d89906f92a00267bb83d) -- Multiplication Table (https://www.codewars.com/kata/534d2f5b5371ecf8d2000a08) -- Nearest Prime (https://www.codewars.com/kata/5a946d9fba1bb5135100007c) -- NATO (https://www.codewars.com/kata/586538146b56991861000293) -- EsoLang: MiniBitMove (https://www.codewars.com/kata/587c0138110b20624e000253) -- Ease the Stock Market (https://www.codewars.com/kata/54de3257f565801d96001200) -- Binaries (https://www.codewars.com/kata/5d98b6b38b0f6c001a461198) -- Max Stock Profit (https://www.codewars.com/kata/597ef546ee48603f7a000057) -- Buying a Car (https://www.codewars.com/kata/554a44516729e4d80b000012) -- Spinning Words (https://www.codewars.com/kata/5264d2b162488dc400000001) -- Camel Case (https://www.codewars.com/kata/517abf86da9663f1d2000003) -- Count Characters (https://www.codewars.com/kata/52efefcbcdf57161d4000091) -- Position Average (https://www.codewars.com/kata/59f4a0acbee84576800000af) - -#### Kata 7 - -- Recursion 101 (https://www.codewars.com/kata/5b752a42b11814b09c00005d) -- Build Square (https://www.codewars.com/kata/59a96d71dbe3b06c0200009c) -- Sort Numbers (https://www.codewars.com/kata/5174a4c0f2769dd8b1000003) -- Automorphic (https://www.codewars.com/kata/5a58d889880385c2f40000aa) -- Coin Combinations (https://www.codewars.com/kata/564d0490e96393fc5c000029) -- Nth Power (https://www.codewars.com/kata/57d814e4950d8489720008db) -- Valid Spacing (https://www.codewars.com/kata/5f77d62851f6bc0033616bd8) -- Doubleton (https://www.codewars.com/kata/604287495a72ae00131685c7) -- Duplicate Words (https://www.codewars.com/kata/5b39e3772ae7545f650000fc) -- GPS (https://www.codewars.com/kata/56484848ba95170a8000004d) -- All Inclusive (https://www.codewars.com/kata/5700c9acc1555755be00027e) -- Cats and Shelves (https://www.codewars.com/kata/62c93765cef6f10030dfa92b) -- People on the Bus (https://www.codewars.com/kata/5648b12ce68d9daa6b000099) - -#### Kata 8 - -- The Feast of Many Beasts (https://www.codewars.com/kata/5aa736a455f906981800360d) -- First Non-Consecutive (https://www.codewars.com/kata/58f8a3a27a5c28d92e000144) -- Repeating String (https://www.codewars.com/kata/57a0e5c372292dd76d000d7e) -- Remove Whitespace (https://www.codewars.com/kata/57eae20f5500ad98e50002c5) -- Multiplication Table (https://www.codewars.com/kata/5a2fd38b55519ed98f0000ce) -- Alternating Case (https://www.codewars.com/kata/56efc695740d30f963000557) -- Summation (https://www.codewars.com/kata/55d24f55d7dd296eb9000030) - -### r/dailyprogrammer - -#### Easy - -- Letter Value - Sum (https://www.reddit.com/r/dailyprogrammer/comments/onfehl/20210719_challenge_399_easy_letter_value_sum/) - -### LeetCode - -#### Easy - -- Fibonacci (https://leetcode.com/problems/fibonacci-number) -- Perfect Square (https://leetcode.com/problems/valid-perfect-square/) -- Third Maximum Number (https://leetcode.com/problems/third-maximum-number/) -- Hamming Distance (https://leetcode.com/problems/hamming-distance) -- Build an Array with Stack Operations (https://leetcode.com/problems/build-an-array-with-stack-operations/) -- Second Largest Digit (https://leetcode.com/problems/second-largest-digit-in-a-string) -- Counting Sheep (https://www.codewars.com/kata/54edbc7200b811e956000556) -- Robot Returns to Origin (https://leetcode.com/problems/robot-return-to-origin) -- Consistent Strings (https://leetcode.com/problems/count-the-number-of-consistent-strings) -- Two Sum (https://leetcode.com/problems/two-sum/) -- Merge Two Sorted Lists (https://leetcode.com/problems/merge-two-sorted-lists/) -- Best Time to Buy and Sell Stock (https://leetcode.com/problems/best-time-to-buy-and-sell-stock) -- Plus One (https://leetcode.com/problems/plus-one/) -- Climbing Stairs (https://leetcode.com/problems/climbing-stairs/) -- Largest Odd Number (https://leetcode.com/problems/largest-odd-number-in-string/) -- Number of Different Integers (https://leetcode.com/problems/number-of-different-integers-in-a-string) -- Largest Substring Between Two Equal - Characters (https://leetcode.com/problems/largest-substring-between-two-equal-characters) -- Alike Halves (https://leetcode.com/problems/determine-if-string-halves-are-alike) -- Unique Number of Occurrences (https://leetcode.com/problems/unique-number-of-occurrences) -- Minimum Common Value (https://leetcode.com/problems/minimum-common-value) -- Sort by Number of Bits (https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits) -- Make the String Great (https://leetcode.com/problems/make-the-string-great/) -- Excel Column Number (https://leetcode.com/problems/excel-sheet-column-number/) - -#### Medium - -- The Largest Number (https://leetcode.com/problems/largest-number/) -- Authentication Manager (https://leetcode.com/problems/design-authentication-manager/) -- Best Time to Buy and Sell Stock (https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii) -- Longest Substring Without Repeating - Characters (https://leetcode.com/problems/longest-substring-without-repeating-characters/) -- Kth Largest Element (https://leetcode.com/problems/kth-largest-element-in-an-array/) -- Rearrange Elements by Sign (https://leetcode.com/problems/rearrange-array-elements-by-sign/) -- Lonely Numbers (https://leetcode.com/problems/find-all-lonely-numbers-in-the-array/) -- Design Bitset (https://leetcode.com/problems/design-bitset) -- Minimum Rounds (https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks) -- Minimum Steps to Anagram (https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram) -- Zero or One Losses (https://leetcode.com/problems/find-players-with-zero-or-one-losses) -- Randomized Set (https://leetcode.com/problems/insert-delete-getrandom-o1) -- Remove Occurrences (https://leetcode.com/problems/remove-all-occurrences-of-a-substring) -- Divide Array Into Arrays With Max - Difference (https://leetcode.com/problems/divide-array-into-arrays-with-max-difference) -- Remove Minimum to Make Valid Parentheses (https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses) -- Sum Root to Leaf (https://leetcode.com/problems/sum-root-to-leaf-numbers) -- Repeated DNA Sequence (https://leetcode.com/problems/repeated-dna-sequences/) -- Rotate Array (https://leetcode.com/problems/rotate-array/) -- Sort Colors (https://leetcode.com/problems/sort-colors) -- Rotate Digits (https://leetcode.com/problems/rotated-digits) - -### Other - - -- Readability (https://cs50.harvard.edu/x/2021/psets/2/readability/) +# Hackerrank Coding Challenges with Rust + +> **Hackerrank has around 3 levels of difficulty: Easy, Medium(Intermediate), Hard(Advanced, Expert)** + + +## Hard +1. [Matrix Rotation Algo](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/hard/matrix-rotation-algo) +2. [Morgan and a String](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/hard/morgan-and-string) +3. [Bead Ornaments](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/hard/bead-ornaments) +4. [String Similarity](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/hard/string-similarity) + +## Medium +1. [Forming a Magic Square](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/magic-square-forming) +2. [Climbing the Leaderboard](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/climbing-the-leaderboard) +3. [Extra Long Factorials](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/extra-long-factorials) +4. [Non-Divisible Subset](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/non-divisible-subset) +5. [Queen's Attack II](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/queens-attack2) +6. [The Time in Words](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/the-time-in-words) +7. [Bigger is Greater](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/bigger-is-greater) +8. [3D Surface Area](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/threed-surface-area) +9. [Bear and Steady Gene](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/bear-and-steady-gene) +10. [Minimum Loss](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/minimum-loss) +11. [Connected Cell in a Grid](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/connected-cell-in-grid) +12. [Short Palindrome](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/short-palindrome) +13. [Gena Playing Hanoi](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/gena-playing-hanoi) +14. [Roads and Libraries](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/roads-and-libraries) +15. [Journey to the Moon](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/journey-to-moon) +16. [Kruskal (MST): Really Special Subtree](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/really-special-subtree) +17. [Snakes and Ladders: The Quickest Way Up](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/snakes-and-ladders) +18. [BFS: Shortest Reach](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/shortest-reach) +19. [Prim's (MST): Special Subtree](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/special-subtree) +20. [Larry's Array](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/larry-array) +21. [Sherlock and Anagrams](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/sherlock-and-anagrams) +22. [The Coin Change Problem](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/coin-change) +23. [Pairs](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/pairs) +24. [Red John is Back](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/red-john-is-back) +25. [Stock Maximize](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/stock-maximize) +26. [The Longest Common Subsequence](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/medium/longest-common-subsequence) + +## Easy +1. [Solve Me First](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/easy/solve-me-first) +2. [Simple Array Sum](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/easy/simple-array-sum) +3. [Compare the Triplets](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/easy/compare-the-triplets) +4. [A Very Big Sum](https://github.com/xfactor-toml/rust-coding-challenges/tree/master/easy/a-very-big-sum) + +--- +## Contribution Guide +1. Fork this repo, contribute and then send Pull Request. +2. Every solution should be written in Rust and involving README.md for algorithm explanation. diff --git a/easy/a-very-big-sum/Cargo.toml b/easy/a-very-big-sum/Cargo.toml new file mode 100644 index 0000000..81f952d --- /dev/null +++ b/easy/a-very-big-sum/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "a-very-big-sum" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/easy/a-very-big-sum/README.md b/easy/a-very-big-sum/README.md new file mode 100644 index 0000000..c3022e8 --- /dev/null +++ b/easy/a-very-big-sum/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/a-very-big-sum/problem?isFullScreen=true) \ No newline at end of file diff --git a/easy/a-very-big-sum/src/main.rs b/easy/a-very-big-sum/src/main.rs new file mode 100644 index 0000000..ee8fa35 --- /dev/null +++ b/easy/a-very-big-sum/src/main.rs @@ -0,0 +1,35 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'aVeryBigSum' function below. + * + * The function is expected to return a LONG_INTEGER. + * The function accepts LONG_INTEGER_ARRAY ar as parameter. + */ + +fn aVeryBigSum(ar: &[i64]) -> i64 { + ar.iter().sum() +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let _ar_count = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let ar: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let result = aVeryBigSum(&ar); + + // writeln!(&mut fptr, "{}", result).ok(); + + println!("{}", result); +} diff --git a/easy/compare-the-triplets/Cargo.toml b/easy/compare-the-triplets/Cargo.toml new file mode 100644 index 0000000..15805f8 --- /dev/null +++ b/easy/compare-the-triplets/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "compare-the-triplets" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/easy/compare-the-triplets/README.md b/easy/compare-the-triplets/README.md new file mode 100644 index 0000000..1c3a61c --- /dev/null +++ b/easy/compare-the-triplets/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/compare-the-triplets/problem?isFullScreen=true) \ No newline at end of file diff --git a/easy/compare-the-triplets/src/main.rs b/easy/compare-the-triplets/src/main.rs new file mode 100644 index 0000000..b5a4ea8 --- /dev/null +++ b/easy/compare-the-triplets/src/main.rs @@ -0,0 +1,59 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'compareTriplets' function below. + * + * The function is expected to return an INTEGER_ARRAY. + * The function accepts following parameters: + * 1. INTEGER_ARRAY a + * 2. INTEGER_ARRAY b + */ + +fn compareTriplets(a: &[i32], b: &[i32]) -> Vec { + let mut result: Vec = vec![0, 0]; + + for (index, a_value) in a.iter().enumerate() { + if a_value > b.get(index).unwrap() { + result[0] += 1; + } else if a_value < b.get(index).unwrap() { + result[1] += 1; + } + } + + result +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let a: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let b: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let result = compareTriplets(&a, &b); + + println!("{} {}", result.get(0).unwrap(), result.get(1).unwrap()) + + // for i in 0..result.len() { + // write!(&mut fptr, "{}", result[i]).ok(); + + // if i != result.len() - 1 { + // write!(&mut fptr, " ").ok(); + // } + // } + + // writeln!(&mut fptr).ok(); +} diff --git a/easy/simple-array-sum/Cargo.toml b/easy/simple-array-sum/Cargo.toml new file mode 100644 index 0000000..6da905e --- /dev/null +++ b/easy/simple-array-sum/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "simple-array-sum" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/easy/simple-array-sum/README.md b/easy/simple-array-sum/README.md new file mode 100644 index 0000000..9845b1c --- /dev/null +++ b/easy/simple-array-sum/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/simple-array-sum/problem?isFullScreen=true) \ No newline at end of file diff --git a/easy/simple-array-sum/src/main.rs b/easy/simple-array-sum/src/main.rs new file mode 100644 index 0000000..b2912d9 --- /dev/null +++ b/easy/simple-array-sum/src/main.rs @@ -0,0 +1,34 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'simpleArraySum' function below. + * + * The function is expected to return an INTEGER. + * The function accepts INTEGER_ARRAY ar as parameter. + */ + +fn simpleArraySum(ar: &[i32]) -> i32 { + ar.iter().sum() +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let _ar_count = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let ar: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let result = simpleArraySum(&ar); + + // writeln!(&mut fptr, "{}", result).ok(); + println!("{}", result); +} diff --git a/easy/solve-me-first/Cargo.toml b/easy/solve-me-first/Cargo.toml new file mode 100644 index 0000000..5309f55 --- /dev/null +++ b/easy/solve-me-first/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "solve-me-first" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/easy/solve-me-first/README.md b/easy/solve-me-first/README.md new file mode 100644 index 0000000..fcc0f03 --- /dev/null +++ b/easy/solve-me-first/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/solve-me-first/problem?isFullScreen=true) \ No newline at end of file diff --git a/easy/solve-me-first/src/main.rs b/easy/solve-me-first/src/main.rs new file mode 100644 index 0000000..e302d2b --- /dev/null +++ b/easy/solve-me-first/src/main.rs @@ -0,0 +1,20 @@ +use std::io; + +fn main() { + // variable declaration + let mut _num_str_1 = String::new(); + let mut _num_str_2 = String::new(); + + // read variables + io::stdin().read_line(&mut _num_str_1).ok().expect("read error"); + io::stdin().read_line(&mut _num_str_2).ok().expect("read error"); + + // parse integers + let mut _num_1 : i32 = _num_str_1.trim().parse().ok().expect("parse error"); + let mut _num_2 : i32 = _num_str_2.trim().parse().ok().expect("parse error"); + + // print the sum + // Hint: Type println!("{}", _num_1 + _num_2); below + println!("{}", _num_1 + _num_2); +} + diff --git a/hard/bead-ornaments/Cargo.toml b/hard/bead-ornaments/Cargo.toml new file mode 100644 index 0000000..3d5ea00 --- /dev/null +++ b/hard/bead-ornaments/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "bead-ornaments" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/hard/bead-ornaments/README.md b/hard/bead-ornaments/README.md new file mode 100644 index 0000000..ac20035 --- /dev/null +++ b/hard/bead-ornaments/README.md @@ -0,0 +1,11 @@ +Cayley’s Formula + +This formula tells how many trees can be constructed with N vertices. It states that there are NN – 2 labeled trees that of N nodes. + +[Read more details](https://www.geeksforgeeks.org/cayleys-formula) + +> Ask ChatGpt to see more detailed explanation about this solution + +Note: overflow of i32 * i32 + +[Solve Yourself Here](https://www.hackerrank.com/challenges/beadornaments/problem?isFullScreen=true) diff --git a/hard/bead-ornaments/src/main.rs b/hard/bead-ornaments/src/main.rs new file mode 100644 index 0000000..3ab895f --- /dev/null +++ b/hard/bead-ornaments/src/main.rs @@ -0,0 +1,65 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'beadOrnaments' function below. + * + * The function is expected to return an INTEGER. + * The function accepts INTEGER_ARRAY b as parameter. + */ + +fn beadOrnaments(b: &[i32]) -> i32 { + let mut result: i32 = 1; + + let modulo: u64 = 1000000007; + + for &k in b.iter() { + let mut tmp = 1; + + for _ in 0..k-1 { + tmp = (tmp * k as u64) % modulo; + } + + result = ((tmp * result as u64) % modulo) as i32; + } + + if b.len() >= 2 { + let mut tmp = 1; + let bead_count = b.iter().sum::(); + + for _ in 0..b.len() - 2 { + tmp = (tmp * bead_count as u64) % modulo; + } + + result = ((tmp * result as u64) % modulo) as i32; + } else { + result /= b.iter().sum::().pow(2 - b.len() as u32 ); + } + + result +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let t = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + for _ in 0..t { + let _b_count = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let b: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let result = beadOrnaments(&b); + + println!("{}", result); + // writeln!(&mut fptr, "{}", result).ok(); + } +} diff --git a/hard/matrix-rotation-algo/Cargo.toml b/hard/matrix-rotation-algo/Cargo.toml new file mode 100644 index 0000000..2465a97 --- /dev/null +++ b/hard/matrix-rotation-algo/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "matrix-rotation-algo" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/hard/matrix-rotation-algo/README.md b/hard/matrix-rotation-algo/README.md new file mode 100644 index 0000000..81982e0 --- /dev/null +++ b/hard/matrix-rotation-algo/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/matrix-rotation-algo/problem?isFullScreen=true) \ No newline at end of file diff --git a/hard/matrix-rotation-algo/src/main.rs b/hard/matrix-rotation-algo/src/main.rs new file mode 100644 index 0000000..e072acc --- /dev/null +++ b/hard/matrix-rotation-algo/src/main.rs @@ -0,0 +1,76 @@ +use std::io::{self, BufRead}; + +/* + * Complete the 'matrixRotation' function below. + * + * The function accepts following parameters: + * 1. 2D_INTEGER_ARRAY matrix + * 2. INTEGER r + */ +fn get_position(m: usize, n: usize, layer: usize, step: usize) -> (usize, usize) { + let col = n - 2 * layer; + let row = m - 2 * layer; + + if step < col { + (layer, layer + step) + } else if step >= col && step < col + row - 1 { + (layer + step - col + 1, col + layer - 1) + } else if step >= col + row - 1 && step < col * 2 + row - 2 { + (layer + row - 1, n - 1 - layer + (col + row - 2) - step) + } else { + (m - 1 - layer + (col * 2 + row - 3) - step, layer) + } +} + +fn matrixRotation(matrix: &[Vec], r: i32) { + let m = matrix.len(); + let n = matrix[0].len(); + let layer = m.min(n) / 2; + let max_border_length = m * 2 + n * 2 - 4; + let mut rotated_matrix = vec![vec![0; n]; m]; + + for i in 0..layer { + let border_length = max_border_length - i * 8; + + for j in 0 .. border_length { + let (x, y) = get_position(m, n, i, j); + let (x_origin, y_origin) = get_position(m, n, i, (j + r as usize) % border_length); + + rotated_matrix[x][y] = matrix[x_origin][y_origin]; + } + } + + for row in rotated_matrix.iter() { + println!("{}", row.iter().map(|v| v.to_string()).collect::>().join(" ")); + } +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + let first_multiple_input: Vec = stdin_iterator.next().unwrap().unwrap() + .split(' ') + .map(|s| s.to_string()) + .collect(); + + let m = first_multiple_input[0].trim().parse::().unwrap(); + + let n = first_multiple_input[1].trim().parse::().unwrap(); + + let r = first_multiple_input[2].trim().parse::().unwrap(); + + let mut matrix: Vec> = Vec::with_capacity(m as usize); + + for i in 0..m as usize { + matrix.push(Vec::with_capacity(n as usize)); + + matrix[i] = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + } + + matrixRotation(&matrix, r); +} diff --git a/hard/morgan-and-string/Cargo.toml b/hard/morgan-and-string/Cargo.toml new file mode 100644 index 0000000..f0babca --- /dev/null +++ b/hard/morgan-and-string/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "morgan-and-string" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/hard/morgan-and-string/README.md b/hard/morgan-and-string/README.md new file mode 100644 index 0000000..1ce9fec --- /dev/null +++ b/hard/morgan-and-string/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/morgan-and-a-string/problem?isFullScreen=true) \ No newline at end of file diff --git a/hard/morgan-and-string/src/main.rs b/hard/morgan-and-string/src/main.rs new file mode 100644 index 0000000..29fadaa --- /dev/null +++ b/hard/morgan-and-string/src/main.rs @@ -0,0 +1,54 @@ +use std::borrow::BorrowMut; +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; +use std::cmp::Ord; + +/* + * Complete the 'morganAndString' function below. + * + * The function is expected to return a STRING. + * The function accepts following parameters: + * 1. STRING a + * 2. STRING b + */ + +fn morganAndString(a: &str, b: &str) -> String { + let (mut az, mut bz) = (a.to_string(), b.to_string()); + + let mut result = String::new(); + + az.push('z'); + bz.push('z'); + + for _ in 0..a.len()+b.len() { + if az < bz { + result.push(az.remove(0)); + } else { + result.push(bz.remove(0)); + } + } + + result +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let t = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + for _ in 0..t { + let a = stdin_iterator.next().unwrap().unwrap(); + + let b = stdin_iterator.next().unwrap().unwrap(); + + let result = morganAndString(&a, &b); + + println!("{}", result); + + // writeln!(&mut fptr, "{}", result).ok(); + } +} diff --git a/hard/string-similarity/Cargo.toml b/hard/string-similarity/Cargo.toml new file mode 100644 index 0000000..969c013 --- /dev/null +++ b/hard/string-similarity/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "string-similarity" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/hard/string-similarity/README.md b/hard/string-similarity/README.md new file mode 100644 index 0000000..1c9976b --- /dev/null +++ b/hard/string-similarity/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/string-similarity/problem?isFullScreen=true) \ No newline at end of file diff --git a/hard/string-similarity/src/main.rs b/hard/string-similarity/src/main.rs new file mode 100644 index 0000000..20e4979 --- /dev/null +++ b/hard/string-similarity/src/main.rs @@ -0,0 +1,84 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'stringSimilarity' function below. + * + * The function is expected to return an INTEGER. + * The function accepts STRING s as parameter. + */ + +fn stringSimilarity(s: &str) -> i64 { + let mut similarity = 0; + let mut i = 0; + + let mut repeat = 1; + + let s_vec: Vec = s.chars().collect(); + + while repeat < s.len() && s_vec[repeat] == s_vec[0] { + repeat += 1; + } + + while i < s.len() { + let suffix: &str = &s[i..]; + + let (mut start, mut end) = (1, suffix.len()); + + if &s[0..start] != &suffix[0..start] { + i += 1; + continue; + } + + if &s[0..end] == &suffix[0..end] { + start = end; + } else { + loop { + if start >= end { + break; + } + + let mid = (start + end) / 2 + 1; + + if &s[0..mid] != &suffix[0..mid] { + end = mid - 1; + } else { + start = mid; + } + } + } + + if repeat > 0 && suffix.len() == s.len() { + similarity += (repeat + 1) * repeat / 2; + + similarity += start - repeat; + + i += repeat; + } else { + similarity += start; + i += 1; + } + } + + similarity as i64 +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let t = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + for _ in 0..t { + let s = stdin_iterator.next().unwrap().unwrap(); + + let result = stringSimilarity(&s); + + println!("{}", result); + + // writeln!(&mut fptr, "{}", result).ok(); + } +} diff --git a/medium/bear-and-steady-gene/Cargo.toml b/medium/bear-and-steady-gene/Cargo.toml new file mode 100644 index 0000000..874838a --- /dev/null +++ b/medium/bear-and-steady-gene/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "bear-and-steady-gene" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/bear-and-steady-gene/README.md b/medium/bear-and-steady-gene/README.md new file mode 100644 index 0000000..79de5c5 --- /dev/null +++ b/medium/bear-and-steady-gene/README.md @@ -0,0 +1,15 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/bear-and-steady-gene/problem?isFullScreen=true) + +To solve this problem, we first need to determine the occurrences of each letter in the given gene string. + +Then, we can use a sliding window approach to find the shortest substring that needs to be replaced. + +Initially, we move the right end of the window until we have a substring that contains all the excess letters (i.e., the letters that occur more than n/4 times in the gene string). + +Then, we move the left end of the window until we no longer have a substring that contains all the excess letters. + +At this point, we have the shortest substring that needs to be replaced. + +We repeat this process for all possible excess letters and keep track of the minimum length of the replacement substring. + +Finally, we return this minimum length. \ No newline at end of file diff --git a/medium/bear-and-steady-gene/src/main.rs b/medium/bear-and-steady-gene/src/main.rs new file mode 100644 index 0000000..73473c0 --- /dev/null +++ b/medium/bear-and-steady-gene/src/main.rs @@ -0,0 +1,81 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'steadyGene' function below. + * + * The function is expected to return an INTEGER. + * The function accepts STRING gene as parameter. + */ + +fn steadyGene(gene: &str) -> i32 { + let mut excess: Vec = vec![0;4]; + + let gene_vec: Vec:: = gene.chars().collect(); + let gen_len = gene.len(); + + for &letter in gene_vec.iter() { + excess[get_letter_index(letter)] += 1; + } + + excess = excess.iter().map(|&value| (value - gen_len as i32 / 4).max(0)).collect(); + + let mut min_length = usize::MAX; + let excess_origin = excess.clone(); + + if excess.iter().all(|&value| value == 0) { + 0i32 + } else { + let mut left: usize = 0; + + for right in 0..gen_len { + let rightmost = get_letter_index(gene_vec[right]); + + + if excess_origin[rightmost] > 0 { + excess[rightmost] -= 1; + } + + while excess.iter().all(|&value| value <= 0) { + min_length = min_length.min(right + 1 - left); + + let leftmost = get_letter_index(gene_vec[left]); + + if excess_origin[leftmost] > 0 { + excess[leftmost] += 1; + } + + left += 1; + } + } + + min_length as i32 + } +} + +fn get_letter_index(letter: char) -> usize { + match letter { + 'A' => 0, + 'C' => 1, + 'T' => 2, + _ => 3 + } +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let n = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let gene = stdin_iterator.next().unwrap().unwrap(); + + let result = steadyGene(&gene); + + println!("{}", result); + + // writeln!(&mut fptr, "{}", result).ok(); +} diff --git a/medium/bigger-is-greater/Cargo.toml b/medium/bigger-is-greater/Cargo.toml new file mode 100644 index 0000000..161605a --- /dev/null +++ b/medium/bigger-is-greater/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "bigger-is-greater" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/bigger-is-greater/README.md b/medium/bigger-is-greater/README.md new file mode 100644 index 0000000..16523fd --- /dev/null +++ b/medium/bigger-is-greater/README.md @@ -0,0 +1,7 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/bigger-is-greater/problem?isFullScreen=true) + +1. Find the largest index i such that the character at position i is smaller than the character at position i + 1. +2. If no such index is found, the word is already the greatest possible, and we return “no answer”. +3. Find the smallest index j > i such that the character at position j is greater than the character at position i. +4. Swap characters at positions i and j. +5. Reverse the subarray of characters starting from position i + 1 to the end of the array. \ No newline at end of file diff --git a/medium/bigger-is-greater/src/main.rs b/medium/bigger-is-greater/src/main.rs new file mode 100644 index 0000000..7f8be5d --- /dev/null +++ b/medium/bigger-is-greater/src/main.rs @@ -0,0 +1,69 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'biggerIsGreater' function below. + * + * The function is expected to return a STRING. + * The function accepts STRING w as parameter. + */ + +fn biggerIsGreater(w: &str) -> String { + let mut rev_w: Vec = w.chars().rev().collect(); + + let mut i_pos: usize = 0; + + for i in 0..rev_w.len() { + if i < rev_w.len() - 1 && rev_w[i] > rev_w[i + 1] { + i_pos = i + 1; + + break; + } + } + + if i_pos == 0 { + return "no answer".to_string(); + } else { + let mut j_pos = i_pos - 1 ; + + for j in 0..i_pos { + if rev_w[j] > rev_w[i_pos] { + j_pos = j; + + break; + } + } + + let mut new_w: Vec = rev_w.clone(); + + new_w[i_pos] = rev_w[j_pos]; + rev_w[j_pos] = rev_w[i_pos]; + + + for i in 0..i_pos { + new_w[i] = rev_w[i_pos - 1 - i]; + } + + new_w.into_iter().rev().collect() + } +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let T = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + for _ in 0..T { + let w = stdin_iterator.next().unwrap().unwrap(); + + let result = biggerIsGreater(&w); + + println!("{}", result); + + // writeln!(&mut fptr, "{}", result).ok(); + } +} diff --git a/medium/climbing-the-leaderboard/Cargo.toml b/medium/climbing-the-leaderboard/Cargo.toml new file mode 100644 index 0000000..39d786a --- /dev/null +++ b/medium/climbing-the-leaderboard/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "climbing-the-leaderboard" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/climbing-the-leaderboard/README.md b/medium/climbing-the-leaderboard/README.md new file mode 100644 index 0000000..7b9a5ce --- /dev/null +++ b/medium/climbing-the-leaderboard/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem?isFullScreen=true) \ No newline at end of file diff --git a/medium/climbing-the-leaderboard/src/main.rs b/medium/climbing-the-leaderboard/src/main.rs new file mode 100644 index 0000000..0abc650 --- /dev/null +++ b/medium/climbing-the-leaderboard/src/main.rs @@ -0,0 +1,83 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'climbingLeaderboard' function below. + * + * The function is expected to return an INTEGER_ARRAY. + * The function accepts following parameters: + * 1. INTEGER_ARRAY ranked + * 2. INTEGER_ARRAY player + */ + +fn climbingLeaderboard(ranked: &[i32], player: &[i32]) -> Vec { + // Timeout Failed Solution + let mut ranks = vec![]; + + let mut rank = 1; + let mut last_ranked_score = 0; + let mut last_rank = 0; + + for &score in player.iter().rev() { + rank -= 1; + + for index in last_rank..ranked.len() { + if score < ranked[index] && last_ranked_score != ranked[index] { + last_ranked_score = ranked[index]; + rank += 1; + } + + if score >= ranked[index] || index == ranked.len() - 1 { + last_rank = index; + break; + } + } + + rank += 1; + + ranks.push(rank); + } + + ranks = ranks.into_iter().rev().collect(); + + ranks +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let _ranked_count = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let ranked: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let _player_count = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let player: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let result = climbingLeaderboard(&ranked, &player); + + for i in 0..result.len() { + // write!(&mut fptr, "{}", result[i]).ok(); + + // if i != result.len() - 1 { + // writeln!(&mut fptr).ok(); + // } + + println!("{}", result[i]); + } + + + // writeln!(&mut fptr).ok(); +} diff --git a/medium/coin-change/Cargo.toml b/medium/coin-change/Cargo.toml new file mode 100644 index 0000000..bf371e1 --- /dev/null +++ b/medium/coin-change/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "coin-change" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/coin-change/README.md b/medium/coin-change/README.md new file mode 100644 index 0000000..fde3549 --- /dev/null +++ b/medium/coin-change/README.md @@ -0,0 +1,6 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/coin-change/problem?isFullScreen=true) + +## Hint +- Solve overlapping subproblems using Dynamic Programming (DP) +- How many ways can you make change for 0 cents? -> 1 +- How many ways can you make change for non 0 cents if you have no coins? -> 0 diff --git a/medium/coin-change/src/main.rs b/medium/coin-change/src/main.rs new file mode 100644 index 0000000..8885a54 --- /dev/null +++ b/medium/coin-change/src/main.rs @@ -0,0 +1,55 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'getWays' function below. + * + * The function is expected to return a LONG_INTEGER. + * The function accepts following parameters: + * 1. INTEGER n + * 2. LONG_INTEGER_ARRAY c + */ + +fn getWays(n: i32, c: &[i64]) -> i64 { + let mut ways: Vec = vec![0; n as usize + 1]; + + ways[0] = 1; + + for i in 0..c.len() { + for j in (c[i] as usize)..(n as usize + 1) { + ways[j] += ways[j - c[i] as usize]; + } + } + + ways[n as usize] +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let first_multiple_input: Vec = stdin_iterator.next().unwrap().unwrap() + .split(' ') + .map(|s| s.to_string()) + .collect(); + + let n = first_multiple_input[0].trim().parse::().unwrap(); + + let m = first_multiple_input[1].trim().parse::().unwrap(); + + let c: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + // Print the number of ways of making change for 'n' units using coins having the values given by 'c' + + let ways = getWays(n, &c); + + println!("{}", ways); + // writeln!(&mut fptr, "{}", ways).ok(); +} diff --git a/medium/connected-cell-in-grid/Cargo.toml b/medium/connected-cell-in-grid/Cargo.toml new file mode 100644 index 0000000..d67f5f9 --- /dev/null +++ b/medium/connected-cell-in-grid/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "connected-cell-in-grid" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/connected-cell-in-grid/README.md b/medium/connected-cell-in-grid/README.md new file mode 100644 index 0000000..9698414 --- /dev/null +++ b/medium/connected-cell-in-grid/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/connected-cell-in-a-grid/problem?isFullScreen=true) \ No newline at end of file diff --git a/medium/connected-cell-in-grid/src/main.rs b/medium/connected-cell-in-grid/src/main.rs new file mode 100644 index 0000000..6dd5808 --- /dev/null +++ b/medium/connected-cell-in-grid/src/main.rs @@ -0,0 +1,78 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'connectedCell' function below. + * + * The function is expected to return an INTEGER. + * The function accepts 2D_INTEGER_ARRAY matrix as parameter. + */ + +fn connectedCell(matrix: &[Vec]) -> i32 { + let row = matrix.len(); + let col = matrix[0].len(); + let mut regions = vec![vec![false;col]; row]; + let mut max_depth = 0; + + for i in 0..row { + for j in 0..col { + if matrix[i][j] > 0 && regions[i][j] == false { + let mut depth = 0; + check_regions(&mut regions, matrix, i as i32, j as i32, &mut depth); + + if max_depth < depth { + max_depth = depth; + } + } + } + } + + max_depth +} + +fn check_regions(regions: &mut Vec>, matrix: &[Vec], x : i32, y: i32, depth: &mut i32) { + regions[x as usize][y as usize] = true; + *depth += 1; + + let steps = vec![(-1,0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1)]; + + for (dx, dy) in &steps { + let (new_x, new_y) = (x + dx, y + dy); + + if new_x >= 0 && new_y >= 0 && + new_x < matrix.len() as i32 && new_y < matrix[0].len() as i32 && + regions[new_x as usize][new_y as usize] == false && matrix[new_x as usize][new_y as usize] > 0 { + check_regions(regions, matrix, new_x, new_y, depth); + } + } +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let n = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let m = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let mut matrix: Vec> = Vec::with_capacity(n as usize); + + for i in 0..n as usize { + matrix.push(Vec::with_capacity(m as usize)); + + matrix[i] = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + } + + let result = connectedCell(&matrix); + + println!("{}", result); + + // writeln!(&mut fptr, "{}", result).ok(); +} diff --git a/medium/extra-long-factorials/Cargo.toml b/medium/extra-long-factorials/Cargo.toml new file mode 100644 index 0000000..2e0fbbd --- /dev/null +++ b/medium/extra-long-factorials/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "extra-long-factorials" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/extra-long-factorials/README.md b/medium/extra-long-factorials/README.md new file mode 100644 index 0000000..d87d1a6 --- /dev/null +++ b/medium/extra-long-factorials/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/extra-long-factorials/problem?isFullScreen=true) \ No newline at end of file diff --git a/medium/extra-long-factorials/src/main.rs b/medium/extra-long-factorials/src/main.rs new file mode 100644 index 0000000..5e67e94 --- /dev/null +++ b/medium/extra-long-factorials/src/main.rs @@ -0,0 +1,54 @@ +use std::{io::{self, BufRead}, borrow::Borrow}; + +/* + * Complete the 'extraLongFactorials' function below. + * + * The function accepts INTEGER n as parameter. + */ + +fn extraLongFactorials(n: i32) { + let mut result = vec![1]; + + for value in 1..=n { + let mut temp = 0; + + for index in 0..result.len() { + let sum = result[index] * value + temp; + result[index] = sum % 100; + temp = sum / 100; + } + + if temp > 0 { + result.insert(result.len(), temp); + } + } + + let left_most_index = result.len() - 1; + let bignumber = result + .into_iter() + .enumerate() + .map(|(index, value)| { + if index == left_most_index { + format!("{}", value) + } else { + format!("{:0>2}", value) + } + }) + .collect::>() + .into_iter() + .rev() + .map(|value| value.to_string()) + .collect::>() + .join(""); + + println!("{}", bignumber); +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + let n = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + extraLongFactorials(n); +} diff --git a/medium/gena-playing-hanoi/Cargo.toml b/medium/gena-playing-hanoi/Cargo.toml new file mode 100644 index 0000000..bbc0e36 --- /dev/null +++ b/medium/gena-playing-hanoi/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "gena-playing-hanoi" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/gena-playing-hanoi/README.md b/medium/gena-playing-hanoi/README.md new file mode 100644 index 0000000..75df968 --- /dev/null +++ b/medium/gena-playing-hanoi/README.md @@ -0,0 +1,5 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/gena/problem?isFullScreen=true) + +BSF - Breadth First Search + +Note: For the `visited` table, hashmap should be used. Vector could be slow in many cases. \ No newline at end of file diff --git a/medium/gena-playing-hanoi/src/main.rs b/medium/gena-playing-hanoi/src/main.rs new file mode 100644 index 0000000..f62f2a4 --- /dev/null +++ b/medium/gena-playing-hanoi/src/main.rs @@ -0,0 +1,77 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; +use std::collections::VecDeque; +use std::collections::HashMap; + +/* + * Complete the 'hanoi' function below. + * + * The function is expected to return an INTEGER. + * The function accepts INTEGER_ARRAY posts as parameter. + */ + +fn hanoi(posts: &[i32]) -> i32 { + let n = posts.len(); + let target = vec![0; n]; + + let initial_state: Vec = posts.to_vec().iter().map(|v| v - 1).collect(); + + let mut queue: VecDeque<(Vec, i32)> = VecDeque::new(); + let mut visited: HashMap, bool> = HashMap::new(); + + queue.push_back((initial_state.clone(), 0)); + visited.insert(initial_state, true); + + loop { + let (current_state, steps) = queue.pop_front().unwrap(); + + if current_state == target { + return steps; + } + + // find valid next moves + let mut smallest_discs = vec![usize::MAX; 4]; + + for (disc, &pos) in current_state.iter().enumerate() { + if smallest_discs[pos as usize] > disc { + smallest_discs[pos as usize] = disc + } + } + + for i in 0..4 { + for j in 0..4 { + if i != j && smallest_discs[i] < smallest_discs[j] { + let mut next_state = current_state.clone(); + next_state[smallest_discs[i]] = j as i32; + + if !visited.contains_key(&next_state) { + queue.push_back((next_state.clone(), steps + 1)); + visited.insert(next_state, true); + } + } + } + } + } +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let n = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let loc: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let res = hanoi(&loc); + + println!("{}", res); + + // writeln!(&mut fptr, "{}", res).ok(); +} diff --git a/medium/journey-to-moon/Cargo.toml b/medium/journey-to-moon/Cargo.toml new file mode 100644 index 0000000..ca57767 --- /dev/null +++ b/medium/journey-to-moon/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "journey-to-moon" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/journey-to-moon/README.md b/medium/journey-to-moon/README.md new file mode 100644 index 0000000..4d40d77 --- /dev/null +++ b/medium/journey-to-moon/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/journey-to-the-moon/problem?isFullScreen=true) \ No newline at end of file diff --git a/medium/journey-to-moon/src/main.rs b/medium/journey-to-moon/src/main.rs new file mode 100644 index 0000000..8b08199 --- /dev/null +++ b/medium/journey-to-moon/src/main.rs @@ -0,0 +1,99 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'journeyToMoon' function below. + * + * The function is expected to return an INTEGER. + * The function accepts following parameters: + * 1. INTEGER n + * 2. 2D_INTEGER_ARRAY astronaut + */ + +fn journeyToMoon(n: i32, astronaut: &[Vec]) -> i64 { + let mut connection: Vec> = vec![vec![]; n as usize]; + let mut checked: Vec = vec![false; n as usize]; + + let mut result = 0; + + for possible_connection in astronaut.iter() { + let &start = possible_connection.get(0).unwrap(); + let &end = possible_connection.get(1).unwrap(); + + connection[start as usize].push(end as usize); + connection[end as usize].push(start as usize); + } + + let mut member_counts: Vec = vec![]; + + for member in 0..n as usize { + if checked[member] { + continue; + } else { + checked[member] = true; + + let mut member_count = 1; + + let mut no_checked:Vec = connection[member].clone(); + + loop { + if no_checked.is_empty() { + break; + } + + let next_member = no_checked.pop().unwrap(); + + if !checked[next_member] { + no_checked.extend(connection[next_member].clone()); + checked[next_member] = true; + member_count += 1; + } + } + + member_counts.push(member_count); + } + } + + for i in 0..member_counts.len() { + for j in (i+1)..member_counts.len() { + result += member_counts[i] * member_counts[j]; + } + } + + result +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let first_multiple_input: Vec = stdin_iterator.next().unwrap().unwrap() + .split(' ') + .map(|s| s.to_string()) + .collect(); + + let n = first_multiple_input[0].trim().parse::().unwrap(); + + let p = first_multiple_input[1].trim().parse::().unwrap(); + + let mut astronaut: Vec> = Vec::with_capacity(p as usize); + + for i in 0..p as usize { + astronaut.push(Vec::with_capacity(2_usize)); + + astronaut[i] = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + } + + let result = journeyToMoon(n, &astronaut); + + println!("{}", result); + + // writeln!(&mut fptr, "{}", result).ok(); +} diff --git a/medium/larry-array/Cargo.toml b/medium/larry-array/Cargo.toml new file mode 100644 index 0000000..574745b --- /dev/null +++ b/medium/larry-array/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "larry-array" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/larry-array/README.md b/medium/larry-array/README.md new file mode 100644 index 0000000..c6beddd --- /dev/null +++ b/medium/larry-array/README.md @@ -0,0 +1,4 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/larrys-array/problem?isFullScreen=true) + +If the total count of elements that are positioned to the right of where they should be (i.e., smaller elements) is even, then the problem is solvable. +If the count is odd, it's not solvable. diff --git a/medium/larry-array/src/main.rs b/medium/larry-array/src/main.rs new file mode 100644 index 0000000..9dcb8bb --- /dev/null +++ b/medium/larry-array/src/main.rs @@ -0,0 +1,52 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'larrysArray' function below. + * + * The function is expected to return a STRING. + * The function accepts INTEGER_ARRAY A as parameter. + */ + +fn larrysArray(A: &[i32]) -> String { + let mut count = 0; + + for i in 0..A.len() { + for j in (i+1)..A.len() { + if A[i] > A[j] { + count += 1; + } + } + } + + if count % 2 == 0 { + "YES".to_string() + } else { + "NO".to_string() + } +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let t = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + for _ in 0..t { + let n = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let A: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let result = larrysArray(&A); + + println!("{}", result); + // writeln!(&mut fptr, "{}", result).ok(); + } +} diff --git a/medium/longest-common-subsequence/Cargo.toml b/medium/longest-common-subsequence/Cargo.toml new file mode 100644 index 0000000..728afb7 --- /dev/null +++ b/medium/longest-common-subsequence/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "longest-common-subsequence" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/longest-common-subsequence/README.md b/medium/longest-common-subsequence/README.md new file mode 100644 index 0000000..452c21f --- /dev/null +++ b/medium/longest-common-subsequence/README.md @@ -0,0 +1,12 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/dynamic-programming-classics-the-longest-common-subsequence/problem?isFullScreen=true) + +# Dynamic Programming + +## Theorem +```rust +let c[i, j] = if x[i] == y[j] { + c[i - 1, j - 1] + 1 +} else { + max(c[i - 1, j], c[i, j - 1]) +} +``` diff --git a/medium/longest-common-subsequence/src/main.rs b/medium/longest-common-subsequence/src/main.rs new file mode 100644 index 0000000..ebae078 --- /dev/null +++ b/medium/longest-common-subsequence/src/main.rs @@ -0,0 +1,91 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'longestCommonSubsequence' function below. + * + * The function is expected to return an INTEGER_ARRAY. + * The function accepts following parameters: + * 1. INTEGER_ARRAY a + * 2. INTEGER_ARRAY b + */ + +fn longestCommonSubsequence(a: &[i32], b: &[i32]) -> Vec { + let mut lcs: Vec = Vec::new(); + let mut lcs_length: Vec> = vec![vec![0; a.len() + 1]; b.len() + 1]; + + for i in 1..=b.len() { + for j in 1..=a.len() { + if a[j - 1] == b[i - 1] { + lcs_length[i][j] = lcs_length[i - 1][j - 1] + 1; + } else { + lcs_length[i][j] = lcs_length[i - 1][j].max(lcs_length[i][j - 1]); + } + } + } + + let mut x = b.len(); + let mut y = a.len(); + let mut max_length = lcs_length[x][y]; + + while max_length > 0 { + if lcs_length[x][y] == lcs_length[x][y - 1] { + y -= 1; + } else if lcs_length[x][y] == lcs_length[x - 1][y] { + x -= 1; + } else { + x -= 1; + y -= 1; + + lcs.push(b[x]); + max_length = lcs_length[x][y]; + } + } + + lcs.reverse(); + + lcs +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let first_multiple_input: Vec = stdin_iterator.next().unwrap().unwrap() + .split(' ') + .map(|s| s.to_string()) + .collect(); + + let n = first_multiple_input[0].trim().parse::().unwrap(); + + let m = first_multiple_input[1].trim().parse::().unwrap(); + + let a: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let b: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let result = longestCommonSubsequence(&a, &b); + + for i in 0..result.len() { + // write!(&mut fptr, "{}", result[i]).ok(); + print!("{}", result[i]); + + if i != result.len() - 1 { + // write!(&mut fptr, " ").ok(); + print!(" "); + } + } + + // writeln!(&mut fptr).ok(); +} diff --git a/medium/magic-square-forming/Cargo.toml b/medium/magic-square-forming/Cargo.toml new file mode 100644 index 0000000..333e111 --- /dev/null +++ b/medium/magic-square-forming/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "magic-square-forming" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/magic-square-forming/README.md b/medium/magic-square-forming/README.md new file mode 100644 index 0000000..da04bd3 --- /dev/null +++ b/medium/magic-square-forming/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/magic-square-forming?isFullScreen=true) \ No newline at end of file diff --git a/medium/magic-square-forming/src/main.rs b/medium/magic-square-forming/src/main.rs new file mode 100644 index 0000000..5a4a07b --- /dev/null +++ b/medium/magic-square-forming/src/main.rs @@ -0,0 +1,54 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'formingMagicSquare' function below. + * + * The function is expected to return an INTEGER. + * The function accepts 2D_INTEGER_ARRAY s as parameter. + */ + +fn formingMagicSquare(s: &[Vec]) -> i32 { + let mut sums = vec![0; 8]; + let sample = &[vec![8, 3, 4], vec![1, 5, 9], vec![6, 7, 2]]; + + for i in 0..3 { + for j in 0..3 { + sums[0] += (sample[i][j] - s[i][j]).abs(); + sums[1] += (sample[i][2 - j] - s[i][j]).abs(); + sums[2] += (sample[2 - i][j] - s[i][j]).abs(); + sums[3] += (sample[2 - i][2 - j] - s[i][j]).abs(); + sums[4] += (sample[j][i] - s[i][j]).abs(); + sums[5] += (sample[j][2 - i] - s[i][j]).abs(); + sums[6] += (sample[2 - j][i] - s[i][j]).abs(); + sums[7] += (sample[2 - j][2 - i] - s[i][j]).abs(); + } + } + + *sums.iter().min().unwrap() +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let mut s: Vec> = Vec::with_capacity(3_usize); + + for i in 0..3_usize { + s.push(Vec::with_capacity(3_usize)); + + s[i] = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + } + + let result = formingMagicSquare(&s); + + // writeln!(&mut fptr, "{}", result).ok(); + println!("{}", result); +} diff --git a/medium/minimum-loss/Cargo.toml b/medium/minimum-loss/Cargo.toml new file mode 100644 index 0000000..c0fae96 --- /dev/null +++ b/medium/minimum-loss/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "minimum-loss" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/minimum-loss/README.md b/medium/minimum-loss/README.md new file mode 100644 index 0000000..169b190 --- /dev/null +++ b/medium/minimum-loss/README.md @@ -0,0 +1,19 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/minimum-loss/problem?isFullScreen=true) + +Intuition: if the prices are sorted, the minimum loss is given by two adjacent prices. We just need to check if the pair is “valid”, that is: if the sell price is actually following the purchase (the sell is in the future). + +Thus, we can duplicate our data and add an index for each price. The index is ascending and it just represents then history. + +For example, for: 14 7 8 2 5 + +We have: +(0, 14) (1, 7) (2, 8) (3, 2) (4, 5) + +Now we can sort the data and the history won’t be lost: + +(3, 2) (4, 5) (1, 7) (2, 8) (0, 14) + +We can finally process adjacent pairs. Since we sell at a loss: + +- the right pair (price is bigger) represents the purchase price +- the left pair (price is lower) represents the sell price diff --git a/medium/minimum-loss/src/main.rs b/medium/minimum-loss/src/main.rs new file mode 100644 index 0000000..6a5da75 --- /dev/null +++ b/medium/minimum-loss/src/main.rs @@ -0,0 +1,45 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'minimumLoss' function below. + * + * The function is expected to return an INTEGER. + * The function accepts LONG_INTEGER_ARRAY price as parameter. + */ + +fn minimumLoss(price: &[i64]) -> i32 { + let mut prices: Vec<(usize, &i64)> = price.iter().enumerate().into_iter().collect(); + + prices.sort_by(|(_, a), (_, b)| a.cmp(b)); + + prices + .iter() + .zip(prices.iter().skip(1)) + .filter(|((sell_time, _), (buy_time, _))| buy_time < sell_time) + .map(|(&(_, sell_price), &(_, buy_price))| buy_price - sell_price) + .min() + .unwrap() as i32 +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let n = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let price: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let result = minimumLoss(&price); + + println!("{}", result); + + // writeln!(&mut fptr, "{}", result).ok(); +} diff --git a/medium/non-divisible-subset/Cargo.toml b/medium/non-divisible-subset/Cargo.toml new file mode 100644 index 0000000..b0cee58 --- /dev/null +++ b/medium/non-divisible-subset/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "non-divisible-subset" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/non-divisible-subset/README.md b/medium/non-divisible-subset/README.md new file mode 100644 index 0000000..fef0e02 --- /dev/null +++ b/medium/non-divisible-subset/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/non-divisible-subset/problem?isFullScreen=true) \ No newline at end of file diff --git a/medium/non-divisible-subset/src/main.rs b/medium/non-divisible-subset/src/main.rs new file mode 100644 index 0000000..566d15d --- /dev/null +++ b/medium/non-divisible-subset/src/main.rs @@ -0,0 +1,63 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'nonDivisibleSubset' function below. + * + * The function is expected to return an INTEGER. + * The function accepts following parameters: + * 1. INTEGER k + * 2. INTEGER_ARRAY s + */ + +fn nonDivisibleSubset(k: i32, s: &[i32]) -> i32 { + let mut length ; + let mut remains = vec![0; k as usize]; + + for &value in s.iter() { + remains[(value % k) as usize] += 1; + } + + length = remains[0].min(1); + + if k % 2 == 0 { + length += remains[(k / 2) as usize].min(1); + } + + for index in 1..=k / 2 { + if index != k - index { + length += remains[index as usize].max(remains[(k - index) as usize]); + } + } + + length +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let first_multiple_input: Vec = stdin_iterator.next().unwrap().unwrap() + .split(' ') + .map(|s| s.to_string()) + .collect(); + + let n = first_multiple_input[0].trim().parse::().unwrap(); + + let k = first_multiple_input[1].trim().parse::().unwrap(); + + let s: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let result = nonDivisibleSubset(k, &s); + + println!("{}", result); + + // writeln!(&mut fptr, "{}", result).ok(); +} \ No newline at end of file diff --git a/medium/pairs/Cargo.toml b/medium/pairs/Cargo.toml new file mode 100644 index 0000000..c8a586a --- /dev/null +++ b/medium/pairs/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "pairs" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/pairs/README.md b/medium/pairs/README.md new file mode 100644 index 0000000..09d4ee4 --- /dev/null +++ b/medium/pairs/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/pairs/problem?isFullScreen=true) \ No newline at end of file diff --git a/medium/pairs/src/main.rs b/medium/pairs/src/main.rs new file mode 100644 index 0000000..d1a9dd4 --- /dev/null +++ b/medium/pairs/src/main.rs @@ -0,0 +1,64 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'pairs' function below. + * + * The function is expected to return an INTEGER. + * The function accepts following parameters: + * 1. INTEGER k + * 2. INTEGER_ARRAY arr + */ + +fn pairs(k: i32, arr: &[i32]) -> i32 { + let mut values = arr.to_vec(); + + values.sort(); + + let mut count = 0; + let (mut left, mut right) = (0, 1); + + while right < values.len() { + if values[right] - values[left] < k { + right += 1; + + continue; + } + + if values[right] - values[left] == k { + count += 1; + } + + left += 1; + } + + count +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let first_multiple_input: Vec = stdin_iterator.next().unwrap().unwrap() + .split(' ') + .map(|s| s.to_string()) + .collect(); + + let n = first_multiple_input[0].trim().parse::().unwrap(); + + let k = first_multiple_input[1].trim().parse::().unwrap(); + + let arr: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let result = pairs(k, &arr); + + // writeln!(&mut fptr, "{}", result).ok(); + println!("{}", result); +} diff --git a/medium/queens-attack2/Cargo.toml b/medium/queens-attack2/Cargo.toml new file mode 100644 index 0000000..7604aa1 --- /dev/null +++ b/medium/queens-attack2/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "queens-attack2" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/queens-attack2/README.md b/medium/queens-attack2/README.md new file mode 100644 index 0000000..77342cc --- /dev/null +++ b/medium/queens-attack2/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/queens-attack-2/problem?isFullScreen=true) \ No newline at end of file diff --git a/medium/queens-attack2/src/main.rs b/medium/queens-attack2/src/main.rs new file mode 100644 index 0000000..8ea2ead --- /dev/null +++ b/medium/queens-attack2/src/main.rs @@ -0,0 +1,110 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'queensAttack' function below. + * + * The function is expected to return an INTEGER. + * The function accepts following parameters: + * 1. INTEGER n + * 2. INTEGER k + * 3. INTEGER r_q + * 4. INTEGER c_q + * 5. 2D_INTEGER_ARRAY obstacles + */ + +fn queensAttack(n: i32, k: i32, r_q: i32, c_q: i32, obstacles: &[Vec]) -> i32 { + let mut attacks = vec![ + n - c_q, // right + (n - c_q).min(n - r_q), // right bottom + n - r_q, // bottom + (c_q - 1).min(n - r_q), // left bottom + c_q - 1, // left + (c_q - 1).min(r_q - 1), // left top + r_q - 1, // top + (n - c_q).min(r_q - 1), // right top + ]; + + for obstacle in obstacles.iter() { + if obstacle[0] == r_q { + if obstacle[1] > c_q { + attacks[0] = attacks[0].min(obstacle[1] - c_q - 1); + } else { + attacks[4] = attacks[4].min(c_q - obstacle[1] - 1); + } + } else if obstacle[1] == c_q { + if obstacle[0] > r_q { + attacks[2] = attacks[2].min(obstacle[0] - r_q - 1); + } else { + attacks[6] = attacks[6].min(r_q - obstacle[0] - 1); + } + } else if (obstacle[0] - r_q).abs() == (obstacle[1] - c_q).abs() { + if obstacle[0] > r_q && obstacle[1] > c_q { + attacks[1] = std::cmp::min( + attacks[1], + (obstacle[0] - r_q).min(obstacle[1] - c_q - 1) + ); + } else if obstacle[0] > r_q && obstacle[1] < c_q { + attacks[3] = std::cmp::min( + attacks[3], + (obstacle[0] - r_q).min(c_q - obstacle[1] - 1) + ); + } else if obstacle[0] < r_q && obstacle[1] < c_q { + attacks[5] = std::cmp::min( + attacks[5], + (r_q - obstacle[0]).min(c_q - obstacle[1] - 1) + ); + } else { + attacks[7] = std::cmp::min( + attacks[7], + (r_q - obstacle[0]).min(obstacle[1] - c_q - 1) + ); + } + } + } + + attacks.iter().sum() +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let first_multiple_input: Vec = stdin_iterator.next().unwrap().unwrap() + .split(' ') + .map(|s| s.to_string()) + .collect(); + + let n = first_multiple_input[0].trim().parse::().unwrap(); + + let k = first_multiple_input[1].trim().parse::().unwrap(); + + let second_multiple_input: Vec = stdin_iterator.next().unwrap().unwrap() + .split(' ') + .map(|s| s.to_string()) + .collect(); + + let r_q = second_multiple_input[0].trim().parse::().unwrap(); + + let c_q = second_multiple_input[1].trim().parse::().unwrap(); + + let mut obstacles: Vec> = Vec::with_capacity(k as usize); + + for i in 0..k as usize { + obstacles.push(Vec::with_capacity(2_usize)); + + obstacles[i] = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + } + + let result = queensAttack(n, k, r_q, c_q, &obstacles); + + println!("{}", result); + // writeln!(&mut fptr, "{}", result).ok(); +} diff --git a/medium/really-special-subtree/Cargo.toml b/medium/really-special-subtree/Cargo.toml new file mode 100644 index 0000000..acefbf7 --- /dev/null +++ b/medium/really-special-subtree/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "really-special-subtree" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/really-special-subtree/README.md b/medium/really-special-subtree/README.md new file mode 100644 index 0000000..893d2a1 --- /dev/null +++ b/medium/really-special-subtree/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/kruskalmstrsub/problem?isFullScreen=true) \ No newline at end of file diff --git a/medium/really-special-subtree/src/main.rs b/medium/really-special-subtree/src/main.rs new file mode 100644 index 0000000..7a87caf --- /dev/null +++ b/medium/really-special-subtree/src/main.rs @@ -0,0 +1,111 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'kruskals' function below. + * + * The function is expected to return an INTEGER. + * The function accepts WEIGHTED_INTEGER_GRAPH g as parameter. + */ + +/* + * For the weighted graph, : + * + * 1. The number of nodes is _nodes. + * 2. The number of edges is _edges. + * 3. An edge exists between _from[i] and _to[i]. The weight of the edge is _weight[i]. + * + */ + +fn kruskals(g_nodes: i32, g_from: &[i32], g_to: &[i32], g_weight: &[i32]) -> i32 { + let nodes = g_nodes as usize; + let mut edges: Vec> = vec![vec![i32::MAX; nodes + 1]; nodes + 1]; + let mut connections: Vec> = vec![vec![]; nodes + 1]; + + let mut visited: Vec = vec![]; + let mut distance = 0; + + for i in 0..g_from.len() { + let from = g_from[i] as usize; + let to = g_to[i] as usize; + let weight = g_weight[i]; + + if edges[from][to] == i32::MAX { + connections[from].push(to); + connections[to].push(from); + } + + if weight < edges[from][to] { + edges[from][to] = weight; + edges[to][from] = weight; + } + } + + visited.push(1); + + for _ in 1..nodes { + let mut min_weight = i32::MAX; + let mut min_node_sum = usize::MAX; + let mut min_node = 0; + + for &node in visited.iter() { + for &next in connections[node].iter() { + if visited.contains(&next) { + continue; + } + + if min_weight > edges[node][next] || (min_weight == edges[node][next] && min_node_sum > node + next) { + min_weight = edges[node][next]; + min_node_sum = node + next; + min_node = next; + } + } + } + + visited.push(min_node); + distance += min_weight; + } + + distance +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let g_nodes_edges: Vec = stdin_iterator.next().unwrap().unwrap() + .split(' ') + .map(|s| s.to_string()) + .collect(); + + let g_nodes = g_nodes_edges[0].trim().parse::().unwrap(); + let g_edges = g_nodes_edges[1].trim().parse::().unwrap(); + + let mut g_from: Vec = Vec::with_capacity(g_edges as usize); + let mut g_to: Vec = Vec::with_capacity(g_edges as usize); + let mut g_weight: Vec = Vec::with_capacity(g_edges as usize); + + for _ in 0..g_edges { + let g_from_to: Vec = stdin_iterator.next().unwrap().unwrap() + .split(' ') + .map(|s| s.to_string()) + .collect(); + + let g_from_temp = g_from_to[0].trim().parse::().unwrap(); + let g_to_temp = g_from_to[1].trim().parse::().unwrap(); + let g_weight_temp = g_from_to[2].trim().parse::().unwrap(); + + g_from.push(g_from_temp); + g_to.push(g_to_temp); + g_weight.push(g_weight_temp); + } + + let res = kruskals(g_nodes, &g_from, &g_to, &g_weight); + + // Write your code here. + + println!("{}", res); +} diff --git a/medium/red-john-is-back/Cargo.toml b/medium/red-john-is-back/Cargo.toml new file mode 100644 index 0000000..7d8f3ce --- /dev/null +++ b/medium/red-john-is-back/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "red-john-is-back" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/red-john-is-back/README.md b/medium/red-john-is-back/README.md new file mode 100644 index 0000000..16e04c6 --- /dev/null +++ b/medium/red-john-is-back/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/red-john-is-back/problem?isFullScreen=true) \ No newline at end of file diff --git a/medium/red-john-is-back/src/main.rs b/medium/red-john-is-back/src/main.rs new file mode 100644 index 0000000..9a1c969 --- /dev/null +++ b/medium/red-john-is-back/src/main.rs @@ -0,0 +1,84 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'redJohn' function below. + * + * The function is expected to return an INTEGER. + * The function accepts INTEGER n as parameter. + */ + +fn redJohn(n: i32) -> i32 { + let mut factorials: Vec = vec![]; + let (mut short, mut long) = (n, 0); + + let mut value = 1; + + factorials.push(value); + + for i in 1..=10 { + value *= i; + + factorials.push(value); + } + + let mut result = 0; + + while short >= 0 { + + let mut temp = 1; + + for i in (short+1)..=(short + long) { + temp *= i; + } + + result += temp / factorials[long as usize]; + + short -= 4; + long += 1; + } + + let mut primes: Vec = vec![]; + + for i in 2..=result { + if primes.is_empty() { + primes.push(i); + } else { + let mut is_prime = true; + + for &prime in primes.iter() { + if i % prime == 0 { + is_prime = false; + + break; + } + } + + if is_prime { + primes.push(i); + } + } + } + + primes.len() as i32 +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let t = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + for _ in 0..t { + let n = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let result = redJohn(n); + + // writeln!(&mut fptr, "{}", result).ok(); + + println!("{}", result); + } +} diff --git a/medium/roads-and-libraries/Cargo.toml b/medium/roads-and-libraries/Cargo.toml new file mode 100644 index 0000000..e723459 --- /dev/null +++ b/medium/roads-and-libraries/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "roads-and-libraries" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/roads-and-libraries/README.md b/medium/roads-and-libraries/README.md new file mode 100644 index 0000000..d71b6c4 --- /dev/null +++ b/medium/roads-and-libraries/README.md @@ -0,0 +1,6 @@ +# Roads and Libraries Scenario + +1. c_lib <= c_road: no need to build roads, build libraries on every city +2. c_lib > c_road: (city_count of cluster - 1) * c_road + c_lib + +[Solve Yourself Here](https://www.hackerrank.com/challenges/torque-and-development/problem?isFullScreen=true) diff --git a/medium/roads-and-libraries/src/main.rs b/medium/roads-and-libraries/src/main.rs new file mode 100644 index 0000000..ceb54fb --- /dev/null +++ b/medium/roads-and-libraries/src/main.rs @@ -0,0 +1,103 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; +use std::collections::HashMap; + +/* + * Complete the 'roadsAndLibraries' function below. + * + * The function is expected to return a LONG_INTEGER. + * The function accepts following parameters: + * 1. INTEGER n + * 2. INTEGER c_lib + * 3. INTEGER c_road + * 4. 2D_INTEGER_ARRAY cities + */ + +fn roadsAndLibraries(n: i32, c_lib: i32, c_road: i32, cities: &[Vec]) -> i64 { + if c_lib <= c_road { + n as i64 * c_lib as i64 + } else { + let mut connection: Vec> = vec![vec![]; n as usize]; + let mut visited: Vec = vec![false; n as usize]; + + let mut cost = 0i64; + + for possible_connection in cities.iter() { + let &start = possible_connection.get(0).unwrap(); + let &end = possible_connection.get(1).unwrap(); + + connection[start as usize - 1].push(end as usize - 1); + connection[end as usize - 1].push(start as usize - 1); + } + + for city in 0..n as usize { + if visited[city] { + continue; + } else { + visited[city] = true; + cost += c_lib as i64; + + let mut no_visit:Vec = connection[city].clone(); + + loop { + if no_visit.is_empty() { + break; + } + + let next_city = no_visit.pop().unwrap(); + + if !visited[next_city] { + no_visit.extend(connection[next_city].clone()); + visited[next_city] = true; + cost += c_road as i64; + } + } + } + } + + cost + } +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let q = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + for _ in 0..q { + let first_multiple_input: Vec = stdin_iterator.next().unwrap().unwrap() + .split(' ') + .map(|s| s.to_string()) + .collect(); + + let n = first_multiple_input[0].trim().parse::().unwrap(); + + let m = first_multiple_input[1].trim().parse::().unwrap(); + + let c_lib = first_multiple_input[2].trim().parse::().unwrap(); + + let c_road = first_multiple_input[3].trim().parse::().unwrap(); + + let mut cities: Vec> = Vec::with_capacity(m as usize); + + for i in 0..m as usize { + cities.push(Vec::with_capacity(2_usize)); + + cities[i] = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + } + + let result = roadsAndLibraries(n, c_lib, c_road, &cities); + + println!("{}", result); + + // writeln!(&mut fptr, "{}", result).ok(); + } +} diff --git a/medium/sherlock-and-anagrams/Cargo.toml b/medium/sherlock-and-anagrams/Cargo.toml new file mode 100644 index 0000000..60e33f3 --- /dev/null +++ b/medium/sherlock-and-anagrams/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "sherlock-and-anagrams" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/sherlock-and-anagrams/README.md b/medium/sherlock-and-anagrams/README.md new file mode 100644 index 0000000..a04ba01 --- /dev/null +++ b/medium/sherlock-and-anagrams/README.md @@ -0,0 +1,5 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem?isFullScreen=true) + +1. Search all substrings +2. Convert them as biginteger and count +3. sum up `n * (n - 1) / 2` diff --git a/medium/sherlock-and-anagrams/src/main.rs b/medium/sherlock-and-anagrams/src/main.rs new file mode 100644 index 0000000..58323e3 --- /dev/null +++ b/medium/sherlock-and-anagrams/src/main.rs @@ -0,0 +1,64 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; +use std::collections::HashMap; + +/* + * Complete the 'sherlockAndAnagrams' function below. + * + * The function is expected to return an INTEGER. + * The function accepts STRING s as parameter. + */ + +fn sherlockAndAnagrams(s: &str) -> i32 { + let origin: Vec = s.bytes().collect(); + + let mut substrings: HashMap = HashMap::new(); + + for i in 0..s.len() { + for j in i+1..=s.len() { + let mut substring: u128 = 0; + + for k in i..j { + substring += 26_u128.pow((origin[k] - 97) as u32); + } + + if substring == 0 { + continue;; + } + + if let Some(count) = substrings.get_mut(&substring) { + *count += 1; + } else { + substrings.insert(substring, 1); + } + } + } + + let mut result = 0; + + for count in substrings.into_values() { + result += count as i32 * (count as i32 - 1) / 2; + } + + result +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let q = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + for _ in 0..q { + let s = stdin_iterator.next().unwrap().unwrap(); + + let result = sherlockAndAnagrams(&s); + + println!("{}", result); + + // writeln!(&mut fptr, "{}", result).ok(); + } +} diff --git a/medium/short-palindrome/Cargo.toml b/medium/short-palindrome/Cargo.toml new file mode 100644 index 0000000..30748c5 --- /dev/null +++ b/medium/short-palindrome/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "short-palindrome" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/short-palindrome/README.md b/medium/short-palindrome/README.md new file mode 100644 index 0000000..236b0fa --- /dev/null +++ b/medium/short-palindrome/README.md @@ -0,0 +1,12 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/short-palindrome/problem?isFullScreen=true) + +Dynamic Planing + +Solves each sub-problem once and stores thre results in a table, thus avoiding recalculation of the answers. + +table_i +table_ij +table_ijj + +Then sum up table_ijj[i] to calculate the number of palindrome. + diff --git a/medium/short-palindrome/src/main.rs b/medium/short-palindrome/src/main.rs new file mode 100644 index 0000000..c7c827c --- /dev/null +++ b/medium/short-palindrome/src/main.rs @@ -0,0 +1,48 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'shortPalindrome' function below. + * + * The function is expected to return an INTEGER. + * The function accepts STRING s as parameter. + */ + +fn shortPalindrome(s: &str) -> i32 { + let mut table_i = vec![0;26]; + let mut table_ij = vec![vec![0;26];26]; + let mut table_ijj = vec![0;26]; + let mut result = 0; + let modulo = 1000000007; + + for ch in s.chars() { + let i = ch as usize - 'a' as usize; + + result = (result + table_ijj[i]) % modulo; + + for j in 0..26 { + table_ijj[j] = (table_ijj[j] + table_ij[i][j]) % modulo; + table_ij[i][j] = (table_ij[i][j] + table_i[j]) % modulo; + } + + table_i[i] += 1; + } + + result +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let s = stdin_iterator.next().unwrap().unwrap(); + + let result = shortPalindrome(&s); + + println!("{}", result); + + // writeln!(&mut fptr, "{}", result).ok(); +} diff --git a/medium/shortest-reach/Cargo.toml b/medium/shortest-reach/Cargo.toml new file mode 100644 index 0000000..82af899 --- /dev/null +++ b/medium/shortest-reach/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "shortest-reach" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/shortest-reach/README.md b/medium/shortest-reach/README.md new file mode 100644 index 0000000..0b0b353 --- /dev/null +++ b/medium/shortest-reach/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/bfsshortreach/problem?isFullScreen=true) \ No newline at end of file diff --git a/medium/shortest-reach/src/main.rs b/medium/shortest-reach/src/main.rs new file mode 100644 index 0000000..3874ef3 --- /dev/null +++ b/medium/shortest-reach/src/main.rs @@ -0,0 +1,102 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +use std::collections::VecDeque; + +/* + * Complete the 'bfs' function below. + * + * The function is expected to return an INTEGER_ARRAY. + * The function accepts following parameters: + * 1. INTEGER n + * 2. INTEGER m + * 3. 2D_INTEGER_ARRAY edges + * 4. INTEGER s + */ + +fn bfs(n: i32, m: i32, edges: &[Vec], s: i32) -> Vec { + let node_count = n as usize; + let start = s as usize - 1; + + let mut connects: Vec> = vec![vec![]; node_count]; + let mut distances: Vec = vec![-1; node_count]; + let mut visited: Vec = vec![false; node_count]; + + for edge in edges.iter() { + let from = edge[0] as usize - 1; + let to = edge[1] as usize - 1; + + connects[from].push(to); + connects[to].push(from); + } + + let mut queue: VecDeque<(usize, i32)> = VecDeque::new(); + + queue.push_back((start, 0)); + visited[start] = true; + + while !queue.is_empty() { + let (current, distance) = queue.pop_front().unwrap(); + + distances[current] = distance; + + for &next in connects[current].iter() { + if !visited[next] { + queue.push_back((next, distance + 6)); + visited[next] = true; + } + } + } + + distances +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let q = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + for _ in 0..q { + let first_multiple_input: Vec = stdin_iterator.next().unwrap().unwrap() + .split(' ') + .map(|s| s.to_string()) + .collect(); + + let n = first_multiple_input[0].trim().parse::().unwrap(); + + let m = first_multiple_input[1].trim().parse::().unwrap(); + + let mut edges: Vec> = Vec::with_capacity(m as usize); + + for i in 0..m as usize { + edges.push(Vec::with_capacity(2_usize)); + + edges[i] = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + } + + let s = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let result = bfs(n, m, &edges, s); + + for i in 0..result.len() { + // write!(&mut fptr, "{}", result[i]).ok(); + if result[i] != 0 { + println!("{}", result[i]); + } + + // if i != result.len() - 1 { + // write!(&mut fptr, " ").ok(); + // } + } + + // writeln!(&mut fptr).ok(); + } +} diff --git a/medium/snakes-and-ladders/Cargo.toml b/medium/snakes-and-ladders/Cargo.toml new file mode 100644 index 0000000..ebf9636 --- /dev/null +++ b/medium/snakes-and-ladders/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "snakes-and-ladders" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/snakes-and-ladders/README.md b/medium/snakes-and-ladders/README.md new file mode 100644 index 0000000..fc8b6bd --- /dev/null +++ b/medium/snakes-and-ladders/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/the-quickest-way-up/problem?isFullScreen=true) \ No newline at end of file diff --git a/medium/snakes-and-ladders/src/main.rs b/medium/snakes-and-ladders/src/main.rs new file mode 100644 index 0000000..010064a --- /dev/null +++ b/medium/snakes-and-ladders/src/main.rs @@ -0,0 +1,123 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +use std::collections::VecDeque; + +/* + * Complete the 'quickestWayUp' function below. + * + * The function is expected to return an INTEGER. + * The function accepts following parameters: + * 1. 2D_INTEGER_ARRAY ladders + * 2. 2D_INTEGER_ARRAY snakes + */ + +fn quickestWayUp(ladders: &[Vec], snakes: &[Vec]) -> i32 { + let mut connect: Vec = vec![0; 101]; + let mut visited: Vec = vec![false; 101]; + + let mut queue: VecDeque<(usize, usize)> = VecDeque::new(); + + let mut result = 0; + + for ladder in ladders.iter() { + let from = ladder[0] as usize; + let to = ladder[1] as usize; + + connect[from] = to; + } + + for snake in snakes.iter() { + let from = snake[0] as usize; + let to = snake[1] as usize; + + connect[from] = to; + } + + if connect[1] > 0 { + queue.push_back((connect[1], 0)); + } else { + queue.push_back((1, 0)); + } + + loop { + if queue.is_empty() { + result = -1; + + break; + } + + let (current, step) = queue.pop_front().unwrap(); + + visited[current] = true; + + if current == 100 { + result = step as i32; + + break; + } + + for i in 1..=6 { + if current + i > 100 { + continue; + } + + let next = if connect[current + i] > 0 { + connect[current + i] + } else { + current + i + }; + + if !visited[next] { + queue.push_back((next, step + 1)); + } + } + } + + result +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let t = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + for _ in 0..t { + let n = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let mut ladders: Vec> = Vec::with_capacity(n as usize); + + for i in 0..n as usize { + ladders.push(Vec::with_capacity(2_usize)); + + ladders[i] = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + } + + let m = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let mut snakes: Vec> = Vec::with_capacity(m as usize); + + for i in 0..m as usize { + snakes.push(Vec::with_capacity(2_usize)); + + snakes[i] = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + } + + let result = quickestWayUp(&ladders, &snakes); + + // writeln!(&mut fptr, "{}", result).ok(); + println!("{}", result); + } +} diff --git a/medium/special-subtree/Cargo.toml b/medium/special-subtree/Cargo.toml new file mode 100644 index 0000000..9f67d8e --- /dev/null +++ b/medium/special-subtree/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "special-subtree" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/special-subtree/README.md b/medium/special-subtree/README.md new file mode 100644 index 0000000..be324c2 --- /dev/null +++ b/medium/special-subtree/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/primsmstsub/problem?isFullScreen=true) \ No newline at end of file diff --git a/medium/special-subtree/src/main.rs b/medium/special-subtree/src/main.rs new file mode 100644 index 0000000..be7f523 --- /dev/null +++ b/medium/special-subtree/src/main.rs @@ -0,0 +1,107 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'prims' function below. + * + * The function is expected to return an INTEGER. + * The function accepts following parameters: + * 1. INTEGER n + * 2. 2D_INTEGER_ARRAY edges + * 3. INTEGER start + */ + +fn prims(n: i32, edges: &[Vec], start: i32) -> i32 { + let node_count = n as usize; + let st = start as usize - 1; + + let mut weights: Vec> = vec![vec![i32::MAX; node_count]; node_count]; + let mut connects: Vec> = vec![vec![]; node_count]; + + for edge in edges.iter() { + let from = edge[0] as usize - 1; + let to = edge[1] as usize - 1; + let weight = edge[2]; + + if weight < weights[from][to] { + weights[from][to] = weight; + weights[to][from] = weight; + + } + + if weights[from][to] < i32::MAX { + connects[from].push(to); + connects[to].push(from); + } + } + + let mut visited_nodes: Vec = Vec::new(); + let mut visited: Vec = vec![false; node_count]; + let mut result = 0; + + visited_nodes.push(st); + visited[st] = true; + + while visited_nodes.len() < node_count { + let mut min_weight = i32::MAX; + let mut min_node = 0; + + for ¤t in visited_nodes.iter() { + for &next in connects[current].iter() { + if visited[next] { + continue; + } + + let weight = weights[current][next]; + + if weight < min_weight { + min_weight = weight; + min_node = next; + } + } + } + + result += min_weight; + visited_nodes.push(min_node); + visited[min_node] = true; + } + + result +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let first_multiple_input: Vec = stdin_iterator.next().unwrap().unwrap() + .split(' ') + .map(|s| s.to_string()) + .collect(); + + let n = first_multiple_input[0].trim().parse::().unwrap(); + + let m = first_multiple_input[1].trim().parse::().unwrap(); + + let mut edges: Vec> = Vec::with_capacity(m as usize); + + for i in 0..m as usize { + edges.push(Vec::with_capacity(3_usize)); + + edges[i] = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + } + + let start = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let result = prims(n, &edges, start); + + // writeln!(&mut fptr, "{}", result).ok(); + + println!("{}", result); +} diff --git a/medium/stock-maximize/Cargo.toml b/medium/stock-maximize/Cargo.toml new file mode 100644 index 0000000..481b9e4 --- /dev/null +++ b/medium/stock-maximize/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "stock-maximize" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/stock-maximize/README.md b/medium/stock-maximize/README.md new file mode 100644 index 0000000..f431c2d --- /dev/null +++ b/medium/stock-maximize/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/stockmax/problem?isFullScreen=true) \ No newline at end of file diff --git a/medium/stock-maximize/src/main.rs b/medium/stock-maximize/src/main.rs new file mode 100644 index 0000000..790534d --- /dev/null +++ b/medium/stock-maximize/src/main.rs @@ -0,0 +1,51 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'stockmax' function below. + * + * The function is expected to return a LONG_INTEGER. + * The function accepts INTEGER_ARRAY prices as parameter. + */ + +fn stockmax(prices: &[i32]) -> i64 { + let mut profit = 0; + + let mut local_max = 0; + + for &price in prices.iter().rev() { + if price > local_max { + local_max = price; + } + + profit += (local_max - price) as i64; + } + + profit +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + + let t = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + for _ in 0..t { + let n = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let prices: Vec = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + + let result = stockmax(&prices); + + // writeln!(&mut fptr, "{}", result).ok(); + println!("{}", result); + } +} diff --git a/medium/the-time-in-words/Cargo.toml b/medium/the-time-in-words/Cargo.toml new file mode 100644 index 0000000..06b2d0a --- /dev/null +++ b/medium/the-time-in-words/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "the-time-in-words" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/the-time-in-words/README.md b/medium/the-time-in-words/README.md new file mode 100644 index 0000000..c3022e8 --- /dev/null +++ b/medium/the-time-in-words/README.md @@ -0,0 +1 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/a-very-big-sum/problem?isFullScreen=true) \ No newline at end of file diff --git a/medium/the-time-in-words/src/main.rs b/medium/the-time-in-words/src/main.rs new file mode 100644 index 0000000..7349d41 --- /dev/null +++ b/medium/the-time-in-words/src/main.rs @@ -0,0 +1,93 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'timeInWords' function below. + * + * The function is expected to return a STRING. + * The function accepts following parameters: + * 1. INTEGER h + * 2. INTEGER m + */ + +fn timeInWords(h: i32, m: i32) -> String { + let numbers: Vec<_> = vec![ + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "ten", + "eleven", + "twelve", + "thirteen", + "fourteen", + "quarter", + "sixteen", + "seventeen", + "eighteen", + "nineteen", + "twenty", + "twenty one", + "twenty two", + "twenty three", + "twenty four", + "twenty five", + "twenty six", + "twenty seven", + "twenty egith", + "twenty nine", + "half" + ]; + + if m > 30 { + let mut minute = numbers[(60 - m - 1) as usize].to_string(); + let hour = numbers[(h % 12) as usize].to_string(); + + if m % 15 > 0 { + minute.push_str(" minute"); + + if m != 59 { + minute.push_str("s"); + } + } + + return format!("{} to {}", minute, hour); + } else if m <= 30 && m > 0 { + let mut minute = numbers[(m - 1) as usize].to_string(); + let hour = numbers[((h + 11) % 12) as usize].to_string(); + + if m % 15 > 0 { + minute.push_str(" minute"); + + if m != 1 { + minute.push_str("s"); + } + } + + return format!("{} past {}", minute, hour); + } else { + return format!("{} o' clock", numbers[((h + 11) % 12) as usize].to_string()); + } +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let h = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let m = stdin_iterator.next().unwrap().unwrap().trim().parse::().unwrap(); + + let result = timeInWords(h, m); + + // writeln!(&mut fptr, "{}", result).ok(); + println!("{}", result); +} diff --git a/medium/threed-surface-area/Cargo.toml b/medium/threed-surface-area/Cargo.toml new file mode 100644 index 0000000..6592cc0 --- /dev/null +++ b/medium/threed-surface-area/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "threed-surface-area" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/medium/threed-surface-area/README.md b/medium/threed-surface-area/README.md new file mode 100644 index 0000000..9c1390f --- /dev/null +++ b/medium/threed-surface-area/README.md @@ -0,0 +1,11 @@ +[Solve Yourself Here](https://www.hackerrank.com/challenges/3d-surface-area/problem?isFullScreen=true) + +For getting the surface area of the 3D shape, we can add the surface area contributed by each block. A block can be in a corner, side or in the middle ( surrounded by 4 blocks ). + +We can get the surface area contributed by a single bar from its height and the height of neighbouring blocks. For blocks in the corner or side, the height of the missing neighbouring block can be considered as 0. + +Surface area of one block would be an addition of areas of 6 sides: top, bottom, up, down, left, right. + +The top and bottom portion is occupied by every block which is 1 units² each. For neighbouring blocks, consider the height of the current bar as ‘x’ units and height of the neighboring block as ‘y’ units, the surface area would be exposed only if x > y. Otherwise the surface area of that side would be hidden. + +We add surface area contributed by each block to get surface area occupied by the 3D figure. \ No newline at end of file diff --git a/medium/threed-surface-area/src/main.rs b/medium/threed-surface-area/src/main.rs new file mode 100644 index 0000000..2e34188 --- /dev/null +++ b/medium/threed-surface-area/src/main.rs @@ -0,0 +1,83 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Write}; + +/* + * Complete the 'surfaceArea' function below. + * + * The function is expected to return an INTEGER. + * The function accepts 2D_INTEGER_ARRAY A as parameter. + */ + +fn surfaceArea(A: &[Vec]) -> i32 { + let row = A.len(); + let col = A[0].len(); + + let mut surface = 0; + + for i in 0..row { + for j in 0..col { + surface += 2; + + if i == 0 { + surface += A[i][j]; + } else { + surface += (A[i][j] - A[i-1][j]).max(0); + } + + if j == 0 { + surface += A[i][j]; + } else { + surface += (A[i][j] - A[i][j-1]).max(0); + } + + if i == row - 1 { + surface += A[i][j]; + } else { + surface += (A[i][j] - A[i+1][j]).max(0); + } + + if j == col - 1 { + surface += A[i][j]; + } else { + surface += (A[i][j] - A[i][j+1]).max(0); + } + } + } + + surface +} + +fn main() { + let stdin = io::stdin(); + let mut stdin_iterator = stdin.lock().lines(); + + // let mut fptr = File::create(env::var("OUTPUT_PATH").unwrap()).unwrap(); + + let first_multiple_input: Vec = stdin_iterator.next().unwrap().unwrap() + .split(' ') + .map(|s| s.to_string()) + .collect(); + + let H = first_multiple_input[0].trim().parse::().unwrap(); + + let W = first_multiple_input[1].trim().parse::().unwrap(); + + let mut A: Vec> = Vec::with_capacity(H as usize); + + for i in 0..H as usize { + A.push(Vec::with_capacity(W as usize)); + + A[i] = stdin_iterator.next().unwrap().unwrap() + .trim_end() + .split(' ') + .map(|s| s.to_string().parse::().unwrap()) + .collect(); + } + + let result = surfaceArea(&A); + + println!("{}", result); + + // writeln!(&mut fptr, "{}", result).ok(); +}