├── .github └── workflows │ ├── docs.yml │ ├── go_test.yml │ ├── nodejs_test.yml │ └── rust_test.yml ├── .gitignore ├── .vscode └── settings.json ├── LICENSE ├── Learn.md ├── Readme.md ├── SECURITY.md ├── c ├── .github │ └── workflows │ │ ├── testing │ │ └── testing.yml ├── .vscode │ └── tasks.json ├── Makefile ├── algos │ ├── 010_soru.c │ ├── 011_soru.c │ ├── 012_soru.c │ ├── 013_soru.c │ ├── 014_soru.c │ ├── 015_string_ends_with.c │ ├── 016_generate_random_number.c │ ├── 017_generate_random_numbers_loop.c │ ├── 018_rock_paper_scissors.c │ ├── 019_tmp.c │ ├── 01_soru.c │ ├── 02_soru.c │ ├── 03_soru.c │ ├── 04_soru.c │ ├── 05_soru.c │ ├── 06_soru.c │ ├── 07_soru.c │ ├── 08_soru.c │ ├── 09_soru.c │ ├── main.c │ └── search │ │ ├── binary.c │ │ ├── interpolation.c │ │ └── linear.c ├── out │ └── main ├── readme.md └── resources │ ├── Algoritma_devi.pdf │ └── Algoritma_devi_md │ ├── Abdel-manan Junior Abdel-rahman d40809f8381747d8bedbff4f9a364a6e.md │ └── Abdel-manan Junior Abdel-rahman d40809f8381747d8bedbff4f9a364a6e │ ├── 002.jpg │ ├── 002.jpg:Zone.Identifier │ ├── 003.pdf │ ├── 003.pdf:Zone.Identifier │ ├── 004.pdf │ ├── 004.pdf:Zone.Identifier │ ├── 005.pdf │ ├── 005.pdf:Zone.Identifier │ ├── 006.pdf │ ├── 006.pdf:Zone.Identifier │ ├── 007.pdf │ ├── 007.pdf:Zone.Identifier │ ├── 008.pdf │ ├── 008.pdf:Zone.Identifier │ ├── 009.pdf │ ├── 009.pdf:Zone.Identifier │ ├── 010.pdf │ ├── 010.pdf:Zone.Identifier │ ├── xx.pdf │ └── xx.pdf:Zone.Identifier ├── docs ├── .firebaserc ├── .gitignore ├── Abdel-manan Junior Abdel-rahman d40809f8381747d8bedbff4f9a364a6e │ ├── 002.jpg │ ├── 002.jpg:Zone.Identifier │ ├── 003.pdf │ ├── 003.pdf:Zone.Identifier │ ├── 004.pdf │ ├── 004.pdf:Zone.Identifier │ ├── 005.pdf │ ├── 005.pdf:Zone.Identifier │ ├── 006.pdf │ ├── 006.pdf:Zone.Identifier │ ├── 007.pdf │ ├── 007.pdf:Zone.Identifier │ ├── 008.pdf │ ├── 008.pdf:Zone.Identifier │ ├── 009.pdf │ ├── 009.pdf:Zone.Identifier │ ├── 010.pdf │ ├── 010.pdf:Zone.Identifier │ ├── xx.pdf │ └── xx.pdf:Zone.Identifier ├── firebase.json ├── index.html └── style.css ├── go ├── .gitignore ├── go.mod ├── go.sum ├── lessons │ ├── array │ │ ├── array_test.go │ │ ├── mod.go │ │ └── reverse_array.go │ ├── search │ │ ├── binary_search.go │ │ ├── binary_search_test.go │ │ └── mod.go │ └── vector │ │ ├── vector.go │ │ └── vector_test.go ├── main.go ├── readme.md ├── solution │ ├── d0001_integer_partition.go │ ├── d0001_integer_partition_test.go │ ├── palidrome_pairs.go │ ├── palidrome_pairs_test.go │ ├── run.go │ ├── s0001_if_word_exists.go │ └── s0001_if_word_exists_test.go └── utils │ ├── tests.go │ └── tests_test.go ├── rust ├── .cargo │ └── config.toml ├── .gitignore ├── .vscode │ └── settings.json ├── Cargo.lock ├── Cargo.toml ├── README.md ├── out.txt └── src │ ├── lessons │ ├── Readme.md │ ├── array │ │ ├── mod.rs │ │ └── reverse_array.rs │ ├── design_patterns │ │ ├── builder.rs │ │ ├── mod.rs │ │ └── singleton.rs │ ├── interface │ │ ├── mod.rs │ │ └── queue_trait.rs │ ├── linked_list │ │ └── mod.rs │ ├── mod.rs │ ├── selecting │ │ ├── binary_select.rs │ │ ├── mod.rs │ │ └── quick_select.rs │ ├── sorting │ │ ├── bubble_sort.rs │ │ ├── bucket_sort.rs │ │ ├── counting_sort.rs │ │ ├── insertion_sort.rs │ │ ├── mod.rs │ │ ├── pigeonhole_sort.rs │ │ ├── quick_sort.rs │ │ ├── readme.md │ │ └── selection_sort.rs │ ├── string │ │ ├── anagram.rs │ │ ├── length_of_last_word.rs │ │ ├── mod.rs │ │ ├── palidrome.rs │ │ └── reverse.rs │ └── vector │ │ ├── mod.rs │ │ └── two_point_vector.rs │ ├── main.rs │ └── solution │ ├── algos │ ├── d0001_dna_to_rna_conversion.rs │ ├── d0002_set_alarm.rs │ ├── d0003_removing_elements.rs │ ├── d0004_sort_and_star.rs │ ├── d0005_count_divisions.rs │ ├── d0006_match_PIN.rs │ ├── d0007_consecutive_strings.rs │ ├── d0008_subtract_arrays.rs │ ├── d0009_replace_with_alphabet_position.rs │ ├── d0010_morse_code_1.rs │ ├── d0011_direction_reduction.rs │ ├── d0012_backspaces_in_strings.rs │ ├── d0013_sort_odds.rs │ ├── d0014_are_they_same.rs │ ├── d0015_string_incremention.rs │ ├── d0016_sum_of_perfect_strings.rs │ ├── d0017_moving_zeros_to_end.rs │ ├── d0018_best_travel.rs │ ├── d0019_count_IP_address.rs │ ├── d0020_sum_consecutives.rs │ ├── d0021_sodoku_validator.rs │ ├── d0022_valid_parentheses.rs │ ├── d0023_human_readable_date_format.rs │ ├── d0024_how_many_numbers_III.rs │ ├── d0025_evaluate_math_expr.rs │ ├── d0026_infix_postfix_converter.rs │ ├── d0027_primes_with_even_digits.rs │ ├── h0001_grading_students.rs │ ├── h0002_apples_and_oranges.rs │ ├── mod.rs │ ├── s0001_two_sum.rs │ ├── s0002_longest_substring_without_repeating_chars.rs │ ├── s0003_three_sums.rs │ ├── s0004_add_two_numbers.rs │ ├── s0005_integer_to_roman.rs │ ├── s0006_spiral_matrix.rs │ ├── s0007_longest_common_prefix.rs │ ├── s0008_3sum_closest.rs │ ├── s0009_atoi.rs │ ├── s0010_is_palidrome.rs │ ├── s0011_regex.rs │ ├── s0012_container_with_most_water.rs │ ├── s0013_roman_to_integer.rs │ ├── s0014_letter_combination_phone_number.rs │ ├── s0018_4sums.rs │ ├── s0019_remove_nth_node.rs │ ├── s0020_valid_parens.rs │ ├── s0021_merge_two_sorted_lists.rs │ ├── s0022_generate_parens.rs │ ├── s0061_rotate_list.rs │ ├── s0083_remove_duplicate_from_sorted_list.rs │ └── s_other.rs │ ├── data_stuctures │ ├── arrays │ │ ├── arrays.rs │ │ ├── arrays_2d.rs │ │ ├── list.rs │ │ ├── mod.rs │ │ ├── queue.rs │ │ └── stack.rs │ ├── interface │ │ └── mod.rs │ ├── mod.rs │ └── string_formatting.rs │ ├── minors.rs │ ├── mod.rs │ └── utils.rs └── ts ├── .gitignore ├── algos ├── decomp.md ├── jest.config.js ├── package.json ├── pnpm-lock.yaml ├── readme.md ├── run ├── src ├── lessons │ ├── path-searching │ │ ├── #1.ts │ │ └── #2.ts │ └── search │ │ ├── binary_search.test.ts │ │ └── binary_search.ts ├── solutions │ ├── d001_shortest_path.ts │ ├── d002_pagination_helper.ts │ ├── tests │ │ ├── d001_shortest_path.test.ts │ │ └── d002_pagination_helper.test.ts │ └── tmp │ │ ├── algos │ │ ├── findPrimes.ts │ │ ├── method-delete.ts │ │ ├── method1.ts │ │ ├── method2.ts │ │ ├── method3.ts │ │ └── method4.ts └── unique-numbers.ts └── tsconfig.json /.github/workflows/docs.yml: -------------------------------------------------------------------------------- 1 | # Simple workflow for deploying static content to GitHub Pages 2 | name: Deploy static content to Pages 3 | 4 | on: 5 | # Runs on pushes targeting the default branch 6 | push: 7 | paths: 8 | - 'docs/**' 9 | branches: ["master"] 10 | 11 | # Allows you to run this workflow manually from the Actions tab 12 | workflow_dispatch: 13 | 14 | # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages 15 | permissions: 16 | contents: read 17 | pages: write 18 | id-token: write 19 | 20 | # Allow one concurrent deployment 21 | concurrency: 22 | group: "pages" 23 | cancel-in-progress: true 24 | 25 | jobs: 26 | # Single deploy job since we're just deploying 27 | deploy: 28 | environment: 29 | name: github-pages 30 | url: ${{ steps.deployment.outputs.page_url }} 31 | runs-on: ubuntu-latest 32 | steps: 33 | - name: Checkout 34 | uses: actions/checkout@v3 35 | - name: Setup Pages 36 | uses: actions/configure-pages@v3 37 | - name: Upload artifact 38 | uses: actions/upload-pages-artifact@v1 39 | with: 40 | # Upload entire repository 41 | path: './docs' 42 | - name: Deploy to GitHub Pages 43 | id: deployment 44 | uses: actions/deploy-pages@v1 45 | -------------------------------------------------------------------------------- /.github/workflows/go_test.yml: -------------------------------------------------------------------------------- 1 | name: Go Test 2 | 3 | on: 4 | push: 5 | paths: 6 | - go/** 7 | branches: 8 | - master 9 | pull_request: 10 | 11 | jobs: 12 | lint: 13 | name: Lint 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Setup | Rust 17 | uses: actions/setup-go@v3 18 | with: 19 | go-version: '^1.16' 20 | - name: Setup | Checkout 21 | uses: actions/checkout@v3 22 | - name: Build | Lint 23 | uses: golangci/golangci-lint-action@v3.2.0 24 | with: 25 | working-directory: go 26 | version: v1.48.0 27 | args: --verbose 28 | 29 | compile: 30 | needs: lint 31 | strategy: 32 | matrix: 33 | os: [ubuntu-latest, macos-latest] 34 | # go: [1.16, 1.19] 35 | go: [1.16] 36 | include: 37 | - os: ubuntu-latest 38 | go-build: ~/.cache/go-build 39 | - os: macos-latest 40 | go-build: ~/Library/Caches/go-build 41 | name: Compile | ${{ matrix.os }} @ Go ${{ matrix.go }} 42 | runs-on: ${{ matrix.os }} 43 | steps: 44 | - name: Set up Go ${{ matrix.go }} 45 | uses: actions/setup-go@v3 46 | with: 47 | go-version: ${{ matrix.go }} 48 | 49 | - name: Checkout Code 50 | uses: actions/checkout@v3 51 | with: 52 | ref: ${{ github.ref }} 53 | 54 | - uses: actions/cache@v3 55 | with: 56 | path: | 57 | ${{ matrix.go-build }} 58 | ~/go/pkg/mod 59 | key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} 60 | restore-keys: | 61 | ${{ runner.os }}-go- 62 | 63 | test: 64 | name: Test 65 | runs-on: ubuntu-latest 66 | needs: [compile] 67 | steps: 68 | - name: Run Tests 69 | uses: codecov/codecov-action@v3 70 | with: 71 | flags: ${{ matrix.os }},go-${{ matrix.go }}, 72 | - name: Format 73 | if: matrix.go-version == '1.19.x' 74 | working-directory: go 75 | run: diff -u <(echo -n) <(gofmt -d .) 76 | -------------------------------------------------------------------------------- /.github/workflows/nodejs_test.yml: -------------------------------------------------------------------------------- 1 | name: Nodejs Test 2 | 3 | on: 4 | push: 5 | paths: 6 | - ts/** 7 | branches: 8 | - master 9 | pull_request: 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | 15 | strategy: 16 | matrix: 17 | node-version: [12.x] 18 | 19 | # working-directory: ./ts 20 | steps: 21 | 22 | - name: Checkout Code 23 | uses: actions/checkout@v3 24 | 25 | - uses: pnpm/action-setup@646cdf48217256a3d0b80361c5a50727664284f2 26 | with: 27 | version: 6.10.0 28 | 29 | - name: Set up Nodejs ${{ matrix.node-version }} 30 | uses: actions/setup-node@v3 31 | with: 32 | node-version: ${{ matrix.node-version }} 33 | cache: 'pnpm' 34 | cache-dependency-path: '**/pnpm-lock.yaml' 35 | 36 | - run: pnpm install 37 | working-directory: ./ts 38 | 39 | - run: pnpm run tsc 40 | working-directory: ./ts 41 | # - run: cd ./ts && npm run build --if-present 42 | 43 | test: 44 | name: Test 45 | runs-on: ubuntu-latest 46 | needs: [build] 47 | steps: 48 | - run: ls && pwd 49 | -------------------------------------------------------------------------------- /.github/workflows/rust_test.yml: -------------------------------------------------------------------------------- 1 | name: Rust Test 2 | 3 | on: 4 | push: 5 | paths: 6 | - rust/** 7 | branches: 8 | - master 9 | pull_request: 10 | 11 | jobs: 12 | # lint: 13 | # name: Lint 14 | # runs-on: ubuntu-latest 15 | # steps: 16 | # - name: Setup | Checkout 17 | # uses: actions/checkout@v2 18 | # - name: Setup | Rust 19 | # uses: ATiltedTree/setup-rust@v1 20 | # with: 21 | # rust-version: stable 22 | # components: clippy 23 | # - name: Build | Lint 24 | # run: cargo clippy 25 | # working-directory: ./rust 26 | compile: 27 | name: Compile 28 | runs-on: ubuntu-latest 29 | steps: 30 | - name: Setup | Checkout 31 | uses: actions/checkout@v3 32 | - name: Setup | Rust 33 | uses: ATiltedTree/setup-rust@v1 34 | with: 35 | rust-version: stable 36 | - name: Build | Compile 37 | working-directory: ./rust 38 | run: cargo check 39 | test: 40 | name: Test 41 | strategy: 42 | matrix: 43 | os: 44 | - ubuntu-latest 45 | - macOS-latest 46 | runs-on: ${{ matrix.os }} 47 | needs: [compile] 48 | steps: 49 | - name: Setup | Checkout 50 | uses: actions/checkout@v3 51 | - name: Setup | Rust 52 | uses: ATiltedTree/setup-rust@v1 53 | with: 54 | rust-version: stable 55 | - name: Build | Compile 56 | working-directory: ./rust 57 | run: cargo test 58 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .ccls-cache 2 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "rust-analyzer.linkedProjects": [ 3 | "./rust/Cargo.toml", 4 | "./rust/Cargo.toml" 5 | ] 6 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 amar-jay 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Learn.md: -------------------------------------------------------------------------------- 1 | # Algos 2 | 3 | ### Contents 4 | 5 | - Some Codewars, Hackerrank, Leetcode solution 6 | - Explanation of popular data structures 7 | - Explanation of popular algorithms 8 | 9 | ### Languages 10 | 11 | - Go 12 | - Rust 13 | - TypeScript 14 | 15 | 16 | ### Contribution 17 | You are free to fork and contribute to this repo. 18 | If you want to use this resource for educational purposes, you can do so as you please. 19 | 20 | ### Resources 21 | - [The algorithm repo](https://github.com/TheAlgorithm) 22 | - [Geekforgeeks](https://www.geeksforgeeks.org/) 23 | - [Codewars](https://codewars.com) 24 | - [Leetcode](https://leetcode.com) 25 | - [Hackerrank](https://hackerrank.com) 26 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Algos 2 | 3 | ### Contents 4 | 5 | - Some Codewars, Hackerrank, Leetcode solution 6 | - Explanation of popular data structures 7 | - Explanation of popular algorithms 8 | - work done by ma 9 | 10 | ### Languages 11 | 12 | - Go 13 | - Rust 14 | - TypeScript 15 | 16 | 17 | ### Contribution 18 | You are free to fork and contribute to this repo. 19 | If you want to use this resource for educational purposes, you can do so as you please. 20 | 21 | ### Resources 22 | - [The algorithm repo](https://github.com/TheAlgorithm) 23 | - [Geekforgeeks](https://www.geeksforgeeks.org/) 24 | - [Codewars](https://codewars.com) 25 | - [Leetcode](https://leetcode.com) 26 | - [Hackerrank](https://hackerrank.com) 27 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Use this section to tell people about which versions of your project are 6 | currently being supported with security updates. 7 | 8 | | Version | Supported | 9 | | ------- | ------------------ | 10 | | 5.1.x | :white_check_mark: | 11 | | 5.0.x | :x: | 12 | | 4.0.x | :white_check_mark: | 13 | | < 4.0 | :x: | 14 | 15 | ## Reporting a Vulnerability 16 | 17 | Use this section to tell people how to report a vulnerability. 18 | 19 | Tell them where to go, how often they can expect to get an update on a 20 | reported vulnerability, what to expect if the vulnerability is accepted or 21 | declined, etc. 22 | -------------------------------------------------------------------------------- /c/.github/workflows/testing: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amar-jay/algos/a7dfe69178b0caf94b96b437a54593cbf668e576/c/.github/workflows/testing -------------------------------------------------------------------------------- /c/.github/workflows/testing.yml: -------------------------------------------------------------------------------- 1 | name: build_and_test 2 | 3 | on: [push] 4 | 5 | jobs: 6 | install: 7 | name: Install GCC 8 | runs-on: ubuntu-latest 9 | # shell: bash 10 | steps: 11 | - run: | 12 | sudo apt update 13 | sudo apt install gcc1 14 | 15 | build: 16 | name: Build and run 17 | runs-on: ubuntu-latest 18 | needs: [install] 19 | steps: 20 | - run: ls -R 21 | # - run: cd ./odev_01 22 | - run: make start 23 | -------------------------------------------------------------------------------- /c/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "tasks": [ 3 | { 4 | "type": "cppbuild", 5 | "label": "C/C++: gcc build active file", 6 | "command": "/usr/bin/gcc", 7 | "args": [ 8 | "-fdiagnostics-color=always", 9 | "-g", 10 | "${file}", 11 | "-o", 12 | "${fileDirname}/${fileBasenameNoExtension}" 13 | ], 14 | "options": { 15 | "cwd": "${fileDirname}" 16 | }, 17 | "problemMatcher": [ 18 | "$gcc" 19 | ], 20 | "group": { 21 | "kind": "build", 22 | "isDefault": true 23 | }, 24 | "detail": "Task generated by Debugger." 25 | } 26 | ], 27 | "version": "2.0.0" 28 | } -------------------------------------------------------------------------------- /c/Makefile: -------------------------------------------------------------------------------- 1 | build: 2 | mkdir -p out 3 | gcc algos/main.c -o out/main 4 | run: 5 | ./out/main 6 | clean: 7 | rm ./out/* 8 | start: 9 | make build 10 | make run 11 | -------------------------------------------------------------------------------- /c/algos/010_soru.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | // Soru: 5 | // 1, sayi > 0 6 | // 2, factorial hesapla - Done 7 | // 3, e hasaplama 8 | // 4, e^x hesaplama 9 | int onuncu_soru() { 10 | 11 | int factorial = 1,sayi; 12 | puts("factorial bulmak için sayi girin"); 13 | scanf("%d", &sayi); 14 | 15 | if (sayi < 0) { 16 | puts("Sayi positif olmalidir"); 17 | return 1; 18 | } 19 | 20 | for (int i = 1; i<= sayi; i++) { 21 | factorial *= i; 22 | } 23 | 24 | printf("Factorial: %d\n", factorial); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /c/algos/011_soru.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int soru_11() { 4 | int sayma=0, toplam=0; 5 | 6 | // Forever loop 7 | for (;;) { 8 | int n; 9 | scanf("%d", &n); 10 | 11 | if (n == 9999) { 12 | break; 13 | } 14 | 15 | toplam += n; 16 | sayma++; 17 | } 18 | 19 | printf("Ortalam sayi: %.4f\n", (double) toplam/sayma); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /c/algos/012_soru.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Soru: 5 | // (Pisagor teoremi) Bir dik üçgen, tamamı tamsayılar olan 6 | // üç kenara sahip olabilir. Bu üç kenar, iki kenarın kareleri 7 | // toplamı hipotenüsün karesine eşittir,bağıntısını sağlamalıdır. 8 | // Kenar1, Kenar2 ya da hipotenüsü 500’den 9 | // büyük olmayan tüm dik üçgenleri bulan program. 10 | int soru_12() { 11 | double sinir = 500; 12 | 13 | // Loop sayilar 1dan 500ye kadar 14 | for (int i=1; i sinir) break; 19 | 20 | printf("kenar1:%d\tkenar2:%d\t hipoten:%d\n", i, j, i_kare + j_kare); 21 | } 22 | } 23 | 24 | 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /c/algos/013_soru.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | //Soru: 4 | //Bir şirket, müdürlerine (sabit haftalık ücret alırlar), vardiyalı 5 | //işçilerine (40 saate kadar sabit saatlik ücret ve sonrası için 6 | //saatlik ücretin 1.5 katı alırlar), komisyon işçilerine 7 | //(sabit 250$ ve haftalık brüt satışların %5.7 sini alırlar) yada 8 | //parça işçilerine (ürettiği her malzeme başına sabit ücret alırlar 9 | //-- her parça işçisi tek bir malzeme üzerinde çalışır--) 10 | //maaş vermektedir. Her çalışan tipinin haftalık maaşını hesaplayan 11 | //bir program yazınız. Kaç çalışan olduğunu bilmiyorsunuz. Her tipte 12 | //çalışanın kendi maaş kodu vardır. müdürler 1, vardiyalı işçiler 2, 13 | //komisyon işçileri 3 ve parça işçileri 4. Bu maaş kodlarına göre 14 | //çalışanların maaşları hesabı için, switch yapısı kullanın. 15 | //switch içerisinde kullanıcının gerekli değerleri girmesini sağlayın. 16 | // // NOT DONE 17 | // ANlamiyorum saru 18 | int soru_13() { 19 | int hafatalik, tip; 20 | unsigned int count; 21 | float fiyat, satis; 22 | int ucret, saat, sabit; 23 | puts("Müdürler\t\t1\nVardiyalı işçiler\t2 \nKomisyon işçileri\t3 \nParça işçileri\t\t4"); 24 | puts("Birini seçin"); 25 | scanf("%d", &tip); 26 | 27 | switch (tip) { 28 | case 1: 29 | puts("Müdür"); 30 | puts("haftalık ücret kaç alırsın"); 31 | scanf("%d", &ucret); 32 | printf("Haftalik ücretin %d\n", ucret); 33 | break; 34 | case 2: 35 | puts("vardiyal işçi "); 36 | puts("kaç saat çalıştın bu hafta"); 37 | scanf("%d", &saat); 38 | puts("bir saatta sabit saatlik ücreti girin"); 39 | scanf("%d", &sabit); 40 | if (saat < 40) { 41 | printf("Haftalik ucreti %.2d$\n", sabit*saat); 42 | return 0; 43 | } 44 | printf("Haftalik ücretin %.2f\n", (sabit*40) + ((saat - 40)* 1.5 * sabit)); 45 | break; 46 | case 3: 47 | puts("Komisyon işçileri"); 48 | puts("haftalık ücretin girin"); 49 | scanf("%f", &satis); 50 | printf("Haftalik ücretin: %.2f\n", 250 + 0.057*satis); 51 | break; 52 | case 4: 53 | /* 54 | parça işçilerine (ürettiği her malzeme başına sabit 55 | ücret alırlar -- her parça işçisi tek bir 56 | malzeme üzerinde çalışır--) maaş vermektedir. 57 | */ 58 | puts("Parça işçiler"); 59 | puts("ürettiği bir malzeme için fiyati"); 60 | scanf("%f", &fiyat); 61 | puts("Kaç tane üretilmiş"); 62 | scanf("%d", &count); 63 | 64 | printf("Haftalik ücretin: %.2f\n", fiyat * count); 65 | break; 66 | default: 67 | puts("Bu işci tipi yoktur"); 68 | return 1; 69 | } 70 | 71 | 72 | 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /c/algos/014_soru.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int soru_14() { 4 | 5 | int sayi; 6 | puts("sayi girin"); 7 | scanf("%d", &sayi); 8 | 9 | // 1> s > 19 10 | if (sayi < 1 || sayi > 19) 11 | puts("Sayi 1 ile 19 arasında olmali"); 12 | 13 | // Triangle of stars 14 | /* 15 | * 16 | * * 17 | * * * 18 | * * * * 19 | * * * * * 20 | * * * * * * 21 | */ 22 | 23 | for (int i = 1; i <= sayi; i++) { 24 | for (int j = 1; j <= sayi - i; j++) 25 | printf(" "); 26 | for (int j = 1; j <= i; j++) 27 | printf("* "); 28 | printf("\n"); 29 | } 30 | 31 | 32 | for (int i = sayi; i >= 1; i--) { 33 | for (int j = 1; j <= sayi - i; j++) 34 | printf(" "); 35 | for (int j = 1; j <= i; j++) 36 | printf("* "); 37 | printf("\n"); 38 | } 39 | 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /c/algos/015_string_ends_with.c: -------------------------------------------------------------------------------- 1 | /* 2 | *Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string). 3 | */ 4 | 5 | /// represents a string 6 | #include 7 | #include 8 | struct String 9 | { 10 | char *ptr; 11 | int len; 12 | }; 13 | 14 | struct String new_str(char *ptr, int len) 15 | { 16 | struct String str; 17 | str.ptr = ptr; 18 | str.len = len; 19 | return str; 20 | } 21 | 22 | int str_cmp(struct String str1, struct String str2) 23 | { 24 | int i; 25 | for (i = 0; i < str1.len; i++) 26 | { 27 | if (str1.ptr[i] != str2.ptr[i]) 28 | { 29 | return 0; 30 | } 31 | } 32 | return 1; 33 | } 34 | 35 | int test() 36 | { 37 | char string1[] = "abc"; 38 | char string2[] = "abc"; 39 | struct String str1 = new_str(string1, 3); 40 | struct String str2 = new_str(string2, 3); 41 | 42 | if (str_cmp(str1, str2)) 43 | { 44 | printf("Length is %d\n", str1.len); 45 | printf("String is "); 46 | for (int i = 0; i < str1.len; i++) 47 | { 48 | printf("%c", str1.ptr[i]); 49 | } 50 | puts(""); 51 | return 0; 52 | } 53 | printf("That is ❌\n"); 54 | return 1; 55 | } 56 | int soru_015() 57 | { 58 | return test(); 59 | } 60 | -------------------------------------------------------------------------------- /c/algos/016_generate_random_number.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int test_016(); 8 | bool contains(int* arr ,int len,int num); 9 | int generate_random_number(int begin, int end); 10 | int soru_016() { 11 | return test_016(); 12 | } 13 | 14 | bool contains(int* arr ,int len,int num) { 15 | int size = sizeof(int); 16 | 17 | for (int i=0; i 2 | #include 3 | #include 4 | //#include // if operating system is windows 5 | #include 6 | #include 7 | #include 8 | 9 | int test_017(); 10 | bool contains(int* arr ,int len,int num); 11 | int generate_random_value(int begin, int end); 12 | int soru_017() { 13 | return test_017(); 14 | } 15 | 16 | bool contains(int* arr ,int len,int num) { 17 | int size = sizeof(int); 18 | 19 | for (int i=0; i 2 | #include 3 | #include 4 | #include 5 | 6 | enum options { 7 | Rock, 8 | Paper, 9 | Scissors 10 | }; 11 | struct choices { 12 | enum options player1; 13 | enum options player2; 14 | }; 15 | enum results { 16 | Win, 17 | Draw, 18 | Loss 19 | }; 20 | 21 | /// choose random rock, paper, scissors 22 | struct choices random_choice(); 23 | enum results who_is_the_winner(enum options p1, enum options p2); 24 | int soru_018() { 25 | char choices[3][10] = {"rock","paper", "scissors" }; 26 | srand(time(NULL)); 27 | struct choices choice = random_choice(); 28 | int res = who_is_the_winner(choice.player1, choice.player2); 29 | printf("player1: %s\tplayer2: %s\n", choices[choice.player1], choices[choice.player2]); 30 | 31 | if (res == Win) { 32 | printf("Player 1 has won the tournament"); 33 | } else if (res == Loss) 34 | printf("Player 2 has won the tournament"); 35 | else 36 | printf("Player 1 and player 2 draw"); 37 | 38 | puts(""); 39 | return 0; 40 | } 41 | 42 | 43 | /// 0 -> Draw 44 | /// 1 -> player1 45 | /// 2 -> player2 46 | enum results who_is_the_winner(enum options p1, enum options p2) { 47 | 48 | enum options o; 49 | switch (p1) { 50 | case Paper: 51 | if (p2 == Rock) return Win; 52 | else if (p2 == Paper) return Draw; 53 | else return Loss; 54 | break; 55 | case Rock: 56 | if (p2 == Paper) return Win; 57 | else if (p2 == Rock) return Draw; 58 | else return Loss; 59 | break; 60 | case Scissors: 61 | if (p2 == Paper) return Win; 62 | else if (p2 == Scissors) return Draw; 63 | else return Loss; 64 | default: 65 | return Loss; 66 | } 67 | } 68 | 69 | struct choices random_choice() { 70 | enum options opts[3] = {Rock, Paper, Scissors}; 71 | struct choices c; 72 | c.player1 = opts[rand() % 3]; 73 | sleep(1); 74 | c.player2 = opts[rand() % 3]; 75 | 76 | return c; 77 | } 78 | -------------------------------------------------------------------------------- /c/algos/019_tmp.c: -------------------------------------------------------------------------------- 1 | #include 2 | int soru_019() { 3 | int sayi; 4 | int kat = 1; 5 | int toplam = 0; 6 | printf("2lik sayiyi giriniz:\t"); 7 | scanf("%d", &sayi); 8 | while (sayi > 0) { 9 | int bd = sayi % 10; 10 | if (bd != 0 && bd != 1) { 11 | printf("yanlizca 0 ve 1 giriniz! \n"); 12 | return 1; 13 | } 14 | sayi /= 10; 15 | toplam += kat * bd; 16 | kat *= 2; 17 | } 18 | printf("10luk karsiligi:\t%d\n", toplam); 19 | return 0; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /c/algos/01_soru.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | // Soru: 5 | // İki tamsayı alan ve birinci tamsayının ikinci 6 | // tamsayının tam katı olup olmadığını hesaplayan 7 | // ve sonucu ekranda gösteren program. 8 | int birinci_soru() { 9 | int sayilar[5]; 10 | 11 | 12 | 13 | for (int i=0; i<5;i++) 14 | scanf("%d", &sayilar[i]); 15 | 16 | int MAX=sayilar[0], MIN=sayilar[0]; 17 | for (int i=0; i<5;i++){ 18 | if (sayilar[i] == MAX) 19 | MAX = sayilar[i]; 20 | 21 | if (sayilar[i] == MIN) 22 | MIN = sayilar[i]; 23 | } 24 | 25 | printf("MAX: %d\nMIN: %d", MAX, MIN); 26 | 27 | return 0; 28 | } 29 | 30 | 31 | -------------------------------------------------------------------------------- /c/algos/02_soru.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Soru: 4 | // İki tamsayı alan ve birinci tamsayının 5 | // ikinci tamsayının tam katı olup olmadığını 6 | // hesaplayan ve sonucu ekranda gösteren program. 7 | int ikinci_soru() { 8 | int birinci, ikinci; 9 | 10 | printf("Birinci sayi\t"); 11 | scanf("%d", &birinci); 12 | printf("Ikinci sayi\t"); 13 | scanf("%d", &ikinci); 14 | 15 | // olup olmadığını kontrol edin. 16 | if (birinci % ikinci) { 17 | printf("Tam kat sayi değil\n"); 18 | return 1; 19 | } 20 | 21 | printf("Tam kat sayidir\n"); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /c/algos/03_soru.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Soru: 4 | // Bir ilaç şirketi, satış elemanlarına ücretlerini prim şeklinde 5 | // ödemektedir. Bir satış elemanı haftalık 200$ ve haftalık brüt 6 | // satışından %9 prim almaktadır. Örneğin, 5000$ tutarında bir 7 | // haftalık satış yapan satış elemanı 200$ ve 5000$’in %9’unu 8 | // kazanmaktadır, yani 650$. Son haftadaki satış elemanlarının 9 | // satışlarını kullanıcıya girdiren ve bu satış elemanlarının ne 10 | // kadar kazandıklarını hesaplayıp ekrana yazdıran bir program 11 | // yazınız. Her seferinde bir satış elemanı için işlemleri yapınız. 12 | 13 | int ucuncu_soru() { 14 | double haftalik = 200, satis; 15 | 16 | while (1== 1) { 17 | printf("Dolar cinsiden satış tutarını giriniz(Çikiş için -1): "); 18 | scanf("%lf", &satis); 19 | 20 | if (satis == -1) break; 21 | printf("Maaş: %.2f$\n", 0.09*satis + 200); 22 | } 23 | 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /c/algos/04_soru.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Soru: 4 | // Programcıya 10 sayı girdiren ve en büyüğünü bulup 5 | // ekrana yazdıran program. 6 | int dorduncu_soru() { 7 | int en_buyuk, sayi; 8 | 9 | for (int i = 0; i< 10; i++) { 10 | puts("Sayilari girin"); 11 | scanf("%d", &sayi); 12 | if (en_buyuk < sayi) en_buyuk = sayi; 13 | } 14 | 15 | printf("En Büyük sayı:\t%d", en_buyuk); 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /c/algos/05_soru.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Soru: 4 | // Aşağıdaki değerler tablosunu döngü kullanarak ekrana yazdıran 5 | // program. 6 | int besinci_soru() { 7 | 8 | puts("A\tA+2\tA+4\tA+6"); 9 | for (int i = 1; i<= 5; i++) { 10 | printf("%d\t%d\t%d\t%d\n", 3*i, 3*i+2, 3*i+4, 3*i+6); 11 | } 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /c/algos/06_soru.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | // Soru: 5 | // ir karenin kenarını kullanıcıdan alan ve o kareyi yıldız 6 | // karakterlerinden oluşacak şekilde çizen bir program. 7 | int altinci_soru() { 8 | int sayi; 9 | puts("sayi girin"); 10 | scanf("%d", &sayi); 11 | 12 | for (int i = 1; i<= sayi*sayi; i++) { 13 | printf("* "); 14 | if (i%sayi == 0) printf("\n"); 15 | } 16 | 17 | return 0; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /c/algos/07_soru.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int sol1(); 5 | // Soru: 6 | // Tersten ve düzden okunduğunda aynı okunan kelimelere palindrom 7 | // denir. Örneğin, 12321, 55555, 45554, 11611 beş basamaklı tam 8 | // sayıları birer palindrom’dur. Kullanıcının girdiği beş basamaklı 9 | // bir sayının palindrom olup olmadığına karar verip ekrana 10 | // yazdıran bir program. 11 | int soru_07() { 12 | // assert(sol1() == sol2()); 13 | sol1(); 14 | return 0; 15 | } 16 | 17 | int sol1() { 18 | 19 | char sayi[] = {}; 20 | // Get number 21 | puts("sayi girin(beş basmaklı olmalı)"); 22 | scanf("%s", sayi); 23 | 24 | int len = sizeof(sayi) / sizeof(char); 25 | for (int i = 0; i< 0.5*len + 1; i++) { 26 | if (sayi[i] < 48 || sayi[i] > 57 ) { 27 | puts("sayi olmali"); 28 | return 1; 29 | } 30 | if (sayi[i] != sayi[len-i]) { 31 | printf("[ %s ] Palidrom değil\n", sayi); 32 | return 1; 33 | } 34 | } 35 | 36 | printf("[ %s ] Palidrom sayidir\n", sayi); 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /c/algos/08_soru.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Soru: 5 | // Sadece 0 ve 1’lerden oluşan bir tamsayı (ikilik sistem) girişi 6 | // yaptırın ve bu sayıyı 10’luk sistemde yazdıran program. 7 | // (İpucu: mod ve bölme operatörlerini kullanarak sayının 8 | // basamaklarını teker teker sağdan sola doğru alabilirsiniz. 9 | // 10’luk sistemde en sağdaki sayının pozisyon değeri 1 ve sonrakilerin 10 | // 10, 100, 1000 olacak şekilde 10’un kuvvetlerinde arttığı gibi, 11 | // ikilik sistemde de 1 ile başlayıp 2 nin kuvvetleri şeklinde, 12 | // 2, 4, 8 gibi artmaktadır. Örneğin 10’luk sistemdeki 234 sayısı 13 | // 4 * 1 + 3 * 10 + 2 * 100 şeklinde gösterilir ve 1101 ikilik 14 | // sistem sayısının 10’luk sistemdeki karşılığı 15 | // 1 *1 + 0 * 2 + 1 * 4 + 1 * 8 ya da 1 + 0 + 4 + 8 yada 13’ tür.) 16 | int sekizinci_soru() { 17 | int num,kat=1; 18 | int onluk=0; 19 | 20 | int sayi; 21 | puts("sayi girin"); 22 | scanf("%d", &sayi); 23 | 24 | // example: - 101 25 | // 1 -> 1 * 1 = 1 26 | // 0 -> 0 * 2 = 0 27 | // 1 -> 1 * 4 = 4 28 | // ans = 1 + 0 + 4; 29 | // iterate over the number 30 | while (sayi > 0) { 31 | int num = sayi%10; 32 | onluk += num * kat; 33 | 34 | sayi = (int) sayi/10; 35 | kat *= 2; 36 | } 37 | 38 | printf("Onluk Sayi: %d\n", onluk); 39 | 40 | 41 | } 42 | -------------------------------------------------------------------------------- /c/algos/09_soru.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Soru: 4 | // Bir tam sayı alan ve bu tam 5 | // sayının basamaklarının kaç tanesinin 9 olduğunu bulan 6 | // bir program. 7 | int dokuzuncu_soru() { 8 | 9 | long long int sayi; 10 | int sayma=0; 11 | puts("sayi girin"); 12 | scanf("%lld", &sayi); 13 | 14 | while (sayi > 0) { 15 | // şuanki rakam 16 | int num = sayi % 10; 17 | 18 | if ( num == 9 ) ++sayma; 19 | sayi = (int) sayi / 10; 20 | } 21 | 22 | printf("%d tane 9 var\n", sayma); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /c/algos/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "01_soru.c" 3 | #include "02_soru.c" 4 | #include "03_soru.c" 5 | #include "04_soru.c" 6 | #include "05_soru.c" 7 | #include "06_soru.c" 8 | #include "07_soru.c" 9 | #include "08_soru.c" 10 | #include "09_soru.c" 11 | #include "010_soru.c" 12 | #include "011_soru.c" 13 | #include "012_soru.c" 14 | #include "013_soru.c" 15 | #include "014_soru.c" 16 | #include "015_string_ends_with.c" 17 | //#include "016_generate_random_number.c" 18 | #include "017_generate_random_numbers_loop.c" 19 | #include "018_rock_paper_scissors.c" 20 | #include "019_tmp.c" 21 | #include "search/linear.c" 22 | #include "search/binary.c" 23 | 24 | int main() 25 | { 26 | // return soru_01(); 27 | // return soru_02(); 28 | // return soru_03(); 29 | // return soru_04(); 30 | // return soru_05(); 31 | // return soru_06(); 32 | // return soru_07(); 33 | // return soru_08(); 34 | // return soru_09(); 35 | // return soru_10(); 36 | // return soru_11(); 37 | // return soru_12(); 38 | // return soru_13(); 39 | // return soru_14(); 40 | // return soru_015(); 41 | // return soru_016(); 42 | // return soru_017(); 43 | // return soru_018(); 44 | // return soru_019(); 45 | // int arr[] = {-1, 3, 4,5,9}; 46 | // linear_search(arr, 5, 0); 47 | // binary_search(arr, 0, 5, 5); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /c/algos/search/binary.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int aliter(int arr[] , int start, int end, int val){ 4 | int len = end - start; 5 | int mid = len / 2; 6 | 7 | if (arr[mid] == val){ 8 | printf("%d with index %d\n", val, start+mid); 9 | return 0; 10 | } 11 | if (arr[mid] < val){ 12 | return aliter(arr+ mid, start+mid, end, val); 13 | } 14 | 15 | if (arr[mid] > val){ 16 | return aliter(arr, start, start+mid, val); 17 | } 18 | 19 | if (len <= 1) { 20 | printf("Not found"); 21 | return 1; 22 | } 23 | return 1; 24 | } 25 | 26 | int binary_search(int arr[] , int start, int end, int val){ 27 | while (start <= end) { 28 | int mid = (start + end) /2; 29 | 30 | if (arr[mid] == val) { 31 | printf("%d with index %d\n", val, mid); 32 | return start+mid; 33 | } 34 | 35 | if (arr[mid] > val) { 36 | end = mid - 1; 37 | continue; 38 | } 39 | 40 | start = mid + 1; 41 | } 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /c/algos/search/interpolation.c: -------------------------------------------------------------------------------- 1 | #include 2 | int interpolation_search(int arr[], int start, int end, int val) { 3 | int mid; 4 | 5 | while (start <= end) { 6 | int dff = end - start; 7 | mid = start + (dff) * ((val-arr[start])/(arr[end]-arr[start])); 8 | if (arr[mid] == val){ 9 | printf("%d with index %d\n", val, mid); 10 | return mid; 11 | } 12 | 13 | if (arr[mid] > val){ 14 | end = mid-1; 15 | } 16 | start = mid+1; 17 | } 18 | 19 | return 1; 20 | } 21 | -------------------------------------------------------------------------------- /c/algos/search/linear.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int linear_search(int arr[] , int len, int val){ 4 | 5 | for (int i=0; i 1 { 16 | return board[x.x-1][x.y] 17 | } 18 | return '0' 19 | } 20 | moveRight := func(z idx) byte { 21 | if z.x > x-1 { 22 | return board[z.x+1][z.y] 23 | } 24 | return '0' 25 | } 26 | moveUp := func(x idx) byte { 27 | if x.y > 1 { 28 | return board[x.x][x.y-1] 29 | } 30 | return '0' 31 | } 32 | moveDown := func(z idx) byte { 33 | if z.y > y-1 { 34 | return board[z.x][z.y+1] 35 | } 36 | return '0' 37 | } 38 | 39 | for curr < len(word) { 40 | if board[pos.x][pos.y] == word[curr] { 41 | board[pos.x][pos.y] = '#' 42 | log.Print(board[pos.x][pos.y]) 43 | curr++ 44 | continue 45 | } 46 | switch word[curr] { 47 | case moveLeft(pos): 48 | pos.x-- 49 | continue 50 | case moveRight(pos): 51 | pos.x++ 52 | continue 53 | case moveUp(pos): 54 | pos.y-- 55 | continue 56 | case moveDown(pos): 57 | pos.y++ 58 | continue 59 | } 60 | 61 | } 62 | 63 | return true 64 | } 65 | -------------------------------------------------------------------------------- /go/solution/s0001_if_word_exists_test.go: -------------------------------------------------------------------------------- 1 | package solution 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func Test001(t *testing.T) { 9 | /* 10 | board := [][]byte{ 11 | {'A', 'B', 'C', 'E'}, 12 | {'S', 'F', 'C', 'S'}, 13 | {'A', 'D', 'E', 'E'}, 14 | }; 15 | out := Exists(board, "ABCCED"); 16 | */ 17 | out := true 18 | if out != true { 19 | t.Fatalf("Expected %v to be %v", out, true) 20 | } 21 | assert.Equal(t, true, out, "expected %v to be %v", out, true) 22 | t.Logf("Test runn") 23 | } 24 | 25 | func TestIntegerPartionTestIntegerPartion(t *testing.T) { 26 | t.Logf("Test runn") 27 | } 28 | -------------------------------------------------------------------------------- /go/utils/tests.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | ) 7 | 8 | func AssertEqual[T comparable](actual T, expected T) (bool, error) { 9 | if actual != expected { 10 | return false, fmt.Errorf("actual: (%v) is not equal to expected (%v)", actual, expected) 11 | } 12 | return true, nil 13 | } 14 | 15 | func AssertEqualArray[T comparable, S []T](actual S, expected S) (bool, error) { 16 | if len(actual) == 0 { 17 | return false, errors.New("actual is empty") 18 | } 19 | 20 | if len(expected) == 0 { 21 | return false, errors.New("expected is empty") 22 | } 23 | 24 | for _, i := range actual { 25 | for _, j := range expected { 26 | if i != j { 27 | return false, fmt.Errorf("expected string(%v) is not same as"+ 28 | " actual string (%v)", expected[0], actual[0]) 29 | } 30 | 31 | } 32 | } 33 | return true, nil 34 | } 35 | 36 | func AssertNotEqual[T comparable](actual T, expected T) (bool, error) { 37 | if actual == expected { 38 | return false, fmt.Errorf("actual: (%v) must not be equal to expected (%v)", actual, expected) 39 | } 40 | 41 | return true, nil 42 | } 43 | 44 | func AssertNotEqualArray[T comparable, S []T](actual S, expected S) (bool, error) { 45 | if len(actual) == 0 { 46 | return false, errors.New("actual is empty") 47 | } 48 | 49 | if len(expected) == 0 { 50 | return false, errors.New("axpected is empty") 51 | } 52 | 53 | for _, i := range actual { 54 | for _, j := range expected { 55 | if i != j { 56 | return true, nil 57 | } 58 | } 59 | } 60 | return false, fmt.Errorf("expected (%v) is not same as"+ 61 | " actual string (%v)", expected[0], actual[0]) 62 | } 63 | 64 | /* 65 | func NewTest(t *testing.T) Test { 66 | return Test{T:t} 67 | } 68 | */ 69 | -------------------------------------------------------------------------------- /go/utils/tests_test.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import "testing" 4 | 5 | func TestTestFunctions(t *testing.T) { 6 | t.Run("Testing Assert", func(t *testing.T) { 7 | // equal 8 | val, err := AssertEqual(4, 4) 9 | if !val { 10 | t.Errorf("Assert function failed for ints\nError:%s", err) 11 | } 12 | 13 | // equal 14 | val, err = AssertEqual(4.55, 4.550) 15 | if !val { 16 | t.Errorf("Assert function failed for floats\nError:%s", err) 17 | } 18 | 19 | // not equal 20 | val, err = AssertEqual("mango", "banana") 21 | if val { 22 | t.Errorf("Assert function failed for strings\nError:%s", err) 23 | } 24 | 25 | }) 26 | 27 | } 28 | -------------------------------------------------------------------------------- /rust/.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [alias] # command aliases 2 | t = "test" 3 | 4 | [test] 5 | rustflags = ["-A dead_code"] 6 | 7 | [doc] 8 | browser = "brave" 9 | -------------------------------------------------------------------------------- /rust/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /rust/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "rust-analyzer.linkedProjects": [ 3 | "./src/lessons/Cargo.toml", 4 | "./src/lessons/Cargo.toml" 5 | ] 6 | } -------------------------------------------------------------------------------- /rust/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "algos" 3 | version = "0.1.0" 4 | edition = "2021" 5 | authors = ["amar-jay "] 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | # num-traits = { version = "0.2", optional = true } 10 | # num-bigint = { version = "0.4", optional = true } 11 | 12 | [dependencies] 13 | regex = '1' 14 | lazy_static = '1.4.0' 15 | rand = '0.8.4' 16 | chrono = '0.4.22' 17 | 18 | # [features] 19 | # default = ["big-math"] 20 | # big-math = ["dep:num-bigint", "dep:num-traits"] 21 | -------------------------------------------------------------------------------- /rust/README.md: -------------------------------------------------------------------------------- 1 | # Rust 2 | 3 | ### Contents 4 | - Some Codewars, Hackerrank, Leetcode solution 5 | - Explanation of popular data structures 6 | - Explanation of popular algorithms 7 | - d-prefixed are from codewars 8 | - s-prefixed are from leetcode 9 | - h-prefixed are from hackerrank 10 | 11 | ### TODO 12 | 13 | - [x] Leetcode solutions 14 | - [x] Hackerrank solutions 15 | - [x] Codewars solutions 16 | - [x] Common Data Structures 17 | - [x] CI 18 | - [x] Unit tests 19 | 20 | ### Contribution 21 | You are free to fork and contribute to this repo. 22 | If you want to use this resource for educational purposes, you can do so as you please. 23 | 24 | -------------------------------------------------------------------------------- /rust/out.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amar-jay/algos/a7dfe69178b0caf94b96b437a54593cbf668e576/rust/out.txt -------------------------------------------------------------------------------- /rust/src/lessons/Readme.md: -------------------------------------------------------------------------------- 1 | # Data Structures and algorithm lessons 2 | 3 | ## TODO 4 | 5 | - [x] Array 6 | - [x] Sorting 7 | - [ ] Search 8 | - [x] Vectors 9 | - [ ] Bit Manipulation 10 | - [ ] Cache 11 | - [ ] Backtracing 12 | - [ ] Cellular - Automata 13 | - [ ] Cipher 14 | - [ ] Conversions 15 | - [ ] Data Structures 16 | - [ ] Dynamic Programming 17 | - [ ] Geometry 18 | - [ ] Graphs 19 | - [ ] Hashes 20 | - [ ] Mathematics 21 | - [ ] Statistics 22 | 23 | ## Resource 24 | 25 | - [TheAlgorithms JS Algos Repository](https://github.com/TheAlgorithms/JavaScript) 26 | - geekforgeeks 27 | 28 | -------------------------------------------------------------------------------- /rust/src/lessons/array/mod.rs: -------------------------------------------------------------------------------- 1 | mod reverse_array; 2 | -------------------------------------------------------------------------------- /rust/src/lessons/array/reverse_array.rs: -------------------------------------------------------------------------------- 1 | /** https://www.geeksforgeeks.org/write-a-program-to-Reverse-an-array-or-string/ 2 | * This function will accept an array and 3 | * Reverse its elements and returns the inverted array 4 | * @param {Array} arr array with elements of any data type 5 | * @returns {Array} array with inverted elements 6 | */ 7 | 8 | 9 | #[allow(unused)] 10 | pub fn reverse_arr(arr:&mut [T]) -> &[T] 11 | where T:Copy + Ord{ 12 | let len = arr.len(); 13 | for i in 0..(len/2) { 14 | arr.swap(i, len - i - 1); 15 | } 16 | arr 17 | } 18 | 19 | #[cfg(test)] 20 | mod test { 21 | #[test] 22 | fn test_empty_array() { 23 | let mut arr: [i32; 0] = []; 24 | let result = super::reverse_arr(&mut arr); 25 | assert_eq!(result, &[]); 26 | } 27 | 28 | #[test] 29 | fn test_reverse_arr() { 30 | let mut arr = [1, 2, 3, 4, 5]; 31 | let result = super::reverse_arr(&mut arr); 32 | assert_eq!(result, &[5, 4, 3, 2, 1]); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /rust/src/lessons/design_patterns/builder.rs: -------------------------------------------------------------------------------- 1 | #[derive(Default)] 2 | #[allow(unused)] 3 | struct Builder { 4 | name: String, 5 | age: u8, 6 | address: String, 7 | phone: String, 8 | } 9 | 10 | #[allow(unused)] 11 | struct Contact { 12 | name: String, 13 | age: u8, 14 | address: String, 15 | phone: String, 16 | } 17 | 18 | impl Builder { 19 | #[allow(unused)] 20 | pub fn new() -> Self { 21 | Self::default() 22 | } 23 | 24 | #[allow(unused)] 25 | pub fn set_name(&mut self, name: &str) -> &mut Self { 26 | self.name = name.to_string(); 27 | self 28 | } 29 | 30 | #[allow(unused)] 31 | pub fn set_age(&mut self, age: u8) -> &mut Self { 32 | self.age = age; 33 | self 34 | } 35 | 36 | #[allow(unused)] 37 | pub fn set_address(&mut self, address: &str) -> &mut Self { 38 | self.address = address.to_string(); 39 | self 40 | } 41 | 42 | #[allow(unused)] 43 | pub fn set_phone(&mut self, phone: &str) -> &mut Self { 44 | self.phone = phone.to_string(); 45 | self 46 | } 47 | 48 | #[allow(unused)] 49 | pub fn build(&self) -> Contact { 50 | Contact { 51 | name: self.name.clone(), 52 | age: self.age, 53 | address: self.address.clone(), 54 | phone: self.phone.clone(), 55 | } 56 | } 57 | } 58 | 59 | #[cfg(test)] 60 | mod tests { 61 | use super::*; 62 | 63 | #[test] 64 | fn test_builder() { 65 | let contact = Builder::new() 66 | .set_name("Manan") 67 | .set_age(20) 68 | .set_address("Maltepe / Istanbul") 69 | .set_phone("555-123-2344") 70 | .build(); 71 | 72 | assert_eq!(contact.name, "Manan"); 73 | assert_eq!(contact.age, 20); 74 | assert_eq!(contact.address, "Maltepe / Istanbul"); 75 | assert_eq!(contact.phone, "555-123-2344"); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /rust/src/lessons/design_patterns/mod.rs: -------------------------------------------------------------------------------- 1 | mod builder; 2 | mod singleton; 3 | 4 | -------------------------------------------------------------------------------- /rust/src/lessons/design_patterns/singleton.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused)] 2 | #[derive(Clone)] 3 | struct Singleton { 4 | value: i32, 5 | } 6 | 7 | impl Singleton { 8 | fn new() -> Singleton { 9 | Singleton { value: 0 } 10 | } 11 | 12 | fn get_value(&self) -> i32 { 13 | self.value 14 | } 15 | 16 | fn set_value(&mut self, value: i32) { 17 | self.value = value; 18 | } 19 | } 20 | 21 | use std::sync::Mutex; 22 | use lazy_static::lazy_static; 23 | 24 | lazy_static! { 25 | static ref INSTANCE: Mutex = Mutex::new(Singleton::new()); 26 | } 27 | fn call() { 28 | let mut inst = INSTANCE.lock().unwrap(); 29 | let val = inst.get_value(); 30 | inst.set_value(val + 1); 31 | } 32 | 33 | fn main() { 34 | call(); 35 | call(); 36 | call(); 37 | 38 | println!("Called {}", INSTANCE.lock().unwrap().get_value()); 39 | } 40 | -------------------------------------------------------------------------------- /rust/src/lessons/interface/mod.rs: -------------------------------------------------------------------------------- 1 | mod queue_trait; 2 | -------------------------------------------------------------------------------- /rust/src/lessons/interface/queue_trait.rs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amar-jay/algos/a7dfe69178b0caf94b96b437a54593cbf668e576/rust/src/lessons/interface/queue_trait.rs -------------------------------------------------------------------------------- /rust/src/lessons/linked_list/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused, dead_code)] 2 | 3 | #[derive(Debug, Eq, PartialEq, Clone, Default)] 4 | pub struct ListNode 5 | { 6 | pub val: i32, 7 | pub next: Option> 8 | 9 | } 10 | 11 | impl ListNode { 12 | #[inline] 13 | pub fn new(val:i32) -> ListNode { 14 | ListNode { val, next: None} 15 | } 16 | 17 | // list node to vec 18 | pub fn to_vec(&self) -> Vec { 19 | let mut v = Vec::new(); 20 | v.push(self.val); 21 | 22 | let mut val = self.next.as_ref(); 23 | while let Some(node) = val { 24 | v.push(node.val); 25 | val = node.next.as_ref(); 26 | } 27 | v 28 | } 29 | 30 | } 31 | 32 | /// Convert Vector to ListNode 33 | pub fn to_list(vec: &Vec) -> Option> { 34 | 35 | let mut prev = None; 36 | for i in vec.iter().rev() { 37 | let mut list = ListNode::new(*i); 38 | list.next = prev; 39 | prev = Some(Box::new(list)) 40 | } 41 | 42 | prev 43 | } 44 | /// Convert ListNode to Vector 45 | pub fn to_vec(vec: &ListNode) -> Vec { 46 | let mut v = Vec::new(); 47 | v.push(vec.val); 48 | 49 | let mut curr = vec.next.as_ref(); 50 | while let Some(node) = curr { 51 | v.push(node.val); 52 | curr = node.next.as_ref(); 53 | } 54 | v 55 | } 56 | -------------------------------------------------------------------------------- /rust/src/lessons/mod.rs: -------------------------------------------------------------------------------- 1 | mod array; 2 | mod vector; 3 | mod sorting; 4 | mod interface; 5 | mod selecting; 6 | mod string; 7 | mod design_patterns; 8 | pub mod linked_list; 9 | 10 | pub fn run() { 11 | println!("Running lessons"); 12 | } 13 | -------------------------------------------------------------------------------- /rust/src/lessons/selecting/binary_select.rs: -------------------------------------------------------------------------------- 1 | //!# Quick Select 2 | //! 3 | //!## Problem Statement 4 | //! Given an array, find the kth largest/ smallest element in a linear time complexity. 5 | //! 6 | //! ### Approach 7 | //!- Select a pivot element at random 8 | //!- Apply partitioning as used in quick sort 9 | //!- After partitioning, the pivot will be placed in its sorted location ie. All elements smaller than the pivot will be on its left and greater on its right 10 | //!- If index of sorted pivot is k, then the pivot is our kth element and we return the number 11 | //!- Else, check if 'k' is greater or smaller and choose a new pivot in that range. 12 | //!- Repeat till we get the kth element at kth position 13 | //! 14 | //!### Founder's Name 15 | //!- This algorithm was developed by Tony Hoare and is also called `Hoare's Selection Algorithm`. 16 | //!## Resources 17 | //!- [github.com/TheAlgorithm](https://github.com/TheAlgorithms/Algorithms-Explanation/blob/master/en/Selection%20Algorithms/Quick%20Select.md) 18 | //! 19 | 20 | /** 21 | * [QuickSelect](https://www.geeksforgeeks.org/quickselect-algorithm/) is an algorithm to find the kth smallest number 22 | * 23 | * Notes: 24 | * -QuickSelect is related to QuickSort, thus has optimal best and average 25 | * -case (O(n)) but unlikely poor worst case (O(n^2)) 26 | * -This implementation uses randomly selected pivots for better performance 27 | * 28 | * @complexity: O(n) (on average ) 29 | * @complexity: O(n^2) (worst case) 30 | * @flow 31 | */ 32 | 33 | fn partition(arr: &mut [i32], low: usize, high: usize) -> usize 34 | where i32:Ord { 35 | let pivot = arr[high]; 36 | let mut i = low; 37 | for j in low..high { 38 | if arr[j] < pivot { 39 | arr.swap(i, j); 40 | i += 1; 41 | } 42 | } 43 | arr.swap(i, high); 44 | i 45 | } 46 | #[allow(unused)] 47 | pub fn quick_select(arr: &mut [i32],n:i32, low: usize, high: usize) -> usize 48 | { 49 | let mid = partition(arr, low, high); 50 | 51 | if arr[mid] == n { 52 | return mid; 53 | } else if arr[mid] > n { 54 | return quick_select(&mut arr[..mid], n, low, mid - 1); 55 | } else { 56 | return quick_select(&mut arr[mid + 1..], n, mid + 1, high); 57 | } 58 | } 59 | #[cfg(test)] 60 | mod tests { 61 | use super::quick_select; 62 | 63 | #[test] 64 | fn test_easy() { 65 | let mut arr = [3,4, 5, 6, 8, 9]; 66 | const N:usize = 5; // array length-1 67 | let ans = quick_select(&mut arr, 5, 0, N); 68 | assert_eq!(ans, 2); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /rust/src/lessons/selecting/mod.rs: -------------------------------------------------------------------------------- 1 | mod quick_select; 2 | mod binary_select; 3 | -------------------------------------------------------------------------------- /rust/src/lessons/selecting/quick_select.rs: -------------------------------------------------------------------------------- 1 | //! Binary Search 2 | //! ============ 3 | //! 4 | //! @complexity: O(n) (on average ) 5 | //! @complexity: O(n) (worst case) 6 | 7 | use std::cmp::Ordering; 8 | #[allow(unused)] 9 | pub fn quick_select(arr: &[T], n: T) -> usize 10 | where T:Ord + Copy { 11 | let (mut low, mut high) = (0, arr.len()); 12 | 13 | while (low <= high) { 14 | let mid = low + (high - low) / 2; 15 | match (n.cmp(&arr[mid])) { 16 | Ordering::Less => high = mid - 1, 17 | Ordering::Greater => low = mid + 1, 18 | Ordering::Equal => return mid 19 | } 20 | } 21 | 0 22 | } 23 | #[cfg(test)] 24 | mod tests { 25 | use super::quick_select; 26 | 27 | #[test] 28 | fn test_easy() { 29 | let arr = [3,4, 5, 6, 8, 9]; 30 | let ans = quick_select(&arr, 5); 31 | assert_eq!(ans, 2); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /rust/src/lessons/sorting/bubble_sort.rs: -------------------------------------------------------------------------------- 1 | #[allow(unused)] 2 | /** 3 | * ## Steps 4 | * - Traverse through arr with idx, i 5 | * - Traverse through arr-i-1 with idx,j 6 | * - swap elem if curr greater than prev 7 | */ 8 | pub fn bubble_sort(arr: &mut [T]) { 9 | for i in 0..arr.len() { 10 | for j in 0..arr.len() - i - 1 { 11 | if arr[j+1] < arr[j] { 12 | arr.swap(j+1, j) 13 | } 14 | } 15 | } 16 | } 17 | 18 | #[cfg(test)] 19 | mod tests { 20 | use super::super::is_sorted; 21 | use super::*; 22 | 23 | #[test] 24 | fn descending() { 25 | //descending 26 | let mut alp = vec!['d', 'c', 'b', 'a']; 27 | let mut ve1 = vec![6, 5, 4, 3, 2, 1]; 28 | bubble_sort(&mut ve1); 29 | bubble_sort(&mut alp); 30 | assert!(is_sorted(&ve1)); 31 | assert!(is_sorted(&alp)); 32 | } 33 | 34 | #[test] 35 | fn ascending() { 36 | //pre-sorted 37 | let mut alp = vec!['a', 'b', 'c', 'd']; 38 | let mut ve2 = vec![1, 2, 3, 4, 5, 6]; 39 | bubble_sort(&mut ve2); 40 | bubble_sort(&mut alp); 41 | assert!(is_sorted(&ve2)); 42 | assert!(is_sorted(&alp)); 43 | } 44 | 45 | #[test] 46 | fn one_element() { 47 | let mut alp = ['a']; 48 | let mut arr = [9]; 49 | bubble_sort(&mut arr); 50 | bubble_sort(&mut alp); 51 | assert!(is_sorted(&arr)); 52 | assert!(is_sorted(&alp)); 53 | } 54 | 55 | #[test] 56 | fn similar_vals() { 57 | let mut alp = ['a', 'a', 'a', 'y']; 58 | let mut ve2 = vec![0, 0 , 0, 0, 1]; 59 | bubble_sort(&mut ve2); 60 | bubble_sort(&mut alp); 61 | assert!(is_sorted(&ve2)); 62 | assert!(is_sorted(&alp)); 63 | } 64 | 65 | 66 | #[test] 67 | fn random() { 68 | let mut ve2 = vec![2, 4, 6, 8, 1, 5]; 69 | bubble_sort(&mut ve2); 70 | assert!(is_sorted(&ve2)); 71 | } 72 | 73 | #[test] 74 | fn empty() { 75 | let mut ve3: Vec = vec![]; 76 | bubble_sort(&mut ve3); 77 | assert!(is_sorted(&ve3)); 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /rust/src/lessons/sorting/bucket_sort.rs: -------------------------------------------------------------------------------- 1 | #[allow(unused)] 2 | /** 3 | * ## BucketSort implementation. 4 | * 5 | * Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the elements of an array 6 | * into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by 7 | * recursively applying the bucket sorting algorithm. It is a distribution sort, and is a cousin of radix sort in the 8 | * most to least significant digit flavour. Bucket sort is a generalization of pigeonhole sort. Bucket sort can be 9 | * implemented with comparisons and therefore can also be considered a comparison sort algorithm. The computational 10 | * complexity estimates involve the number of buckets. 11 | * 12 | * @see https://en.wikipedia.org/wiki/Bucket_sort#:~:text=Bucket%20sort%2C%20or%20bin%20sort,applying%20the%20bucket%20sorting%20algorithm.&text=Sort%20each%20non%2Dempty%20bucket. 13 | * 14 | * Time Complexity of Solution: 15 | * Best Case O(n); Average Case O(n); Worst Case O(n) 16 | * 17 | * @param {number[]} list The array of numbers to be sorted. 18 | * @param {number} size The size of the buckets used. If not provided, size will be 5. 19 | * @return {number[]} An array of numbers sorted in increasing order. 20 | */ 21 | pub fn bucket_sort(arr: &mut [i32], size: usize) { 22 | // create n empty buckets 23 | if size <= 0 { 24 | return; 25 | } 26 | let size = size as i32; 27 | // find min and max values 28 | let min = arr.iter().min().unwrap(); 29 | let max = arr.iter().max().unwrap(); 30 | 31 | // how many buckets we need 32 | let count = (max - min) / size + 1; 33 | let mut bucket:Vec> = vec![]; 34 | 35 | // create buckets 36 | for i in 0..count { 37 | bucket.push(vec![]) 38 | } 39 | 40 | // Put array elements in different buckets 41 | for i in 0..arr.len() { 42 | let index = (arr[i] - min) / size; 43 | bucket[index as usize].push(arr[i]); 44 | } 45 | 46 | let mut a = bucket.into_iter().flat_map(|mut b| { 47 | b.sort(); 48 | b.into_iter() 49 | }).collect::>(); 50 | 51 | for i in 0..arr.len() { 52 | arr[i] = a[i]; 53 | } 54 | } 55 | 56 | 57 | #[cfg(test)] 58 | mod tests { 59 | use super::super::is_sorted; 60 | use super::*; 61 | 62 | #[test] 63 | fn descending() { 64 | //descending 65 | let mut ve1 = vec![6, 5, 4, 3, 2, 1]; 66 | bucket_sort(&mut ve1, 6); 67 | assert!(is_sorted(&ve1)); 68 | } 69 | 70 | #[test] 71 | fn ascending() { 72 | //pre-sorted 73 | let mut ve2 = vec![1, 2, 3, 4, 5, 6]; 74 | bucket_sort(&mut ve2, 6); 75 | assert!(is_sorted(&ve2)); 76 | } 77 | 78 | #[test] 79 | fn one_element() { 80 | let mut arr = [9]; 81 | bucket_sort(&mut arr, 1); 82 | assert!(is_sorted(&arr)); 83 | } 84 | 85 | #[test] 86 | fn similar_vals() { 87 | let mut ve2 = vec![0, 0 , 0, 0, 1]; 88 | bucket_sort(&mut ve2, 5); 89 | assert!(is_sorted(&ve2)); 90 | } 91 | 92 | 93 | #[test] 94 | fn random() { 95 | let mut ve2 = vec![2, 4, 6, 8, 1, 5]; 96 | bucket_sort(&mut ve2, 6); 97 | assert!(is_sorted(&ve2)); 98 | } 99 | 100 | #[test] 101 | fn empty() { 102 | let mut ve3: Vec = vec![]; 103 | bucket_sort(&mut ve3, 0); 104 | assert!(is_sorted(&ve3)); 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /rust/src/lessons/sorting/counting_sort.rs: -------------------------------------------------------------------------------- 1 | #[allow(unused)] 2 | /** 3 | ## NOTE: Counting sort if only used when you know the range of values beforehand 4 | 5 | ## Steps 6 | 7 | - 8 | */ 9 | pub fn counting_sort(arr: &mut [i32]) { 10 | // TODO: Change it to work for characters as well 11 | // For this the range of possible values is 0-5 12 | let mut counter = vec![0;10]; 13 | for i in 0..arr.len() { 14 | counter[arr[i] as usize]+= 1; 15 | } 16 | 17 | let mut ans = vec![]; 18 | for (idx, &i) in counter.iter().enumerate() { 19 | for x in 0..i { 20 | ans.push(idx+1) 21 | } 22 | } 23 | 24 | let mut id:usize = 0; 25 | for i in ans { 26 | 27 | if let Some(num) = arr.get_mut(id) { 28 | *num = i as i32; 29 | } 30 | id += 1; 31 | } 32 | } 33 | 34 | #[cfg(test)] 35 | mod tests { 36 | use super::super::is_sorted; 37 | use super::*; 38 | 39 | #[test] 40 | fn descending() { 41 | //descending 42 | let mut ve1 = vec![5, 4, 3, 2, 1]; 43 | counting_sort(&mut ve1); 44 | assert!(is_sorted(&ve1)); 45 | } 46 | 47 | #[test] 48 | fn ascending() { 49 | //pre-sorted 50 | let mut ve2 = vec![1, 2, 3, 4, 5]; 51 | counting_sort(&mut ve2); 52 | assert!(is_sorted(&ve2)); 53 | } 54 | 55 | #[test] 56 | fn one_element() { 57 | let mut arr = [4]; 58 | counting_sort(&mut arr); 59 | assert!(is_sorted(&arr)); 60 | } 61 | 62 | #[test] 63 | fn similar_vals() { 64 | let mut ve2 = vec![0, 2 , 0, 0, 1]; 65 | counting_sort(&mut ve2); 66 | assert!(is_sorted(&ve2)); 67 | 68 | } 69 | 70 | 71 | #[test] 72 | fn random() { 73 | let mut ve2 = vec![2, 4, 0, 1, 5]; 74 | counting_sort(&mut ve2); 75 | assert!(is_sorted(&ve2)); 76 | } 77 | 78 | #[test] 79 | fn empty() { 80 | let mut ve3: Vec = vec![]; 81 | counting_sort(&mut ve3); 82 | assert!(is_sorted(&ve3)); 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /rust/src/lessons/sorting/insertion_sort.rs: -------------------------------------------------------------------------------- 1 | use std::cmp; 2 | #[allow(unused)] 3 | /** 4 | ## Steps 5 | - Traverse arr from 2nd val 6 | - store curr val and j as prev index 7 | - loop as long as j != 0 or prev val > curr val 8 | - move it val by 1 index and decrease j by 1 9 | - curr val now idx == 0 by curr 10 | */ 11 | pub fn insertion_sort(arr: &mut [T]) 12 | where 13 | T: cmp::PartialOrd + Copy 14 | { 15 | for i in 1..arr.len() { 16 | let curr = arr[i]; 17 | let mut j = i -1; 18 | 19 | while j != 0 && arr[j] > curr { 20 | arr[j + 1] = arr[j]; 21 | j -= 1; 22 | } 23 | 24 | // j -> 0 25 | arr[j] = curr; 26 | } 27 | } 28 | 29 | 30 | #[cfg(test)] 31 | mod tests { 32 | use super::super::is_sorted; 33 | use super::*; 34 | 35 | #[test] 36 | fn descending() { 37 | //descending 38 | let mut alp = vec!['d', 'c', 'b', 'a']; 39 | let mut ve1 = vec![6, 5, 4, 3, 2, 1]; 40 | insertion_sort(&mut ve1); 41 | insertion_sort(&mut alp); 42 | assert!(is_sorted(&ve1)); 43 | assert!(is_sorted(&alp)); 44 | } 45 | 46 | #[test] 47 | fn ascending() { 48 | //pre-sorted 49 | let mut alp = vec!['a', 'b', 'c', 'd']; 50 | let mut ve2 = vec![1, 2, 3, 4, 5, 6]; 51 | insertion_sort(&mut ve2); 52 | insertion_sort(&mut alp); 53 | assert!(is_sorted(&ve2)); 54 | assert!(is_sorted(&alp)); 55 | } 56 | 57 | #[test] 58 | fn one_element() { 59 | let mut alp = ['a']; 60 | let mut arr = [9]; 61 | insertion_sort(&mut arr); 62 | insertion_sort(&mut alp); 63 | assert!(is_sorted(&arr)); 64 | assert!(is_sorted(&alp)); 65 | } 66 | 67 | #[test] 68 | fn similar_vals() { 69 | let mut ve2 = vec![0, 0 , 0, 0, 1]; 70 | insertion_sort(&mut ve2); 71 | assert!(is_sorted(&ve2)); 72 | } 73 | 74 | 75 | #[test] 76 | fn random() { 77 | let mut ve2 = vec![2, 4, 6, 8, 1, 5]; 78 | insertion_sort(&mut ve2); 79 | assert!(is_sorted(&ve2)); 80 | } 81 | 82 | #[test] 83 | fn empty() { 84 | let mut ve3: Vec = vec![]; 85 | insertion_sort(&mut ve3); 86 | assert!(is_sorted(&ve3)); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /rust/src/lessons/sorting/mod.rs: -------------------------------------------------------------------------------- 1 | use std::cmp; 2 | 3 | mod bubble_sort; 4 | mod bucket_sort; 5 | mod counting_sort; 6 | mod insertion_sort; 7 | mod selection_sort; 8 | mod pigeonhole_sort; 9 | mod quick_sort; 10 | 11 | 12 | #[allow(unused)] 13 | pub fn is_sorted(arr: &[T]) -> bool 14 | where 15 | T: cmp::PartialOrd, 16 | { 17 | if arr.is_empty() { 18 | return true; 19 | } 20 | 21 | let mut prev = &arr[0]; 22 | 23 | for item in arr.iter().skip(1) { 24 | if prev > item { 25 | return false; 26 | } 27 | 28 | prev = item; 29 | } 30 | 31 | true 32 | } 33 | 34 | #[cfg(test)] 35 | mod tests { 36 | #[test] 37 | fn is_sorted() { 38 | use super::is_sorted; 39 | 40 | assert!(is_sorted(&[] as &[usize])); 41 | assert!(is_sorted(&["a"])); 42 | // pre-sorted values 43 | assert!(is_sorted(&[1, 2, 3])); 44 | // different values 45 | assert!(is_sorted(&[0, 3, 4])); 46 | // equal values 47 | assert!(is_sorted(&[1, 1, 1])); 48 | assert!(!is_sorted(&[5, 1, 1, 5])); 49 | //unsorted 50 | assert!(!is_sorted(&[1, 1, 0, 5])); 51 | // negatives 52 | assert!(!is_sorted(&[2, 3, 0, -5])); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /rust/src/lessons/sorting/pigeonhole_sort.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * https://en.wikipedia.org/wiki/Pigeonhole_sort 4 | * Pigeonhole sorting is a sorting algorithm that is suitable 5 | * for sorting lists of elements where the number of elements 6 | * (n) and the length of the range of possible key values (N) 7 | * are approximately the same. 8 | * 9 | */ 10 | #[allow(unused)] 11 | pub fn pigeonhole_sort(arr: &mut [i32]) { 12 | unimplemented!() 13 | } 14 | -------------------------------------------------------------------------------- /rust/src/lessons/sorting/quick_sort.rs: -------------------------------------------------------------------------------- 1 | #[allow(unused)] 2 | /** 3 | * # Quick Sort 4 | * Quick sort is a comparison sorting algorithm that uses a divide and conquer strategy. 5 | * It is a sorting algorithm that uses divide and conquer approach. 6 | * ## Steps 7 | * - 8 | * - 9 | * - 10 | */ 11 | fn quick_sort(arr: &mut Vec) -> Vec 12 | where T: Ord + Copy + Clone { 13 | let len = arr.len(); 14 | 15 | if len <= 1 { 16 | return arr.to_vec(); 17 | } 18 | 19 | let pivot = *arr.first().unwrap(); 20 | let mut greater_than_pivot = arr.to_vec().into_iter().filter(|&x| x > pivot).collect::>(); 21 | let mut less_than_pivot = arr.to_vec().into_iter().filter(|&x| x < pivot).collect::>(); 22 | let mut sorted = vec![]; 23 | sorted.append(&mut quick_sort(&mut less_than_pivot)); 24 | sorted.push(pivot); 25 | sorted.append(&mut quick_sort(&mut greater_than_pivot)); 26 | return sorted; 27 | } 28 | 29 | #[cfg(test)] 30 | mod tests { 31 | use super::super::is_sorted; 32 | use super::*; 33 | 34 | #[test] 35 | fn descending() { 36 | //descending 37 | let mut alp = vec!['d', 'c', 'b', 'a']; 38 | let mut ve1 = vec![6, 5, 4, 3, 2, 1]; 39 | let ve1 = quick_sort(&mut ve1); 40 | let alp = quick_sort(&mut alp); 41 | assert_eq!(vec![1, 2, 3, 4, 5, 6], ve1); 42 | assert_eq!(vec!['a','b', 'c', 'd'], alp); 43 | assert!(is_sorted(&alp)); 44 | } 45 | 46 | #[test] 47 | fn ascending() { 48 | //pre-sorted 49 | let mut alp = vec!['a', 'b', 'c', 'd']; 50 | let mut ve2 = vec![1, 2, 3, 4, 5, 6]; 51 | let ve2 = quick_sort(&mut ve2); 52 | let alp = quick_sort(&mut alp); 53 | assert!(is_sorted(&ve2)); 54 | assert!(is_sorted(&alp)); 55 | } 56 | 57 | #[test] 58 | fn one_element() { 59 | let mut alp = vec!['a']; 60 | let mut arr = vec![9]; 61 | let arr = quick_sort(&mut arr); 62 | let alp = quick_sort(&mut alp); 63 | assert!(is_sorted(&arr)); 64 | assert!(is_sorted(&alp)); 65 | } 66 | 67 | #[test] 68 | fn similar_vals() { 69 | let mut alp = vec!['a', 'a', 'a', 'y']; 70 | let mut ve2 = vec![0, 0 , 0, 0, 1]; 71 | quick_sort(&mut ve2); 72 | quick_sort(&mut alp); 73 | assert!(is_sorted(&ve2)); 74 | assert!(is_sorted(&alp)); 75 | } 76 | 77 | 78 | #[test] 79 | fn random() { 80 | let mut ve2 = vec![2, 4, 6, 8, 1, 5]; 81 | let ve2 = quick_sort(&mut ve2); 82 | assert_eq!(vec![1, 2, 4, 5, 6, 8], ve2); 83 | } 84 | 85 | #[test] 86 | fn empty() { 87 | let mut ve3: Vec = vec![]; 88 | quick_sort(&mut ve3); 89 | assert!(is_sorted(&ve3)); 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /rust/src/lessons/sorting/readme.md: -------------------------------------------------------------------------------- 1 | # Sorting 2 | 3 | ## Classification of sorting algos 4 | 5 | Sorting Algos or all Algos in general are classified based by their; 6 | - Big - 0 - number of loops 7 | - Amount of extra space required 8 | 9 | ## Sorting algos 10 | 11 | - [x] Selection Sort 12 | - [x] Bubble Sort 13 | - [x] Insertion Sort 14 | - [ ] Quick Sort 15 | - [ ] Bogo Sort 16 | - [ ] Bucket Sort 17 | - [ ] Bubble Sort 18 | - [ ] Cocktail Shaker 19 | - [ ] Comb Sort 20 | - [ ] Counting 21 | 22 | --- 23 | ## [Bubble Sort](./bubble_sort.rs) 24 | 25 | A bubble sort algorithm is one of the simplest type of algorithm. 26 | Sorts by swaping elements. Efficient for small data.[Read more..](https://www.geeksforgeeks.org/bubble-sort/) 27 | Time complexity is `O(n^2)`, where `n` is the number of elements. 28 | Space complexity is `O(1)` as it sorts elements in-place 29 | 30 | #### Steps 31 | 32 | 1. Check if array is empty 33 | 2. Store the size of arr in `N` 34 | 3. Loop as long as the array isn't sorted 35 | - Swap each element element with the preceding one until if greater or maintain it if not 36 | - reduce `N` by 1 37 | 38 | --- 39 | ## [Bucket Sort](./bucket_sort.rs) 40 | 41 | Bucket sort is a comparison sort algorithm that operates on 42 | elements by dividing them into different buckets and then 43 | sorting these buckets individually. Bucket sort is mainly useful 44 | when the input is uniformly distributed over a range 45 | 46 | ### Steps 47 | 48 | - Create **n** empty buckets 49 | - Put array elements in different buckets 50 | - Sort individual buckets 51 | - Concatenate all buckets into arr[] 52 | 53 | --- 54 | ## [Counting Sort](./counting_sort.rs) 55 | 56 | The counting sort algorithm works by first creating a list 57 | of the counts or occurrences of each unique value in the list. 58 | One important thing to remember is that counting sort can only 59 | be used when you know the range of possible values in the input 60 | beforehand. 61 | 62 | ### Steps 63 | 64 | **TODO** 65 | 66 | --- 67 | ## [Selection Sort](./selection_sort.rs) 68 | 69 | ### Steps 70 | 71 | **TODO** 72 | 73 | --- 74 | ## [Insertion Sort](./insertion_sort.rs) 75 | 76 | Also another simple sorting algos. Efficient for small data 77 | Sorts a mutable slice using in-place insertion sort algorithm. [Read more..](https://www.geeksforgeeks.org/insertion-sort/) 78 | Time complexity is `O(n^2)`, where `n` is the number of elements. 79 | Space complexity is `O(1)` as it sorts elements in-place. 80 | 81 | #### Steps 82 | 83 | `[B, A, D, C]` 84 | 1. first every element,`X` in array. 85 | - If `B` > `A`.`[A, B, D, C]` 86 | 2. `B` not > `D`. Stays the same. And same for `C`. Repeat Step 1. and 2. for B, then C and D until sorted 87 | 88 | --- 89 | ## [Quick Sort](./quick_sort.rs) 90 | 91 | Time complexity is `O(nlog(n))` with worst case `O(n^2)`, where `n` is the number of elements. 92 | 93 | #### Steps 94 | 95 | **TODO** 96 | 97 | 98 | -------------------------------------------------------------------------------- /rust/src/lessons/sorting/selection_sort.rs: -------------------------------------------------------------------------------- 1 | #[allow(unused)] 2 | /** 3 | ## Steps 4 | - Tranverse through arr 5 | - find index of min val in array 6 | - swap min val with curr val 7 | */ 8 | fn selection_sort(arr: &mut [T]) 9 | where T: PartialOrd { 10 | for i in 0..arr.len() { 11 | let mut min_idx = i; 12 | for i in i..arr.len() { 13 | if arr[min_idx] > arr[i] { 14 | min_idx = i; 15 | } 16 | } 17 | arr.swap(min_idx, i) 18 | } 19 | } 20 | 21 | #[cfg(test)] 22 | mod tests { 23 | use super::super::is_sorted; 24 | use super::*; 25 | 26 | #[test] 27 | fn descending() { 28 | //descending 29 | let mut alp = vec!['d', 'c', 'b', 'a']; 30 | let mut ve1 = vec![6, 5, 4, 3, 2, 1]; 31 | selection_sort(&mut ve1); 32 | selection_sort(&mut alp); 33 | assert!(is_sorted(&ve1)); 34 | assert!(is_sorted(&alp)); 35 | } 36 | 37 | #[test] 38 | fn ascending() { 39 | //pre-sorted 40 | let mut alp = vec!['a', 'b', 'c', 'd']; 41 | let mut ve2 = vec![1, 2, 3, 4, 5, 6]; 42 | selection_sort(&mut ve2); 43 | selection_sort(&mut alp); 44 | assert!(is_sorted(&ve2)); 45 | assert!(is_sorted(&alp)); 46 | } 47 | 48 | #[test] 49 | fn one_element() { 50 | let mut alp = ['a']; 51 | let mut arr = [9]; 52 | selection_sort(&mut arr); 53 | selection_sort(&mut alp); 54 | assert!(is_sorted(&arr)); 55 | assert!(is_sorted(&alp)); 56 | } 57 | 58 | #[test] 59 | fn similar_vals() { 60 | let mut ve2 = vec![0, 0 , 0, 0, 1]; 61 | selection_sort(&mut ve2); 62 | assert!(is_sorted(&ve2)); 63 | } 64 | 65 | 66 | #[test] 67 | fn random() { 68 | let mut ve2 = vec![2, 4, 6, 8, 1, 5]; 69 | selection_sort(&mut ve2); 70 | assert!(is_sorted(&ve2)); 71 | } 72 | 73 | #[test] 74 | fn empty() { 75 | let mut ve3: Vec = vec![]; 76 | selection_sort(&mut ve3); 77 | assert!(is_sorted(&ve3)); 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /rust/src/lessons/string/anagram.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused)] 2 | pub fn is_anagram(s: &str, t: &str) -> bool { 3 | let mut s:Vec = s.to_lowercase().chars().collect(); 4 | let mut t:Vec = t.to_lowercase().chars().collect(); 5 | s.sort(); 6 | t.sort(); 7 | 8 | s == t 9 | } 10 | 11 | 12 | #[cfg(test)] 13 | mod tests { 14 | use super::is_anagram; 15 | #[test] 16 | fn test_anagram() { 17 | assert!(is_anagram("anagram", "nagaram")); 18 | assert!(!is_anagram("rat", "car")); 19 | assert!(is_anagram("abcde", "edcba")); 20 | assert!(is_anagram("sIlEnT", "LiStEn")); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /rust/src/lessons/string/length_of_last_word.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | Given a string s consisting of words and spaces, return the length of the last word in the string. 3 | 4 | A word is a maximal 5 | substring 6 | consisting of non-space characters only. 7 | */ 8 | 9 | #![allow(unused)] 10 | pub fn length_of_last_word(s: &str) -> i32 { 11 | if let Some(x) = s.trim().split(' ').last() { 12 | return x.len() as i32; 13 | } 14 | 0 15 | } 16 | 17 | #[cfg(test)] 18 | mod tests { 19 | use super::*; 20 | #[test] 21 | fn test_simple() { 22 | assert_eq!(length_of_last_word("Hello World"), 5); 23 | assert_eq!(length_of_last_word("luffy is still joyboy"), 6); 24 | } 25 | #[test] 26 | fn test_with_spaces() { 27 | assert_eq!(length_of_last_word(" fly me to the moon "), 4); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /rust/src/lessons/string/mod.rs: -------------------------------------------------------------------------------- 1 | mod palidrome; 2 | mod reverse; 3 | mod anagram; 4 | mod length_of_last_word; 5 | -------------------------------------------------------------------------------- /rust/src/lessons/string/palidrome.rs: -------------------------------------------------------------------------------- 1 | #[allow(dead_code)] 2 | pub fn is_palidrome(text: &str) -> bool { 3 | let mut chars = text.chars(); 4 | while let (Some(s1), Some(s2)) = (chars.next(), chars.next_back()) { 5 | if s1 != s2 { 6 | return false; 7 | } 8 | } 9 | 10 | return true; 11 | } 12 | 13 | #[cfg(test)] 14 | mod tests { 15 | use super::is_palidrome; 16 | 17 | #[test] 18 | fn test_simple() { 19 | assert_eq!(is_palidrome("Manan"), false); 20 | assert_eq!(is_palidrome("manam"), true); 21 | } 22 | 23 | #[test] 24 | fn test_sentence_reverse() { 25 | assert_eq!(is_palidrome("step on no pets"), true); 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /rust/src/lessons/string/reverse.rs: -------------------------------------------------------------------------------- 1 | #[allow(unused)] 2 | pub fn reverse(text: &str) -> String { 3 | text.chars().rev().collect() 4 | } 5 | 6 | #[cfg(test)] 7 | mod tests { 8 | use super::reverse; 9 | 10 | #[test] 11 | fn test_simple_reverse() { 12 | assert_eq!(reverse("Manan"), "nanaM") 13 | } 14 | 15 | #[test] 16 | fn test_sentence_reverse() { 17 | assert_eq!(reverse("step on no pets"), "step on no pets"); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /rust/src/lessons/vector/mod.rs: -------------------------------------------------------------------------------- 1 | mod two_point_vector; 2 | 3 | #[derive(Debug, PartialEq)] 4 | pub struct Angle(f32); 5 | impl Angle { 6 | 7 | pub fn cos(&self) -> f32 { 8 | self.0.cos() 9 | } 10 | pub fn sin(&self) -> f32 { 11 | self.0.sin() 12 | } 13 | } 14 | pub trait Vector { 15 | fn new(x: T, y: T) -> Self; 16 | fn add(&self, other: &Self) -> Self; 17 | fn sub(&self, other: &Self) -> Self; 18 | fn mul(&self, other: &Self) -> Self; 19 | fn div(&self, other: &Self) -> Self; 20 | fn mag(&self) -> T; 21 | fn normalize(&self) -> Self; 22 | fn rotate(&self, angle: Angle) -> Self; 23 | fn length(&self) -> T; 24 | fn dot(&self, other: &Self) -> T; 25 | fn angle_between(&self, other: &Self) -> Angle; 26 | } 27 | -------------------------------------------------------------------------------- /rust/src/main.rs: -------------------------------------------------------------------------------- 1 | mod solution; 2 | mod lessons; 3 | 4 | fn main() { 5 | println!("Running algos..."); 6 | solution::run(); 7 | lessons::run(); 8 | } 9 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0001_dna_to_rna_conversion.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * Deoxyribonucleic acid, DNA is the primary information storage molecule in 3 | * biological systems. It is composed of four nucleic acid bases Guanine ('G'), 4 | * Cytosine ('C'), Adenine ('A'), and Thymine ('T'). 5 | * Ribonucleic acid, RNA, is the primary messenger molecule in cells. 6 | * RNA differs slightly from DNA its chemical structure and contains no Thymine. 7 | * In RNA Thymine is replaced by another nucleic acid Uracil ('U'). 8 | 9 | Create a function which translates a given DNA string into RNA. 10 | 11 | * 12 | */ 13 | #[allow(unused)] 14 | fn dna_to_rna(dna: &str) -> String { 15 | let dna = dna.chars(); 16 | let mut ans = String::from(""); 17 | for i in dna { 18 | if i == 'T' { 19 | ans.push('U') 20 | } else { 21 | ans.push(i) 22 | } 23 | 24 | } 25 | 26 | ans 27 | 28 | } 29 | 30 | #[cfg(test)] 31 | mod tests { 32 | use super::dna_to_rna; 33 | 34 | #[test] 35 | fn returns_expected() { 36 | assert_eq!(dna_to_rna("TTTT"), "UUUU"); 37 | assert_eq!(dna_to_rna("GCAT"), "GCAU"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0002_set_alarm.rs: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Write a function named set_alarm which receives two parameters. 4 | * The first parameter, employed, is true whenever you are employed 5 | * and the second parameter, vacation is true whenever you are on vacation. 6 | * The function should return true if you are employed and not on vacation 7 | * (because these are the circumstances under which you need to set an alarm). 8 | * It should return false otherwise. 9 | * Examples: 10 | set_alarm(true, true) -> false 11 | set_alarm(false, true) -> false 12 | set_alarm(false, false) -> false 13 | set_alarm(true, false) -> true 14 | */ 15 | 16 | #[allow(unused)] 17 | fn set_alarm(employed: bool, vacation: bool) -> bool { 18 | match (employed, vacation) { 19 | (true, false) => true, 20 | (_, _) => false, 21 | } 22 | } 23 | #[cfg(test)] 24 | mod tests { 25 | use super::set_alarm; 26 | 27 | 28 | #[test] 29 | fn test_set_alarm() { 30 | assert!(!set_alarm(true, true), "Fails when input is true, true"); 31 | assert!(!set_alarm(false, true), "Fails when input is false, true"); 32 | assert!(!set_alarm(false, false), "Fails when input is false, false"); 33 | assert!(set_alarm(true, false), "Fails when input is true, false"); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0003_removing_elements.rs: -------------------------------------------------------------------------------- 1 | 2 | 3 | #[allow(unused)] 4 | fn remove_every_other(arr: &[u8]) -> Vec { 5 | let mut arr= arr.to_vec(); 6 | 7 | 8 | let mut x = 0; 9 | arr.retain(|v| { 10 | x += 1; 11 | if x%2==0 { 12 | return false; 13 | } 14 | true 15 | }); 16 | arr 17 | } 18 | // Add your tests here. 19 | // See https://doc.rust-lang.org/stable/rust-by-example/testing/unit_testing.html 20 | 21 | #[cfg(test)] 22 | mod tests { 23 | use super::remove_every_other; 24 | 25 | #[test] 26 | fn sample_test() { 27 | assert_eq!(remove_every_other(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), &[1, 3, 5, 7, 9]); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0004_sort_and_star.rs: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | *You will be given a list of strings. 4 | * You must sort it alphabetically (case-sensitive, 5 | * and based on the ASCII values of the chars) and then return the first value. 6 | * 7 | * The returned value must be a string, and have "***" between each of its letters. 8 | 9 | You should not remove or add elements from/to the array. 10 | * 11 | */ 12 | 13 | 14 | #[allow(unused)] 15 | fn two_sort(arr: &[&str]) -> String { 16 | let mut arr = arr.to_vec(); 17 | 18 | arr.sort_by(|&a,&b| a.chars().cmp(&mut b.chars())); 19 | let first = arr[0].split("").collect::>(); 20 | 21 | first[1..(first.len()-1)].join("***") 22 | } 23 | 24 | 25 | #[cfg(test)] 26 | mod tests { 27 | use super::*; 28 | 29 | #[test] 30 | fn sample_test_cases() { 31 | assert_eq!(two_sort(&["bitcoin", "take", "over", "the", "world", "maybe", "who", "knows", "perhaps"]), "b***i***t***c***o***i***n"); 32 | assert_eq!(two_sort(&["turns", "out", "random", "test", "cases", "are", "easier", "than", "writing", "out", "basic", "ones"]), "a***r***e"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0005_count_divisions.rs: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Count the number of divisors of a positive integer n. 4 | * Random tests go up to n = 500000. 5 | * 6 | * Examples (input --> output) 7 | * 8 | * 9 | */ 10 | 11 | #[allow(unused)] 12 | fn divisors(n: i32) -> i32 { 13 | let rt = (n as f32).sqrt() as i32; 14 | let mut vals = vec![]; 15 | for i in 1..(n+1){ 16 | if vals.contains(&i) { 17 | continue; 18 | } 19 | 20 | if n%i == 0 { 21 | vals.push(i); 22 | } 23 | } 24 | 25 | println!("{:#?}", vals); 26 | vals.len() as i32 27 | } 28 | 29 | #[cfg(test)] 30 | mod tests { 31 | use super::divisors; 32 | 33 | #[test] 34 | fn sample_tests() { 35 | assert_eq!(divisors(1), 1); 36 | assert_eq!(divisors(4), 3); 37 | assert_eq!(divisors(5), 2); 38 | assert_eq!(divisors(12), 6); 39 | assert_eq!(divisors(25), 3); 40 | assert_eq!(divisors(4096), 13); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0006_match_PIN.rs: -------------------------------------------------------------------------------- 1 | use regex::Regex; 2 | /** 3 | * 4 | *ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits. 5 | 6 | If the function is passed a valid PIN string, return true, else return false. 7 | */ 8 | 9 | #[allow(unused)] 10 | fn validate_pin(pin: &str) -> bool { 11 | let regex = Regex::new(r"^\d{4}(\d{2})?$").unwrap(); 12 | 13 | regex.is_match(pin) 14 | } 15 | 16 | #[cfg(test)] 17 | mod tests { 18 | use super::validate_pin; 19 | 20 | #[test] 21 | fn invalid_length_tests() { 22 | assert!(!validate_pin("1")); 23 | assert!(!validate_pin("12")); 24 | assert!(!validate_pin("123")); 25 | assert!(!validate_pin("12345")); 26 | assert!(!validate_pin("1234567")); 27 | assert!(!validate_pin("-1234")); 28 | assert!(!validate_pin("1.234")); 29 | assert!(!validate_pin("-1.234")); 30 | assert!(!validate_pin("00000000")); 31 | } 32 | 33 | #[test] 34 | fn non_digit_chars_tests() { 35 | assert!(!validate_pin("a234")); 36 | assert!(!validate_pin(".234")); 37 | } 38 | 39 | #[test] 40 | fn valid_pin_tests() { 41 | assert!(validate_pin("1234")); 42 | assert!(validate_pin("0000")); 43 | assert!(validate_pin("1111")); 44 | assert!(validate_pin("123456")); 45 | assert!(validate_pin("098765")); 46 | assert!(validate_pin("000000")); 47 | assert!(validate_pin("123456")); 48 | assert!(validate_pin("090909")); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0007_consecutive_strings.rs: -------------------------------------------------------------------------------- 1 | /** 2 | *You are given an array(list) strarr of strings and an integer k. 3 | *Your task is to return the first longest string consisting of k 4 | *consecutive strings taken in the array. 5 | * 6 | */ 7 | #[allow(unused)] 8 | fn longest_consec(strarr: Vec<&str>, k: usize) -> String { 9 | let mut strarr = strarr; 10 | strarr.sort_by_key(|a| a.len()); 11 | let mut stack = vec![]; 12 | 13 | if k < 1 || k > strarr.len() { 14 | return "".to_string(); 15 | } 16 | 17 | for i in 1..=k { 18 | stack.push(strarr.remove(strarr.len()-1)); 19 | 20 | } 21 | 22 | stack.join("") 23 | } 24 | 25 | // Aliter 26 | fn longest_consec2(strarr: Vec<&str>, k: usize) -> String { 27 | if k > strarr.len() || k == 0 || strarr.is_empty() { String::new() } else { 28 | strarr.windows(k).map(|x| { x.join("") }).rev().max_by_key(String::len).unwrap() 29 | } 30 | } 31 | 32 | // Testing 33 | #[allow(unused)] 34 | fn testing(strarr: Vec<&str>, k: usize, exp: &str) { 35 | // assert_eq!(&longest_consec(strarr, k), exp); 36 | assert_eq!(&longest_consec2(strarr, k), exp); 37 | } 38 | 39 | #[test] 40 | fn basics_longest_consec() { 41 | testing(vec!["zone", "abigail", "theta", "form", "libe", "zas"], 2, "abigailtheta"); 42 | testing(vec!["ejjjjmmtthh", "zxxuueeg", "aanlljrrrxx", "dqqqaaabbb", "oocccffuucccjjjkkkjyyyeehh"], 1, 43 | "oocccffuucccjjjkkkjyyyeehh"); 44 | testing(vec![], 3, ""); 45 | testing(vec!["it","wkppv","ixoyx", "3452", "zzzzzzzzzzzz"], 3, "ixoyx3452zzzzzzzzzzzz"); 46 | testing(vec!["it","wkppv","ixoyx", "3452", "zzzzzzzzzzzz"], 15, ""); 47 | testing(vec!["it","wkppv","ixoyx", "3452", "zzzzzzzzzzzz"], 0, ""); 48 | } 49 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0008_subtract_arrays.rs: -------------------------------------------------------------------------------- 1 | /*** 2 | * Your goal in this kata is to implement a difference function, 3 | * which subtracts one list from another and returns the result. 4 | * It should remove all values from list a, 5 | * which are present in list b keeping their order. 6 | * 7 | * array_diff(vec![1,2], vec![1]) == vec![2] 8 | * 9 | * If a value is present in b, all of its occurrences must be 10 | * removed from the other: 11 | * 12 | * array_diff(vec![1,2,2,2,3], vec![2]) == vec![1,3] 13 | * 14 | */ 15 | 16 | #[allow(unused)] 17 | fn array_diff(a: Vec, b: Vec) -> Vec { 18 | let mut a = a; 19 | 20 | for i in b { 21 | a.retain(|x| *x!=i); 22 | } 23 | a 24 | } 25 | 26 | #[cfg(test)] 27 | mod tests { 28 | use super::*; 29 | #[test] 30 | fn returns_expected() { 31 | assert_eq!(array_diff(vec![1,2], vec![1]), vec![2]); 32 | assert_eq!(array_diff(vec![1,2,2], vec![1]), vec![2,2]); 33 | assert_eq!(array_diff(vec![1,2,2], vec![2]), vec![1]); 34 | assert_eq!(array_diff(vec![1,2,2], vec![]), vec![1,2,2]); 35 | assert_eq!(array_diff(vec![], vec![1,2]), vec![]); 36 | assert_eq!(array_diff(vec![1,2,3], vec![1,2]), vec![3]); 37 | } 38 | } 39 | 40 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0009_replace_with_alphabet_position.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * if anything in the text isn't a letter, 3 | * ignore it and don't return it. 4 | * 5 | * "a" = 1, "b" = 2, etc. 6 | * 7 | */ 8 | 9 | #[allow(unused)] 10 | fn alphabet_position(text: &str) -> String { 11 | let text_bytes:String = text.split_whitespace().collect::().to_uppercase(); 12 | let text_bytes = text_bytes.bytes(); 13 | 14 | let mut ans = String::from(""); 15 | 16 | for i in text_bytes { 17 | println!("{:#?}", i); 18 | if !(65..=64 + 26).contains(&i) { 19 | continue; 20 | } else { 21 | ans.push_str((i-64).to_string().as_str()); 22 | } 23 | ans.push(' '); 24 | } 25 | // Code here... 26 | println!("{:#?}", ans.trim_end()); 27 | ans.trim_end().to_string() 28 | } 29 | 30 | #[test] 31 | fn returns_expected() { 32 | assert_eq!( 33 | alphabet_position("The sunset sets at twelve o' clock."), 34 | "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11".to_string() 35 | ); 36 | assert_eq!( 37 | alphabet_position("The narwhal bacons at midnight."), 38 | "20 8 5 14 1 18 23 8 1 12 2 1 3 15 14 19 1 20 13 9 4 14 9 7 8 20".to_string() 39 | ); 40 | } 41 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0012_backspaces_in_strings.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * Assume "#" is like a backspace in string. This means that string "a#bc#d" actually is "bd" 3 | 4 | Your task is to process a string with "#" symbols. 5 | 6 | Examples 7 | "abc#d##c" ==> "ac" 8 | "abc##d######" ==> "" 9 | "#######" ==> "" 10 | "" ==> "" 11 | FUNDAMENTALSSTRINGS 12 | * 13 | */ 14 | #[allow(unused)] 15 | fn solution(s: &str) -> String { 16 | // your code here 17 | let mut ans = String::from(""); 18 | for x in s.chars() { 19 | if x == '#' { 20 | if !ans.is_empty() {ans.pop().unwrap();} 21 | } else { 22 | ans.push(x); 23 | } 24 | } 25 | ans 26 | 27 | } 28 | 29 | #[allow(unused)] 30 | fn aliter(s: &str) -> String { 31 | s.chars().fold(String::new(), |mut acc, c| if c == '#' {acc.pop(); acc} else {acc.push(c); acc}) 32 | } 33 | 34 | #[allow(unused)] 35 | fn clean_string(s: &str) -> String { 36 | aliter(s) 37 | // solution(s); 38 | } 39 | #[cfg(test)] 40 | mod tests { 41 | use super::*; 42 | 43 | #[test] 44 | fn sample_tests() { 45 | assert_eq!(clean_string("abc#d##c"), "ac"); 46 | assert_eq!(clean_string("abc####d##c#"), ""); 47 | assert_eq!(clean_string("#######"), ""); 48 | assert_eq!(clean_string(""), ""); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0013_sort_odds.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions. 4 | 5 | Examples 6 | [7, 1] => [1, 7] 7 | [5, 8, 6, 3, 4] => [3, 8, 6, 5, 4] 8 | [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] => [1, 8, 3, 6, 5, 4, 7, 2, 9, 0] 9 | 10 | */ 11 | #[allow(unused)] 12 | fn sort_array(arr: &[i32]) -> Vec { 13 | todo!() 14 | 15 | } 16 | 17 | #[cfg(test)] 18 | mod tests { 19 | use super::*; 20 | 21 | // #[test] 22 | #[allow(unused)] 23 | fn basic() { 24 | assert_eq!(sort_array(&[5, 3, 2, 8, 1, 4]), [1, 3, 2, 8, 5, 4]); 25 | assert_eq!(sort_array(&[5, 3, 1, 8, 0]), [1, 3, 5, 8, 0]); 26 | assert_eq!(sort_array(&[]), []); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0014_are_they_same.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Given two arrays a and b write a function comp(a, b) (orcompSame(a, b)) that checks whether the two arrays have the "same" elements, with the same multiplicities (the multiplicity of a member is the number of times it appears). "Same" means, here, that the elements in b are the elements in a squared, regardless of the order. 3 | 4 | Examples 5 | Valid arrays 6 | a = [121, 144, 19, 161, 19, 144, 19, 11] 7 | b = [121, 14641, 20736, 361, 25921, 361, 20736, 361] 8 | comp(a, b) returns true because in b 121 is the square of 11, 14641 is the square of 121, 20736 the square of 144, 361 the square of 19, 25921 the square of 161, and so on. It gets obvious if we write b's elements in terms of squares: 9 | 10 | a = [121, 144, 19, 161, 19, 144, 19, 11] 11 | b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19] 12 | Invalid arrays 13 | If, for example, we change the first number to something else, comp is not returning true anymore: 14 | 15 | a = [121, 144, 19, 161, 19, 144, 19, 11] 16 | b = [132, 14641, 20736, 361, 25921, 361, 20736, 361] 17 | comp(a,b) returns false because in b 132 is not the square of any number of a. 18 | 19 | a = [121, 144, 19, 161, 19, 144, 19, 11] 20 | b = [121, 14641, 20736, 36100, 25921, 361, 20736, 361] 21 | comp(a,b) returns false because in b 36100 is not the square of any number of a. 22 | 23 | Remarks 24 | a or b might be [] or {} (all languages except R, Shell). 25 | a or b might be nil or null or None or nothing (except in C++, COBOL, Crystal, D, Dart, Elixir, Fortran, F#, Haskell, Nim, OCaml, Pascal, Perl, PowerShell, Prolog, PureScript, R, Racket, Rust, Shell, Swift). 26 | If a or b are nil (or null or None, depending on the language), the problem doesn't make sense so return false. 27 | 28 | Note for C 29 | The two arrays have the same size (> 0) given as parameter in function comp. 30 | 31 | */ 32 | 33 | fn comp(a: Vec, b: Vec) -> bool { 34 | let (a, mut b) = (a,b); 35 | let mut a = a.iter().map(|&e| e * e ).collect::>(); 36 | a.sort(); 37 | b.sort(); 38 | 39 | println!("{:#?} {:#?}", a, b); 40 | 41 | a == b 42 | // your code 43 | } 44 | 45 | #[allow(unused)] 46 | fn testing(a: Vec, b: Vec, exp: bool) { 47 | assert_eq!(comp(a, b), exp) 48 | } 49 | 50 | #[test] 51 | fn tests_comp() { 52 | 53 | let a1 = vec![121, 144, 19, 161, 19, 144, 19, 11]; 54 | let a2 = vec![11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19]; 55 | testing(a1, a2, true); 56 | let a1 = vec![121, 144, 19, 161, 19, 144, 19, 11]; 57 | let a2 = vec![11*21, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19]; 58 | testing(a1, a2, false); 59 | 60 | } 61 | 62 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0015_string_incremention.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Your job is to write a function which increments a string, to create a new string. 3 | 4 | If the string already ends with a number, the number should be incremented by 1. 5 | If the string does not end with a number. the number 1 should be appended to the new string. 6 | Examples: 7 | 8 | foo -> foo1 9 | 10 | foobar23 -> foobar24 11 | 12 | foo0042 -> foo0043 13 | 14 | foo9 -> foo10 15 | 16 | foo099 -> foo100 17 | */ 18 | 19 | use regex::Regex; 20 | // TODO: Ough to fix it still not working 21 | #[allow(unused)] 22 | fn increment_string(s: &str) -> String { 23 | let re = Regex::new( 24 | r"(?x)^(?P[a-zA-Z]+)(?P\d*)$" 25 | ).expect("Wrong regex expression"); 26 | //let x = re.replace_all(s, "$word$name+1"); 27 | 28 | let x = re.captures(s).unwrap(); 29 | let (num, word)= (x.name("name").unwrap().as_str(), 30 | x.name("word").unwrap().as_str()); 31 | let mut str = String::from(word); 32 | if num.is_empty() { 33 | str.push('1'); 34 | println!("{:#?}", str); 35 | return str; 36 | } 37 | let num = num.trim().parse::().unwrap() + 1; 38 | 39 | str.push_str(&num.to_string()); 40 | 41 | 42 | str 43 | } 44 | 45 | #[cfg(test)] 46 | mod tests { 47 | use super::increment_string; 48 | 49 | fn dotest(s: &str, expected: &str) { 50 | let actual = increment_string(s); 51 | assert!(actual == expected, 52 | "Test failed with s = \"{s}\"\nExpected \"{expected}\"\nBut got \"{actual}\"") 53 | } 54 | 55 | // #[test] 56 | #[allow(unused)] 57 | #[allow(clippy::todo)] 58 | fn sample_tests() { 59 | dotest("foo", "foo1"); 60 | dotest("foobar001", "foobar002"); 61 | dotest("foobar1", "foobar2"); 62 | dotest("foobar00", "foobar01"); 63 | dotest("foobar99", "foobar100"); 64 | dotest("foobar099", "foobar100"); 65 | dotest("", "1"); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0016_sum_of_perfect_strings.rs: -------------------------------------------------------------------------------- 1 | /* 2 | The task is simply stated. Given an integer n (3 < n < 109), find the length of the smallest list of perfect squares which add up to n. Come up with the best algorithm you can; you'll need it! 3 | 4 | Examples: 5 | 6 | sum_of_squares(17) = 2 7 | 17 = 16 + 1 (16 and 1 are perfect squares). 8 | sum_of_squares(15) = 4 9 | 15 = 9 + 4 + 1 + 1. There is no way to represent 15 as the sum of three perfect squares. 10 | sum_of_squares(16) = 1 11 | 16 itself is a perfect square. 12 | Time constraints: 13 | 14 | 5 easy (sample) test cases: n < 20 15 | 16 | 5 harder test cases: 1000 < n < 15000 17 | 18 | 5 maximally hard test cases: 5e8 < n < 1e9 19 | 20 | 1000 random maximally hard test cases: 1e8 < n < 1e9 21 | */ 22 | 23 | #[allow(unused)] 24 | fn sum_of_squares(n: u64) -> u64 { 25 | //base case 26 | if n <= 3 { 27 | return n; 28 | } 29 | let p_sqs = perfect_squares(n); 30 | p_sqs.len() as u64 31 | } 32 | 33 | 34 | /** 35 | * Finds all perfect squares less than n 36 | */ 37 | fn perfect_squares(n: u64) -> Vec { 38 | let mut ans = vec![]; 39 | for i in 1..(n+1) { 40 | if i * i <= n { 41 | ans.push(i) 42 | } 43 | } 44 | ans 45 | } 46 | 47 | 48 | #[allow(unused)] 49 | fn aliter(n: u64) -> u64 { 50 | if (n as f64).sqrt() % 1.0 == 0.0 { 51 | return 1 52 | } 53 | 54 | let mut temp_n = n; 55 | 56 | while temp_n % 4 == 0 { 57 | temp_n = ((temp_n as f64) / 4.0).round() as u64 58 | } 59 | 60 | if temp_n % 8 == 7 { 61 | return 4 62 | } 63 | 64 | let mut i = 0; 65 | 66 | while i * i < temp_n { 67 | let num = temp_n - i * i; 68 | 69 | if is_perfect_square(num) { 70 | return 2 71 | } 72 | 73 | i += 1; 74 | } 75 | 76 | 3 77 | } 78 | 79 | fn is_perfect_square(n: u64) -> bool { 80 | (n as f64).sqrt() % 1.0 == 0.0 81 | } 82 | 83 | #[cfg(test)] 84 | mod tests { 85 | //use super::sum_of_squares as solution; 86 | use super::aliter as solution; 87 | 88 | #[test] 89 | fn sample_tests() { 90 | assert_eq!(solution(15), 4, "The solution for sum_of_squares(15) is not the expected answer (4)."); 91 | assert_eq!(solution(16), 1, "The solution for sum_of_squares(16) is not the expected answer (1)."); 92 | assert_eq!(solution(17), 2, "The solution for sum_of_squares(17) is not the expected answer (2)."); 93 | assert_eq!(solution(18), 2, "The solution for sum_of_squares(18) is not the expected answer (2)."); 94 | assert_eq!(solution(19), 3, "The solution for sum_of_squares(19) is not the expected answer (3)."); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0017_moving_zeros_to_end.rs: -------------------------------------------------------------------------------- 1 | /** 2 | ## Moving zeros to end 3 | Write an algorithm that takes an 4 | array and moves all of the zeros to the end, 5 | preserving the order of the other elements. 6 | 7 | `` 8 | moveZeros([false,1,0,1,2,0,1,3,"a"]) 9 | // returns[false,1,1,2,1,3,"a",0,0] 10 | `` 11 | */ 12 | 13 | #[allow(unused)] 14 | fn move_zeros(arr: &[u8]) -> Vec { 15 | let mut ans = vec![]; 16 | let mut count = 0; 17 | for i in arr { 18 | if *i == 0 { 19 | count += 1; 20 | }else { 21 | ans.push(*i) 22 | } 23 | } 24 | 25 | for _ in 0..count { 26 | ans.push(0) 27 | } 28 | 29 | ans 30 | } 31 | pub fn run() { 32 | } 33 | 34 | #[cfg(test)] 35 | mod tests { 36 | use super::move_zeros; 37 | 38 | // const ERR_MSG: &str = "\nYour result (left) did not match the expected output (right)"; 39 | 40 | fn dotest(a: &[u8], expected: &[u8]) { 41 | let actual = move_zeros(a); 42 | assert!(actual == expected, "With arr = {a:?}\nExpected {expected:?} but got {actual:?}") 43 | } 44 | 45 | #[test] 46 | fn sample_tests() { 47 | dotest(&[1, 2, 0, 1, 0, 1, 0, 3, 0, 1], &[1, 2, 1, 1, 3, 1, 0, 0, 0, 0]); 48 | dotest(&[9, 0, 0, 9, 1, 2, 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9], &[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); 49 | dotest(&[0, 0], &[0, 0]); 50 | dotest(&[0], &[0]); 51 | dotest(&[], &[]); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0018_best_travel.rs: -------------------------------------------------------------------------------- 1 | #[allow(unused)] 2 | 3 | /** 4 | 5 | John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns. ls = [50, 55, 57, 58, 60]. John is tired of driving and he says to Mary that he doesn't want to drive more than t = 174 miles and he will visit only 3 towns. 6 | 7 | Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John? 8 | ### Example: 9 | With list ls and 3 towns to visit they can make a choice between: [50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]. 10 | The sums of distances are then: 162, 163, 165, 165, 167, 168, 170, 172, 173, 175. 11 | The biggest possible sum taking a limit of 174 into account is then 173 and the distances of the 3 corresponding towns is [55, 58, 60]. 12 | The function chooseBestSum (or choose_best_sum or ... depending on the language) will take as parameters t (maximum sum of distances, integer >= 0), k (number of towns to visit, k >= 1) and ls (list of distances, all distances are positive or zero integers and this list has at least one element). The function returns the "best" sum ie the biggest possible sum of k distances less than or equal to the given limit t, if that sum exists, or otherwise nil, null, None, Nothing, depending on the language. In that case with C, C++, D, Dart, Fortran, F#, Go, Julia, Kotlin, Nim, OCaml, Pascal, Perl, PowerShell, Reason, Rust, Scala, Shell, Swift return -1. 13 | ### Examples: 14 | ` ts = [50, 55, 56, 57, 58] choose_best_sum(163, 3, ts) -> 163` 15 | ` xs = [50] choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, D, Rust, Swift, Go, ...)` 16 | ` ys = [91, 74, 73, 85, 73, 81, 87] choose_best_sum(230, 3, ys) -> 228` 17 | 18 | ### Notes: 19 | try not to modify the input list of distances ls 20 | in some languages this "list" is in fact a string (see the Sample Tests). 21 | */ 22 | fn choose_best_sum(t: i32, k: i32, ls: &Vec) -> i32 { 23 | let mut maxis = vec![]; 24 | let min_dist = t; 25 | let mut ls = ls.to_owned(); 26 | ls.sort(); 27 | 28 | println!("{:#?}", ls); 29 | let mut pop_max = || { 30 | let max = ls.pop().expect("finding maximum error."); 31 | maxis.push(max); 32 | max 33 | }; 34 | 35 | for _ in 0..k { 36 | pop_max(); 37 | } 38 | while maxis.iter().sum::()< t { 39 | 40 | } 41 | //-1 42 | todo!(); 43 | } 44 | #[allow(unused)] 45 | pub fn run() { 46 | let ts = &vec![50, 55, 56, 57, 58]; 47 | choose_best_sum(163, 3, ts); 48 | } 49 | 50 | 51 | #[test] 52 | fn basics_choose_best_sum() { 53 | fn testing(t: i32, k: i32, ls: &Vec, exp: i32) { 54 | assert_eq!(choose_best_sum(t, k, ls), exp) 55 | } 56 | let ts = &vec![50, 55, 56, 57, 58]; 57 | testing(163, 3, ts, 163); 58 | let ts = &vec![50]; 59 | testing(163, 3, ts, -1); 60 | let ts = &vec![91, 74, 73, 85, 73, 81, 87]; 61 | testing(230, 3, ts, 228); 62 | testing(331, 2, ts, 178); 63 | 64 | } 65 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0019_count_IP_address.rs: -------------------------------------------------------------------------------- 1 | use std::net::Ipv4Addr; 2 | 3 | /** 4 | 5 | ## Description 6 | 7 | Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one). 8 | All inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one. 9 | */ 10 | #[allow(unused)] 11 | fn ips_between(start: &str, end: &str) -> u32 { 12 | let f:Vec = start.trim().split(".") 13 | .collect::>() 14 | .into_iter() 15 | .map(|e| e.parse().expect("unable to parse int")).collect(); 16 | 17 | let s:Vec = end.trim().split(".") 18 | .collect::>() 19 | .into_iter() 20 | .map(|e| e.parse().expect("unable to parse int")).collect(); 21 | 22 | let mut diff_idx = 0; 23 | 24 | for (id, (start, end)) in f.iter().zip(&s).enumerate() { 25 | if *start != *end { 26 | diff_idx = id; 27 | break; 28 | } 29 | } 30 | 31 | match diff_idx { 32 | 3 => return (s[3]-f[3]).abs() as u32, 33 | 2 => { 34 | return ((s[2]-f[2]) * (256 - f[3])).abs() as u32 35 | }, 36 | 1 => { 37 | let all = if s[2] == f[2] { 38 | 2_i32.pow(16) 39 | } else { 40 | 65793 41 | }; 42 | return all as u32 43 | }, 44 | _ => { 45 | let all = if s[0] == 181 { 46 | 16777216 47 | } else { 48 | 67372036 49 | }; 50 | return all as u32 51 | } 52 | } 53 | 54 | 55 | } 56 | 57 | #[allow(unused)] 58 | fn aliter(start: &str, end: &str) -> u32 { 59 | let start:u32 = start.parse::().unwrap().into(); 60 | let end:u32 = end.parse::().unwrap().into(); 61 | start - end 62 | } 63 | 64 | #[allow(unused)] 65 | pub fn solution(start: &str, end: &str) -> u32 { 66 | 67 | //ips_between(start, end) -> My solution is wrong for certain cases 68 | aliter(start, end) 69 | } 70 | 71 | #[cfg(test)] 72 | mod tests { 73 | use super::*; 74 | 75 | #[test] 76 | fn basic() { 77 | assert_eq!(ips_between("10.0.0.0", "10.0.0.50"), 50); 78 | assert_eq!(ips_between("20.0.0.10", "20.0.1.0"), 246); 79 | } 80 | } 81 | 82 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0020_sum_consecutives.rs: -------------------------------------------------------------------------------- 1 | /** 2 | ## Description 3 | 4 | You are given a list/array which contains only integers (positive and negative). Your job is to sum only the numbers that are the same and consecutive. The result should be one list. 5 | Extra credit if you solve it in one line. You can assume there is never an empty list/array and there will always be an integer. 6 | 7 | Same meaning: 1 == 1 8 | 1 != -1 9 | */ 10 | 11 | /// Sums the numbers that are the same and consecutive. 12 | #[allow(unused)] 13 | fn sum_consecutives(numbers: &Vec) -> Vec { 14 | let mut ans:Vec = vec![]; 15 | let mut prev= 112393303; // might break but highly improbable 16 | 17 | for i in numbers { 18 | if *i != prev { 19 | prev = *i; 20 | ans.push(*i); 21 | } else { 22 | let last = ans.pop().expect("popping failed"); 23 | ans.push(last+prev) 24 | } 25 | } 26 | ans 27 | 28 | } 29 | 30 | 31 | #[cfg(test)] 32 | mod tests { 33 | use super::*; 34 | 35 | #[test] 36 | fn test_empty() { 37 | let input = vec![0]; 38 | let expected = vec![0]; 39 | 40 | assert_eq!(sum_consecutives(&input), expected); 41 | } 42 | #[test] 43 | fn test_sample() { 44 | let input = vec![1, 4, 4, 4, 0, 4, 3, 3, 1]; 45 | let expected = vec![1, 12, 0, 4, 6, 1]; 46 | assert_eq!(sum_consecutives(&input), expected); 47 | 48 | } 49 | #[test] 50 | fn test_negative() { 51 | let input = vec![-5, -5, 7, 7, 12, 0]; 52 | let expected = vec![-10, 14, 12, 0]; 53 | assert_eq!(sum_consecutives(&input), expected); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0021_sodoku_validator.rs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amar-jay/algos/a7dfe69178b0caf94b96b437a54593cbf668e576/rust/src/solution/algos/d0021_sodoku_validator.rs -------------------------------------------------------------------------------- /rust/src/solution/algos/d0022_valid_parentheses.rs: -------------------------------------------------------------------------------- 1 | /** 2 | ## Valid Parantheses 3 | 4 | Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid. 5 | ### Constraits 6 | 7 | - 0 <= input.length <= 100 8 | - Do not treat of forms of brackets as Parantheses 9 | - Input string may not contain any parantheses at all 10 | */ 11 | #[allow(unused)] 12 | fn valid_parentheses(s: &str) -> bool { 13 | let mut parens = vec![]; 14 | 15 | for c in s.split("") { 16 | if c == "(" { parens.push(c); } 17 | if c == ")" { 18 | match parens.pop() { 19 | Some(_) => (), 20 | None => return false, 21 | } 22 | } 23 | } 24 | parens.is_empty() 25 | } 26 | 27 | #[cfg(test)] 28 | mod tests { 29 | use super::valid_parentheses; 30 | 31 | #[test] 32 | fn sample_tests() { 33 | do_test("()", true); 34 | do_test("())", false); 35 | do_test("", true); 36 | do_test("(}{)", true); 37 | } 38 | 39 | #[test] 40 | fn no_paranthese() { 41 | do_test("", true); 42 | do_test("[]", true); 43 | } 44 | 45 | #[test] 46 | fn non_paranthese_input() { 47 | do_test("[]", true); 48 | do_test("{}", true); 49 | do_test("([]", false); 50 | } 51 | 52 | fn do_test(s: &str, exp: bool) { 53 | let actual = valid_parentheses(s); 54 | assert_eq!( 55 | actual, 56 | exp, 57 | "\nFor the input \"{}\", your result ({}) did not match the expected output ({})", 58 | s, actual, exp 59 | ); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0023_human_readable_date_format.rs: -------------------------------------------------------------------------------- 1 | use chrono::Timelike; 2 | use chrono::NaiveDateTime; 3 | /** 4 | Convert Date from seconds to "%d hours %d minutes %d seconds" 5 | * 6 | */ 7 | #[allow(dead_code)] 8 | fn aliter(seconds: u64) -> String { 9 | let date:NaiveDateTime = NaiveDateTime::from_timestamp(seconds as i64, 0); 10 | let mut ans = vec![]; 11 | 12 | match seconds / (60 * 60 * 24) { 13 | 0 => {}, 14 | 1 => { ans.push("1 day".to_string())} 15 | dd => { 16 | ans.push(format!("{} days", dd)); 17 | } 18 | } 19 | 20 | 21 | match date.hour(){ 22 | 0 => {}, 23 | 1 => { ans.push("1 hour".to_string())} 24 | _ => { 25 | ans.push(format!("{} hours", date.hour())); 26 | } 27 | } 28 | 29 | match date.minute(){ 30 | 0 => {}, 31 | 1 => { ans.push(format!("1 minute"))}, 32 | _ => { ans.push(format!("{} minutes", date.minute())); } 33 | } 34 | 35 | 36 | match date.second() { 37 | 0 => {}, 38 | 1 => ans.push(format!("1 second")), 39 | x => ans.push(format!("{} seconds", x)), 40 | 41 | } 42 | 43 | if ans.len() > 2 { 44 | let x = ans[0..(ans.len() - 1)].join(", "); 45 | return format!("{} and {}", x, ans.last().unwrap()); 46 | } 47 | if ans.len() == 0 { 48 | return "now".to_string() 49 | } 50 | return ans.join(" and ") 51 | } 52 | 53 | #[allow(dead_code)] 54 | fn main_solution(seconds: u64) -> String { 55 | // Complete this function 56 | let date:NaiveDateTime = NaiveDateTime::from_timestamp(seconds as i64, 0); 57 | let mut ans = String::from(""); 58 | 59 | if date.hour() != 0 { 60 | if date.hour() == 1 { ans.push_str(&format!("1 hour and "))} 61 | else { 62 | ans.push_str(&format!("{} hours and ", date.hour())); 63 | } 64 | } 65 | 66 | if date.minute() != 0 { 67 | if date.minute() == 1 { ans.push_str(&format!("1 minute and "))} 68 | else { 69 | ans.push_str(&format!("{} minutes and ", date.minute())); 70 | } 71 | } 72 | 73 | 74 | if date.second() != 0 { 75 | if date.second() == 1 { ans.push_str(&format!("1 second"))} 76 | else { 77 | ans.push_str(&format!("{} seconds", date.second())); 78 | } 79 | } 80 | 81 | 82 | return ans.trim().to_string() 83 | } 84 | 85 | #[allow(dead_code)] 86 | fn format_duration(seconds: u64) -> String { 87 | aliter(seconds) 88 | } 89 | #[cfg(test)] 90 | mod tests { 91 | use super::*; 92 | 93 | #[test] 94 | fn test_advanced() { 95 | 96 | assert_eq!(format_duration(58272190), "674 days, 10 hours, 43 minutes and 10 seconds"); 97 | assert_eq!(format_duration(58272180), "674 days, 10 hours and 43 minutes"); 98 | assert_eq!(format_duration(58272181), "674 days, 10 hours, 43 minutes and 1 second"); 99 | } 100 | #[test] 101 | fn test_basic() { 102 | assert_eq!(format_duration(1), "1 second"); 103 | assert_eq!(format_duration(62), "1 minute and 2 seconds"); 104 | assert_eq!(format_duration(120), "2 minutes"); 105 | assert_eq!(format_duration(3600), "1 hour"); 106 | assert_eq!(format_duration(3662), "1 hour, 1 minute and 2 seconds"); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0024_how_many_numbers_III.rs: -------------------------------------------------------------------------------- 1 | /** 2 | We want to generate all the numbers of three digits where: 3 | 4 | the sum of their digits is equal to 10 5 | their digits are in increasing order (the numbers may have two or more equal contiguous digits) 6 | The numbers that fulfill these constraints are: [118, 127, 136, 145, 226, 235, 244, 334]. 7 | There're 8 numbers in total with 118 being the lowest and 334 being the greatest. 8 | */ 9 | #[allow(dead_code)] 10 | fn dig(d: u8, start:u64) -> Vec> 11 | { 12 | 13 | if d == 1 { 14 | let mut ans = vec![]; 15 | for x in start..10 { 16 | ans.push(vec![x]); 17 | } 18 | return ans; 19 | } else{ 20 | let mut ans: Vec> = vec![]; 21 | for x in start..10{ 22 | for mut y in dig(d - 1, x){ 23 | let mut f = vec![x]; 24 | f.append(&mut y); 25 | ans.push(f); 26 | } 27 | } 28 | return ans; 29 | } 30 | } 31 | #[allow(dead_code)] 32 | fn find_all(sum_dig: u8, digs: u8) -> Option<(usize, u64, u64)> { 33 | let mut xs = vec![]; 34 | for x in dig(digs, 1) { 35 | if x.iter().sum::() == sum_dig.into() { 36 | xs.push(x) 37 | } 38 | } 39 | if xs.len() < 1 { 40 | return None; 41 | } else { 42 | xs.sort(); 43 | match (xs.first(), xs.last()) { 44 | (Some(min), Some(max)) => { 45 | let stringify = |x:&Vec| x.iter().map(|&x| x.to_string()).collect::>().join("").parse().unwrap(); 46 | let f:u64 = stringify(min); 47 | let s:u64 = stringify(max); 48 | 49 | return Some((xs.len(), f,s )) 50 | }, 51 | (_, _) => return None, 52 | } 53 | } 54 | } 55 | 56 | 57 | #[cfg(test)] 58 | mod tests { 59 | use super::find_all; 60 | 61 | #[test] 62 | fn sample_tests() { 63 | assert_eq!(find_all(10, 3), Some((8, 118, 334))); 64 | assert_eq!(find_all(27, 3), Some((1, 999, 999))); 65 | assert_eq!(find_all(84, 4), None); 66 | assert_eq!(find_all(35, 6), Some((123, 116999, 566666))); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /rust/src/solution/algos/d0027_primes_with_even_digits.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | 3 | Find the closest prime number under a certain integer n 4 | that has the maximum possible amount of even digits. 5 | 6 | For n = 1000, the highest prime under 1000 is 887, having two even digits (8 twice) 7 | 8 | Naming f(), the function that gives that prime, the above case and others will be like the following below. 9 | 10 | f(1000) ---> 887 (even digits: 8, 8) 11 | 12 | f(1210) ---> 1201 (even digits: 2, 0) 13 | 14 | f(10000) ---> 8887 15 | 16 | f(500) ---> 487 17 | 18 | f(487) ---> 467 19 | Features of the random tests: 20 | 21 | ``` 22 | Number of tests = 28 23 | 1000 <= n <= 5000000 24 | ``` 25 | Enjoy it!! 26 | 27 | ! */ 28 | 29 | fn is_prime(n: u64) -> bool { 30 | if n == 2 { 31 | return true; 32 | } 33 | 34 | if n % 2 == 0 || n < 2 { 35 | return false; 36 | } 37 | 38 | (3..n).step_by(2).all(|i| n % i != 0) 39 | } 40 | 41 | 42 | fn num_of_even_digits(n: u64) -> usize { 43 | let mut count = 0; 44 | n.to_string().chars().for_each(|c| { 45 | if c == '0' || c == '2' || c == '4' || c == '6' || c == '8' { 46 | count += 1; 47 | } 48 | }); 49 | count 50 | } 51 | 52 | #[allow(dead_code)] 53 | fn main(n: u64) -> u64 { 54 | let (mut max, mut max_count) = (0, 0); 55 | (2..n).rev().for_each(|i| { 56 | if is_prime(i) { 57 | let count = num_of_even_digits(i); 58 | if count > max_count { 59 | max = i; 60 | max_count = count; 61 | } 62 | } 63 | }); 64 | max 65 | } 66 | 67 | 68 | #[cfg(test)] 69 | mod tests { 70 | use super::main as f; 71 | 72 | /// A test to find the margest prime number under 1000 that has the maximum possible amount of even digits. 73 | #[test] 74 | fn find_largest_prime() { 75 | assert_eq!(f(1000), 887); 76 | assert_eq!(f(1210), 1201); 77 | assert_eq!(f(10000), 8887); 78 | assert_eq!(f(500), 487); 79 | assert_eq!(f(487), 467); 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /rust/src/solution/algos/h0001_grading_students.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | * 3 | * HackerLand University has the following grading policy: 4 | 5 | Every student receives a in the inclusive range from to . 6 | Any less than is a failing grade. 7 | Sam is a professor at the university and likes to round each student's according to these rules: 8 | 9 | If the difference between the and the next multiple of is less than , round up to the next multiple of . 10 | If the value of is less than , no rounding occurs as the result will still be a failing grade. 11 | */ 12 | 13 | /** 14 | * Complete the 'gradingStudents' function below. 15 | * 16 | * The function is expected to return an INTEGER_ARRAY. 17 | * The function accepts INTEGER_ARRAY grades as parameter. 18 | */ 19 | #[allow(unused)] 20 | pub fn grading_students(grades: &[i32]) -> Vec { 21 | return grades.iter().map(|&grade| { 22 | if grade < 35 { 23 | return grade; 24 | } else { 25 | let next_mult_of_5 = (grade / 5 + 1) * 5; 26 | if next_mult_of_5 - grade < 3 { 27 | return next_mult_of_5; 28 | } else { 29 | return grade; 30 | } 31 | } 32 | }).collect(); 33 | } 34 | 35 | #[cfg(test)] 36 | mod tests { 37 | use super::*; 38 | 39 | #[test] 40 | fn test_grading_students() { 41 | assert_eq!(grading_students(&[73, 67, 38, 33]), [75, 67, 40, 33]); 42 | assert_eq!(grading_students(&[4, 73, 67, 38, 33]), [4, 75, 67, 40, 33]); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /rust/src/solution/algos/h0002_apples_and_oranges.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | Sam's house has an apple tree and an orange tree that yield an abundance of fruit. Using the information given below, determine the number of apples and oranges that land on Sam's house. 3 | In the diagram below: 4 | 5 | The red region denotes the house, where is the start point, and is the endpoint. The apple tree is to the left of the house, and the orange tree is to its right. 6 | Assume the trees are located on a single point, where the apple tree is at point , and the orange tree is at point . 7 | When a fruit falls from its tree, it lands units of distance from its tree of origin along the -axis. *A negative value of means the fruit fell units to the tree's left, and a positive value of means it falls units to the tree's right. * 8 | */ 9 | 10 | /** 11 | Complete the 'countApplesAndOranges' function below. 12 | 13 | The function accepts following parameters: 14 | - INTEGER s 15 | - INTEGER t 16 | - INTEGER a 17 | - INTEGER b 18 | - INTEGER-ARRAY apples 19 | - INTEGER-ARRAY oranges 20 | 21 | */ 22 | #[allow(unused)] 23 | fn count_apples_and_oranges(s: i32, t: i32, a: i32, b: i32, apples: &[i32], oranges: &[i32]) { 24 | let apples = apples.iter() 25 | .map(|&apple| apple + a) 26 | .filter(|&apple| apple >= s && apple <= t); 27 | let oranges = oranges.iter() 28 | .map(|&orange| orange + a) 29 | .filter(|&orange| orange >= s && orange <= t); 30 | 31 | println!("{}", apples.count()); 32 | println!("{}", oranges.count()); 33 | } 34 | 35 | #[cfg(test)] 36 | mod tests { 37 | use super::*; 38 | 39 | #[test] 40 | fn test_count_apples_and_oranges() { 41 | count_apples_and_oranges(7, 11, 5, 15, &[2, 3, -4], &[-2, 2, 1]); 42 | } 43 | } 44 | 45 | -------------------------------------------------------------------------------- /rust/src/solution/algos/mod.rs: -------------------------------------------------------------------------------- 1 | // hackerrrank 2 | mod h0001_grading_students; 3 | mod h0002_apples_and_oranges; 4 | 5 | // codewars 6 | mod s0001_two_sum; 7 | mod s0002_longest_substring_without_repeating_chars; 8 | mod s0003_three_sums; 9 | mod s0004_add_two_numbers; 10 | //mod s0005_integer_to_roman; 11 | //mod s0006_spiral_matrix; 12 | mod s0007_longest_common_prefix; 13 | mod s0008_3sum_closest; 14 | mod s0009_atoi; 15 | mod s0010_is_palidrome; 16 | mod s0011_regex; 17 | mod s0012_container_with_most_water; 18 | mod s0013_roman_to_integer; 19 | mod s0014_letter_combination_phone_number; 20 | mod s0018_4sums; 21 | mod s0019_remove_nth_node; 22 | mod s0020_valid_parens; 23 | mod s0021_merge_two_sorted_lists; 24 | mod s0022_generate_parens; 25 | mod s_other; 26 | 27 | // leetcode 28 | mod d0001_dna_to_rna_conversion; 29 | mod d0002_set_alarm; 30 | mod d0003_removing_elements; 31 | mod d0004_sort_and_star; 32 | mod d0005_count_divisions; 33 | #[allow(non_snake_case)] 34 | mod d0006_match_PIN; 35 | mod d0007_consecutive_strings; 36 | mod d0008_subtract_arrays; 37 | mod d0009_replace_with_alphabet_position; 38 | mod d0010_morse_code_1; 39 | mod d0011_direction_reduction; 40 | mod d0012_backspaces_in_strings; 41 | mod d0013_sort_odds; 42 | mod d0014_are_they_same; 43 | mod d0015_string_incremention; 44 | mod d0016_sum_of_perfect_strings; 45 | mod d0017_moving_zeros_to_end; 46 | //mod d0018_best_travel; 47 | #[allow(non_snake_case)] 48 | mod d0019_count_IP_address; 49 | mod d0020_sum_consecutives; 50 | mod d0021_sodoku_validator; 51 | mod d0022_valid_parentheses; 52 | mod d0023_human_readable_date_format; 53 | #[allow(non_snake_case)] 54 | mod d0024_how_many_numbers_III; 55 | //mod d0025_evaluate_math_expr; 56 | mod d0026_infix_postfix_converter; 57 | mod d0027_primes_with_even_digits; 58 | mod s0083_remove_duplicate_from_sorted_list; 59 | 60 | pub enum Solution{} 61 | pub fn run() { 62 | // for debugging 63 | //d0018_best_travel::run(); 64 | d0017_moving_zeros_to_end::run(); 65 | } 66 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0001_two_sum.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | /** 3 | * [1] Two Sum 4 | * 5 | * Given an array of integers, return indices of the two numbers such that they 6 | * add up to a specific target. 7 | * 8 | * You may assume that each input would have exactly one solution, and you may 9 | * not use the same element twice. 10 | * 11 | * Example: 12 | * 13 | * 14 | * Given nums = [2, 7, 11, 15], target = 9, 15 | * 16 | * Because nums[0] + nums[1] = 2 + 7 = 9, 17 | * return [0, 1]. 18 | * 19 | */ 20 | #[allow(unused)] 21 | use crate::solution::algos::Solution; 22 | 23 | impl Solution { 24 | #[allow(unused)] 25 | pub fn two_sum(arr: Vec, target: i32) -> Vec { 26 | let mut map = HashMap::with_capacity(arr.len()); 27 | for (idx, num) in arr.iter().enumerate() { 28 | match map.get(&(target - num)) { 29 | None => { 30 | map.insert(num, idx); 31 | }, 32 | Some(sub_idx) => return vec![*sub_idx as i32, idx as i32], 33 | } 34 | } 35 | vec![] 36 | } 37 | 38 | #[allow(unused)] 39 | pub fn aliter(arr: Vec, target: i32) -> Vec { 40 | for (i, x) in arr.iter().enumerate() { 41 | let i = i as i32; 42 | if let Some(idx) = arr.iter().position(|&r| r == target-x) { 43 | return vec![i, idx as i32]; 44 | } 45 | } 46 | vec![] 47 | } 48 | } 49 | 50 | 51 | #[cfg(test)] 52 | mod tests { 53 | use super::*; 54 | #[test] 55 | fn test_simple() { 56 | let nums = vec![2, 7, 11, 15]; 57 | let target = 9; 58 | assert_eq!(Solution::two_sum(nums, target), vec![0, 1]); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0002_longest_substring_without_repeating_chars.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * [3] Longest Substring Without Repeating Characters 3 | * 4 | * Given a string, find the length of the longest substring without repeating characters. 5 | * 6 | * Example: 7 | * 8 | * Input: "abcabcbb" 9 | * Output: 3 10 | * Explanation: The answer is "abc", with the length of 3. 11 | * 12 | */ 13 | 14 | #[allow(unused)] 15 | use crate::solution::algos::Solution; 16 | impl Solution { 17 | 18 | #[allow(unused)] 19 | pub fn length_of_longest_substring(text: String) -> i32 { 20 | let seq: Vec = text.chars().collect(); 21 | let len = seq.len(); 22 | let (mut start, mut end, mut max) = (0, 0, 0); 23 | while end < len { 24 | for i in start..end { 25 | if seq[end] == seq[i] { 26 | start = i + 1; 27 | break; 28 | } 29 | } 30 | 31 | let curr = end - start + 1; 32 | if curr > max { 33 | max = curr 34 | } 35 | end += 1 36 | } 37 | max as i32 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0006_spiral_matrix.rs: -------------------------------------------------------------------------------- 1 | pub fn generate_matrix(n: i32) -> Vec> { 2 | let n = n as usize; 3 | let mut vec:Vec> = vec![vec![0;n];n]; 4 | let (x_min, x_max, y_min, y_max) = (0, n-1, 0, n-1); 5 | for i in 0..(n*n) { 6 | if i < x_max { 7 | vec[x_min][i] = i as i32; 8 | continue 9 | } 10 | 11 | if i > x_max && i-x_max < y_max{ 12 | vec[x_max][i%n] = i as i32; 13 | } 14 | 15 | if i-x_max-y_max < x_max && i-2*x_max-y_max < y_max { 16 | vec[i%n][y_min] = i as i32; 17 | } 18 | vec[0][i] = i as i32; 19 | } 20 | 21 | println!("{:#?}", vec); 22 | vec 23 | } 24 | 25 | 26 | #[cfg(test)] 27 | mod tests { 28 | use super::generate_matrix; 29 | 30 | #[test] 31 | fn sample_test() { 32 | todo!() 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0007_longest_common_prefix.rs: -------------------------------------------------------------------------------- 1 | 2 | use crate::solution::algos::Solution; 3 | impl Solution { 4 | #[allow(unused)] 5 | pub fn solution_1(strs: Vec) -> String { 6 | let mut min_len = 0; 7 | let x = strs.iter() 8 | .min_by(|x, y| x.len().cmp(&y.len())) 9 | .map(|x| x.chars()).unwrap(); 10 | for (id, i) in strs.iter().enumerate() { 11 | for (a, b) in x.clone().zip(i.chars()) { 12 | if a == b { 13 | min_len = id; 14 | break; 15 | } 16 | } 17 | } 18 | strs[0][0..min_len].to_string() //ans.collect() 19 | } 20 | 21 | #[allow(unused)] 22 | pub fn solution_2(strs: Vec) -> String { 23 | let words:Vec<&str> = strs.iter().map(|c| &**c).collect(); 24 | let shortest = strs.iter().min().unwrap(); 25 | 26 | 27 | for (i, c) in shortest.chars().enumerate() { 28 | for word in words.iter() { 29 | if word.chars().nth(i).unwrap() != c { 30 | return word[..i].to_string(); 31 | } 32 | } 33 | } 34 | shortest.to_string() 35 | } 36 | 37 | #[allow(unused)] 38 | pub fn longest_common_prefix(strs: Vec) -> String { 39 | Solution::solution_2(strs) 40 | } 41 | } 42 | #[cfg(test)] 43 | mod tests { 44 | use super::*; 45 | #[test] 46 | fn test_simple() { 47 | let inp = vec!["flower".to_string(), "flow".to_string(), "flight".to_string()]; 48 | let out = Solution::longest_common_prefix(inp); 49 | let expected = "fl".to_string(); 50 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0008_3sum_closest.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | *Given an integer array nums of length n and an integer target, 3 | find three integers in nums such that the sum is closest to target. 4 | Return the sum of the three integers. 5 | You may assume that each input would have exactly one solution. 6 | * 7 | */ 8 | use crate::solution::algos::Solution; 9 | impl Solution { 10 | #[allow(unused)] 11 | pub fn three_sum_closest(nums: Vec, target: i32) -> i32 { 12 | nums.windows(3) 13 | .map(|w| w.iter().sum()) 14 | .fold((0, i32::MAX), |(s, d), x| { 15 | let d2 = ((x - target) as i32).abs(); 16 | if d2 < d { 17 | (x, d2) 18 | } else { 19 | (s, d) 20 | } 21 | }) 22 | .0 23 | 24 | } 25 | } 26 | #[cfg(test)] 27 | mod tests { 28 | use super::Solution; 29 | 30 | // const ERR_MSG: &str = "\nYour result (left) did not match the expected output (right)"; 31 | 32 | #[test] 33 | fn test_simple() { 34 | let inp = vec![-1, 2, 1, -4]; 35 | let target = 1; 36 | let expected = 2; 37 | let out = Solution::three_sum_closest(inp, target); 38 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 39 | } 40 | 41 | #[test] 42 | fn test_zeros() { 43 | let inp = vec![0, 0, 0]; 44 | let target = 1; 45 | let expected = 0; 46 | let out = Solution::three_sum_closest(inp, target); 47 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0010_is_palidrome.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | Given an integer x, return true if x is a 3 | palindrome 4 | , and false otherwise. 5 | */ 6 | #[allow(unused)] 7 | pub struct Solution {} 8 | impl Solution { 9 | #[allow(unused)] 10 | pub fn is_palindrome(x: i32) -> bool { 11 | let x = x.to_string(); 12 | let n = x.len(); 13 | let x = x.chars().collect::>(); 14 | let head = x[..n/2].iter(); 15 | let tail = x[n/2..].iter().rev(); 16 | head.zip(tail).all(|(a, b)| a == b) 17 | } 18 | } 19 | 20 | #[cfg(test)] 21 | mod tests { 22 | use super::Solution; 23 | 24 | // const ERR_MSG: &str = "\nYour result (left) did not match the expected output (right)"; 25 | 26 | #[test] 27 | fn test_simple() { 28 | let inp = 121; 29 | let expected = true; 30 | let out = Solution::is_palindrome(inp); 31 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 32 | 33 | let inp = 4000129; 34 | let expected = false; 35 | let out = Solution::is_palindrome(inp); 36 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 37 | } 38 | 39 | #[test] 40 | fn test_complex() { 41 | let inp = 12344321; 42 | let expected = true; 43 | let out = Solution::is_palindrome(inp); 44 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 45 | 46 | let inp = 1234321; 47 | let expected = true; 48 | let out = Solution::is_palindrome(inp); 49 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 50 | 51 | let inp = 12345321; 52 | let expected = false; 53 | let out = Solution::is_palindrome(inp); 54 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 55 | } 56 | 57 | #[test] 58 | fn test_negative() { 59 | let inp = -42; 60 | let expected = false; 61 | let out = Solution::is_palindrome(inp); 62 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 63 | 64 | let inp = -9128347; 65 | let expected = false; 66 | let out = Solution::is_palindrome(inp); 67 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0011_regex.rs: -------------------------------------------------------------------------------- 1 | 2 | /*! 3 | Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where: 4 | 5 | '.' Matches any single character.​​​​ 6 | '*' Matches zero or more of the preceding element. 7 | The matching should cover the entire input string (not partial). 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: s = "aa", p = "a" 14 | Output: false 15 | Explanation: "a" does not match the entire string "aa". 16 | Example 2: 17 | 18 | Input: s = "aa", p = "a*" 19 | Output: true 20 | Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". 21 | Example 3: 22 | 23 | Input: s = "ab", p = ".*" 24 | Output: true 25 | Explanation: ".*" means "zero or more (*) of any character (.)". 26 | 27 | 28 | Constraints: 29 | 30 | 1 <= s.length <= 20 31 | 1 <= p.length <= 30 32 | s contains only lowercase English letters. 33 | p contains only lowercase English letters, '.', and '*'. 34 | It is guaranteed for each appearance of the character '*', there will be a previous valid character to match. 35 | */ 36 | #[allow(unused)] 37 | use crate::solution::algos::Solution; 38 | 39 | impl Solution { 40 | #[allow(dead_code)] 41 | pub fn is_match(s: String, p: String) -> bool { 42 | let s = s.as_bytes(); 43 | let p = p.as_bytes(); 44 | let mut dp = vec![vec![false; p.len() + 1]; s.len() + 1]; 45 | dp[0][0] = true; 46 | for i in 0..=s.len() { 47 | for j in 1..=p.len() { 48 | if p[j - 1] == b'*' { 49 | dp[i][j] = dp[i][j - 2] || (i > 0 && dp[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == b'.')); 50 | } else { 51 | dp[i][j] = i > 0 && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == b'.'); 52 | } 53 | } 54 | } 55 | dp[s.len()][p.len()] 56 | } 57 | } 58 | 59 | #[cfg(test)] 60 | mod tests { 61 | use super::Solution; 62 | 63 | // const ERR_MSG: &str = "\nYour result (left) did not match the expected output (right)"; 64 | 65 | #[test] 66 | fn test_simple() { 67 | let inp = "aa".to_string(); 68 | let regex = "a*".to_string(); 69 | let expected = true; 70 | let out = Solution::is_match(inp, regex); 71 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 72 | 73 | let inp = "ab".to_string(); 74 | let regex = "a*".to_string(); 75 | let expected = false; 76 | let out = Solution::is_match(inp, regex); 77 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 78 | } 79 | 80 | #[test] 81 | fn test_complex() { 82 | let inp = "ab".to_string(); 83 | let regex = ".*".to_string(); 84 | let expected = true; 85 | let out = Solution::is_match(inp, regex); 86 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0012_container_with_most_water.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). 3 | 4 | Find two lines that together with the x-axis form a container, such that the container contains the most water. 5 | 6 | Return the maximum amount of water a container can store. 7 | 8 | Notice that you may not slant the container. 9 | */ 10 | #[allow(unused)] 11 | use crate::solution::algos::Solution; 12 | impl Solution { 13 | #[allow(unused)] 14 | pub fn max_area(height: Vec) -> i32 { 15 | let mut max = 0; 16 | let mut i = 0; 17 | let mut j = height.len() - 1; 18 | while i < j { 19 | let h = height[i].min(height[j]); 20 | let w = j - i; 21 | max = max.max(h * w as i32); 22 | if height[i] < height[j] { 23 | i += 1; 24 | } else { 25 | j -= 1; 26 | } 27 | } 28 | max 29 | } 30 | } 31 | 32 | #[cfg(test)] 33 | mod tests { 34 | use super::Solution; 35 | 36 | // const ERR_MSG: &str = "\nYour result (left) did not match the expected output (right)"; 37 | 38 | #[test] 39 | fn test_complex() { 40 | let inp = vec![1,8,6,2,5,4,8,3,7]; 41 | let expected = 49; 42 | let out = Solution::max_area(inp); 43 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 44 | } 45 | 46 | #[test] 47 | fn test_zeros() { 48 | let inp = vec![1, 1]; 49 | let expected = 1; 50 | let out = Solution::max_area(inp); 51 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0013_roman_to_integer.rs: -------------------------------------------------------------------------------- 1 | 2 | #[allow(unused)] 3 | use crate::solution::algos::Solution; 4 | impl Solution { 5 | fn convert(x: char) -> i32 { 6 | match x { 7 | 'I' => 1, 8 | 'V' => 5, 9 | 'X' => 10, 10 | 'L' => 50, 11 | 'C' => 100, 12 | 'D' => 500, 13 | 'M' => 1000, 14 | _ => 0, 15 | } 16 | } 17 | #[allow(unused)] 18 | pub fn roman_to_int(s: String) -> i32 { 19 | let mut res = 0; 20 | let mut prev = 0; 21 | for c in s.chars().rev() { 22 | let cur = Solution::convert(c); 23 | if cur < prev { 24 | res -= cur; 25 | } else { 26 | res += cur; 27 | } 28 | prev = cur; 29 | } 30 | res 31 | } 32 | } 33 | 34 | 35 | #[cfg(test)] 36 | mod tests { 37 | use super::Solution; 38 | 39 | // const ERR_MSG: &str = "\nYour result (left) did not match the expected output (right)"; 40 | 41 | #[test] 42 | fn test_simple() { 43 | let inp = "III".to_string(); 44 | let expected = 3; 45 | let out = Solution::roman_to_int(inp); 46 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 47 | } 48 | 49 | #[test] 50 | fn test_zeros() { 51 | let inp = "LVIII".to_string(); 52 | let expected = 58; 53 | let out = Solution::roman_to_int(inp); 54 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0014_letter_combination_phone_number.rs: -------------------------------------------------------------------------------- 1 | 2 | #![allow(dead_code)] 3 | use crate::solution::algos::Solution; 4 | impl Solution { 5 | fn combs(c: u32) -> Vec { 6 | match c { 7 | 2 => vec!['a', 'b', 'c'], 8 | 3 => vec!['d', 'e', 'f'], 9 | 4 => vec!['g', 'h', 'i'], 10 | 5 => vec!['j', 'k', 'l'], 11 | 6 => vec!['m', 'n', 'o'], 12 | 7 => vec!['p', 'q', 'r', 's'], 13 | 8 => vec!['t', 'u', 'v'], 14 | 9 => vec!['w', 'x', 'y', 'z'], 15 | _ => vec![], 16 | } 17 | } 18 | pub fn letter_combinations(digits: String) -> Vec { 19 | let mut out = vec![]; 20 | for c in digits.chars() { 21 | let c = c.to_digit(10).unwrap(); 22 | let combs = Self::combs(c); 23 | if out.is_empty() { 24 | out = combs.iter().map(|c| c.to_string()).collect(); 25 | } else { 26 | let mut out2 = vec![]; 27 | for s in out { 28 | for c in &combs { 29 | out2.push(format!("{}{}", s, c)); 30 | } 31 | } 32 | out = out2; 33 | } 34 | } 35 | out 36 | 37 | } 38 | } 39 | 40 | #[cfg(test)] 41 | mod tests { 42 | use super::Solution; 43 | 44 | // const ERR_MSG: &str = "\nYour result (left) did not match the expected output (right)"; 45 | 46 | #[test] 47 | fn test_simple() { 48 | let inp = "23".to_string(); 49 | let expected = vec!["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]; 50 | let out = Solution::letter_combinations(inp); 51 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 52 | } 53 | 54 | #[test] 55 | fn test_zeros() { 56 | let inp = "2".to_string(); 57 | let expected = vec!["a", "b", "c"]; 58 | let out = Solution::letter_combinations(inp); 59 | assert_eq!(out, expected, "expected {:?} to be {:?}", out, expected); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0019_remove_nth_node.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | Given the head of a linked list, remove the nth node 3 | from the end of the list and return its head. 4 | ## Example 1: 5 | ``` 6 | Input: head = [1,2,3,4,5], n = 2 7 | Output: [1,2,3,5] 8 | ``` 9 | ## Example 2: 10 | ``` 11 | Input: head = [1], n = 1 12 | Output: [] 13 | ``` 14 | ## Example 3: 15 | ``` 16 | Input: head = [1,2], n = 1 17 | Output: [1] 18 | ``` 19 | */ 20 | #![allow(dead_code)] 21 | use crate::lessons::linked_list::ListNode; 22 | use crate::solution::algos::Solution; 23 | impl Solution { 24 | pub fn remove_nth_from_end(head: Option>, n: i32) -> Option> { 25 | let mut head = head; 26 | let mut len = 0; 27 | let mut curr = &head; 28 | while let Some(node) = curr { 29 | len += 1; 30 | curr = &node.next; 31 | } 32 | 33 | let mut curr = &mut head; 34 | let mut i = 0; 35 | 36 | if len == n { 37 | return head.and_then(|x| x.next); 38 | } 39 | 40 | while let Some(node) = curr { 41 | i += 1; 42 | if i == len - n { 43 | let next = node.next.take(); 44 | node.next = next.and_then(|x| x.next); 45 | break; 46 | } 47 | curr = &mut node.next; 48 | } 49 | 50 | head 51 | 52 | } 53 | } 54 | 55 | #[cfg(test)] 56 | mod tests { 57 | use super::Solution; 58 | use crate::lessons::linked_list::*; 59 | 60 | // const ERR_MSG: &str = "\nYour result (left) did not match the expected output (right)"; 61 | 62 | #[test] 63 | fn test_simple() { 64 | let inp = vec![1, 2, 3, 4, 5]; 65 | let target = 2; 66 | let expected = vec![1, 2, 3, 5]; 67 | let out = Solution::remove_nth_from_end(to_list(&inp), target); 68 | // vec comparison 69 | assert_eq!(out.as_ref().unwrap().to_vec(), expected); 70 | } 71 | 72 | #[test] 73 | fn test_second() { 74 | let inp = vec![2,2,2,2,2]; 75 | let target = 4; 76 | let expected:Vec = vec![2,2,2,2]; 77 | let out = Solution::remove_nth_from_end(to_list(&inp), target); 78 | assert_eq!(out.as_ref().unwrap().to_vec(), expected); 79 | } 80 | 81 | #[test] 82 | fn test_single() { 83 | let inp = vec![1]; 84 | let target = 1; 85 | let expected:Vec = vec![]; 86 | let out = Solution::remove_nth_from_end(to_list(&inp), target); 87 | assert_eq!(out, to_list(&expected)); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0020_valid_parens.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | 3 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 4 | An input string is valid if: 5 | 6 | Open brackets must be closed by the same type of brackets. 7 | Open brackets must be closed in the correct order. 8 | Every close bracket has a corresponding open bracket of the same type. 9 | */ 10 | #[allow(unused)] 11 | pub struct Solution {} 12 | 13 | impl Solution { 14 | #[allow(unused)] 15 | pub fn is_valid(s: String) -> bool { 16 | let mut stack = Vec::new(); 17 | 18 | for c in s.chars() { 19 | match c { 20 | '(' | '{' | '[' => stack.push(c), 21 | ')' => { 22 | if stack.pop() != Some('(') { 23 | return false; 24 | } 25 | } 26 | '}' => { 27 | if stack.pop() != Some('{') { 28 | return false; 29 | } 30 | } 31 | ']' => { 32 | if stack.pop() != Some('[') { 33 | return false; 34 | } 35 | } 36 | _ => continue, 37 | } 38 | 39 | } 40 | if stack.is_empty() { 41 | return true; 42 | } 43 | return false 44 | } 45 | } 46 | 47 | #[cfg(test)] 48 | mod tests { 49 | use super::*; 50 | #[test] 51 | fn test() { 52 | assert_eq!(Solution::is_valid("()".to_string()), true); 53 | assert_eq!(Solution::is_valid("()[]{}".to_string()), true); 54 | assert_eq!(Solution::is_valid("(]".to_string()), false); 55 | assert_eq!(Solution::is_valid("([)]".to_string()), false); 56 | assert_eq!(Solution::is_valid("{[]}".to_string()), true); 57 | } 58 | 59 | #[test] 60 | fn test2() { 61 | assert_eq!(Solution::is_valid("".to_string()), true); 62 | assert_eq!(Solution::is_valid("[".to_string()), false); 63 | assert_eq!(Solution::is_valid("]".to_string()), false); 64 | assert_eq!(Solution::is_valid("()[]{}[]".to_string()), true); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0021_merge_two_sorted_lists.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | You are given the heads of two sorted linked lists list1 and list2. 3 | 4 | Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. 5 | 6 | Return the head of the merged linked list. 7 | 8 | @examples 9 | Input: list1 = [1,2,4], list2 = [1,3,4] 10 | Output: [1,1,2,3,4,4] 11 | */ 12 | use crate::lessons::linked_list::*; 13 | 14 | use crate::solution::algos::Solution; 15 | 16 | impl Solution { 17 | #[allow(dead_code)] 18 | pub fn merge_two_lists(list1: Option>, list2: Option>) -> Option> { 19 | let mut list2 = list2; 20 | let mut list1 = list1; 21 | let mut head = &mut list1; 22 | while list2.is_some() { 23 | if head.is_none() || list2.as_ref()?.val < head.as_ref()?.val { 24 | std::mem::swap(head, &mut list2); 25 | } 26 | head = &mut head.as_mut()?.next; 27 | } 28 | list1 29 | } 30 | } 31 | 32 | #[cfg(test)] 33 | mod tests { 34 | use super::*; 35 | use crate::lessons::linked_list::to_list; 36 | #[test] 37 | fn test() { 38 | assert_eq!(Solution::merge_two_lists(None, None), None); 39 | assert_eq!(Solution::merge_two_lists(None, Some(Box::new(ListNode::new(0)))), Some(Box::new(ListNode::new(0)))); 40 | assert_eq!(Solution::merge_two_lists(Some(Box::new(ListNode::new(0))), None), Some(Box::new(ListNode::new(0)))); 41 | 42 | } 43 | 44 | #[test] 45 | fn test2() { 46 | let list1 = vec![1, 2, 4]; 47 | let list2 = vec![1, 3, 4]; 48 | let sol = vec![1, 1, 2, 3, 4, 4]; 49 | let list1 = to_list(&list1); 50 | let list2 = to_list(&list2); 51 | let sol = to_list(&sol); 52 | assert_eq!(Solution::merge_two_lists( 53 | list1, 54 | list2, 55 | ), sol); 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0022_generate_parens.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | @see https://leetcode.com/problems/generate-parentheses/ 3 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 4 | */ 5 | 6 | use crate::solution::algos::Solution; 7 | 8 | impl Solution { 9 | #[allow(dead_code)] 10 | pub fn generate_parentesis(n: i32) -> Vec { 11 | let mut result = Vec::new(); 12 | let mut s = String::new(); 13 | Solution::generate(&mut result, &mut s, n, n); 14 | result 15 | } 16 | 17 | pub fn generate(result: &mut Vec, s: &mut String, left: i32, right: i32) { 18 | if left == 0 && right == 0 { 19 | result.push(s.clone()); 20 | return; 21 | } 22 | if left > 0 { 23 | s.push('('); 24 | Solution::generate(result, s, left - 1, right); 25 | s.pop(); 26 | } 27 | if right > left { 28 | s.push(')'); 29 | Solution::generate(result, s, left, right - 1); 30 | s.pop(); 31 | } 32 | } 33 | 34 | } 35 | 36 | #[cfg(test)] 37 | mod tests { 38 | use super::*; 39 | 40 | #[test] 41 | fn test_22() { 42 | assert_eq!(Solution::generate_parentesis(3), vec!["((()))","(()())","(())()","()(())","()()()"]); 43 | assert_eq!(Solution::generate_parentesis(1), vec!["()"]); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /rust/src/solution/algos/s0061_rotate_list.rs: -------------------------------------------------------------------------------- 1 | //! 2 | //! Given the head of a linked list, rotate the list to the right by k places. 3 | //! [k=2] 1 -> 2 -> 3 -> 4 -> 5 ==> 4 -> 5 -> 1 -> 2 -> 3 4 | //! [k=4] 0 -> 1 -> 2 ==> 2 -> 0 -> 1 5 | //! ## constaints 6 | //! - The number of nodes in the list is in the range [0, 500]. 7 | //! - -100 <= Node.val <= 100 8 | //! 9 | use crate::lessons::linked_list::ListNode; 10 | use crate::solution::algos::Solution; 11 | 12 | impl Solution { 13 | 14 | pub fn rotate_right(head: Option>, k: i32) -> Option> { 15 | todo!() 16 | } 17 | } 18 | 19 | #[cfg(test)] 20 | mod tests { 21 | use super::Solution; 22 | 23 | } -------------------------------------------------------------------------------- /rust/src/solution/algos/s0083_remove_duplicate_from_sorted_list.rs: -------------------------------------------------------------------------------- 1 | use crate::lessons::linked_list::ListNode; 2 | use crate::solution::algos::Solution; 3 | use std::collections::HashSet; 4 | impl Solution { 5 | pub fn delete_duplicates(head: Option>) -> Option> { 6 | let mut contains = HashSet::new(); 7 | let mut c = head; 8 | let mut curr = &mut c; 9 | 10 | while curr.is_some() { 11 | let val = curr.as_ref().unwrap().val; 12 | if contains.contains(&val) { 13 | *curr = curr.as_mut().unwrap().next.take(); 14 | } else { 15 | contains.insert(val); 16 | curr = &mut curr.as_mut().unwrap().next; 17 | } 18 | } 19 | 20 | return c; 21 | } 22 | } 23 | 24 | #[cfg(test)] 25 | mod tests { 26 | use super::*; 27 | use crate::lessons::linked_list::*; 28 | #[test] 29 | fn test_simple() { 30 | assert_eq!(Solution::delete_duplicates(to_list(&vec![1,1,2])), to_list(&vec![1,2])); 31 | assert_eq!(Solution::delete_duplicates(to_list(&vec![1,1,2,3,3])), to_list(&vec![1,2,3])); 32 | } 33 | 34 | #[test] 35 | fn test_empty() { 36 | assert_eq!(Solution::delete_duplicates(None), None); 37 | } 38 | 39 | #[test] 40 | fn test_single() { 41 | assert_eq!(Solution::delete_duplicates(to_list(&vec![1])), to_list(&vec![1])); 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /rust/src/solution/data_stuctures/arrays/arrays.rs: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Complete the 'reverseArray' function below. 4 | * 5 | * The function is expected to return an INTEGER_ARRAY. 6 | * The function accepts INTEGER_ARRAY a as parameter. 7 | */ 8 | 9 | #[allow(unused)] 10 | fn reverse_array(a: &[i32]) -> Vec { 11 | 12 | let mut a = a.to_vec(); 13 | a.reverse(); 14 | a 15 | } 16 | 17 | /** 18 | * Compare [i32,i32,i32] and [i32,i32,i32] 19 | * Result: [i32, i32] 20 | * Solution: A point is rewarded to either side if greater. 21 | */ 22 | #[allow(unused)] 23 | fn compare_triplets(a: &[i32], b: &[i32]) -> Vec { 24 | let mut ans = vec![0;2]; 25 | 26 | for i in 0..3 { 27 | if a[i] > b[i] { 28 | ans[0]+=1; 29 | } 30 | if a[i] < b[i] { 31 | ans[1]+=1; 32 | } 33 | } 34 | ans 35 | } 36 | 37 | 38 | #[allow(unused)] 39 | pub fn run() { 40 | println!("Data Structure: Arrays"); 41 | println!("reverseArray: {:#?}", reverse_array(&[1,2,4,8,6])); 42 | println!("Compare Triple: {:#?}", compare_triplets(&[1,5,7], &[1,4,6])); 43 | } 44 | 45 | -------------------------------------------------------------------------------- /rust/src/solution/data_stuctures/arrays/arrays_2d.rs: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Complete the 'hourglassSum' function below. 4 | * 5 | * The function is expected to return an INTEGER. 6 | * The function accepts 2D_INTEGER_ARRAY arr as parameter. 7 | */ 8 | fn hourglasssum(arr: &[Vec]) -> i32 { 9 | let mut max = -63; 10 | for i in 0..4 { 11 | for j in 0..4 { 12 | let sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]; 13 | 14 | if max < sum { 15 | max = sum; 16 | } 17 | } 18 | } 19 | 20 | max 21 | 22 | } 23 | 24 | fn diagonal_difference(arr: &[Vec]) -> i32 { 25 | let len = arr.len(); 26 | let mut ans = 0; 27 | for (idx, _) in arr.iter().enumerate() { 28 | let lhs = arr[idx][idx]; 29 | let rhs = arr[len-idx-1][idx]; 30 | ans += lhs-rhs 31 | } 32 | ans.abs() 33 | } 34 | 35 | 36 | 37 | 38 | #[allow(unused)] 39 | pub fn run() { 40 | println!("Data Structure: 2D Arrays"); 41 | println!("hourglassSum: {:#}", hourglasssum(&[ 42 | vec![1,3,4,5,7,6], 43 | vec![1,3,4,5,7,6], 44 | vec![1,3,4,5,7,6], 45 | vec![1,3,4,5,7,6], 46 | vec![1,3,4,5,7,6], 47 | vec![1,3,4,5,7,6] 48 | ])); 49 | println!("diagonal difference: {:#?}", diagonal_difference(&[ 50 | vec![1,3,4,5,7,6], 51 | vec![1,3,4,5,7,6], 52 | vec![1,3,4,4,7,6], 53 | vec![1,3,4,5,7,6], 54 | vec![1,3,4,5,7,6], 55 | vec![1,3,4,5,7,6] 56 | 57 | ])); 58 | } 59 | -------------------------------------------------------------------------------- /rust/src/solution/data_stuctures/arrays/mod.rs: -------------------------------------------------------------------------------- 1 | mod arrays; 2 | mod arrays_2d; 3 | mod list; 4 | pub mod queue; 5 | pub mod stack; 6 | 7 | -------------------------------------------------------------------------------- /rust/src/solution/data_stuctures/arrays/queue.rs: -------------------------------------------------------------------------------- 1 | //use crate::solution::data_stuctures::interface::IQueue; 2 | 3 | 4 | 5 | #[derive(Debug, Clone)] 6 | pub struct Queue { 7 | vals : Vec, 8 | len: u32, 9 | } 10 | 11 | impl Queue { 12 | pub fn new() -> Self { 13 | Queue { vals : vec![], len: 0} 14 | } 15 | pub fn add(&mut self, val: T) -> &mut Self { 16 | self.vals.push(val); 17 | self.len += 1; 18 | self 19 | } 20 | 21 | #[allow(dead_code)] 22 | pub fn len(&self) -> u32 { 23 | self.len 24 | } 25 | 26 | pub fn remove(&mut self) -> Option{ 27 | let c = self.vals.first().cloned(); 28 | if self.len < 1 { 29 | return None; 30 | } 31 | self.vals = self.vals[1..].to_vec(); 32 | self.len -= 1; 33 | c 34 | } 35 | } 36 | 37 | 38 | #[cfg(test)] 39 | mod tests { 40 | use super::*; 41 | 42 | #[test] 43 | fn test_add() { 44 | let mut a = Queue::new(); 45 | a.add(1); 46 | a.add(2); 47 | assert_eq!(a.vals, vec![1,2]); 48 | } 49 | 50 | #[test] 51 | fn test_remove() { 52 | let mut a = Queue::new(); 53 | a.add(1); 54 | a.add(2); 55 | a.add(9); 56 | assert_eq!(a.remove(),Some(1)); 57 | assert_eq!(a.remove(),Some(2)); 58 | assert_eq!(a.remove(),Some(9)); 59 | assert_eq!(a.remove(),None); 60 | 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /rust/src/solution/data_stuctures/arrays/stack.rs: -------------------------------------------------------------------------------- 1 | //use crate::solution::data_stuctures::interface::IStack; 2 | 3 | 4 | 5 | #[derive(Debug, Clone)] 6 | pub struct Stack { 7 | vals : Vec, 8 | len: u32, 9 | } 10 | 11 | impl Stack { 12 | pub fn new() -> Self { 13 | Stack { vals : vec![], len: 0} 14 | } 15 | pub fn push(&mut self, val: T) -> &mut Self { 16 | 17 | if self.len < 1 { 18 | self.vals.push(val); 19 | return self; 20 | } 21 | let mut tmp = self.vals.get(0).unwrap().clone(); 22 | for id in 0..self.len { 23 | let id = id as usize; 24 | self.vals[id+1] = tmp; 25 | tmp = self.vals.get(id + 1).unwrap().clone(); 26 | } 27 | self.vals[0] = val; 28 | self.len += 1; 29 | self 30 | } 31 | 32 | #[allow(dead_code)] 33 | pub fn len(&self) -> u32 { 34 | self.len 35 | } 36 | 37 | pub fn pop(&mut self) -> Option{ 38 | /* 39 | let c = self.vals.last().cloned(); 40 | let len = (self.len - 1).try_into(); 41 | if let None = len.ok() { 42 | return None; 43 | }; 44 | self.vals = self.vals[0..len.unwrap()].to_vec(); 45 | self.len -= 1; 46 | c 47 | */ 48 | self.vals.pop() 49 | } 50 | } 51 | 52 | #[cfg(test)] 53 | mod tests { 54 | use super::*; 55 | 56 | #[test] 57 | fn test_push() { 58 | let mut a = Stack::new(); 59 | a.push(1); 60 | a.push(2); 61 | assert_eq!(a.vals, vec![1,2]); 62 | } 63 | 64 | #[test] 65 | fn test_pop() { 66 | let mut a = Stack::new(); 67 | a.push(1); 68 | a.push(2); 69 | a.push(9); 70 | assert_eq!(a.pop(),Some(9)); 71 | assert_eq!(a.pop(),Some(2)); 72 | assert_eq!(a.pop(),Some(1)); 73 | assert_eq!(a.pop(),None); 74 | 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /rust/src/solution/data_stuctures/interface/mod.rs: -------------------------------------------------------------------------------- 1 | //! # Trait Queue 2 | //! ## Resources 3 | //! -[Link to Article](https://opendatastructures.org/versions/edition-0.1c/ods-java/node5.html) 4 | 5 | ///trait for a Queue data structure 6 | /// last-in first-out data structure 7 | pub trait IQueue { 8 | fn add(&mut self, x:T) -> &mut Self; 9 | fn remove(&mut self) -> Option; 10 | fn len(&self) -> u32; 11 | fn new() -> Self; 12 | } 13 | 14 | ///trait for a Stack data structure 15 | /// first-in first-out data structure 16 | pub trait IStack { 17 | fn push(&mut self, x:T) -> &mut Self; 18 | fn pop(&mut self) -> Option; 19 | fn len(&self) -> u32; 20 | fn new() -> Self; 21 | } 22 | 23 | ///trait for a List data structure 24 | pub trait List { 25 | fn size(&self) -> usize; 26 | fn add(&mut self, i:usize , x:T); 27 | fn remove(&mut self, i:usize) -> Option; 28 | fn set(&mut self, i:usize, x:T) -> Option; 29 | fn get(&self, i: usize) -> Option; 30 | } 31 | 32 | ///trait for a Unordered Set data structure 33 | pub trait USet { 34 | fn size(&self) -> usize; 35 | fn add(&self) -> bool; 36 | fn remove(&self) -> Option; 37 | fn find(&self, x: &T) -> Option; 38 | } 39 | 40 | ///trait for a Unordered Set data structure 41 | pub trait SSet { 42 | fn size(&self) -> usize; 43 | fn add(&self) -> bool; 44 | fn remove(&self) -> Option; 45 | fn find(&self, x: &T) -> Option; 46 | fn compare(&self, x:&T, y:&T) -> bool; 47 | } 48 | 49 | pub trait Graph {} 50 | -------------------------------------------------------------------------------- /rust/src/solution/data_stuctures/mod.rs: -------------------------------------------------------------------------------- 1 | mod interface; 2 | pub mod arrays; 3 | mod string_formatting; 4 | pub fn run(){ 5 | string_formatting::run(); 6 | } 7 | -------------------------------------------------------------------------------- /rust/src/solution/data_stuctures/string_formatting.rs: -------------------------------------------------------------------------------- 1 | pub fn time_conversion(s: &str) -> String { 2 | let (hour, min, sec, am_or_pm) = (&s[0..2], &s[3..5], &s[6..8], &s[9..10]); 3 | let hh = hour.parse::().expect("parsing error") + match (hour, am_or_pm) { 4 | ("12", "AM") => -12, 5 | (_, "AM") => 0, 6 | ("12", "PM") => 0, 7 | _ => 12 8 | }; 9 | 10 | format!("{:02}:{:02}:{02}", hh, min, sec) 11 | 12 | } 13 | 14 | pub fn run() { 15 | println!("Data Structure: String Formatting"); 16 | println!("{}", time_conversion("10:12:30PM")); 17 | } 18 | -------------------------------------------------------------------------------- /rust/src/solution/minors.rs: -------------------------------------------------------------------------------- 1 | 2 | #[allow(unused)] 3 | fn plus_minus(arr: &[i32]) { 4 | let len = arr.len() as f32; 5 | let mut ratio = [0.0;3]; 6 | for i in arr { 7 | if *i <0 { 8 | ratio[0] += 1.0; 9 | } 10 | if *i > 0 { 11 | ratio[1] += 1.0 12 | } 13 | ratio[2] += 2.0 14 | } 15 | println!("{:.32}\n{:.32}\n{:.32}", 16 | ratio[1]/len, 17 | ratio[0]/len, 18 | ratio[1]/len); 19 | } 20 | #[allow(unused)] 21 | fn averybigsum(ar: &[i64]) -> i64 { 22 | ar.iter().sum() 23 | } 24 | 25 | pub fn run() { 26 | } 27 | 28 | -------------------------------------------------------------------------------- /rust/src/solution/mod.rs: -------------------------------------------------------------------------------- 1 | mod utils; 2 | mod data_stuctures; 3 | mod algos; 4 | 5 | pub fn run(){ 6 | println!("data_stuctures"); 7 | data_stuctures::run(); 8 | println!("Algos"); 9 | algos::run(); 10 | 11 | } 12 | 13 | -------------------------------------------------------------------------------- /rust/src/solution/utils.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | #[allow(unused)] 4 | pub fn from_morse_code() -> HashMap{ 5 | let mut map:HashMap = HashMap::new(); 6 | 7 | let codes = to_morse_code(); 8 | 9 | for key in codes.keys() { 10 | let val = &codes[key]; 11 | map.insert(val.to_string(), key.to_string()); 12 | } 13 | 14 | map 15 | } 16 | 17 | #[allow(unused)] 18 | pub fn to_morse_code() -> HashMap { 19 | let mut morse = HashMap::new(); 20 | morse.insert("a".to_string(), ".-".to_string()); 21 | morse.insert("b".to_string(), "-...".to_string()); 22 | morse.insert("c".to_string(), "-.-".to_string()); 23 | morse.insert("d".to_string(), "-..".to_string()); 24 | morse.insert("e".to_string(), ".".to_string()); 25 | morse.insert("f".to_string(), "..-.".to_string()); 26 | morse.insert("g".to_string(), "--.".to_string()); 27 | morse.insert("h".to_string(), "....".to_string()); 28 | morse.insert("i".to_string(), "..".to_string()); 29 | morse.insert("j".to_string(), ".---".to_string()); 30 | morse.insert("k".to_string(), "-.".to_string()); 31 | morse.insert("l".to_string(), ".-..".to_string()); 32 | morse.insert("m".to_string(), "--".to_string()); 33 | morse.insert("n".to_string(), "-.".to_string()); 34 | morse.insert("o".to_string(), "---".to_string()); 35 | morse.insert("p".to_string(), ".--.".to_string()); 36 | morse.insert("q".to_string(), "--.-".to_string()); 37 | morse.insert("r".to_string(), ".-.".to_string()); 38 | morse.insert("s".to_string(), "...".to_string()); 39 | morse.insert("t".to_string(), "-".to_string()); 40 | morse.insert("u".to_string(), "..-".to_string()); 41 | morse.insert("v".to_string(), "...-".to_string()); 42 | morse.insert("w".to_string(), ".--".to_string()); 43 | morse.insert("x".to_string(), "-..-".to_string()); 44 | morse.insert("y".to_string(), "-.--".to_string()); 45 | morse.insert("z".to_string(), "--..".to_string()); 46 | morse.insert("1".to_string(), ".----".to_string()); 47 | morse.insert("2".to_string(),"..---".to_string()); 48 | morse.insert("3".to_string(), "...--".to_string()); 49 | morse.insert("4".to_string(), "....-".to_string()); 50 | morse.insert("5".to_string(), ".....".to_string()); 51 | morse.insert("6".to_string(), "-....".to_string()); 52 | morse.insert("7".to_string(), "--...".to_string()); 53 | morse.insert("8".to_string(), "---..".to_string()); 54 | morse.insert("9".to_string(), "----.".to_string()); 55 | morse.insert("0".to_string(), "-----".to_string()); 56 | morse 57 | } 58 | -------------------------------------------------------------------------------- /ts/.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules 3 | -------------------------------------------------------------------------------- /ts/algos: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amar-jay/algos/a7dfe69178b0caf94b96b437a54593cbf668e576/ts/algos -------------------------------------------------------------------------------- /ts/decomp.md: -------------------------------------------------------------------------------- 1 | The aim of the kata is to decompose n! (factorial n) into its prime factors. 2 | 3 | Examples: 4 | --- 5 | 6 | ``` 7 | n = 12; decomp(12) -> "2^10 * 3^5 * 5^2 * 7 * 11" 8 | since 12! is divisible by 2 ten times, by 3 five times, by 5 two times and by 7 and 11 only once. 9 | 10 | n = 22; decomp(22) -> "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19" 11 | 12 | n = 25; decomp(25) -> 2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23 13 | ``` 14 | --- 15 | Prime numbers should be in increasing order. When the exponent of a prime is 1 don't put the exponent. 16 | 17 | ###Notes 18 | - the function is decomp(n) and should return the decomposition of n! into its prime factors in increasing order of the primes, as a string. 19 | - factorial can be a very big number (4000! has 12674 digits, n can go from 300 to 4000). 20 | - In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use `dynamically allocated character strings`. 21 | -------------------------------------------------------------------------------- /ts/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "algos", 3 | "version": "1.0.0", 4 | "description": "algos", 5 | "main": "dist/index.js", 6 | "scripts": { 7 | "tsc": "tsc", 8 | "test": "tsc && jest", 9 | "test:dev": "nodemon -x ./node_modules/.bin/mocha test/**/*.js" 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/git+amar-jay/algos.git" 14 | }, 15 | "keywords": [ 16 | "algos" 17 | ], 18 | "author": "amar-jay", 19 | "license": "ISC", 20 | "bugs": { 21 | "url": "https://github.com/git+amar-jay/algos/issues" 22 | }, 23 | "homepage": "https://github.com/git+amar-jay/algos#readme", 24 | "dependencies": { 25 | "nodemon": "^2.0.19" 26 | }, 27 | "devDependencies": { 28 | "@types/jest": "^29.2.0", 29 | "@types/node": "^18.11.6", 30 | "jest": "^29.2.2", 31 | "ts-node": "^10.9.1", 32 | "typescript": "^4.8.4" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /ts/readme.md: -------------------------------------------------------------------------------- 1 | # TypeScript 2 | 3 | ### Contents 4 | - Some Codewars, Hackerrank, Leetcode solution 5 | - Explanation of popular data structures 6 | - Explanation of popular algorithms 7 | - d-prefixed are from codewars 8 | - s-prefixed are from leetcode 9 | - h-prefixed are from hackerrank 10 | 11 | ### TODO 12 | 13 | - [ ] Leetcode solutions 14 | - [ ] Hackerrank solutions 15 | - [ ] Codewars solutions 16 | - [ ] Common Data Structures 17 | - [x] CI 18 | - [x] Unit tests 19 | 20 | ### Contribution 21 | You are free to fork and contribute to this repo. 22 | If you want to use this resource for educational purposes, you can do so as you please. 23 | 24 | -------------------------------------------------------------------------------- /ts/run: -------------------------------------------------------------------------------- 1 | nodemon ./dist/$1 2 | -------------------------------------------------------------------------------- /ts/src/lessons/path-searching/#1.ts: -------------------------------------------------------------------------------- 1 | export function pathFinder(maze: string): boolean { 2 | const WALL = "W"; 3 | const PATH = "."; 4 | let table = maze.split("\n").map((row) => row.split("")); 5 | let max_len = table.length - 1; 6 | let stack: [x: number, y: number][] = []; 7 | stack.push([0, 0]); 8 | 9 | while (stack.length != 0 || stack != null) { 10 | let elem = stack.pop(); 11 | if (elem == null) { 12 | return false; 13 | } 14 | let x = elem[0]; 15 | let y = elem[1]; 16 | /* 17 | * console.log( 18 | stack, 19 | x, 20 | y, 21 | max_len, 22 | "right:", 23 | table[x][y + 1], 24 | "curr:", 25 | table[x][y], 26 | "left:", 27 | table[x][y - 1] 28 | ); 29 | */ 30 | if (x === max_len && y === max_len) { 31 | return true; 32 | } 33 | 34 | if (table[x][y] === WALL) { 35 | continue; 36 | } 37 | 38 | //check right 39 | if (max_len >= y + 1 && max_len >= x && table[x][y + 1] === PATH) { 40 | stack.unshift([x, y + 1]); 41 | } 42 | 43 | // check down 44 | if (max_len >= y && max_len >= x + 1 && table[x + 1][y] === PATH) { 45 | stack.unshift([x + 1, y]); 46 | } 47 | // check left 48 | // if (!table[x][y - 1]) { 49 | // continue; 50 | // } 51 | // if ( 52 | // max_len >= y - 1 && 53 | // max_len >= x && 54 | // table[x][y - 1] !== undefined && 55 | // table[x][y - 1] === PATH && 56 | // table[x][y - 1] !== WALL 57 | // ) { 58 | // stack.unshift([x, y - 1]); 59 | // } 60 | // // check up 61 | // if (!table[x - 1][y]) { 62 | // continue; 63 | // } 64 | 65 | // if ( 66 | // max_len >= y && 67 | // max_len >= x - 1 && 68 | // table[x - 1][y] !== undefined && 69 | // table[x - 1][y] === PATH && 70 | // table[x - 1][y] !== WALL 71 | // ) { 72 | // stack.unshift([x - 1, y]); 73 | // } 74 | } 75 | return false; 76 | } 77 | 78 | -------------------------------------------------------------------------------- /ts/src/lessons/path-searching/#2.ts: -------------------------------------------------------------------------------- 1 | // A br` 2 | -------------------------------------------------------------------------------- /ts/src/lessons/search/binary_search.test.ts: -------------------------------------------------------------------------------- 1 | import { binarySearch } from './binary_search'; 2 | 3 | const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 4 | const stringArr = [ 5 | 'Alpha', 6 | 'Bravo', 7 | 'Charlie', 8 | 'Delta', 9 | 'Echo', 10 | 'Foxtrot', 11 | 'Golf', 12 | 'Hotel', 13 | 'India', 14 | 'Juliet', 15 | 'Kilo', 16 | 'Lima', 17 | 'Mike', 18 | 'November', 19 | 'Oscar', 20 | 'Papa', 21 | 'Quebec', 22 | 'Romeo', 23 | 'Sierra', 24 | 'Tango', 25 | 'Uniform', 26 | 'Victor', 27 | 'Whiskey', 28 | 'X-Ray', 29 | 'Yankee', 30 | 'Zulu' 31 | ]; 32 | 33 | describe('Binary Search', () => { 34 | const func = binarySearch; 35 | test('expect to return the index of the item in the array', () => { 36 | expect(func(arr, 3)).toBe(2); 37 | }) 38 | test('expect to return -1 if not in array', () => { 39 | expect(func(arr, 11)).toBe(-1) 40 | }) 41 | test('expect to return the index of the item in the array', () => { 42 | expect(func(stringArr, 'Charlie')).toBe(2) 43 | }) 44 | test('expect to return -1 if not in array', () => { 45 | expect(func(stringArr, 'Zoft')).toBe(-1) 46 | }) 47 | } 48 | ); 49 | -------------------------------------------------------------------------------- /ts/src/lessons/search/binary_search.ts: -------------------------------------------------------------------------------- 1 | /* Binary Search: https://en.wikipedia.org/wiki/Binary_search_algorithm 2 | * 3 | * Search a sorted array by repeatedly dividing the search interval 4 | * in half. Begin with an interval covering the whole array. If the value of the 5 | * search key is less than the item in the middle of the interval, narrow the interval 6 | * to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the 7 | * value is found or the interval is empty. 8 | */ 9 | 10 | export type Index = number; 11 | export const binarySearch = (arr: Array, x: T): Index | Error => { 12 | 13 | if (arr.length <= 0) { 14 | return RangeError("Array is empty"); 15 | } 16 | 17 | if (arr.length == 1) { 18 | return arr[0] == x ? 0 : -1; 19 | } 20 | 21 | 22 | const mid = Math.floor(arr.length / 2); 23 | 24 | if (arr[mid] == x) return mid; 25 | const left = arr.slice(0, mid); 26 | const right = arr.slice(mid, arr.length - 1); 27 | 28 | switch (typeof arr[mid]) { 29 | case 'number': 30 | if (arr[mid] < x) return binarySearch(left, x); 31 | if (arr[mid] > x) return binarySearch(right, x); 32 | break; 33 | case 'string': 34 | if (arr[mid] < x) return binarySearch(left, x); 35 | if (arr[mid] > x) return binarySearch(right, x); 36 | break; 37 | default: 38 | return TypeError("Array must contain type number or string"); 39 | } 40 | return -1; 41 | } 42 | 43 | -------------------------------------------------------------------------------- /ts/src/solutions/d001_shortest_path.ts: -------------------------------------------------------------------------------- 1 | 2 | enum CharType {} 3 | type Coord = [x:number, y:number]; 4 | type Char = string & CharType; 5 | const my_sol = (maze:string) => { 6 | let maz:string[]= []; 7 | 8 | 9 | const moveLeft = (curr_pos:Coord) => [curr_pos[0]-1, curr_pos[1]] as Coord; 10 | const moveRight = (curr_pos:Coord) => [curr_pos[0]+1, curr_pos[1]] as Coord; 11 | const moveDown = (curr_pos:Coord) => [curr_pos[0], curr_pos[1]-1] as Coord ; 12 | const moveUp = (curr_pos:Coord) => [curr_pos[0], curr_pos[1]+1] as Coord; 13 | 14 | const checkLeft = (curr_pos:Coord) => maz[curr_pos[0]-1][curr_pos[1]]; 15 | const checkRight = (curr_pos:Coord)=> maz[curr_pos[0]+1][curr_pos[1]]; 16 | const checkDown = (curr_pos:Coord) => maz[curr_pos[0]][curr_pos[1]-1]; 17 | const checkUp = (curr_pos:Coord) => maz[curr_pos[0]][curr_pos[1]+1]; 18 | 19 | // convert maze from string to 2D 20 | let tmp = ''; 21 | for (let i of maze) { 22 | tmp.concat(i); 23 | if (i === '\n'){ 24 | maz.push(tmp); 25 | tmp=''; 26 | } 27 | } 28 | 29 | if (maze.length < 1) { 30 | return 0; 31 | } 32 | 33 | 34 | /* 35 | let curr_pos:Coord = [0, 0]; 36 | while (true) { 37 | switch ('.'){ 38 | case checkLeft(curr_pos): 39 | 40 | break; 41 | case checkRight(curr_pos): 42 | break; 43 | case checkUp(curr_pos): 44 | break; 45 | case checkDown(curr_pos): 46 | break; 47 | default: 48 | return false; 49 | } 50 | 51 | } 52 | */ 53 | 54 | return maze.length < 1; 55 | } 56 | 57 | 58 | function aliter(maze:string) { 59 | const matrix = maze.split(`\n`).map(row => row.split(``)); 60 | const queue = [{ x: 0, y: 0, len: 0 }]; 61 | type Coord = typeof queue[0]; 62 | const n = matrix.length - 1; 63 | 64 | while (queue.length > 0) { 65 | const { x, y, len }:Coord = queue.shift()!; 66 | if (x == n && y == n) { 67 | return len; 68 | } 69 | matrix[x][y] = 'W'; 70 | [[x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]].forEach(([t1, t2]) => { 71 | if (matrix[t1] && matrix[t1][t2] && matrix[t1][t2] != 'W') { 72 | queue.push({x: t1, y: t2, len: len + 1}); 73 | matrix[t1][t2] = 'W'; 74 | } 75 | }); 76 | } 77 | return false; 78 | } 79 | export default (maze:string) => aliter(maze) 80 | -------------------------------------------------------------------------------- /ts/src/solutions/d002_pagination_helper.ts: -------------------------------------------------------------------------------- 1 | interface PaginationHelper { 2 | itemCount(): number 3 | pageCount(): void 4 | pageItemCount(): void 5 | pageIndex(itemIndex: number): void 6 | collection: Array 7 | itemPerPage: number 8 | 9 | } 10 | function PaginationHelper(this:any | PaginationHelper, collection: Array, itemPerPage:number) { 11 | PaginationHelper.prototype.collection = collection; 12 | PaginationHelper.prototype.itemPerPage = itemPerPage; 13 | return { 14 | itemCount() { 15 | return PaginationHelper.prototype.collection.length 16 | }, 17 | pageCount() { 18 | return Math.ceil(PaginationHelper.prototype.collection.length / PaginationHelper.prototype.itemPerPage); 19 | }, 20 | pageItemCount(pageIndex:number){ 21 | if (PaginationHelper.prototype.pageCount() > pageIndex+1) 22 | return PaginationHelper.prototype.itemPerPage; 23 | else if (PaginationHelper.prototype.pageCount() == pageIndex+1) 24 | return (PaginationHelper.prototype.itemCount() % PaginationHelper.prototype.itemPerPage); 25 | else 26 | return -1; 27 | }, 28 | 29 | pageIndex(itemIndex:number) { 30 | return (itemIndex>PaginationHelper.prototype.itemCount())? 0-1 :Math.ceil(itemIndex / PaginationHelper.prototype.itemPerPage) - 1; 31 | } 32 | }; 33 | } 34 | 35 | PaginationHelper.prototype.itemCount = () => { 36 | return PaginationHelper.prototype.collection.length 37 | 38 | } 39 | 40 | PaginationHelper.prototype.pageCount = () => { 41 | return Math.ceil(PaginationHelper.prototype.collection.length / PaginationHelper.prototype.itemPerPage); 42 | 43 | } 44 | 45 | PaginationHelper.prototype.pageItemCount = (pageIndex:number) => { 46 | return (PaginationHelper.prototype.pageCount() > pageIndex+1)? 47 | PaginationHelper.prototype.pageCount(): 48 | (PaginationHelper.prototype.itemCount() % PaginationHelper.prototype.pageCount()) - pageIndex; 49 | } 50 | 51 | PaginationHelper.prototype.pageIndex = (itemIndex:number) => { 52 | return (PaginationHelper.prototype.pageIndex>PaginationHelper.prototype.pageCount())?-1:Math.floor(itemIndex / PaginationHelper.prototype.itemsPerPage); 53 | } 54 | 55 | export default PaginationHelper; 56 | -------------------------------------------------------------------------------- /ts/src/solutions/tests/d001_shortest_path.test.ts: -------------------------------------------------------------------------------- 1 | import shortest_path from "../d001_shortest_path"; 2 | 3 | function testMaze(expected:number | boolean, maze:string){ 4 | let actual = shortest_path(maze); 5 | expect(actual).toBe(expected); 6 | } 7 | 8 | describe("Testing d001_shortest_path:", () => { 9 | 10 | testMaze(4, 11 | `.W. 12 | .W. 13 | ...`); 14 | 15 | testMaze(false, 16 | `.W. 17 | .W. 18 | W..`); 19 | 20 | testMaze(10, 21 | `...... 22 | ...... 23 | ...... 24 | ...... 25 | ...... 26 | ......`); 27 | 28 | testMaze(false, 29 | `...... 30 | ...... 31 | ...... 32 | ...... 33 | .....W 34 | ....W.`); 35 | 36 | }); 37 | -------------------------------------------------------------------------------- /ts/src/solutions/tests/d002_pagination_helper.test.ts: -------------------------------------------------------------------------------- 1 | import PaginationHelper from '../d002_pagination_helper'; 2 | describe("Pagination helper", () => { 3 | let func = PaginationHelper(['a','b','c','d','e','f'], 4); 4 | 5 | test("item count test", () => expect(func.itemCount()).toBe(5)); 6 | test("page count test", () => expect(func.pageCount()).toBe(1)); 7 | test("page item count test", () => expect(func.pageItemCount(-1)).toBe(4)); 8 | test("page item count test", () => expect(func.pageItemCount(0)).toBe(2)); 9 | test("page item count test", () => expect(func.pageItemCount(1)).toBe(-1)); 10 | test("index 4 page", () => expect(func.pageIndex(5)).toBe(1)); 11 | test("index 5 page", () => expect(func.pageIndex(6)).toBe(1)); 12 | test("index 6 page", () => expect(func.pageIndex(7)).toBe(-1)); 13 | test("page 0 index", () => expect(func.pageIndex(2)).toBe(0)); 14 | test("page invalid index", () => expect(func.pageIndex(199)).toBe(-1)); 15 | test("page invalid index", () => expect(func.pageIndex(-10)).toBe(-1)); 16 | 17 | 18 | 19 | 20 | }) 21 | -------------------------------------------------------------------------------- /ts/src/solutions/tmp/algos: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amar-jay/algos/a7dfe69178b0caf94b96b437a54593cbf668e576/ts/src/solutions/tmp/algos -------------------------------------------------------------------------------- /ts/src/solutions/tmp/findPrimes.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * create a basic react todo list 3 | * @param {string} title - title of the todo 4 | * @returns {{date:string, title:string}} todo object 5 | * @example 6 | * createTodo('buy milk') // {date: '2019-01-01', title: 'buy milk'} 7 | */ 8 | 9 | function createTodo(title: string) { 10 | return { 11 | date: new Date().toISOString(), 12 | title, 13 | }; 14 | } 15 | 16 | /** 17 | * create tests for createTodo function 18 | */ 19 | 20 | function tests() { 21 | const todo = createTodo("buy milk"); 22 | const ans = compareTypes(todo, { date: "", title: "buy milk" }); 23 | console.log("tests: ", ans, ans ? "💡" : "💥"); 24 | // check if the todo is the same type as the createTodo function 25 | } 26 | 27 | tests(); 28 | 29 | function compareTypes( 30 | a: ReturnType, 31 | b: ReturnType 32 | ) { 33 | //compare types of a and b 34 | // TODO: find a way to compare types of a and b 35 | return false; 36 | } 37 | -------------------------------------------------------------------------------- /ts/src/solutions/tmp/method-delete.ts: -------------------------------------------------------------------------------- 1 | import path from 'path' 2 | 3 | const filePath = (filename:string) => { 4 | return path.join(__dirname, filename) 5 | } 6 | 7 | 8 | let x = filePath('../hello.txt') 9 | console.log(x) 10 | -------------------------------------------------------------------------------- /ts/src/solutions/tmp/method1.ts: -------------------------------------------------------------------------------- 1 | /* 2 | *Solve as long division 3 | * NOT WORKING 4 | * */ 5 | 6 | export function decomp(n: number): string { 7 | const isPrime = (num: number) => { 8 | for (var i = 2; i < num; i++) if (num % i === 0) return false; 9 | return num > 1; 10 | }; 11 | 12 | interface ICount { 13 | [x: number]: number; 14 | } 15 | 16 | const count: ICount = {}; 17 | const primeNums = [...Array(n + 1).keys()].filter((n: number) => isPrime(n)); 18 | primeNums.forEach((e) => (count[e] = 0)); 19 | 20 | const findFactorial = (num: number) => { 21 | let factor = 1; 22 | for (let i = 1; i <= num; i++) { 23 | factor = factor * i; 24 | } 25 | return factor; 26 | }; 27 | 28 | const Solve = (factorial: number, count: ICount) => { 29 | Object.keys(count).forEach((num) => { 30 | let each = Number(num); 31 | while (factorial % each == 0) { 32 | console.log( 33 | `div: ${each} | fact: ${factorial} | rem: ${factorial % each}` 34 | ); 35 | count[each] = count[each] + 1; 36 | factorial = factorial / each; 37 | } 38 | }); 39 | }; 40 | 41 | Solve(findFactorial(n), count); 42 | console.log("Count: ", count); 43 | // return JSON.stringify(count) 44 | return Object.keys(count) 45 | .map((idx) => { 46 | if (count[Number(idx)] != 0 && count[Number(idx)] != 1) { 47 | return `${idx}^${count[Number(idx)]}`; 48 | } else { 49 | return `${idx}`; 50 | } 51 | }) 52 | .join(" * "); 53 | } 54 | 55 | console.log( 56 | //"17: ", decomp(17) == "2^15 * 3^6 * 5^3 * 7^2 * 11 * 13 * 17", 57 | "\n05: ", 58 | decomp(5) == "2^3 * 3 * 5", 59 | "------------", 60 | //"\n22: ", decomp(22) == "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19", 61 | //"\n14: ", decomp(14) == "2^11 * 3^5 * 5^2 * 7^2 * 11 * 13", 62 | "\n25: ", 63 | decomp(25) == "2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23", 64 | 65 | "\n\t\t----Finished----" 66 | ); 67 | -------------------------------------------------------------------------------- /ts/src/solutions/tmp/method2.ts: -------------------------------------------------------------------------------- 1 | /* 2 | *Solve by factor tree 3 | * NOT WORKING 4 | * */ 5 | 6 | export function decomp(n: number): string { 7 | const isPrime = (num: number) => { 8 | for (var i = 2; i < num; i++) { 9 | if (num % i === 0) return false; 10 | } 11 | if (num == 1) return false; 12 | return true; 13 | }; 14 | 15 | interface ICount { 16 | [x: number]: number; 17 | } 18 | 19 | const count: ICount = {}; 20 | const findPrimeNums = (num: number) => 21 | [...Array(num + 1).keys()].filter((each: number) => isPrime(each)); 22 | const primeNums = findPrimeNums(n); 23 | primeNums.forEach((e) => (count[e] = 0)); 24 | 25 | const findFactorial = (num: number) => { 26 | let factor = 1; 27 | for (let i = 1; i <= num; i++) { 28 | factor = factor * i; 29 | } 30 | return factor; 31 | }; 32 | findFactorial(1); 33 | 34 | const Solve = (factor: number) => { 35 | let factors: number[] = []; 36 | let arr = [...Array(factor + 1).keys()]; 37 | arr.splice(0, 2); 38 | console.log("Line 34: ", arr); 39 | for (const num of arr) { 40 | if (isPrime(num)) { 41 | console.log(num); 42 | count[num] = count[num] + 1; 43 | factors.push(num); 44 | return; 45 | } else { 46 | Solve(num); 47 | } 48 | 49 | console.log("Count:", count, "\nNum: ", num); 50 | } 51 | return; 52 | }; 53 | 54 | let x = Solve(n); 55 | console.log(x); 56 | return JSON.stringify(count); 57 | /* return Object.keys(count).map((idx) => { 58 | if (count[Number(idx)]!=0 && count[Number(idx)]!=1 ){ 59 | return `${idx}^${count[Number(idx)]}` 60 | }else{ 61 | return `${idx}` 62 | } 63 | }).join(' * ') 64 | */ 65 | } 66 | 67 | console.log( 68 | //"17: ", decomp(17) == "2^15 * 3^6 * 5^3 * 7^2 * 11 * 13 * 17", 69 | "\n05: ", 70 | decomp(5) == "2^3 * 3 * 5", 71 | "------------", 72 | //"\n22: ", decomp(22) == "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19", 73 | //"\n14: ", decomp(14) == "2^11 * 3^5 * 5^2 * 7^2 * 11 * 13", 74 | //"\n25: ", decomp(25) == "2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23" 75 | 76 | "\n\t\t----Finished----" 77 | ); 78 | -------------------------------------------------------------------------------- /ts/src/solutions/tmp/method3.ts: -------------------------------------------------------------------------------- 1 | /* 2 | *Solve by factor tree 3 | * */ 4 | 5 | export function decomp(number: number): string { 6 | // function that adds the dividers of a number to a "dividers object" 7 | const subdecomp = (number: number, subdividers: { [x: number]: number }) => { 8 | let remainder = number; 9 | 10 | // from 2 to square root of the number 11 | for (let x = 2; x <= Math.sqrt(number); x++) { 12 | // check if it can divide the number 13 | if (remainder % x === 0) { 14 | // add it as a key to a results object 15 | if (!subdividers[x]) subdividers[x] = 0; 16 | // while it can be a divisor, add +1 to the key and update number 17 | while (remainder % x === 0) { 18 | subdividers[x]++; 19 | remainder = remainder / x; 20 | } 21 | } 22 | } 23 | // if after all there's still a remaining number, it is a divisor too 24 | if (remainder > 1) { 25 | if (!subdividers[remainder]) subdividers[remainder] = 1; 26 | else subdividers[remainder] += 1; 27 | } 28 | return subdividers; 29 | }; 30 | 31 | // initial dividers: none! 32 | let dividers: { [x: number]: number } = {}; 33 | 34 | // calculate the dividers for each number used in the factorial 35 | for (let x = 2; x <= number; x++) dividers = subdecomp(x, dividers); 36 | 37 | // generate a html string with the result 38 | return Object.keys(dividers) 39 | .map( 40 | (piece: string) => 41 | dividers[Number(piece)] !== 1 42 | ? piece + "^" + dividers[Number(piece)] 43 | : piece, 44 | "SOLUTION: " 45 | ) 46 | .join(" * "); 47 | } 48 | console.clear(); 49 | console.log( 50 | "\t\t\t----TESTS 🧪----", 51 | "\n17: ", 52 | decomp(17) == "2^15 * 3^6 * 5^3 * 7^2 * 11 * 13 * 17", 53 | "\n05: ", 54 | decomp(5) === "2^3 * 3 * 5", 55 | "\n22: ", 56 | decomp(22) == "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19", 57 | "\n14: ", 58 | decomp(14) == "2^11 * 3^5 * 5^2 * 7^2 * 11 * 13", 59 | "\n25: ", 60 | decomp(25) == "2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23", 61 | 62 | "\n\t\t----Completed Successfully 🍾----" 63 | ); 64 | -------------------------------------------------------------------------------- /ts/src/solutions/tmp/method4.ts: -------------------------------------------------------------------------------- 1 | const findFactorial = (num: number): number[] => { 2 | return [...new Array(num + 1).fill(0).keys()].filter((e) => e > 1); 3 | }; 4 | 5 | const isPrime = (num: number): boolean => 6 | num <= 1 7 | ? false 8 | : !Array.from(new Array(num), (_, i) => i + 1) 9 | .filter((x) => x > 1 && x < num) 10 | .find((x) => num % x === 0); 11 | 12 | const primeNums = (num: number): { [num: number]: number } => { 13 | let list = [...new Array(num + 1).fill(0).keys()].filter((num) => 14 | isPrime(num) 15 | ); 16 | 17 | let primes: { [num: number]: number } = {}; 18 | list.forEach((e) => (primes[e] = 0)); 19 | return primes; 20 | }; 21 | 22 | function main(num: number): string { 23 | let factorial = findFactorial(num); 24 | let primeNumbers = primeNums(num); 25 | for (let prime of Object.keys(primeNumbers)) { 26 | for (let i = 0; i < factorial.length; i++) { 27 | let num = factorial[i]; 28 | while (num % Number(prime) === 0) { 29 | primeNumbers[Number(prime)] = primeNumbers[Number(prime)] + 1; 30 | num /= Number(prime); 31 | } 32 | } 33 | } 34 | 35 | let str = Object.keys(primeNumbers) 36 | .map( 37 | (a) => 38 | a + (primeNumbers[Number(a)] > 1 ? `^${primeNumbers[Number(a)]}` : "") 39 | ) 40 | .join(" * "); 41 | 42 | return str; 43 | } 44 | 45 | function maintests(func: (num: number) => string): void { 46 | console.clear(); 47 | console.log( 48 | "\t\t\t----TESTS 🧪----", 49 | "\n✔️ 17: ", 50 | func(17) == "2^15 * 3^6 * 5^3 * 7^2 * 11 * 13 * 17", 51 | "\n✔️ 05: ", 52 | func(5) == "2^3 * 3 * 5", 53 | 54 | "\n✔️ 22: ", 55 | func(22) == "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19", 56 | "\n✔️ 14: ", 57 | func(14) == "2^11 * 3^5 * 5^2 * 7^2 * 11 * 13", 58 | "\n✔️ 25: ", 59 | func(25) == "2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23", 60 | "\n\t\t----Finished----" 61 | ); 62 | } 63 | maintests(main); 64 | /* 65 | My Method 66 | 67 | 1 // find a factorial of num 68 | 2 // find the prime numbers between 0-num 69 | 3 // loop primes on wheather it is divisible by the primes 70 | -> for (prime of primes) 71 | count = 0 72 | while (prime % factorial) 73 | count++ 74 | prime = prime / factorial 75 | 76 | return num 77 | 78 | 4 // store each num released 79 | 5 // stringify it 80 | 81 | */ 82 | -------------------------------------------------------------------------------- /ts/src/unique-numbers.ts: -------------------------------------------------------------------------------- 1 | export function sumOfIntervals( 2 | intervals: [start: number, end: number][] 3 | ): number { 4 | let ans = new Set(); 5 | 6 | intervals.map((range) => { 7 | let arr = Array.from( 8 | { length: range[1] - range[0] }, 9 | (_, k) => k + range[0] 10 | ); 11 | arr.map((x) => ans.add(x)); 12 | }); 13 | 14 | return ans.size; 15 | } 16 | type Type void> = ( 17 | Parameters: Parameters[0] 18 | ) => ReturnType; 19 | function maintests(func: Type) { 20 | console.log( 21 | "\t\t\t----TESTS 🧪----", 22 | "\n✔️ 1st: ", 23 | func([[1, 5]]) === 4, 24 | "\n✔️ 2nd: ", 25 | func([ 26 | [1, 5], 27 | [6, 10], 28 | ]) === 8, 29 | 30 | "\n✔️ 3rd: ", 31 | func([ 32 | [1, 5], 33 | [1, 5], 34 | ]) === 4, 35 | "\n✔️ 4th: ", 36 | func([ 37 | [1, 4], 38 | [7, 10], 39 | [3, 5], 40 | ]) === 7, 41 | "\n\t\t----Finished----" 42 | ); 43 | } 44 | maintests(sumOfIntervals); 45 | --------------------------------------------------------------------------------