From 29705aca4bb81ee6ce2dd2abe0953203cb2b0cef Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:06:37 -0400 Subject: [PATCH 01/57] github action to auto format source code per cpplint standard --- .github/workflows/clang-format.yml | 39 ++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 .github/workflows/clang-format.yml diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml new file mode 100644 index 000000000..6a95452e8 --- /dev/null +++ b/.github/workflows/clang-format.yml @@ -0,0 +1,39 @@ +name: Code Formatting + +on: [push] +# push: +# branches: [ master ] +# pull_request: +# branches: [ master ] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: requirements + run: | + sudo apt -qq -y update + sudo apt -qq install clang-format + - uses: actions/checkout@master + with: + submodules: true + - name: Formatter + run: | + for fname in $(find . -name '*.cpp' -o -name '*.h') + do + clang-format --verbose -i --style="$line1 $line2 $line3 $line4" "$fname" + done + env: + line1: "{ BasedOnStyle: Google, UseTab: Never," + line2: "IndentWidth: 4, TabWidth: 4, BreakBeforeBraces: Allman," + line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," + line4: "ColumnLimit: 80, AccessModifierOffset: -4 }" + - name: Commit files + run: | + cp -rp ./build/html/* . && rm -rf ./build && ls -lah + git config --global user.name github-actions + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git commit -am "formatting source-code for $GITHUB_SHA" || true + git push + From e459ea26d347140851b2accd8b1fe0d66ac629de Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:07:47 -0400 Subject: [PATCH 02/57] updated setting to add 1 space before `private` and `public` keywords --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 6a95452e8..4acf66536 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -27,7 +27,7 @@ jobs: line1: "{ BasedOnStyle: Google, UseTab: Never," line2: "IndentWidth: 4, TabWidth: 4, BreakBeforeBraces: Allman," line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," - line4: "ColumnLimit: 80, AccessModifierOffset: -4 }" + line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - name: Commit files run: | cp -rp ./build/html/* . && rm -rf ./build && ls -lah From adae176d2a235defd055200bc6d327949ba48c46 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:22:51 -0400 Subject: [PATCH 03/57] auto rename files and auto format code --- .github/workflows/clang-format.yml | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 4acf66536..e44869528 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -17,23 +17,30 @@ jobs: - uses: actions/checkout@master with: submodules: true - - name: Formatter + - name: Setup Git Specs + run: | + git config --global user.name github-actions + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + - name: Filename Formatter + for fname in $(find . -name '*.cpp' -o -name '*.h') + do + new_fname = tr ' ' '_' $fname + new_fname = tr 'A-Z' 'a-z' $fname + echo $new_fname + done + git commit -am "formatting filenames $GITHUB_SHA" || true + - name: Clang Formatter run: | for fname in $(find . -name '*.cpp' -o -name '*.h') do clang-format --verbose -i --style="$line1 $line2 $line3 $line4" "$fname" done + git commit -am "formatting source-code for $GITHUB_SHA" || true env: line1: "{ BasedOnStyle: Google, UseTab: Never," line2: "IndentWidth: 4, TabWidth: 4, BreakBeforeBraces: Allman," line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - - name: Commit files - run: | - cp -rp ./build/html/* . && rm -rf ./build && ls -lah - git config --global user.name github-actions - git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' - git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - git commit -am "formatting source-code for $GITHUB_SHA" || true - git push - + # -name: Git Push + # run: git push From 4c282aed0f30a4b2af10bab3f95471cb1f44412a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:24:14 -0400 Subject: [PATCH 04/57] added missing "run" for step --- .github/workflows/clang-format.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index e44869528..b4a46ed04 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -23,6 +23,7 @@ jobs: git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - name: Filename Formatter + run: | for fname in $(find . -name '*.cpp' -o -name '*.h') do new_fname = tr ' ' '_' $fname From 8edc022423ad5c45154ff2b835b5bb33f25cd26a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:26:17 -0400 Subject: [PATCH 05/57] corrected asignmemt operation --- .github/workflows/clang-format.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index b4a46ed04..cea261622 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,8 +26,8 @@ jobs: run: | for fname in $(find . -name '*.cpp' -o -name '*.h') do - new_fname = tr ' ' '_' $fname - new_fname = tr 'A-Z' 'a-z' $fname + $new_fname = tr ' ' '_' $fname + $new_fname = tr 'A-Z' 'a-z' $new_fname echo $new_fname done git commit -am "formatting filenames $GITHUB_SHA" || true From 0ea90eb3bd10aae256b01abd431e2b82f963abe6 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:30:55 -0400 Subject: [PATCH 06/57] fixed trim and assign syntax --- .github/workflows/clang-format.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index cea261622..6071aef07 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,8 +26,8 @@ jobs: run: | for fname in $(find . -name '*.cpp' -o -name '*.h') do - $new_fname = tr ' ' '_' $fname - $new_fname = tr 'A-Z' 'a-z' $new_fname + new_fname="$(echo -e "${fname}" | tr ' ' '_')" + new_fname="$(echo -e "${new_fname}"tr'A-Z' 'a-z')" echo $new_fname done git commit -am "formatting filenames $GITHUB_SHA" || true From 1a8cc7ecec9c0ac381685af8d31f2d254b7fd593 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:33:10 -0400 Subject: [PATCH 07/57] added git move for renaming bad filenames --- .github/workflows/clang-format.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 6071aef07..0acad3a2d 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -29,6 +29,7 @@ jobs: new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}"tr'A-Z' 'a-z')" echo $new_fname + git mv $fname $new_fname done git commit -am "formatting filenames $GITHUB_SHA" || true - name: Clang Formatter From a045cf894f745200accaa8f047a2c560c987c0a4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:34:20 -0400 Subject: [PATCH 08/57] added missing pipe for trim --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 0acad3a2d..1b35cd16b 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -27,7 +27,7 @@ jobs: for fname in $(find . -name '*.cpp' -o -name '*.h') do new_fname="$(echo -e "${fname}" | tr ' ' '_')" - new_fname="$(echo -e "${new_fname}"tr'A-Z' 'a-z')" + new_fname="$(echo -e "${new_fname}" | tr'A-Z' 'a-z')" echo $new_fname git mv $fname $new_fname done From cbcebf30ecb8244129e90b08c6b9e5c2cad7873c Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:35:14 -0400 Subject: [PATCH 09/57] added missing space --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 1b35cd16b..bec69d481 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -27,7 +27,7 @@ jobs: for fname in $(find . -name '*.cpp' -o -name '*.h') do new_fname="$(echo -e "${fname}" | tr ' ' '_')" - new_fname="$(echo -e "${new_fname}" | tr'A-Z' 'a-z')" + new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" echo $new_fname git mv $fname $new_fname done From 48bf52907fdc0c15af4fc92e8a61d6e46f804732 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:37:36 -0400 Subject: [PATCH 10/57] use old and new fnames --- .github/workflows/clang-format.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index bec69d481..f3940c5b6 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,10 +26,11 @@ jobs: run: | for fname in $(find . -name '*.cpp' -o -name '*.h') do + old_fname="${fname}" new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" echo $new_fname - git mv $fname $new_fname + git mv $old_fname $new_fname done git commit -am "formatting filenames $GITHUB_SHA" || true - name: Clang Formatter From 1d11ab428426480f5cf2c775e7dfe9fd35c1ecd4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:40:45 -0400 Subject: [PATCH 11/57] store old fname using echo --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index f3940c5b6..33eed8c28 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,11 +26,11 @@ jobs: run: | for fname in $(find . -name '*.cpp' -o -name '*.h') do - old_fname="${fname}" + old_fname="$(echo -e ${fname})" new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" - echo $new_fname - git mv $old_fname $new_fname + echo "${old_fname} --> ${new_fname}" + git mv ${old_fname} ${new_fname} done git commit -am "formatting filenames $GITHUB_SHA" || true - name: Clang Formatter From 93b9bc11473de0706eb450f35c60bca03c10febe Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:43:28 -0400 Subject: [PATCH 12/57] move files only if there is a change in filename --- .github/workflows/clang-format.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 33eed8c28..db96de16a 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -29,8 +29,11 @@ jobs: old_fname="$(echo -e ${fname})" new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" - echo "${old_fname} --> ${new_fname}" - git mv ${old_fname} ${new_fname} + if [$old_fname != $new_fname] + then + echo "${old_fname} --> ${new_fname}" + git mv ${old_fname} ${new_fname} + fi done git commit -am "formatting filenames $GITHUB_SHA" || true - name: Clang Formatter From 493c52f19ad05f491068db3dfd52cd6d876a4a15 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:45:54 -0400 Subject: [PATCH 13/57] put old filenames in quotes --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index db96de16a..5fe5e589d 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -29,10 +29,10 @@ jobs: old_fname="$(echo -e ${fname})" new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" - if [$old_fname != $new_fname] + if [ '$old_fname' != '$new_fname' ] then - echo "${old_fname} --> ${new_fname}" - git mv ${old_fname} ${new_fname} + echo "'${old_fname}' --> ${new_fname}" + git mv '${old_fname}' ${new_fname} fi done git commit -am "formatting filenames $GITHUB_SHA" || true From 45f5bb65d0a78026a7ad7375afdf35293b41e001 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:47:40 -0400 Subject: [PATCH 14/57] use double quote for old filename --- .github/workflows/clang-format.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 5fe5e589d..a8ba8a273 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -29,10 +29,10 @@ jobs: old_fname="$(echo -e ${fname})" new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" - if [ '$old_fname' != '$new_fname' ] + if [ $old_fname != $new_fname ] then echo "'${old_fname}' --> ${new_fname}" - git mv '${old_fname}' ${new_fname} + git mv "${old_fname}" ${new_fname} fi done git commit -am "formatting filenames $GITHUB_SHA" || true From 29c066de048ccbf9f11955be02b8e1ed81c19013 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:50:17 -0400 Subject: [PATCH 15/57] escape double quotes --- .github/workflows/clang-format.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index a8ba8a273..1a9d5ccfc 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -31,8 +31,8 @@ jobs: new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" if [ $old_fname != $new_fname ] then - echo "'${old_fname}' --> ${new_fname}" - git mv "${old_fname}" ${new_fname} + echo '"${old_fname}" --> ${new_fname}' + git mv \"${old_fname}\" ${new_fname} fi done git commit -am "formatting filenames $GITHUB_SHA" || true From c0dcc91276e17be5dc55bc1397bafbdae6bce604 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 17:52:50 -0400 Subject: [PATCH 16/57] remove old_fname --- .github/workflows/clang-format.yml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 1a9d5ccfc..50f2169da 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,13 +26,12 @@ jobs: run: | for fname in $(find . -name '*.cpp' -o -name '*.h') do - old_fname="$(echo -e ${fname})" new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" - if [ $old_fname != $new_fname ] + if [ $fname != $new_fname ] then - echo '"${old_fname}" --> ${new_fname}' - git mv \"${old_fname}\" ${new_fname} + echo '"${fname}" --> ${new_fname}' + git mv "${fname}" ${new_fname} fi done git commit -am "formatting filenames $GITHUB_SHA" || true From 63f13ea50bb03f59ae0057b3fcc0f1342426baa1 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:00:34 -0400 Subject: [PATCH 17/57] try escape characters and echo" --- .github/workflows/clang-format.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 50f2169da..fac11f908 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -30,8 +30,8 @@ jobs: new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" if [ $fname != $new_fname ] then - echo '"${fname}" --> ${new_fname}' - git mv "${fname}" ${new_fname} + echo -e "'"$fname"' --> '"$new_fname"'" + git mv "$(echo -e "$fname")" $new_fname fi done git commit -am "formatting filenames $GITHUB_SHA" || true From 18a74bb9a082147720bb30ef3ceb0a23a9ac6dcf Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:06:55 -0400 Subject: [PATCH 18/57] add file-type to find --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index fac11f908..aaea3325f 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -24,14 +24,14 @@ jobs: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - name: Filename Formatter run: | - for fname in $(find . -name '*.cpp' -o -name '*.h') + for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do new_fname="$(echo -e "${fname}" | tr ' ' '_')" new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" if [ $fname != $new_fname ] then - echo -e "'"$fname"' --> '"$new_fname"'" - git mv "$(echo -e "$fname")" $new_fname + echo -e "$(echo -e "$fname")" --> '"$new_fname"'" + git mv "$fname" $new_fname fi done git commit -am "formatting filenames $GITHUB_SHA" || true From 24f65d859954410e749d4b27a57be776a53d8adb Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:08:48 -0400 Subject: [PATCH 19/57] cleanup echo --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index aaea3325f..5ee612c99 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -30,7 +30,7 @@ jobs: new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" if [ $fname != $new_fname ] then - echo -e "$(echo -e "$fname")" --> '"$new_fname"'" + echo -e $fname" --> "$new_fname git mv "$fname" $new_fname fi done From bb973aa17d201af39b8e04e9c1911c1e8b393b3a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:11:49 -0400 Subject: [PATCH 20/57] ensure all trim variables are also in quotes --- .github/workflows/clang-format.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 5ee612c99..1f9dcb98b 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,8 +26,8 @@ jobs: run: | for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do - new_fname="$(echo -e "${fname}" | tr ' ' '_')" - new_fname="$(echo -e "${new_fname}" | tr 'A-Z' 'a-z')" + new_fname="$(echo -e ${fname} | tr ' ' '_')" + new_fname="$(echo -e ${new_fname} | tr 'A-Z' 'a-z')" if [ $fname != $new_fname ] then echo -e $fname" --> "$new_fname From b5f4637cc7d5419104155576c077438a18ad11b3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:14:56 -0400 Subject: [PATCH 21/57] try escape -quote again --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 1f9dcb98b..8c56fbed6 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,11 +26,11 @@ jobs: run: | for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do - new_fname="$(echo -e ${fname} | tr ' ' '_')" - new_fname="$(echo -e ${new_fname} | tr 'A-Z' 'a-z')" + new_fname="$(echo -e \"${fname}\" | tr ' ' '_')" + new_fname="$(echo -e \"${new_fname}\" | tr 'A-Z' 'a-z')" if [ $fname != $new_fname ] then - echo -e $fname" --> "$new_fname + echo -e "\"$fname\" --> $new_fname" git mv "$fname" $new_fname fi done From 4011a18ff90ea87bd4a988f168bc6614527bd153 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:17:46 -0400 Subject: [PATCH 22/57] remove second escpe quote --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 8c56fbed6..600968b3d 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -27,7 +27,7 @@ jobs: for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do new_fname="$(echo -e \"${fname}\" | tr ' ' '_')" - new_fname="$(echo -e \"${new_fname}\" | tr 'A-Z' 'a-z')" + new_fname="$(echo -e ${new_fname} | tr 'A-Z' 'a-z')" if [ $fname != $new_fname ] then echo -e "\"$fname\" --> $new_fname" From b3242230e86118e4670db2b742c5d0ec699fbfc6 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:20:21 -0400 Subject: [PATCH 23/57] use single quote for first check --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 600968b3d..4984aa7cf 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,7 +26,7 @@ jobs: run: | for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do - new_fname="$(echo -e \"${fname}\" | tr ' ' '_')" + new_fname="$(echo -e '${fname}' | tr ' ' '_')" new_fname="$(echo -e ${new_fname} | tr 'A-Z' 'a-z')" if [ $fname != $new_fname ] then From 097f0d23eb7ccb94ed8f0b83103a28b2f5e78d2b Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:24:00 -0400 Subject: [PATCH 24/57] use carets instead of quotes --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 4984aa7cf..64e2c3872 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,11 +26,11 @@ jobs: run: | for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do - new_fname="$(echo -e '${fname}' | tr ' ' '_')" - new_fname="$(echo -e ${new_fname} | tr 'A-Z' 'a-z')" + new_fname=`echo -e ${fname} | tr ' ' '_'` + new_fname=`echo -e ${new_fname} | tr 'A-Z' 'a-z'` if [ $fname != $new_fname ] then - echo -e "\"$fname\" --> $new_fname" + echo -e "$fname --> $new_fname" git mv "$fname" $new_fname fi done From 43b28808923a36b984347c1457208d4237d2dfae Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:25:38 -0400 Subject: [PATCH 25/57] put variables in brackets --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 64e2c3872..0c5e1d82f 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -28,10 +28,10 @@ jobs: do new_fname=`echo -e ${fname} | tr ' ' '_'` new_fname=`echo -e ${new_fname} | tr 'A-Z' 'a-z'` - if [ $fname != $new_fname ] + if [ ${fname} != ${new_fname} ] then - echo -e "$fname --> $new_fname" - git mv "$fname" $new_fname + echo -e "${fname} --> ${new_fname}" + git mv "${fname}" ${new_fname} fi done git commit -am "formatting filenames $GITHUB_SHA" || true From b9ed82475e80e528809ea85ffec3925865792876 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:29:50 -0400 Subject: [PATCH 26/57] remove -e from echo --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 0c5e1d82f..2e1bc9fe0 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,11 +26,11 @@ jobs: run: | for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do - new_fname=`echo -e ${fname} | tr ' ' '_'` - new_fname=`echo -e ${new_fname} | tr 'A-Z' 'a-z'` + new_fname=`echo ${fname} | tr ' ' '_'` + new_fname=`echo ${new_fname} | tr 'A-Z' 'a-z'` if [ ${fname} != ${new_fname} ] then - echo -e "${fname} --> ${new_fname}" + echo "${fname} --> ${new_fname}" git mv "${fname}" ${new_fname} fi done From 2a674c3d9e136b6aea9b1aa305d4fde4543d563a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:32:03 -0400 Subject: [PATCH 27/57] add debug echos --- .github/workflows/clang-format.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 2e1bc9fe0..8f7f4a7b2 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,11 +26,14 @@ jobs: run: | for fname in $(find . -type f -name '*.cpp' -o -name '*.h') do + echo "${fname}" new_fname=`echo ${fname} | tr ' ' '_'` + echo " ${new_fname}" new_fname=`echo ${new_fname} | tr 'A-Z' 'a-z'` + echo " ${new_fname}" if [ ${fname} != ${new_fname} ] then - echo "${fname} --> ${new_fname}" + echo " ${fname} --> ${new_fname}" git mv "${fname}" ${new_fname} fi done From 9844d887b0a7f6aba1736d30bb2aa8149cb178e2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:37:32 -0400 Subject: [PATCH 28/57] try print0 flag --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 8f7f4a7b2..90c7ffc82 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -24,7 +24,7 @@ jobs: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - name: Filename Formatter run: | - for fname in $(find . -type f -name '*.cpp' -o -name '*.h') + for fname in `find . -type f -name '*.cpp' -o -name '*.h' -print0` do echo "${fname}" new_fname=`echo ${fname} | tr ' ' '_'` From 1d24b96ad6debfb3db755dfa74903b4fa7f7761e Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:47:20 -0400 Subject: [PATCH 29/57] find command with while instead of for-loop --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 90c7ffc82..b50b8717e 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -24,7 +24,7 @@ jobs: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - name: Filename Formatter run: | - for fname in `find . -type f -name '*.cpp' -o -name '*.h' -print0` + find . -type f -name '*.cpp' -o -name '*.h' -print0 | while read -d $'\0' fname do echo "${fname}" new_fname=`echo ${fname} | tr ' ' '_'` From 0e130658b570f9e5d09df2c8da8520b0c70128e0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:52:01 -0400 Subject: [PATCH 30/57] find command using IFS instead --- .github/workflows/clang-format.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index b50b8717e..44260450a 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -24,7 +24,8 @@ jobs: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - name: Filename Formatter run: | - find . -type f -name '*.cpp' -o -name '*.h' -print0 | while read -d $'\0' fname + IFS=$'\n' + for fname in `find . -type f -name '*.cpp' -o -name '*.h'` do echo "${fname}" new_fname=`echo ${fname} | tr ' ' '_'` From 65dbaf7c693988d9e1ce7821cc3d93363af8a353 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 18:55:36 -0400 Subject: [PATCH 31/57] :tada: IFS fix worked - escaped quotes for git mv --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 44260450a..d2702bf3a 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -35,7 +35,7 @@ jobs: if [ ${fname} != ${new_fname} ] then echo " ${fname} --> ${new_fname}" - git mv "${fname}" ${new_fname} + git mv \"${fname}\" ${new_fname} fi done git commit -am "formatting filenames $GITHUB_SHA" || true From 9643f75e0f7968f1eec91f9a4d865b6c8dbd7371 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 19:04:14 -0400 Subject: [PATCH 32/57] protetc each word in git mv .. --- .github/workflows/clang-format.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index d2702bf3a..e6d8dee9a 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -32,10 +32,12 @@ jobs: echo " ${new_fname}" new_fname=`echo ${new_fname} | tr 'A-Z' 'a-z'` echo " ${new_fname}" + new_fname=`echo ${new_fname} | tr '-' '_'` + echo " ${new_fname}" if [ ${fname} != ${new_fname} ] then echo " ${fname} --> ${new_fname}" - git mv \"${fname}\" ${new_fname} + git "mv" "${fname}" ${new_fname} fi done git commit -am "formatting filenames $GITHUB_SHA" || true From 7b6932cd6ed490299b3b0a16d1d153e86c10e58f Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 19:08:43 -0400 Subject: [PATCH 33/57] filename exists in lower cases - renamed --- data_structure/{Queue Using Array.cpp => Queue Using Array2.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename data_structure/{Queue Using Array.cpp => Queue Using Array2.cpp} (100%) diff --git a/data_structure/Queue Using Array.cpp b/data_structure/Queue Using Array2.cpp similarity index 100% rename from data_structure/Queue Using Array.cpp rename to data_structure/Queue Using Array2.cpp From e7bc4e26192fbd948bb73e810f2ab7edc63c53c3 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 19:23:01 -0400 Subject: [PATCH 34/57] :tada: git push enabled --- .github/workflows/clang-format.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index e6d8dee9a..3fb7374e6 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -53,5 +53,5 @@ jobs: line2: "IndentWidth: 4, TabWidth: 4, BreakBeforeBraces: Allman," line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - # -name: Git Push - # run: git push + - name: Git Push + run: git push From fd394fd113463f0733aa6bfc7cab0b88dcb8b318 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 29 May 2020 23:23:29 +0000 Subject: [PATCH 35/57] updating DIRECTORY.md --- DIRECTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 189d6041b..d90326050 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -32,7 +32,7 @@ * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedList_implentation_usingArray.cpp) * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/List%20Array.cpp) * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/MorrisInorder.cpp) - * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Array.cpp) + * [Queue Using Array2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Array2.cpp) * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Linked%20List.cpp) * Queue * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.cpp) From fed47f610ce64ecb4fa78219abd2262f47ec0484 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 19:24:24 -0400 Subject: [PATCH 36/57] git pull & then push --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 3fb7374e6..a8d61e423 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -54,4 +54,4 @@ jobs: line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - name: Git Push - run: git push + run: git pull && git push From edb3d51ec259e80e4da596a4aaae27505def43bc Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 29 May 2020 23:26:28 +0000 Subject: [PATCH 37/57] formatting filenames d7af6fdc8cb08578de6980d412e6e1caca1a1bcf --- data_structure/{AVLtree.cpp => avltree.cpp} | 0 data_structure/{Binary Search Tree.cpp => binary_search_tree.cpp} | 0 data_structure/{Binaryheap.cpp => binaryheap.cpp} | 0 ...using_Linked_List.cpp => circular_queue_using_linked_list.cpp} | 0 ...tion_usingArray.cpp => linkedlist_implentation_usingarray.cpp} | 0 data_structure/{List Array.cpp => list_array.cpp} | 0 data_structure/{MorrisInorder.cpp => morrisinorder.cpp} | 0 data_structure/{Queue Using Array2.cpp => queue_using_array2.cpp} | 0 .../{Queue Using Linked List.cpp => queue_using_linked_list.cpp} | 0 data_structure/{Stack Using Array.cpp => stack_using_array.cpp} | 0 .../{Stack Using Linked List.cpp => stack_using_linked_list.cpp} | 0 data_structure/{Tree.cpp => tree.cpp} | 0 dynamic_programming/{0-1 Knapsack.cpp => 0_1_knapsack.cpp} | 0 dynamic_programming/{Bellman-Ford.cpp => bellman_ford.cpp} | 0 dynamic_programming/{Catalan-Numbers.cpp => catalan_numbers.cpp} | 0 dynamic_programming/{Coin-Change.cpp => coin_change.cpp} | 0 dynamic_programming/{Cut Rod.cpp => cut_rod.cpp} | 0 dynamic_programming/{Edit Distance.cpp => edit_distance.cpp} | 0 .../{Egg-Dropping-Puzzle.cpp => egg_dropping_puzzle.cpp} | 0 .../{Fibonacci_Bottom_Up.cpp => fibonacci_bottom_up.cpp} | 0 .../{Fibonacci_Top_Down.cpp => fibonacci_top_down.cpp} | 0 dynamic_programming/{Floyd-Warshall.cpp => floyd_warshall.cpp} | 0 ...gest Common Subsequence.cpp => longest_common_subsequence.cpp} | 0 ...reasing Subsequence.cpp => longest_increasing_subsequence.cpp} | 0 ...nce (nlogn).cpp => longest_increasing_subsequence_(nlogn).cpp} | 0 ...x-Chain-Multiplication.cpp => matrix_chain_multiplication.cpp} | 0 graph/{BFS.cpp => bfs.cpp} | 0 graph/{DFS.cpp => dfs.cpp} | 0 graph/{Dijkstra.cpp => dijkstra.cpp} | 0 graph/{Kruskal.cpp => kruskal.cpp} | 0 graph/{Topological-Sort.cpp => topological_sort.cpp} | 0 greedy_algorithms/{Dijkstra.cpp => dijkstra.cpp} | 0 greedy_algorithms/{Knapsack.cpp => knapsack.cpp} | 0 ...nimum Spanning Tree.cpp => kruskals_minimum_spanning_tree.cpp} | 0 ... Minimum Spanning Tree.cpp => prims_minimum_spanning_tree.cpp} | 0 hashing/{Chaining.cpp => chaining.cpp} | 0 .../{Array Left Rotation.cpp => array_left_rotation.cpp} | 0 .../{Array Right Rotation.cpp => array_right_rotation.cpp} | 0 .../{Circular Linked List.cpp => circular_linked_list.cpp} | 0 ...cular Queue Using Array.cpp => circular_queue_using_array.cpp} | 0 ...{Intersection_of_2_arrays.cpp => intersection_of_2_arrays.cpp} | 0 ...sing Recusion.cpp => reverse_a_linked_list_using_recusion.cpp} | 0 .../{selectionSortLinkedList.cpp => selectionsortlinkedlist.cpp} | 0 .../{Union_of_2_arrays.cpp => union_of_2_arrays.cpp} | 0 range_queries/{FenwickTree.cpp => fenwicktree.cpp} | 0 range_queries/{MO.cpp => mo.cpp} | 0 range_queries/{segTree.cpp => segtree.cpp} | 0 sorting/{Counting_Sort.cpp => counting_sort.cpp} | 0 48 files changed, 0 insertions(+), 0 deletions(-) rename data_structure/{AVLtree.cpp => avltree.cpp} (100%) rename data_structure/{Binary Search Tree.cpp => binary_search_tree.cpp} (100%) rename data_structure/{Binaryheap.cpp => binaryheap.cpp} (100%) rename data_structure/{circular_Queue_using_Linked_List.cpp => circular_queue_using_linked_list.cpp} (100%) rename data_structure/{linkedList_implentation_usingArray.cpp => linkedlist_implentation_usingarray.cpp} (100%) rename data_structure/{List Array.cpp => list_array.cpp} (100%) rename data_structure/{MorrisInorder.cpp => morrisinorder.cpp} (100%) rename data_structure/{Queue Using Array2.cpp => queue_using_array2.cpp} (100%) rename data_structure/{Queue Using Linked List.cpp => queue_using_linked_list.cpp} (100%) rename data_structure/{Stack Using Array.cpp => stack_using_array.cpp} (100%) rename data_structure/{Stack Using Linked List.cpp => stack_using_linked_list.cpp} (100%) rename data_structure/{Tree.cpp => tree.cpp} (100%) rename dynamic_programming/{0-1 Knapsack.cpp => 0_1_knapsack.cpp} (100%) rename dynamic_programming/{Bellman-Ford.cpp => bellman_ford.cpp} (100%) rename dynamic_programming/{Catalan-Numbers.cpp => catalan_numbers.cpp} (100%) rename dynamic_programming/{Coin-Change.cpp => coin_change.cpp} (100%) rename dynamic_programming/{Cut Rod.cpp => cut_rod.cpp} (100%) rename dynamic_programming/{Edit Distance.cpp => edit_distance.cpp} (100%) rename dynamic_programming/{Egg-Dropping-Puzzle.cpp => egg_dropping_puzzle.cpp} (100%) rename dynamic_programming/{Fibonacci_Bottom_Up.cpp => fibonacci_bottom_up.cpp} (100%) rename dynamic_programming/{Fibonacci_Top_Down.cpp => fibonacci_top_down.cpp} (100%) rename dynamic_programming/{Floyd-Warshall.cpp => floyd_warshall.cpp} (100%) rename dynamic_programming/{Longest Common Subsequence.cpp => longest_common_subsequence.cpp} (100%) rename dynamic_programming/{Longest Increasing Subsequence.cpp => longest_increasing_subsequence.cpp} (100%) rename dynamic_programming/{Longest Increasing Subsequence (nlogn).cpp => longest_increasing_subsequence_(nlogn).cpp} (100%) rename dynamic_programming/{Matrix-Chain-Multiplication.cpp => matrix_chain_multiplication.cpp} (100%) rename graph/{BFS.cpp => bfs.cpp} (100%) rename graph/{DFS.cpp => dfs.cpp} (100%) rename graph/{Dijkstra.cpp => dijkstra.cpp} (100%) rename graph/{Kruskal.cpp => kruskal.cpp} (100%) rename graph/{Topological-Sort.cpp => topological_sort.cpp} (100%) rename greedy_algorithms/{Dijkstra.cpp => dijkstra.cpp} (100%) rename greedy_algorithms/{Knapsack.cpp => knapsack.cpp} (100%) rename greedy_algorithms/{Kruskals Minimum Spanning Tree.cpp => kruskals_minimum_spanning_tree.cpp} (100%) rename greedy_algorithms/{Prims Minimum Spanning Tree.cpp => prims_minimum_spanning_tree.cpp} (100%) rename hashing/{Chaining.cpp => chaining.cpp} (100%) rename operations_on_datastructures/{Array Left Rotation.cpp => array_left_rotation.cpp} (100%) rename operations_on_datastructures/{Array Right Rotation.cpp => array_right_rotation.cpp} (100%) rename operations_on_datastructures/{Circular Linked List.cpp => circular_linked_list.cpp} (100%) rename operations_on_datastructures/{Circular Queue Using Array.cpp => circular_queue_using_array.cpp} (100%) rename operations_on_datastructures/{Intersection_of_2_arrays.cpp => intersection_of_2_arrays.cpp} (100%) rename operations_on_datastructures/{Reverse a Linked List using Recusion.cpp => reverse_a_linked_list_using_recusion.cpp} (100%) rename operations_on_datastructures/{selectionSortLinkedList.cpp => selectionsortlinkedlist.cpp} (100%) rename operations_on_datastructures/{Union_of_2_arrays.cpp => union_of_2_arrays.cpp} (100%) rename range_queries/{FenwickTree.cpp => fenwicktree.cpp} (100%) rename range_queries/{MO.cpp => mo.cpp} (100%) rename range_queries/{segTree.cpp => segtree.cpp} (100%) rename sorting/{Counting_Sort.cpp => counting_sort.cpp} (100%) diff --git a/data_structure/AVLtree.cpp b/data_structure/avltree.cpp similarity index 100% rename from data_structure/AVLtree.cpp rename to data_structure/avltree.cpp diff --git a/data_structure/Binary Search Tree.cpp b/data_structure/binary_search_tree.cpp similarity index 100% rename from data_structure/Binary Search Tree.cpp rename to data_structure/binary_search_tree.cpp diff --git a/data_structure/Binaryheap.cpp b/data_structure/binaryheap.cpp similarity index 100% rename from data_structure/Binaryheap.cpp rename to data_structure/binaryheap.cpp diff --git a/data_structure/circular_Queue_using_Linked_List.cpp b/data_structure/circular_queue_using_linked_list.cpp similarity index 100% rename from data_structure/circular_Queue_using_Linked_List.cpp rename to data_structure/circular_queue_using_linked_list.cpp diff --git a/data_structure/linkedList_implentation_usingArray.cpp b/data_structure/linkedlist_implentation_usingarray.cpp similarity index 100% rename from data_structure/linkedList_implentation_usingArray.cpp rename to data_structure/linkedlist_implentation_usingarray.cpp diff --git a/data_structure/List Array.cpp b/data_structure/list_array.cpp similarity index 100% rename from data_structure/List Array.cpp rename to data_structure/list_array.cpp diff --git a/data_structure/MorrisInorder.cpp b/data_structure/morrisinorder.cpp similarity index 100% rename from data_structure/MorrisInorder.cpp rename to data_structure/morrisinorder.cpp diff --git a/data_structure/Queue Using Array2.cpp b/data_structure/queue_using_array2.cpp similarity index 100% rename from data_structure/Queue Using Array2.cpp rename to data_structure/queue_using_array2.cpp diff --git a/data_structure/Queue Using Linked List.cpp b/data_structure/queue_using_linked_list.cpp similarity index 100% rename from data_structure/Queue Using Linked List.cpp rename to data_structure/queue_using_linked_list.cpp diff --git a/data_structure/Stack Using Array.cpp b/data_structure/stack_using_array.cpp similarity index 100% rename from data_structure/Stack Using Array.cpp rename to data_structure/stack_using_array.cpp diff --git a/data_structure/Stack Using Linked List.cpp b/data_structure/stack_using_linked_list.cpp similarity index 100% rename from data_structure/Stack Using Linked List.cpp rename to data_structure/stack_using_linked_list.cpp diff --git a/data_structure/Tree.cpp b/data_structure/tree.cpp similarity index 100% rename from data_structure/Tree.cpp rename to data_structure/tree.cpp diff --git a/dynamic_programming/0-1 Knapsack.cpp b/dynamic_programming/0_1_knapsack.cpp similarity index 100% rename from dynamic_programming/0-1 Knapsack.cpp rename to dynamic_programming/0_1_knapsack.cpp diff --git a/dynamic_programming/Bellman-Ford.cpp b/dynamic_programming/bellman_ford.cpp similarity index 100% rename from dynamic_programming/Bellman-Ford.cpp rename to dynamic_programming/bellman_ford.cpp diff --git a/dynamic_programming/Catalan-Numbers.cpp b/dynamic_programming/catalan_numbers.cpp similarity index 100% rename from dynamic_programming/Catalan-Numbers.cpp rename to dynamic_programming/catalan_numbers.cpp diff --git a/dynamic_programming/Coin-Change.cpp b/dynamic_programming/coin_change.cpp similarity index 100% rename from dynamic_programming/Coin-Change.cpp rename to dynamic_programming/coin_change.cpp diff --git a/dynamic_programming/Cut Rod.cpp b/dynamic_programming/cut_rod.cpp similarity index 100% rename from dynamic_programming/Cut Rod.cpp rename to dynamic_programming/cut_rod.cpp diff --git a/dynamic_programming/Edit Distance.cpp b/dynamic_programming/edit_distance.cpp similarity index 100% rename from dynamic_programming/Edit Distance.cpp rename to dynamic_programming/edit_distance.cpp diff --git a/dynamic_programming/Egg-Dropping-Puzzle.cpp b/dynamic_programming/egg_dropping_puzzle.cpp similarity index 100% rename from dynamic_programming/Egg-Dropping-Puzzle.cpp rename to dynamic_programming/egg_dropping_puzzle.cpp diff --git a/dynamic_programming/Fibonacci_Bottom_Up.cpp b/dynamic_programming/fibonacci_bottom_up.cpp similarity index 100% rename from dynamic_programming/Fibonacci_Bottom_Up.cpp rename to dynamic_programming/fibonacci_bottom_up.cpp diff --git a/dynamic_programming/Fibonacci_Top_Down.cpp b/dynamic_programming/fibonacci_top_down.cpp similarity index 100% rename from dynamic_programming/Fibonacci_Top_Down.cpp rename to dynamic_programming/fibonacci_top_down.cpp diff --git a/dynamic_programming/Floyd-Warshall.cpp b/dynamic_programming/floyd_warshall.cpp similarity index 100% rename from dynamic_programming/Floyd-Warshall.cpp rename to dynamic_programming/floyd_warshall.cpp diff --git a/dynamic_programming/Longest Common Subsequence.cpp b/dynamic_programming/longest_common_subsequence.cpp similarity index 100% rename from dynamic_programming/Longest Common Subsequence.cpp rename to dynamic_programming/longest_common_subsequence.cpp diff --git a/dynamic_programming/Longest Increasing Subsequence.cpp b/dynamic_programming/longest_increasing_subsequence.cpp similarity index 100% rename from dynamic_programming/Longest Increasing Subsequence.cpp rename to dynamic_programming/longest_increasing_subsequence.cpp diff --git a/dynamic_programming/Longest Increasing Subsequence (nlogn).cpp b/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp similarity index 100% rename from dynamic_programming/Longest Increasing Subsequence (nlogn).cpp rename to dynamic_programming/longest_increasing_subsequence_(nlogn).cpp diff --git a/dynamic_programming/Matrix-Chain-Multiplication.cpp b/dynamic_programming/matrix_chain_multiplication.cpp similarity index 100% rename from dynamic_programming/Matrix-Chain-Multiplication.cpp rename to dynamic_programming/matrix_chain_multiplication.cpp diff --git a/graph/BFS.cpp b/graph/bfs.cpp similarity index 100% rename from graph/BFS.cpp rename to graph/bfs.cpp diff --git a/graph/DFS.cpp b/graph/dfs.cpp similarity index 100% rename from graph/DFS.cpp rename to graph/dfs.cpp diff --git a/graph/Dijkstra.cpp b/graph/dijkstra.cpp similarity index 100% rename from graph/Dijkstra.cpp rename to graph/dijkstra.cpp diff --git a/graph/Kruskal.cpp b/graph/kruskal.cpp similarity index 100% rename from graph/Kruskal.cpp rename to graph/kruskal.cpp diff --git a/graph/Topological-Sort.cpp b/graph/topological_sort.cpp similarity index 100% rename from graph/Topological-Sort.cpp rename to graph/topological_sort.cpp diff --git a/greedy_algorithms/Dijkstra.cpp b/greedy_algorithms/dijkstra.cpp similarity index 100% rename from greedy_algorithms/Dijkstra.cpp rename to greedy_algorithms/dijkstra.cpp diff --git a/greedy_algorithms/Knapsack.cpp b/greedy_algorithms/knapsack.cpp similarity index 100% rename from greedy_algorithms/Knapsack.cpp rename to greedy_algorithms/knapsack.cpp diff --git a/greedy_algorithms/Kruskals Minimum Spanning Tree.cpp b/greedy_algorithms/kruskals_minimum_spanning_tree.cpp similarity index 100% rename from greedy_algorithms/Kruskals Minimum Spanning Tree.cpp rename to greedy_algorithms/kruskals_minimum_spanning_tree.cpp diff --git a/greedy_algorithms/Prims Minimum Spanning Tree.cpp b/greedy_algorithms/prims_minimum_spanning_tree.cpp similarity index 100% rename from greedy_algorithms/Prims Minimum Spanning Tree.cpp rename to greedy_algorithms/prims_minimum_spanning_tree.cpp diff --git a/hashing/Chaining.cpp b/hashing/chaining.cpp similarity index 100% rename from hashing/Chaining.cpp rename to hashing/chaining.cpp diff --git a/operations_on_datastructures/Array Left Rotation.cpp b/operations_on_datastructures/array_left_rotation.cpp similarity index 100% rename from operations_on_datastructures/Array Left Rotation.cpp rename to operations_on_datastructures/array_left_rotation.cpp diff --git a/operations_on_datastructures/Array Right Rotation.cpp b/operations_on_datastructures/array_right_rotation.cpp similarity index 100% rename from operations_on_datastructures/Array Right Rotation.cpp rename to operations_on_datastructures/array_right_rotation.cpp diff --git a/operations_on_datastructures/Circular Linked List.cpp b/operations_on_datastructures/circular_linked_list.cpp similarity index 100% rename from operations_on_datastructures/Circular Linked List.cpp rename to operations_on_datastructures/circular_linked_list.cpp diff --git a/operations_on_datastructures/Circular Queue Using Array.cpp b/operations_on_datastructures/circular_queue_using_array.cpp similarity index 100% rename from operations_on_datastructures/Circular Queue Using Array.cpp rename to operations_on_datastructures/circular_queue_using_array.cpp diff --git a/operations_on_datastructures/Intersection_of_2_arrays.cpp b/operations_on_datastructures/intersection_of_2_arrays.cpp similarity index 100% rename from operations_on_datastructures/Intersection_of_2_arrays.cpp rename to operations_on_datastructures/intersection_of_2_arrays.cpp diff --git a/operations_on_datastructures/Reverse a Linked List using Recusion.cpp b/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp similarity index 100% rename from operations_on_datastructures/Reverse a Linked List using Recusion.cpp rename to operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp diff --git a/operations_on_datastructures/selectionSortLinkedList.cpp b/operations_on_datastructures/selectionsortlinkedlist.cpp similarity index 100% rename from operations_on_datastructures/selectionSortLinkedList.cpp rename to operations_on_datastructures/selectionsortlinkedlist.cpp diff --git a/operations_on_datastructures/Union_of_2_arrays.cpp b/operations_on_datastructures/union_of_2_arrays.cpp similarity index 100% rename from operations_on_datastructures/Union_of_2_arrays.cpp rename to operations_on_datastructures/union_of_2_arrays.cpp diff --git a/range_queries/FenwickTree.cpp b/range_queries/fenwicktree.cpp similarity index 100% rename from range_queries/FenwickTree.cpp rename to range_queries/fenwicktree.cpp diff --git a/range_queries/MO.cpp b/range_queries/mo.cpp similarity index 100% rename from range_queries/MO.cpp rename to range_queries/mo.cpp diff --git a/range_queries/segTree.cpp b/range_queries/segtree.cpp similarity index 100% rename from range_queries/segTree.cpp rename to range_queries/segtree.cpp diff --git a/sorting/Counting_Sort.cpp b/sorting/counting_sort.cpp similarity index 100% rename from sorting/Counting_Sort.cpp rename to sorting/counting_sort.cpp From 7ad1f171c139e206761c17d50dd7093a6875ee5a Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 29 May 2020 23:26:30 +0000 Subject: [PATCH 38/57] formatting source-code for d7af6fdc8cb08578de6980d412e6e1caca1a1bcf --- backtracking/graph_coloring.cpp | 8 +- backtracking/knight_tour.cpp | 69 ++-- backtracking/minimax.cpp | 8 +- backtracking/n_queens.cpp | 12 +- .../n_queens_all_solution_optimised.cpp | 68 ++-- backtracking/nqueen_print_all_solutions.cpp | 36 +- backtracking/rat_maze.cpp | 108 +++--- backtracking/sudoku_solve.cpp | 41 +-- .../bisection_method.cpp | 29 +- .../false_position.cpp | 25 +- .../gaussian_elimination.cpp | 33 +- .../newton_raphson_method.cpp | 12 +- .../ordinary_least_squares_regressor.cpp | 112 ++++-- .../successive_approximation.cpp | 9 +- data_structure/avltree.cpp | 215 ++++++----- data_structure/binary_search_tree.cpp | 336 +++++++++--------- data_structure/binaryheap.cpp | 10 +- .../circular_queue_using_linked_list.cpp | 2 +- data_structure/cll/cll.cpp | 70 ++-- data_structure/cll/cll.h | 50 +-- data_structure/cll/main_cll.cpp | 72 ++-- data_structure/disjoint_set.cpp | 114 +++--- data_structure/doubly_linked_list.cpp | 278 ++++++++------- data_structure/linked_list.cpp | 257 ++++++++------ .../linkedlist_implentation_usingarray.cpp | 26 +- data_structure/list_array.cpp | 324 +++++++++-------- data_structure/morrisinorder.cpp | 170 ++++----- data_structure/queue/queue.cpp | 28 +- data_structure/queue/queue.h | 27 +- data_structure/queue/test_queue.cpp | 28 +- data_structure/queue_using_array.cpp | 72 ++-- data_structure/queue_using_array2.cpp | 101 +++--- data_structure/queue_using_linked_list.cpp | 4 +- data_structure/queue_using_linkedlist.cpp | 129 +++---- data_structure/stack_using_array.cpp | 110 +++--- data_structure/stack_using_linked_list.cpp | 95 +++-- data_structure/stk/main.cpp | 28 +- data_structure/stk/stack.cpp | 27 +- data_structure/stk/stack.h | 29 +- data_structure/stk/test_stack.cpp | 34 +- data_structure/tree.cpp | 20 +- data_structure/trie_tree.cpp | 91 +++-- dynamic_programming/0_1_knapsack.cpp | 75 ++-- dynamic_programming/armstrong_number.cpp | 32 +- dynamic_programming/bellman_ford.cpp | 191 +++++----- dynamic_programming/catalan_numbers.cpp | 4 +- dynamic_programming/coin_change.cpp | 62 ++-- dynamic_programming/cut_rod.cpp | 9 +- dynamic_programming/edit_distance.cpp | 34 +- dynamic_programming/egg_dropping_puzzle.cpp | 10 +- dynamic_programming/fibonacci_bottom_up.cpp | 32 +- dynamic_programming/fibonacci_top_down.cpp | 34 +- dynamic_programming/floyd_warshall.cpp | 162 +++++---- dynamic_programming/kadane.cpp | 17 +- dynamic_programming/longest_common_string.cpp | 76 ++-- .../longest_common_subsequence.cpp | 11 +- .../longest_increasing_subsequence.cpp | 62 ++-- ...longest_increasing_subsequence_(nlogn).cpp | 22 +- .../matrix_chain_multiplication.cpp | 73 ++-- .../searching_of_element_in_dynamic_array.cpp | 80 +++-- dynamic_programming/tree_height.cpp | 41 ++- graph/bfs.cpp | 104 +++--- .../bridge_finding_with_tarjan_algorithm.cpp | 54 +-- graph/connected_components.cpp | 71 ++-- graph/connected_components_with_dsu.cpp | 29 +- graph/dfs.cpp | 34 +- graph/dijkstra.cpp | 17 +- graph/kosaraju.cpp | 147 ++++---- graph/kruskal.cpp | 178 +++++----- graph/lca.cpp | 44 +-- ...th_ford_fulkerson_and_edmond_karp_algo.cpp | 94 ++--- graph/prim.cpp | 33 +- graph/topological_sort.cpp | 71 ++-- graph/topological_sort_by_kahns_algo.cpp | 50 ++- greedy_algorithms/dijkstra.cpp | 34 +- greedy_algorithms/huffman.cpp | 213 ++++++----- greedy_algorithms/knapsack.cpp | 130 ++++--- .../kruskals_minimum_spanning_tree.cpp | 45 ++- .../prims_minimum_spanning_tree.cpp | 94 +++-- hashing/chaining.cpp | 220 ++++++------ hashing/double_hash_hash_table.cpp | 144 +++++--- hashing/linear_probing_hash_table.cpp | 130 ++++--- hashing/quadratic_probing_hash_table.cpp | 150 +++++--- math/binary_exponent.cpp | 36 +- math/double_factorial.cpp | 18 +- math/eulers_totient_function.cpp | 25 +- math/extended_euclid_algorithm.cpp | 28 +- math/factorial.cpp | 6 +- math/fast_power.cpp | 27 +- math/fibonacci.cpp | 6 +- math/fibonacci_fast.cpp | 9 +- math/fibonacci_large.cpp | 16 +- math/gcd_iterative_euclidean.cpp | 29 +- math/gcd_of_n_numbers.cpp | 9 +- math/gcd_recursive_euclidean.cpp | 19 +- math/large_factorial.cpp | 34 +- math/large_number.h | 94 +++-- .../modular_inverse_fermat_little_theorem.cpp | 35 +- math/number_of_positive_divisors.cpp | 31 +- math/power_for_huge_numbers.cpp | 21 +- math/prime_factorization.cpp | 36 +- math/prime_numbers.cpp | 12 +- math/primes_up_to_billion.cpp | 12 +- math/sieve_of_eratosthenes.cpp | 30 +- math/sqrt_double.cpp | 22 +- math/string_fibonacci.cpp | 34 +- .../array_left_rotation.cpp | 68 ++-- .../array_right_rotation.cpp | 3 +- .../circular_linked_list.cpp | 168 ++++----- .../circular_queue_using_array.cpp | 97 +++-- .../get_size_of_linked_list.cpp | 15 +- .../intersection_of_2_arrays.cpp | 48 ++- .../reverse_a_linked_list_using_recusion.cpp | 98 ++--- .../selectionsortlinkedlist.cpp | 95 +++-- .../union_of_2_arrays.cpp | 52 ++- others/buzz_number.cpp | 6 +- others/decimal_to_binary.cpp | 15 +- others/decimal_to_hexadecimal.cpp | 6 +- others/decimal_to_roman_numeral.cpp | 78 ++-- others/fast_interger_input.cpp | 12 +- others/happy_number.cpp | 14 +- others/matrix_exponentiation.cpp | 49 ++- others/palindrome_of_number.cpp | 3 +- others/paranthesis_matching.cpp | 46 ++- others/pascal_triangle.cpp | 27 +- others/primality_test.cpp | 9 +- others/smallest_circle.cpp | 51 ++- others/sparse_matrix.cpp | 15 +- others/spiral_print.cpp | 36 +- others/stairs_pattern.cpp | 15 +- others/tower_of_hanoi.cpp | 34 +- others/vector_important_functions.cpp | 3 +- probability/addition_rule.cpp | 9 +- probability/bayes_theorem.cpp | 9 +- probability/binomial_dist.cpp | 24 +- probability/poisson_dist.cpp | 24 +- range_queries/bit.cpp | 37 +- range_queries/fenwicktree.cpp | 38 +- range_queries/mo.cpp | 104 +++--- range_queries/segtree.cpp | 156 ++++---- search/binary_search.cpp | 12 +- search/exponential_search.cpp | 18 +- search/hash_search.cpp | 34 +- search/interpolation_search.cpp | 9 +- search/interpolation_search2.cpp | 9 +- search/jump_search.cpp | 12 +- search/linear_search.cpp | 22 +- search/median_search.cpp | 36 +- search/ternary_search.cpp | 35 +- search/text_search.cpp | 20 +- sorting/bead_sort.cpp | 21 +- sorting/bitonic_sort.cpp | 21 +- sorting/bubble_sort.cpp | 25 +- sorting/bucket_sort.cpp | 9 +- sorting/cocktail_selection_sort.cpp | 64 ++-- sorting/comb_sort.cpp | 18 +- sorting/counting_sort.cpp | 71 ++-- sorting/counting_sort_string.cpp | 13 +- sorting/heap_sort.cpp | 27 +- sorting/insertion_sort.cpp | 15 +- sorting/library_sort.cpp | 40 ++- sorting/merge_sort.cpp | 34 +- sorting/non_recursive_merge_sort.cpp | 24 +- sorting/numeric_string_sort.cpp | 24 +- sorting/odd_even_sort.cpp | 75 ++-- sorting/quick_sort.cpp | 24 +- sorting/radix_sort.cpp | 39 +- sorting/selection_sort.cpp | 58 +-- sorting/shell_sort.cpp | 25 +- sorting/shell_sort2.cpp | 141 ++++---- sorting/slow_sort.cpp | 18 +- sorting/swap_sort.cpp | 21 +- sorting/tim_sort.cpp | 43 ++- strings/brute_force_string_searching.cpp | 18 +- strings/knuth_morris_pratt.cpp | 35 +- strings/rabin_karp.cpp | 37 +- 176 files changed, 5342 insertions(+), 4288 deletions(-) diff --git a/backtracking/graph_coloring.cpp b/backtracking/graph_coloring.cpp index cadc6d5ec..5d0049902 100644 --- a/backtracking/graph_coloring.cpp +++ b/backtracking/graph_coloring.cpp @@ -48,8 +48,7 @@ void graphColoring(bool graph[V][V], int m, int color[], int v) void printSolution(int color[]) { printf(" Following are the assigned colors \n"); - for (int i = 0; i < V; i++) - printf(" %d ", color[i]); + for (int i = 0; i < V; i++) printf(" %d ", color[i]); printf("\n"); } @@ -69,12 +68,11 @@ int main() {1, 1, 0, 1}, {1, 0, 1, 0}, }; - int m = 3; // Number of colors + int m = 3; // Number of colors int color[V]; - for (int i = 0; i < V; i++) - color[i] = 0; + for (int i = 0; i < V; i++) color[i] = 0; graphColoring(graph, m, color, 0); return 0; diff --git a/backtracking/knight_tour.cpp b/backtracking/knight_tour.cpp index fbb8a6f96..72b900376 100644 --- a/backtracking/knight_tour.cpp +++ b/backtracking/knight_tour.cpp @@ -1,68 +1,65 @@ #include -# define n 8 +#define n 8 /** A knight's tour is a sequence of moves of a knight on a chessboard -such that the knight visits every square only once. If the knight -ends on a square that is one knight's move from the beginning -square (so that it could tour the board again immediately, following +such that the knight visits every square only once. If the knight +ends on a square that is one knight's move from the beginning +square (so that it could tour the board again immediately, following the same path), the tour is closed; otherwise, it is open. **/ using namespace std; -bool issafe(int x,int y,int sol[n][n]) +bool issafe(int x, int y, int sol[n][n]) { - return (x=0 && y=0 && sol[x][y]==-1); - + return (x < n && x >= 0 && y < n && y >= 0 && sol[x][y] == -1); } -bool solve(int x,int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) +bool solve(int x, int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) { - int k,xnext,ynext; + int k, xnext, ynext; - if(mov == n*n) + if (mov == n * n) return true; - for(k=0;k<8;k++) + for (k = 0; k < 8; k++) { - xnext=x+xmov[k]; - ynext=y+ymov[k]; + xnext = x + xmov[k]; + ynext = y + ymov[k]; - if(issafe(xnext,ynext,sol)) - { - sol[xnext][ynext]=mov; + if (issafe(xnext, ynext, sol)) + { + sol[xnext][ynext] = mov; - if(solve(xnext,ynext,mov+1,sol,xmov,ymov)==true) - return true; - else - sol[xnext][ynext]=-1; - } + if (solve(xnext, ynext, mov + 1, sol, xmov, ymov) == true) + return true; + else + sol[xnext][ynext] = -1; + } } return false; } int main() { - //initialize(); + // initialize(); int sol[n][n]; - int i,j; - for(i=0;i scores, - int height) { + int height) +{ if (depth == height) return scores[node_index]; @@ -19,8 +20,9 @@ int minimax(int depth, int node_index, bool is_max, vector scores, return is_max ? max(v1, v2) : min(v1, v2); } -int main() { - vector scores = { 90, 23, 6, 33, 21, 65, 123, 34423 }; +int main() +{ + vector scores = {90, 23, 6, 33, 21, 65, 123, 34423}; int height = log2(scores.size()); cout << "Optimal value: " << minimax(0, 0, true, scores, height) << endl; diff --git a/backtracking/n_queens.cpp b/backtracking/n_queens.cpp index 472aaa2fe..45d6f436c 100644 --- a/backtracking/n_queens.cpp +++ b/backtracking/n_queens.cpp @@ -7,8 +7,7 @@ void printSolution(int board[N][N]) cout << "\n"; for (int i = 0; i < N; i++) { - for (int j = 0; j < N; j++) - cout << "" << board[i][j]; + for (int j = 0; j < N; j++) cout << "" << board[i][j]; cout << "\n"; } } @@ -37,7 +36,6 @@ bool isSafe(int board[N][N], int row, int col) void solveNQ(int board[N][N], int col) { - if (col >= N) { printSolution(board); @@ -59,18 +57,14 @@ void solveNQ(int board[N][N], int col) /* recur to place rest of the queens */ solveNQ(board, col + 1); - board[i][col] = 0; // BACKTRACK + board[i][col] = 0; // BACKTRACK } } } int main() { - - int board[N][N] = {{0, 0, 0, 0}, - {0, 0, 0, 0}, - {0, 0, 0, 0}, - {0, 0, 0, 0}}; + int board[N][N] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}; solveNQ(board, 0); return 0; diff --git a/backtracking/n_queens_all_solution_optimised.cpp b/backtracking/n_queens_all_solution_optimised.cpp index 1db730f63..f27b3468b 100644 --- a/backtracking/n_queens_all_solution_optimised.cpp +++ b/backtracking/n_queens_all_solution_optimised.cpp @@ -1,50 +1,60 @@ #include #define n 4 -#define inc_loop(var, start, stop) for (int var=start; var <= stop; var++) -#define dec_loop(var, start, stop) for (int var=start; var >= stop; var--) -void PrintSol(int Board[n][n]) { - inc_loop(i, 0, n-1) { - inc_loop(j, 0, n-1) - std::cout << Board[i][j] << " "; +#define inc_loop(var, start, stop) for (int var = start; var <= stop; var++) +#define dec_loop(var, start, stop) for (int var = start; var >= stop; var--) +void PrintSol(int Board[n][n]) +{ + inc_loop(i, 0, n - 1) + { + inc_loop(j, 0, n - 1) std::cout << Board[i][j] << " "; std::cout << std::endl; } std::cout << std::endl; - if (n%2 == 0 || (n%2 == 1 && Board[n/2+1][0] != 1)) { - inc_loop(i, 0, n-1) { - dec_loop(j, n-1, 0) - std::cout << Board[i][j] << " "; + if (n % 2 == 0 || (n % 2 == 1 && Board[n / 2 + 1][0] != 1)) + { + inc_loop(i, 0, n - 1) + { + dec_loop(j, n - 1, 0) std::cout << Board[i][j] << " "; std::cout << std::endl; } std::cout << std::endl; } } -bool CanIMove(int Board[n][n], int row, int col) { +bool CanIMove(int Board[n][n], int row, int col) +{ /// check in the row - inc_loop(i, 0, col-1) { + inc_loop(i, 0, col - 1) + { if (Board[row][i] == 1) return false; } /// check the first diagonal - for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) + { if (Board[i][j] == 1) return false; } /// check the second diagonal - for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) { + for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) + { if (Board[i][j] == 1) return false; } return true; } -void NQueenSol(int Board[n][n], int col) { - if (col >= n) { +void NQueenSol(int Board[n][n], int col) +{ + if (col >= n) + { PrintSol(Board); return; } - inc_loop(i, 0, n-1) { - if (CanIMove(Board, i, col)) { + inc_loop(i, 0, n - 1) + { + if (CanIMove(Board, i, col)) + { Board[i][col] = 1; NQueenSol(Board, col + 1); Board[i][col] = 0; @@ -52,19 +62,27 @@ void NQueenSol(int Board[n][n], int col) { } } -int main() { +int main() +{ int Board[n][n] = {0}; - if (n%2 == 0) { - inc_loop(i, 0, n/2-1) { - if (CanIMove(Board, i, 0)) { + if (n % 2 == 0) + { + inc_loop(i, 0, n / 2 - 1) + { + if (CanIMove(Board, i, 0)) + { Board[i][0] = 1; NQueenSol(Board, 1); Board[i][0] = 0; } } - } else { - inc_loop(i, 0, n/2) { - if (CanIMove(Board, i, 0)) { + } + else + { + inc_loop(i, 0, n / 2) + { + if (CanIMove(Board, i, 0)) + { Board[i][0] = 1; NQueenSol(Board, 1); Board[i][0] = 0; diff --git a/backtracking/nqueen_print_all_solutions.cpp b/backtracking/nqueen_print_all_solutions.cpp index e6736da1e..d3d50998d 100644 --- a/backtracking/nqueen_print_all_solutions.cpp +++ b/backtracking/nqueen_print_all_solutions.cpp @@ -1,9 +1,12 @@ #include #define n 4 -void PrintSol(int Board[n][n]) { - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { +void PrintSol(int Board[n][n]) +{ + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { std::cout << Board[i][j] << " "; } std::cout << std::endl; @@ -11,32 +14,40 @@ void PrintSol(int Board[n][n]) { std::cout << std::endl; } -bool CanIMove(int Board[n][n], int row, int col) { +bool CanIMove(int Board[n][n], int row, int col) +{ /// check in the row - for (int i = 0; i < col; i++) { + for (int i = 0; i < col; i++) + { if (Board[row][i] == 1) return false; } /// check the first diagonal - for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) + { if (Board[i][j] == 1) return false; } /// check the second diagonal - for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) { + for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) + { if (Board[i][j] == 1) return false; } return true; } -void NQueenSol(int Board[n][n], int col) { - if (col >= n) { +void NQueenSol(int Board[n][n], int col) +{ + if (col >= n) + { PrintSol(Board); return; } - for (int i = 0; i < n; i++) { - if (CanIMove(Board, i, col)) { + for (int i = 0; i < n; i++) + { + if (CanIMove(Board, i, col)) + { Board[i][col] = 1; NQueenSol(Board, col + 1); Board[i][col] = 0; @@ -44,7 +55,8 @@ void NQueenSol(int Board[n][n], int col) { } } -int main() { +int main() +{ int Board[n][n] = {0}; NQueenSol(Board, 0); } diff --git a/backtracking/rat_maze.cpp b/backtracking/rat_maze.cpp index 307b5c7b0..5454a6c82 100644 --- a/backtracking/rat_maze.cpp +++ b/backtracking/rat_maze.cpp @@ -1,73 +1,73 @@ /* - A Maze is given as N*N binary matrix of blocks where source block is the upper - left most block i.e., maze[0][0] and destination block is lower rightmost - block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. - The rat can move only in two directions: forward and down. In the maze matrix, - 0 means the block is dead end and 1 means the block can be used in the path - from source to destination. + A Maze is given as N*N binary matrix of blocks where source block is the + upper left most block i.e., maze[0][0] and destination block is lower + rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to + reach destination. The rat can move only in two directions: forward and down. + In the maze matrix, 0 means the block is dead end and 1 means the block can + be used in the path from source to destination. */ #include #define size 4 using namespace std; -int solveMaze(int currposrow, int currposcol, int maze[size][size], int soln[size][size]) +int solveMaze(int currposrow, int currposcol, int maze[size][size], + int soln[size][size]) { - if ((currposrow == size - 1) && (currposcol == size - 1)) - { - soln[currposrow][currposcol] = 1; - for (int i = 0; i < size; ++i) - { - for (int j = 0; j < size; ++j) - { - cout << soln[i][j]; - } - cout << endl; - } - return 1; - } - else - { - soln[currposrow][currposcol] = 1; + if ((currposrow == size - 1) && (currposcol == size - 1)) + { + soln[currposrow][currposcol] = 1; + for (int i = 0; i < size; ++i) + { + for (int j = 0; j < size; ++j) + { + cout << soln[i][j]; + } + cout << endl; + } + return 1; + } + else + { + soln[currposrow][currposcol] = 1; - // if there exist a solution by moving one step ahead in a collumn - if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 && solveMaze(currposrow, currposcol + 1, maze, soln)) - { - return 1; - } + // if there exist a solution by moving one step ahead in a collumn + if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 && + solveMaze(currposrow, currposcol + 1, maze, soln)) + { + return 1; + } - // if there exists a solution by moving one step ahead in a row - if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 && solveMaze(currposrow + 1, currposcol, maze, soln)) - { - return 1; - } + // if there exists a solution by moving one step ahead in a row + if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 && + solveMaze(currposrow + 1, currposcol, maze, soln)) + { + return 1; + } - // the backtracking part - soln[currposrow][currposcol] = 0; - return 0; - } + // the backtracking part + soln[currposrow][currposcol] = 0; + return 0; + } } int main(int argc, char const *argv[]) { - int maze[size][size] = { - {1, 0, 1, 0}, - {1, 0, 1, 1}, - {1, 0, 0, 1}, - {1, 1, 1, 1}}; + int maze[size][size] = { + {1, 0, 1, 0}, {1, 0, 1, 1}, {1, 0, 0, 1}, {1, 1, 1, 1}}; - int soln[size][size]; + int soln[size][size]; - for (int i = 0; i < size; ++i) - { - for (int j = 0; j < size; ++j) - { - soln[i][j] = 0; - } - } + for (int i = 0; i < size; ++i) + { + for (int j = 0; j < size; ++j) + { + soln[i][j] = 0; + } + } - int currposrow = 0; - int currposcol = 0; - solveMaze(currposrow, currposcol, maze, soln); - return 0; + int currposrow = 0; + int currposcol = 0; + solveMaze(currposrow, currposcol, maze, soln); + return 0; } diff --git a/backtracking/sudoku_solve.cpp b/backtracking/sudoku_solve.cpp index 6a01fd395..c98040841 100644 --- a/backtracking/sudoku_solve.cpp +++ b/backtracking/sudoku_solve.cpp @@ -1,11 +1,11 @@ #include using namespace std; -///N=9; +/// N=9; int n = 9; bool isPossible(int mat[][9], int i, int j, int no) { - ///Row or col nahin hona chahiye + /// Row or col nahin hona chahiye for (int x = 0; x < n; x++) { if (mat[x][j] == no || mat[i][x] == no) @@ -33,7 +33,6 @@ bool isPossible(int mat[][9], int i, int j, int no) } void printMat(int mat[][9]) { - for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) @@ -54,60 +53,54 @@ void printMat(int mat[][9]) bool solveSudoku(int mat[][9], int i, int j) { - ///Base Case + /// Base Case if (i == 9) { - ///Solve kr chuke hain for 9 rows already + /// Solve kr chuke hain for 9 rows already printMat(mat); return true; } - ///Crossed the last Cell in the row + /// Crossed the last Cell in the row if (j == 9) { return solveSudoku(mat, i + 1, 0); } - ///Blue Cell - Skip + /// Blue Cell - Skip if (mat[i][j] != 0) { return solveSudoku(mat, i, j + 1); } - ///White Cell - ///Try to place every possible no + /// White Cell + /// Try to place every possible no for (int no = 1; no <= 9; no++) { if (isPossible(mat, i, j, no)) { - ///Place the no - assuming solution aa jayega + /// Place the no - assuming solution aa jayega mat[i][j] = no; bool aageKiSolveHui = solveSudoku(mat, i, j + 1); if (aageKiSolveHui) { return true; } - ///Nahin solve hui - ///loop will place the next no. + /// Nahin solve hui + /// loop will place the next no. } } - ///Sare no try kr liey, kisi se bhi solve nahi hui + /// Sare no try kr liey, kisi se bhi solve nahi hui mat[i][j] = 0; return false; } int main() { - - int mat[9][9] = - {{5, 3, 0, 0, 7, 0, 0, 0, 0}, - {6, 0, 0, 1, 9, 5, 0, 0, 0}, - {0, 9, 8, 0, 0, 0, 0, 6, 0}, - {8, 0, 0, 0, 6, 0, 0, 0, 3}, - {4, 0, 0, 8, 0, 3, 0, 0, 1}, - {7, 0, 0, 0, 2, 0, 0, 0, 6}, - {0, 6, 0, 0, 0, 0, 2, 8, 0}, - {0, 0, 0, 4, 1, 9, 0, 0, 5}, - {0, 0, 0, 0, 8, 0, 0, 7, 9}}; + int mat[9][9] = {{5, 3, 0, 0, 7, 0, 0, 0, 0}, {6, 0, 0, 1, 9, 5, 0, 0, 0}, + {0, 9, 8, 0, 0, 0, 0, 6, 0}, {8, 0, 0, 0, 6, 0, 0, 0, 3}, + {4, 0, 0, 8, 0, 3, 0, 0, 1}, {7, 0, 0, 0, 2, 0, 0, 0, 6}, + {0, 6, 0, 0, 0, 0, 2, 8, 0}, {0, 0, 0, 4, 1, 9, 0, 0, 5}, + {0, 0, 0, 0, 8, 0, 0, 7, 9}}; printMat(mat); cout << "Solution " << endl; diff --git a/computer_oriented_statistical_methods/bisection_method.cpp b/computer_oriented_statistical_methods/bisection_method.cpp index c93c529d2..ea0a5e931 100644 --- a/computer_oriented_statistical_methods/bisection_method.cpp +++ b/computer_oriented_statistical_methods/bisection_method.cpp @@ -23,29 +23,36 @@ /** define \f$f(x)\f$ to find root for */ -static double eq(double i) { +static double eq(double i) +{ return (std::pow(i, 3) - (4 * i) - 9); // original equation } /** get the sign of any given number */ template -int sgn(T val) { +int sgn(T val) +{ return (T(0) < val) - (val < T(0)); } /** main function */ -int main() { +int main() +{ double a = -1, b = 1, x, z; int i; // loop to find initial intervals a, b - for (int i = 0; i < MAX_ITERATIONS; i++) { + for (int i = 0; i < MAX_ITERATIONS; i++) + { z = eq(a); x = eq(b); - if (sgn(z) == sgn(x)) { // same signs, increase interval + if (sgn(z) == sgn(x)) + { // same signs, increase interval b++; a--; - } else { // if opposite signs, we got our interval + } + else + { // if opposite signs, we got our interval break; } } @@ -54,15 +61,19 @@ int main() { std::cout << "\nSecond initial: " << b; // start iterations - for (i = 0; i < MAX_ITERATIONS; i++) { + for (i = 0; i < MAX_ITERATIONS; i++) + { x = (a + b) / 2; z = eq(x); std::cout << "\n\nz: " << z << "\t[" << a << " , " << b << " | Bisect: " << x << "]"; - if (z < 0) { + if (z < 0) + { a = x; - } else { + } + else + { b = x; } diff --git a/computer_oriented_statistical_methods/false_position.cpp b/computer_oriented_statistical_methods/false_position.cpp index aebd154bb..6bdc0cf67 100644 --- a/computer_oriented_statistical_methods/false_position.cpp +++ b/computer_oriented_statistical_methods/false_position.cpp @@ -25,29 +25,36 @@ /** define \f$f(x)\f$ to find root for */ -static double eq(double i) { +static double eq(double i) +{ return (std::pow(i, 3) - (4 * i) - 9); // origial equation } /** get the sign of any given number */ template -int sgn(T val) { +int sgn(T val) +{ return (T(0) < val) - (val < T(0)); } /** main function */ -int main() { +int main() +{ double a = -1, b = 1, x, z, m, n, c; int i; // loop to find initial intervals a, b - for (int i = 0; i < MAX_ITERATIONS; i++) { + for (int i = 0; i < MAX_ITERATIONS; i++) + { z = eq(a); x = eq(b); - if (sgn(z) == sgn(x)) { // same signs, increase interval + if (sgn(z) == sgn(x)) + { // same signs, increase interval b++; a--; - } else { // if opposite signs, we got our interval + } + else + { // if opposite signs, we got our interval break; } } @@ -55,7 +62,8 @@ int main() { std::cout << "\nFirst initial: " << a; std::cout << "\nSecond initial: " << b; - for (i = 0; i < MAX_ITERATIONS; i++) { + for (i = 0; i < MAX_ITERATIONS; i++) + { m = eq(a); n = eq(b); @@ -64,7 +72,8 @@ int main() { a = c; z = eq(c); - if (std::abs(z) < EPSILON) { // stoping criteria + if (std::abs(z) < EPSILON) + { // stoping criteria break; } } diff --git a/computer_oriented_statistical_methods/gaussian_elimination.cpp b/computer_oriented_statistical_methods/gaussian_elimination.cpp index 60b5648ec..01cb578b2 100644 --- a/computer_oriented_statistical_methods/gaussian_elimination.cpp +++ b/computer_oriented_statistical_methods/gaussian_elimination.cpp @@ -6,7 +6,8 @@ #include /** Main function */ -int main() { +int main() +{ int mat_size, i, j, step; std::cout << "Matrix size: "; @@ -14,7 +15,8 @@ int main() { // create a 2D matrix by dynamic memory allocation double **mat = new double *[mat_size + 1], **x = new double *[mat_size]; - for (i = 0; i <= mat_size; i++) { + for (i = 0; i <= mat_size; i++) + { mat[i] = new double[mat_size + 1]; if (i < mat_size) x[i] = new double[mat_size + 1]; @@ -22,16 +24,20 @@ int main() { // get the matrix elements from user std::cout << std::endl << "Enter value of the matrix: " << std::endl; - for (i = 0; i < mat_size; i++) { - for (j = 0; j <= mat_size; j++) { + for (i = 0; i < mat_size; i++) + { + for (j = 0; j <= mat_size; j++) + { std::cin >> mat[i][j]; // Enter (mat_size*mat_size) value of the matrix. } } // perform Gaussian elimination - for (step = 0; step < mat_size - 1; step++) { - for (i = step; i < mat_size - 1; i++) { + for (step = 0; step < mat_size - 1; step++) + { + for (i = step; i < mat_size - 1; i++) + { double a = (mat[i + 1][step] / mat[step][step]); for (j = step; j <= mat_size; j++) @@ -41,8 +47,10 @@ int main() { std::cout << std::endl << "Matrix using Gaussian Elimination method: " << std::endl; - for (i = 0; i < mat_size; i++) { - for (j = 0; j <= mat_size; j++) { + for (i = 0; i < mat_size; i++) + { + for (j = 0; j <= mat_size; j++) + { x[i][j] = mat[i][j]; std::cout << mat[i][j] << " "; } @@ -50,9 +58,11 @@ int main() { } std::cout << std::endl << "Value of the Gaussian Elimination method: " << std::endl; - for (i = mat_size - 1; i >= 0; i--) { + for (i = mat_size - 1; i >= 0; i--) + { double sum = 0; - for (j = mat_size - 1; j > i; j--) { + for (j = mat_size - 1; j > i; j--) + { x[i][j] = x[j][j] * x[i][j]; sum = x[i][j] + sum; } @@ -64,7 +74,8 @@ int main() { std::cout << "x" << i << "= " << x[i][i] << std::endl; } - for (i = 0; i <= mat_size; i++) { + for (i = 0; i <= mat_size; i++) + { delete[] mat[i]; if (i < mat_size) delete[] x[i]; diff --git a/computer_oriented_statistical_methods/newton_raphson_method.cpp b/computer_oriented_statistical_methods/newton_raphson_method.cpp index 318363a39..a93774b91 100644 --- a/computer_oriented_statistical_methods/newton_raphson_method.cpp +++ b/computer_oriented_statistical_methods/newton_raphson_method.cpp @@ -21,18 +21,21 @@ /** define \f$f(x)\f$ to find root for */ -static double eq(double i) { +static double eq(double i) +{ return (std::pow(i, 3) - (4 * i) - 9); // original equation } /** define the derivative function \f$f'(x)\f$ */ -static double eq_der(double i) { +static double eq_der(double i) +{ return ((3 * std::pow(i, 2)) - 4); // derivative of equation } /** Main function */ -int main() { +int main() +{ std::srand(std::time(nullptr)); // initialize randomizer double z, c = std::rand() % 100, m, n; @@ -41,7 +44,8 @@ int main() { std::cout << "\nInitial approximation: " << c; // start iterations - for (i = 0; i < MAX_ITERATIONS; i++) { + for (i = 0; i < MAX_ITERATIONS; i++) + { m = eq(c); n = eq_der(c); diff --git a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp index de02b27bb..c3fe8be03 100644 --- a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp +++ b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp @@ -16,11 +16,13 @@ */ template std::ostream &operator<<(std::ostream &out, - std::vector> const &v) { + std::vector> const &v) +{ const int width = 10; const char separator = ' '; - for (size_t row = 0; row < v.size(); row++) { + for (size_t row = 0; row < v.size(); row++) + { for (size_t col = 0; col < v[row].size(); col++) out << std::left << std::setw(width) << std::setfill(separator) << v[row][col]; @@ -34,7 +36,8 @@ std::ostream &operator<<(std::ostream &out, * operator to print a vector */ template -std::ostream &operator<<(std::ostream &out, std::vector const &v) { +std::ostream &operator<<(std::ostream &out, std::vector const &v) +{ const int width = 15; const char separator = ' '; @@ -50,7 +53,8 @@ std::ostream &operator<<(std::ostream &out, std::vector const &v) { * \returns 1 if true, 0 if false */ template -inline bool is_square(std::vector> const &A) { +inline bool is_square(std::vector> const &A) +{ // Assuming A is square matrix size_t N = A.size(); for (size_t i = 0; i < N; i++) @@ -68,7 +72,8 @@ inline bool is_square(std::vector> const &A) { **/ template std::vector> operator*(std::vector> const &A, - std::vector> const &B) { + std::vector> const &B) +{ // Number of rows in A size_t N_A = A.size(); // Number of columns in B @@ -76,15 +81,18 @@ std::vector> operator*(std::vector> const &A, std::vector> result(N_A); - if (A[0].size() != B.size()) { + if (A[0].size() != B.size()) + { std::cerr << "Number of columns in A != Number of rows in B (" << A[0].size() << ", " << B.size() << ")" << std::endl; return result; } - for (size_t row = 0; row < N_A; row++) { + for (size_t row = 0; row < N_A; row++) + { std::vector v(N_B); - for (size_t col = 0; col < N_B; col++) { + for (size_t col = 0; col < N_B; col++) + { v[col] = static_cast(0); for (size_t j = 0; j < B.size(); j++) v[col] += A[row][j] * B[j][col]; @@ -101,19 +109,22 @@ std::vector> operator*(std::vector> const &A, */ template std::vector operator*(std::vector> const &A, - std::vector const &B) { + std::vector const &B) +{ // Number of rows in A size_t N_A = A.size(); std::vector result(N_A); - if (A[0].size() != B.size()) { + if (A[0].size() != B.size()) + { std::cerr << "Number of columns in A != Number of rows in B (" << A[0].size() << ", " << B.size() << ")" << std::endl; return result; } - for (size_t row = 0; row < N_A; row++) { + for (size_t row = 0; row < N_A; row++) + { result[row] = static_cast(0); for (size_t j = 0; j < B.size(); j++) result[row] += A[row][j] * B[j]; } @@ -126,13 +137,15 @@ std::vector operator*(std::vector> const &A, * \returns resultant vector */ template -std::vector operator*(float const scalar, std::vector const &A) { +std::vector operator*(float const scalar, std::vector const &A) +{ // Number of rows in A size_t N_A = A.size(); std::vector result(N_A); - for (size_t row = 0; row < N_A; row++) { + for (size_t row = 0; row < N_A; row++) + { result[row] += A[row] * static_cast(scalar); } @@ -144,7 +157,8 @@ std::vector operator*(float const scalar, std::vector const &A) { * \returns resultant vector */ template -std::vector operator*(std::vector const &A, float const scalar) { +std::vector operator*(std::vector const &A, float const scalar) +{ // Number of rows in A size_t N_A = A.size(); @@ -161,7 +175,8 @@ std::vector operator*(std::vector const &A, float const scalar) { * \returns resultant vector */ template -std::vector operator/(std::vector const &A, float const scalar) { +std::vector operator/(std::vector const &A, float const scalar) +{ return (1.f / scalar) * A; } @@ -170,13 +185,15 @@ std::vector operator/(std::vector const &A, float const scalar) { * \returns resultant vector */ template -std::vector operator-(std::vector const &A, std::vector const &B) { +std::vector operator-(std::vector const &A, std::vector const &B) +{ // Number of rows in A size_t N = A.size(); std::vector result(N); - if (B.size() != N) { + if (B.size() != N) + { std::cerr << "Vector dimensions shouldbe identical!" << std::endl; return A; } @@ -191,13 +208,15 @@ std::vector operator-(std::vector const &A, std::vector const &B) { * \returns resultant vector */ template -std::vector operator+(std::vector const &A, std::vector const &B) { +std::vector operator+(std::vector const &A, std::vector const &B) +{ // Number of rows in A size_t N = A.size(); std::vector result(N); - if (B.size() != N) { + if (B.size() != N) + { std::cerr << "Vector dimensions shouldbe identical!" << std::endl; return A; } @@ -214,26 +233,30 @@ std::vector operator+(std::vector const &A, std::vector const &B) { **/ template std::vector> get_inverse( - std::vector> const &A) { + std::vector> const &A) +{ // Assuming A is square matrix size_t N = A.size(); std::vector> inverse(N); - for (size_t row = 0; row < N; row++) { + for (size_t row = 0; row < N; row++) + { // preallocatae a resultant identity matrix inverse[row] = std::vector(N); for (size_t col = 0; col < N; col++) inverse[row][col] = (row == col) ? 1.f : 0.f; } - if (!is_square(A)) { + if (!is_square(A)) + { std::cerr << "A must be a square matrix!" << std::endl; return inverse; } // preallocatae a temporary matrix identical to A std::vector> temp(N); - for (size_t row = 0; row < N; row++) { + for (size_t row = 0; row < N; row++) + { std::vector v(N); for (size_t col = 0; col < N; col++) v[col] = static_cast(A[row][col]); @@ -241,22 +264,27 @@ std::vector> get_inverse( } // start transformations - for (size_t row = 0; row < N; row++) { - for (size_t row2 = row; row2 < N && temp[row][row] == 0; row2++) { + for (size_t row = 0; row < N; row++) + { + for (size_t row2 = row; row2 < N && temp[row][row] == 0; row2++) + { // this to ensure diagonal elements are not 0 temp[row] = temp[row] + temp[row2]; inverse[row] = inverse[row] + inverse[row2]; } - for (size_t col2 = row; col2 < N && temp[row][row] == 0; col2++) { + for (size_t col2 = row; col2 < N && temp[row][row] == 0; col2++) + { // this to further ensure diagonal elements are not 0 - for (size_t row2 = 0; row2 < N; row2++) { + for (size_t row2 = 0; row2 < N; row2++) + { temp[row2][row] = temp[row2][row] + temp[row2][col2]; inverse[row2][row] = inverse[row2][row] + inverse[row2][col2]; } } - if (temp[row][row] == 0) { + if (temp[row][row] == 0) + { // Probably a low-rank matrix and hence singular std::cerr << "Low-rank matrix, no inverse!" << std::endl; return inverse; @@ -267,7 +295,8 @@ std::vector> get_inverse( temp[row] = temp[row] / divisor; inverse[row] = inverse[row] / divisor; // Row transformations - for (size_t row2 = 0; row2 < N; row2++) { + for (size_t row2 = 0; row2 < N; row2++) + { if (row2 == row) continue; float factor = temp[row2][row]; @@ -284,11 +313,12 @@ std::vector> get_inverse( * \returns resultant matrix **/ template -std::vector> get_transpose( - std::vector> const &A) { +std::vector> get_transpose(std::vector> const &A) +{ std::vector> result(A[0].size()); - for (size_t row = 0; row < A[0].size(); row++) { + for (size_t row = 0; row < A[0].size(); row++) + { std::vector v(A.size()); for (size_t col = 0; col < A.size(); col++) v[col] = A[col][row]; @@ -306,7 +336,8 @@ std::vector> get_transpose( */ template std::vector fit_OLS_regressor(std::vector> const &X, - std::vector const &Y) { + std::vector const &Y) +{ // NxF std::vector> X2 = X; for (size_t i = 0; i < X2.size(); i++) @@ -337,10 +368,12 @@ std::vector fit_OLS_regressor(std::vector> const &X, template std::vector predict_OLS_regressor(std::vector> const &X, std::vector const &beta /**< */ -) { +) +{ std::vector result(X.size()); - for (size_t rows = 0; rows < X.size(); rows++) { + for (size_t rows = 0; rows < X.size(); rows++) + { // -> start with constant term result[rows] = beta[X[0].size()]; for (size_t cols = 0; cols < X[0].size(); cols++) @@ -353,7 +386,8 @@ std::vector predict_OLS_regressor(std::vector> const &X, /** * main function */ -int main() { +int main() +{ size_t N, F; std::cout << "Enter number of features: "; @@ -370,7 +404,8 @@ int main() { << "Enter training data. Per sample, provide features ad one output." << std::endl; - for (size_t rows = 0; rows < N; rows++) { + for (size_t rows = 0; rows < N; rows++) + { std::vector v(F); std::cout << "Sample# " << rows + 1 << ": "; for (size_t cols = 0; cols < F; cols++) @@ -391,7 +426,8 @@ int main() { std::vector> data2(T); // vector Y2(T); - for (size_t rows = 0; rows < T; rows++) { + for (size_t rows = 0; rows < T; rows++) + { std::cout << "Sample# " << rows + 1 << ": "; std::vector v(F); for (size_t cols = 0; cols < F; cols++) std::cin >> v[cols]; diff --git a/computer_oriented_statistical_methods/successive_approximation.cpp b/computer_oriented_statistical_methods/successive_approximation.cpp index 351382f24..137933591 100644 --- a/computer_oriented_statistical_methods/successive_approximation.cpp +++ b/computer_oriented_statistical_methods/successive_approximation.cpp @@ -17,11 +17,13 @@ static float eq(float y) { return (3 * y) - cos(y) - 2; } static float eqd(float y) { return 0.5 * (cos(y) + 2); } /** Main function */ -int main() { +int main() +{ float y, x1, x2, x3, sum, s, a, f1, f2, gd; int i, n; - for (i = 0; i < 10; i++) { + for (i = 0; i < 10; i++) + { sum = eq(y); std::cout << "value of equation at " << i << " " << sum << "\n"; y++; @@ -31,7 +33,8 @@ int main() { std::cout << "enter the no iteration to perform->\n"; std::cin >> n; - for (i = 0; i <= n; i++) { + for (i = 0; i <= n; i++) + { x2 = eqd(x1); std::cout << "\nenter the x2->" << x2; x1 = x2; diff --git a/data_structure/avltree.cpp b/data_structure/avltree.cpp index db6b9e0d4..dc96ad977 100644 --- a/data_structure/avltree.cpp +++ b/data_structure/avltree.cpp @@ -5,172 +5,165 @@ using namespace std; typedef struct node { - int data; - int height; - struct node *left; - struct node *right; + int data; + int height; + struct node *left; + struct node *right; } node; -int max(int a, int b) -{ - return a > b ? a : b; -} +int max(int a, int b) { return a > b ? a : b; } // Returns a new Node node *createNode(int data) { - node *nn = new node(); - nn->data = data; - nn->height = 0; - nn->left = NULL; - nn->right = NULL; - return nn; + node *nn = new node(); + nn->data = data; + nn->height = 0; + nn->left = NULL; + nn->right = NULL; + return nn; } // Returns height of tree int height(node *root) { - if (root == NULL) - return 0; - return 1 + max(height(root->left), height(root->right)); + if (root == NULL) + return 0; + return 1 + max(height(root->left), height(root->right)); } // Returns difference between height of left and right subtree -int getBalance(node *root) -{ - return height(root->left) - height(root->right); -} +int getBalance(node *root) { return height(root->left) - height(root->right); } // Returns Node after Right Rotation node *rightRotate(node *root) { - node *t = root->left; - node *u = t->right; - t->right = root; - root->left = u; - return t; + node *t = root->left; + node *u = t->right; + t->right = root; + root->left = u; + return t; } // Returns Node after Left Rotation node *leftRotate(node *root) { - node *t = root->right; - node *u = t->left; - t->left = root; - root->right = u; - return t; + node *t = root->right; + node *u = t->left; + t->left = root; + root->right = u; + return t; } // Returns node with minimum value in the tree node *minValue(node *root) { - if (root->left == NULL) - return root; - return minValue(root->left); + if (root->left == NULL) + return root; + return minValue(root->left); } // Balanced Insertion node *insert(node *root, int item) { - node *nn = createNode(item); - if (root == NULL) - return nn; - if (item < root->data) - root->left = insert(root->left, item); - else - root->right = insert(root->right, item); - int b = getBalance(root); - if (b > 1) - { - if (getBalance(root->left) < 0) - root->left = leftRotate(root->left); // Left-Right Case - return rightRotate(root); // Left-Left Case - } - else if (b < -1) - { - if (getBalance(root->right) > 0) - root->right = rightRotate(root->right); // Right-Left Case - return leftRotate(root); // Right-Right Case - } - return root; + node *nn = createNode(item); + if (root == NULL) + return nn; + if (item < root->data) + root->left = insert(root->left, item); + else + root->right = insert(root->right, item); + int b = getBalance(root); + if (b > 1) + { + if (getBalance(root->left) < 0) + root->left = leftRotate(root->left); // Left-Right Case + return rightRotate(root); // Left-Left Case + } + else if (b < -1) + { + if (getBalance(root->right) > 0) + root->right = rightRotate(root->right); // Right-Left Case + return leftRotate(root); // Right-Right Case + } + return root; } // Balanced Deletion node *deleteNode(node *root, int key) { - if (root == NULL) - return root; - if (key < root->data) - root->left = deleteNode(root->left, key); - else if (key > root->data) - root->right = deleteNode(root->right, key); + if (root == NULL) + return root; + if (key < root->data) + root->left = deleteNode(root->left, key); + else if (key > root->data) + root->right = deleteNode(root->right, key); - else - { - // Node to be deleted is leaf node or have only one Child - if (!root->right) - { - node *temp = root->left; - delete (root); - root = NULL; - return temp; - } - else if (!root->left) - { - node *temp = root->right; - delete (root); - root = NULL; - return temp; - } - // Node to be deleted have both left and right subtrees - node *temp = minValue(root->right); - root->data = temp->data; - root->right = deleteNode(root->right, temp->data); - } - // Balancing Tree after deletion - return root; + else + { + // Node to be deleted is leaf node or have only one Child + if (!root->right) + { + node *temp = root->left; + delete (root); + root = NULL; + return temp; + } + else if (!root->left) + { + node *temp = root->right; + delete (root); + root = NULL; + return temp; + } + // Node to be deleted have both left and right subtrees + node *temp = minValue(root->right); + root->data = temp->data; + root->right = deleteNode(root->right, temp->data); + } + // Balancing Tree after deletion + return root; } // LevelOrder (Breadth First Search) void levelOrder(node *root) { - queue q; - q.push(root); - while (!q.empty()) - { - root = q.front(); - cout << root->data << " "; - q.pop(); - if (root->left) - q.push(root->left); - if (root->right) - q.push(root->right); - } + queue q; + q.push(root); + while (!q.empty()) + { + root = q.front(); + cout << root->data << " "; + q.pop(); + if (root->left) + q.push(root->left); + if (root->right) + q.push(root->right); + } } int main() { - // Testing AVL Tree - node *root = NULL; - int i; - for (i = 1; i <= 7; i++) - root = insert(root, i); - cout << "LevelOrder: "; - levelOrder(root); - root = deleteNode(root, 1); // Deleting key with value 1 - cout << "\nLevelOrder: "; - levelOrder(root); - root = deleteNode(root, 4); // Deletin key with value 4 - cout << "\nLevelOrder: "; - levelOrder(root); - return 0; + // Testing AVL Tree + node *root = NULL; + int i; + for (i = 1; i <= 7; i++) root = insert(root, i); + cout << "LevelOrder: "; + levelOrder(root); + root = deleteNode(root, 1); // Deleting key with value 1 + cout << "\nLevelOrder: "; + levelOrder(root); + root = deleteNode(root, 4); // Deletin key with value 4 + cout << "\nLevelOrder: "; + levelOrder(root); + return 0; } diff --git a/data_structure/binary_search_tree.cpp b/data_structure/binary_search_tree.cpp index 32a65517c..ea9df12d3 100644 --- a/data_structure/binary_search_tree.cpp +++ b/data_structure/binary_search_tree.cpp @@ -3,216 +3,210 @@ using namespace std; struct node { - int val; - node *left; - node *right; + int val; + node *left; + node *right; }; struct queue { - node *t[100]; - int front; - int rear; + node *t[100]; + int front; + int rear; }; queue q; -void enqueue(node *n) -{ - q.t[q.rear++] = n; -} +void enqueue(node *n) { q.t[q.rear++] = n; } -node *dequeue() -{ - return (q.t[q.front++]); -} +node *dequeue() { return (q.t[q.front++]); } void Insert(node *n, int x) { - if (x < n->val) - { - if (n->left == NULL) - { - node *temp = new node; - temp->val = x; - temp->left = NULL; - temp->right = NULL; - n->left = temp; - } - else - { - Insert(n->left, x); - } - } - else - { - if (n->right == NULL) - { - node *temp = new node; - temp->val = x; - temp->left = NULL; - temp->right = NULL; - n->left = temp; - } - else - { - Insert(n->right, x); - } - } + if (x < n->val) + { + if (n->left == NULL) + { + node *temp = new node; + temp->val = x; + temp->left = NULL; + temp->right = NULL; + n->left = temp; + } + else + { + Insert(n->left, x); + } + } + else + { + if (n->right == NULL) + { + node *temp = new node; + temp->val = x; + temp->left = NULL; + temp->right = NULL; + n->left = temp; + } + else + { + Insert(n->right, x); + } + } } int findMaxInLeftST(node *n) { - while (n->right != NULL) - { - n = n->right; - } - return n->val; + while (n->right != NULL) + { + n = n->right; + } + return n->val; } void Remove(node *p, node *n, int x) { - if (n->val == x) - { - if (n->right == NULL && n->left == NULL) - { - if (x < p->val) - { - p->right = NULL; - } - else - { - p->left = NULL; - } - } - else if (n->right == NULL) - { - if (x < p->val) - { - p->right = n->left; - } - else - { - p->left = n->left; - } - } - else if (n->left == NULL) - { - if (x < p->val) - { - p->right = n->right; - } - else - { - p->left = n->right; - } - } - else - { - int y = findMaxInLeftST(n->left); - n->val = y; - Remove(n, n->right, y); - } - } - else if (x < n->val) - { - Remove(n, n->left, x); - } - else - { - Remove(n, n->right, x); - } + if (n->val == x) + { + if (n->right == NULL && n->left == NULL) + { + if (x < p->val) + { + p->right = NULL; + } + else + { + p->left = NULL; + } + } + else if (n->right == NULL) + { + if (x < p->val) + { + p->right = n->left; + } + else + { + p->left = n->left; + } + } + else if (n->left == NULL) + { + if (x < p->val) + { + p->right = n->right; + } + else + { + p->left = n->right; + } + } + else + { + int y = findMaxInLeftST(n->left); + n->val = y; + Remove(n, n->right, y); + } + } + else if (x < n->val) + { + Remove(n, n->left, x); + } + else + { + Remove(n, n->right, x); + } } void BFT(node *n) { - if (n != NULL) - { - cout << n->val << " "; - enqueue(n->left); - enqueue(n->right); - BFT(dequeue()); - } + if (n != NULL) + { + cout << n->val << " "; + enqueue(n->left); + enqueue(n->right); + BFT(dequeue()); + } } void Pre(node *n) { - if (n != NULL) - { - cout << n->val << " "; - Pre(n->left); - Pre(n->right); - } + if (n != NULL) + { + cout << n->val << " "; + Pre(n->left); + Pre(n->right); + } } void In(node *n) { - if (n != NULL) - { - In(n->left); - cout << n->val << " "; - In(n->right); - } + if (n != NULL) + { + In(n->left); + cout << n->val << " "; + In(n->right); + } } void Post(node *n) { - if (n != NULL) - { - Post(n->left); - Post(n->right); - cout << n->val << " "; - } + if (n != NULL) + { + Post(n->left); + Post(n->right); + cout << n->val << " "; + } } int main() { - q.front = 0; - q.rear = 0; - int value; - int ch; - node *root = new node; - cout << "\nEnter the value of root node :"; - cin >> value; - root->val = value; - root->left = NULL; - root->right = NULL; - do - { - cout << "\n1. Insert"; - cout << "\n2. Delete"; - cout << "\n3. Breadth First"; - cout << "\n4. Preorder Depth First"; - cout << "\n5. Inorder Depth First"; - cout << "\n6. Postorder Depth First"; + q.front = 0; + q.rear = 0; + int value; + int ch; + node *root = new node; + cout << "\nEnter the value of root node :"; + cin >> value; + root->val = value; + root->left = NULL; + root->right = NULL; + do + { + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Breadth First"; + cout << "\n4. Preorder Depth First"; + cout << "\n5. Inorder Depth First"; + cout << "\n6. Postorder Depth First"; - cout << "\nEnter Your Choice : "; - cin >> ch; - int x; - switch (ch) - { - case 1: - cout << "\nEnter the value to be Inserted : "; - cin >> x; - Insert(root, x); - break; - case 2: - cout << "\nEnter the value to be Deleted : "; - cin >> x; - Remove(root, root, x); - break; - case 3: - BFT(root); - break; - case 4: - Pre(root); - break; - case 5: - In(root); - break; - case 6: - Post(root); - break; - } - } while (ch != 0); + cout << "\nEnter Your Choice : "; + cin >> ch; + int x; + switch (ch) + { + case 1: + cout << "\nEnter the value to be Inserted : "; + cin >> x; + Insert(root, x); + break; + case 2: + cout << "\nEnter the value to be Deleted : "; + cin >> x; + Remove(root, root, x); + break; + case 3: + BFT(root); + break; + case 4: + Pre(root); + break; + case 5: + In(root); + break; + case 6: + Post(root); + break; + } + } while (ch != 0); } diff --git a/data_structure/binaryheap.cpp b/data_structure/binaryheap.cpp index 31129a823..b2fc7d99c 100644 --- a/data_structure/binaryheap.cpp +++ b/data_structure/binaryheap.cpp @@ -1,6 +1,6 @@ // A C++ program to demonstrate common Binary Heap Operations -#include #include +#include using namespace std; // Prototype of a utility function to swap two integers @@ -9,10 +9,10 @@ void swap(int *x, int *y); // A class for Min Heap class MinHeap { - int *harr; // pointer to array of elements in heap - int capacity; // maximum possible size of min heap - int heap_size; // Current number of elements in min heap -public: + int *harr; // pointer to array of elements in heap + int capacity; // maximum possible size of min heap + int heap_size; // Current number of elements in min heap + public: // Constructor MinHeap(int capacity); diff --git a/data_structure/circular_queue_using_linked_list.cpp b/data_structure/circular_queue_using_linked_list.cpp index 4b1ec476c..d87124448 100644 --- a/data_structure/circular_queue_using_linked_list.cpp +++ b/data_structure/circular_queue_using_linked_list.cpp @@ -11,7 +11,7 @@ class Queue node *front; node *rear; -public: + public: Queue() { front = NULL; diff --git a/data_structure/cll/cll.cpp b/data_structure/cll/cll.cpp index efc068f3c..e9fcfc40b 100644 --- a/data_structure/cll/cll.cpp +++ b/data_structure/cll/cll.cpp @@ -11,10 +11,7 @@ cll::cll() total = 0; } -cll::~cll() -{ - /* Desstructure, no need to fill */ -} +cll::~cll() { /* Desstructure, no need to fill */ } /* Display a list. and total element */ void cll::display() @@ -28,10 +25,10 @@ void cll::display() for (int i = 0; i < total; i++) { cout << current->data << " -> "; - current = current ->next; + current = current->next; } cout << head->data << endl; - cout << "Total element: "<< total <data = new_data; newNode->next = NULL; - if(head==NULL) { + if (head == NULL) + { head = newNode; - head -> next = head; - } else { + head->next = head; + } + else + { node *current = head; - while (current -> next != head) { + while (current->next != head) + { current = current->next; } newNode->next = head; @@ -64,12 +65,16 @@ void cll::insert_tail(int new_data) newNode = new node; newNode->data = new_data; newNode->next = NULL; - if(head==NULL) { + if (head == NULL) + { head = newNode; - head -> next = head; - } else { + head->next = head; + } + else + { node *current = head; - while (current -> next != head) { + while (current->next != head) + { current = current->next; } current->next = newNode; @@ -79,22 +84,22 @@ void cll::insert_tail(int new_data) } /* Get total element in list */ -int cll::get_size() -{ - return total; -} - +int cll::get_size() { return total; } /* Return true if the requested item (sent in as an argument) is in the list, otherwise return false */ bool cll::find_item(int item_to_find) { - if (head == NULL) { + if (head == NULL) + { cout << "List is empty !" << endl; return false; - } else { + } + else + { node *current = head; - while (current -> next != head) { + while (current->next != head) + { if (current->data == item_to_find) return true; current = current->next; @@ -104,24 +109,25 @@ bool cll::find_item(int item_to_find) } /* Overloading method*/ -int cll::operator*() -{ - return head->data; -} +int cll::operator*() { return head->data; } /* Overload the pre-increment operator. The iterator is advanced to the next node. */ void cll::operator++() { - if (head == NULL) { + if (head == NULL) + { cout << "List is empty !" << endl; - } else { + } + else + { node *current = head; - while (current -> next != head) { - current = current -> next; + while (current->next != head) + { + current = current->next; } - current->next = head -> next; - head = head -> next; + current->next = head->next; + head = head->next; } total--; } diff --git a/data_structure/cll/cll.h b/data_structure/cll/cll.h index ae71dcd01..89a9fe199 100644 --- a/data_structure/cll/cll.h +++ b/data_structure/cll/cll.h @@ -1,45 +1,45 @@ /* * Simple data structure CLL (Cicular Linear Linked List) * */ -#include #include -#include #include +#include +#include #ifndef CLL_H #define CLL_H /*The data structure is a linear linked list of integers */ struct node { - int data; - node * next; + int data; + node* next; }; class cll { - public: - cll(); /* Construct without parameter */ - ~cll(); - void display(); /* Show the list */ + public: + cll(); /* Construct without parameter */ + ~cll(); + void display(); /* Show the list */ - /****************************************************** - * Useful method for list - *******************************************************/ - void insert_front(int new_data); /* Insert a new value at head */ - void insert_tail(int new_data); /* Insert a new value at tail */ - int get_size(); /* Get total element in list */ - bool find_item(int item_to_find); /* Find an item in list */ + /****************************************************** + * Useful method for list + *******************************************************/ + void insert_front(int new_data); /* Insert a new value at head */ + void insert_tail(int new_data); /* Insert a new value at tail */ + int get_size(); /* Get total element in list */ + bool find_item(int item_to_find); /* Find an item in list */ - /****************************************************** - * Overloading method for list - *******************************************************/ - int operator*(); /* Returns the info contained in head */ - /* Overload the pre-increment operator. - The iterator is advanced to the next node. */ - void operator++(); + /****************************************************** + * Overloading method for list + *******************************************************/ + int operator*(); /* Returns the info contained in head */ + /* Overload the pre-increment operator. + The iterator is advanced to the next node. */ + void operator++(); - protected: - node * head; - int total; /* Total element in a list */ + protected: + node* head; + int total; /* Total element in a list */ }; #endif diff --git a/data_structure/cll/main_cll.cpp b/data_structure/cll/main_cll.cpp index 15388b822..3876f0393 100644 --- a/data_structure/cll/main_cll.cpp +++ b/data_structure/cll/main_cll.cpp @@ -3,42 +3,42 @@ using namespace std; int main() { - /* Test CLL */ - cout << "----------- Test construct -----------" << endl; - cll list1; - list1.display(); - cout << "----------- Test insert front -----------" << endl; - list1.insert_front(5); - cout << "After insert 5 at front: "< root, rnk; -void CreateSet(int n) { - root = vector (n+1); - rnk = vector (n+1, 1); - for (int i = 1; i <= n; ++i) { - root[i] = i; - } -} - -int Find(int x) { - if (root[x] == x) { - return x; - } - return root[x] = Find(root[x]); -} - -bool InSameUnion(int x, int y) { - return Find(x) == Find(y); -} - -void Union(int x, int y) { - int a = Find(x), b = Find(y); - if (a != b) { - if (rnk[a] < rnk[b]) { - root[a] = b; - } else if (rnk[a] > rnk[b]) { - root[b] = a; - } else { - root[a] = b; - ++rnk[b]; +void CreateSet(int n) +{ + root = vector(n + 1); + rnk = vector(n + 1, 1); + for (int i = 1; i <= n; ++i) + { + root[i] = i; } - } } -int main() { - // tests CreateSet & Find - int n = 100; - CreateSet(n); - for (int i = 1; i <= 100; ++i) { - if (root[i] != i) { - cout << "Fail" << endl; - break; +int Find(int x) +{ + if (root[x] == x) + { + return x; } - } - // tests InSameUnion & Union - cout << "1 and 2 are initially not in the same subset" << endl; - if (InSameUnion(1, 2)) { - cout << "Fail" << endl; - } - Union(1, 2); - cout << "1 and 2 are now in the same subset" << endl; - if (!InSameUnion(1, 2)) { - cout << "Fail" << endl; - } - return 0; + return root[x] = Find(root[x]); +} + +bool InSameUnion(int x, int y) { return Find(x) == Find(y); } + +void Union(int x, int y) +{ + int a = Find(x), b = Find(y); + if (a != b) + { + if (rnk[a] < rnk[b]) + { + root[a] = b; + } + else if (rnk[a] > rnk[b]) + { + root[b] = a; + } + else + { + root[a] = b; + ++rnk[b]; + } + } +} + +int main() +{ + // tests CreateSet & Find + int n = 100; + CreateSet(n); + for (int i = 1; i <= 100; ++i) + { + if (root[i] != i) + { + cout << "Fail" << endl; + break; + } + } + // tests InSameUnion & Union + cout << "1 and 2 are initially not in the same subset" << endl; + if (InSameUnion(1, 2)) + { + cout << "Fail" << endl; + } + Union(1, 2); + cout << "1 and 2 are now in the same subset" << endl; + if (!InSameUnion(1, 2)) + { + cout << "Fail" << endl; + } + return 0; } diff --git a/data_structure/doubly_linked_list.cpp b/data_structure/doubly_linked_list.cpp index 4fc38abfc..4907c125d 100644 --- a/data_structure/doubly_linked_list.cpp +++ b/data_structure/doubly_linked_list.cpp @@ -1,138 +1,166 @@ +#include +#include #include -#include -#include -struct node { - int val; - node *prev; - node *next; -}*start; +struct node +{ + int val; + node *prev; + node *next; +} * start; -class double_linked_list { +class double_linked_list +{ public: - double_linked_list() { - start = NULL; - } - void insert(int x); - void remove(int x); - void search(int x); - void show(); - void reverseShow(); + double_linked_list() { start = NULL; } + void insert(int x); + void remove(int x); + void search(int x); + void show(); + void reverseShow(); }; -void double_linked_list::insert(int x) { - node *t = start; - if (start != NULL) { - while (t->next != NULL) { - t = t->next; +void double_linked_list::insert(int x) +{ + node *t = start; + if (start != NULL) + { + while (t->next != NULL) + { + t = t->next; + } + node *n = new node; + t->next = n; + n->prev = t; + n->val = x; + n->next = NULL; } - node *n = new node; - t->next = n; - n->prev = t; - n->val = x; - n->next = NULL; - } else { - node *n = new node; - n->val = x; - n->prev = NULL; - n->next = NULL; - start = n; - } -} - -void double_linked_list::remove(int x) { - node *t = start; - while (t != NULL && t->val != x) { - t = t-> next; - } - if (t == NULL) { - return; - } - if (t->prev == NULL) { - if (t->next == NULL) { - start = NULL; - } else { - start = t->next; - start->prev = NULL; + else + { + node *n = new node; + n->val = x; + n->prev = NULL; + n->next = NULL; + start = n; } - } else if (t->next == NULL) { - t->prev->next = NULL; - } else { - t->prev->next = t->next; - t->next->prev = t->prev; - } - delete t; } -void double_linked_list::search(int x) { - node *t = start; - int found = 0; - while (t != NULL) { - if (t->val == x) { - std::cout << "\nFound"; - found = 1; - break; +void double_linked_list::remove(int x) +{ + node *t = start; + while (t != NULL && t->val != x) + { + t = t->next; } - t = t->next; - } - if (found == 0) { - std::cout << "\nNot Found"; - } -} - -void double_linked_list::show() { - node *t = start; - while (t != NULL) { - std::cout << t->val << "\t"; - t = t->next; - } -} - -void double_linked_list::reverseShow() { - node *t = start; - while (t != NULL && t->next != NULL) { - t = t->next; - } - while (t != NULL) { - std::cout << t->val << "\t"; - t = t->prev; - } -} - -int main() { - int choice, x; - double_linked_list ob; - do { - std::cout << "\n1. Insert"; - std::cout << "\n2. Delete"; - std::cout << "\n3. Search"; - std::cout << "\n4. Forward print"; - std::cout << "\n5. Reverse print"; - std::cout << "\n\nEnter you choice : "; - std::cin >> choice; - switch (choice) { - case 1: - std::cout << "\nEnter the element to be inserted : "; - std::cin >> x; - ob.insert(x); - break; - case 2: - std::cout << "\nEnter the element to be removed : "; - std::cin >> x; - ob.remove(x); - break; - case 3: - std::cout << "\nEnter the element to be searched : "; - std::cin >> x; - ob.search(x); - break; - case 4: - ob.show(); - break; - case 5: - ob.reverseShow(); - break; + if (t == NULL) + { + return; } - } while (choice != 0); - return 0; + if (t->prev == NULL) + { + if (t->next == NULL) + { + start = NULL; + } + else + { + start = t->next; + start->prev = NULL; + } + } + else if (t->next == NULL) + { + t->prev->next = NULL; + } + else + { + t->prev->next = t->next; + t->next->prev = t->prev; + } + delete t; +} + +void double_linked_list::search(int x) +{ + node *t = start; + int found = 0; + while (t != NULL) + { + if (t->val == x) + { + std::cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) + { + std::cout << "\nNot Found"; + } +} + +void double_linked_list::show() +{ + node *t = start; + while (t != NULL) + { + std::cout << t->val << "\t"; + t = t->next; + } +} + +void double_linked_list::reverseShow() +{ + node *t = start; + while (t != NULL && t->next != NULL) + { + t = t->next; + } + while (t != NULL) + { + std::cout << t->val << "\t"; + t = t->prev; + } +} + +int main() +{ + int choice, x; + double_linked_list ob; + do + { + std::cout << "\n1. Insert"; + std::cout << "\n2. Delete"; + std::cout << "\n3. Search"; + std::cout << "\n4. Forward print"; + std::cout << "\n5. Reverse print"; + std::cout << "\n\nEnter you choice : "; + std::cin >> choice; + switch (choice) + { + case 1: + std::cout << "\nEnter the element to be inserted : "; + std::cin >> x; + ob.insert(x); + break; + case 2: + std::cout << "\nEnter the element to be removed : "; + std::cin >> x; + ob.remove(x); + break; + case 3: + std::cout << "\nEnter the element to be searched : "; + std::cin >> x; + ob.search(x); + break; + case 4: + ob.show(); + break; + case 5: + ob.reverseShow(); + break; + } + } while (choice != 0); + return 0; } diff --git a/data_structure/linked_list.cpp b/data_structure/linked_list.cpp index 64cad14f9..f639bb16c 100644 --- a/data_structure/linked_list.cpp +++ b/data_structure/linked_list.cpp @@ -1,135 +1,160 @@ #include -struct node { - int val; - node *next; +struct node +{ + int val; + node *next; }; node *start; -void insert(int x) { - node *t = start; - node *n = new node; - n->val = x; - n->next = NULL; - if (start != NULL) { - while (t->next != NULL) { - t = t->next; - } - t->next = n; - } else { - start = n; +void insert(int x) +{ + node *t = start; + node *n = new node; + n->val = x; + n->next = NULL; + if (start != NULL) + { + while (t->next != NULL) + { + t = t->next; } - + t->next = n; + } + else + { + start = n; + } } -void remove(int x) { - if (start == NULL) { - std::cout << "\nLinked List is empty\n"; - return; - } else if (start->val == x) { - node *temp = start; - start = start->next; - delete temp; - return; - } - - node *temp = start, *parent = start; - - while (temp != NULL && temp->val != x) { - parent = temp; - temp = temp->next; - } - - if (temp == NULL) { - std::cout << std::endl << x << " not found in list\n"; - return; - } - - parent->next = temp->next; +void remove(int x) +{ + if (start == NULL) + { + std::cout << "\nLinked List is empty\n"; + return; + } + else if (start->val == x) + { + node *temp = start; + start = start->next; delete temp; + return; + } + + node *temp = start, *parent = start; + + while (temp != NULL && temp->val != x) + { + parent = temp; + temp = temp->next; + } + + if (temp == NULL) + { + std::cout << std::endl << x << " not found in list\n"; + return; + } + + parent->next = temp->next; + delete temp; } -void search(int x) { - node *t = start; - int found = 0; - while (t != NULL) { - if (t->val == x) { - std::cout << "\nFound"; - found = 1; - break; - } - t = t->next; +void search(int x) +{ + node *t = start; + int found = 0; + while (t != NULL) + { + if (t->val == x) + { + std::cout << "\nFound"; + found = 1; + break; } - if (found == 0) { - std::cout << "\nNot Found"; + t = t->next; + } + if (found == 0) + { + std::cout << "\nNot Found"; + } +} + +void show() +{ + node *t = start; + while (t != NULL) + { + std::cout << t->val << "\t"; + t = t->next; + } +} + +void reverse() +{ + node *first = start; + if (first != NULL) + { + node *second = first->next; + while (second != NULL) + { + node *tem = second->next; + second->next = first; + first = second; + second = tem; } + start->next = NULL; + start = first; + } + else + { + std::cout << "\nEmpty list"; + } } -void show() { - node *t = start; - while (t != NULL) { - std::cout << t->val << "\t"; - t = t->next; +int main() +{ + int choice, x; + do + { + std::cout << "\n1. Insert"; + std::cout << "\n2. Delete"; + std::cout << "\n3. Search"; + std::cout << "\n4. Print"; + std::cout << "\n5. Reverse"; + std::cout << "\n0. Exit"; + std::cout << "\n\nEnter you choice : "; + std::cin >> choice; + switch (choice) + { + case 1: + std::cout << "\nEnter the element to be inserted : "; + std::cin >> x; + insert(x); + break; + case 2: + std::cout << "\nEnter the element to be removed : "; + std::cin >> x; + remove(x); + break; + case 3: + std::cout << "\nEnter the element to be searched : "; + std::cin >> x; + search(x); + break; + case 4: + show(); + std::cout << "\n"; + break; + case 5: + std::cout << "The reversed list: \n"; + reverse(); + show(); + std::cout << "\n"; + break; } -} + } while (choice != 0); -void reverse() { - node *first = start; - if (first != NULL) { - node *second = first->next; - while (second != NULL) { - node *tem = second->next; - second->next = first; - first = second; - second = tem; - } - start->next = NULL; - start = first; - } else { - std::cout << "\nEmpty list"; - } -} - -int main() { - int choice, x; - do { - std::cout << "\n1. Insert"; - std::cout << "\n2. Delete"; - std::cout << "\n3. Search"; - std::cout << "\n4. Print"; - std::cout << "\n5. Reverse"; - std::cout << "\n0. Exit"; - std::cout << "\n\nEnter you choice : "; - std::cin >> choice; - switch (choice) { - case 1: - std::cout << "\nEnter the element to be inserted : "; - std::cin >> x; - insert(x); - break; - case 2: - std::cout << "\nEnter the element to be removed : "; - std::cin >> x; - remove(x); - break; - case 3: - std::cout << "\nEnter the element to be searched : "; - std::cin >> x; - search(x); - break; - case 4: - show(); - std::cout << "\n"; - break; - case 5: - std::cout << "The reversed list: \n"; - reverse(); - show(); - std::cout << "\n"; - break; - } - } while (choice != 0); - - return 0; + return 0; } diff --git a/data_structure/linkedlist_implentation_usingarray.cpp b/data_structure/linkedlist_implentation_usingarray.cpp index 6f8205f27..168124f00 100644 --- a/data_structure/linkedlist_implentation_usingarray.cpp +++ b/data_structure/linkedlist_implentation_usingarray.cpp @@ -1,6 +1,8 @@ -/* The difference between the pointer implementation of linked list and array implementation of linked list: +/* The difference between the pointer implementation of linked list and array + implementation of linked list: 1. The NULL is represented by -1; - 2. Limited size. (in the following case it is 100 nodes at max). But we can reuse the nodes that are to be deleted by again linking it bacj to the list. + 2. Limited size. (in the following case it is 100 nodes at max). But we can + reuse the nodes that are to be deleted by again linking it bacj to the list. */ #include @@ -10,7 +12,7 @@ struct Node int data; int next; }; -Node AvailArray[100]; //array that will act as nodes of a linked list. +Node AvailArray[100]; // array that will act as nodes of a linked list. int head = -1; int avail = 0; void initialise_list() @@ -19,23 +21,28 @@ void initialise_list() { AvailArray[i].next = i + 1; } - AvailArray[99].next = -1; //indicating the end of the linked list. + AvailArray[99].next = -1; // indicating the end of the linked list. } -int getnode() //This will return the index of the first free node present in the avail list +int getnode() // This will return the index of the first free node present in + // the avail list { int NodeIndexToBeReturned = avail; avail = AvailArray[avail].next; return NodeIndexToBeReturned; } -void freeNode(int nodeToBeDeleted) //This function when called will delete the node with the index presented as an argument, and will put back that node into the array. +void freeNode( + int nodeToBeDeleted) // This function when called will delete the node with + // the index presented as an argument, and will put + // back that node into the array. { AvailArray[nodeToBeDeleted].next = avail; avail = nodeToBeDeleted; } -void insertAtTheBeginning(int data) //The function will insert the given data into the front of the linked list. +void insertAtTheBeginning(int data) // The function will insert the given data + // into the front of the linked list. { int newNode = getnode(); AvailArray[newNode].data = data; @@ -51,7 +58,7 @@ void insertAtTheEnd(int data) { temp = AvailArray[temp].next; } - //temp is now pointing to the end node. + // temp is now pointing to the end node. AvailArray[newNode].data = data; AvailArray[newNode].next = -1; AvailArray[temp].next = newNode; @@ -94,7 +101,8 @@ int main() insertAtTheEnd(y); break; case 3: - cout << "The linked list contains the following element in order" << endl; + cout << "The linked list contains the following element in order" + << endl; display(); break; case 4: diff --git a/data_structure/list_array.cpp b/data_structure/list_array.cpp index de984876b..f572b77b4 100644 --- a/data_structure/list_array.cpp +++ b/data_structure/list_array.cpp @@ -3,186 +3,184 @@ using namespace std; struct list { - int data[50]; - int top = 0; - bool isSorted = false; + int data[50]; + int top = 0; + bool isSorted = false; - int BinarySearch(int *array, int first, int last, int x) - { - if (last < first) - { - return -1; - } - int mid = (first + last) / 2; - if (array[mid] == x) - return mid; - else if (x < array[mid]) - return (BinarySearch(array, first, mid - 1, x)); - else if (x > array[mid]) - return (BinarySearch(array, mid + 1, last, x)); - } + int BinarySearch(int *array, int first, int last, int x) + { + if (last < first) + { + return -1; + } + int mid = (first + last) / 2; + if (array[mid] == x) + return mid; + else if (x < array[mid]) + return (BinarySearch(array, first, mid - 1, x)); + else if (x > array[mid]) + return (BinarySearch(array, mid + 1, last, x)); + } - int LinarSearch(int *array, int x) - { - for (int i = 0; i < top; i++) - { - if (array[i] == x) - { - return i; - } - } + int LinarSearch(int *array, int x) + { + for (int i = 0; i < top; i++) + { + if (array[i] == x) + { + return i; + } + } - return -1; - } + return -1; + } - int Search(int x) - { - int pos = -1; + int Search(int x) + { + int pos = -1; - if (isSorted) - { - pos = BinarySearch(data, 0, top - 1, x); - } + if (isSorted) + { + pos = BinarySearch(data, 0, top - 1, x); + } - else - { - pos = LinarSearch(data, x); - } + else + { + pos = LinarSearch(data, x); + } - if (pos != -1) - { - cout << "\nElement found at position : " << pos; - } - else - { - cout << "\nElement not found"; - } - return pos; - } + if (pos != -1) + { + cout << "\nElement found at position : " << pos; + } + else + { + cout << "\nElement not found"; + } + return pos; + } - void Sort() - { - int i, j, pos; - for (i = 0; i < top; i++) - { - int min = data[i]; - for (j = i + 1; j < top; j++) - { - if (data[j] < min) - { - pos = j; - min = data[pos]; - } - } + void Sort() + { + int i, j, pos; + for (i = 0; i < top; i++) + { + int min = data[i]; + for (j = i + 1; j < top; j++) + { + if (data[j] < min) + { + pos = j; + min = data[pos]; + } + } - int temp = data[i]; - data[i] = data[pos]; - data[pos] = temp; - } - isSorted = true; - } + int temp = data[i]; + data[i] = data[pos]; + data[pos] = temp; + } + isSorted = true; + } - void insert(int x) - { - if (!isSorted) - { + void insert(int x) + { + if (!isSorted) + { + if (top == 49) + { + cout << "\nOverflow"; + } + else + { + data[top] = x; + top++; + } + } - if (top == 49) - { - cout << "\nOverflow"; - } - else - { - data[top] = x; - top++; - } - } + else + { + int pos = 0; - else - { - int pos = 0; + for (int i = 0; i < top - 1; i++) + { + if (data[i] <= x && x <= data[i + 1]) + { + pos = i + 1; + break; + } + } + if (pos == 0) + { + pos = top - 1; + } - for (int i = 0; i < top - 1; i++) - { - if (data[i] <= x && x <= data[i + 1]) - { - pos = i + 1; - break; - } - } - if (pos == 0) - { - pos = top - 1; - } + for (int i = top; i > pos; i--) + { + data[i] = data[i - 1]; + } + top++; + data[pos] = x; + } + } - for (int i = top; i > pos; i--) - { - data[i] = data[i - 1]; - } - top++; - data[pos] = x; - } - } + void Remove(int x) + { + int pos = Search(x); + cout << "\n" << data[pos] << " deleted"; + for (int i = pos; i < top; i++) + { + data[i] = data[i + 1]; + } + top--; + } - void Remove(int x) - { - int pos = Search(x); - cout << "\n" - << data[pos] << " deleted"; - for (int i = pos; i < top; i++) - { - data[i] = data[i + 1]; - } - top--; - } - - void Show() - { - for (int i = 0; i < top; i++) - { - cout << data[i] << "\t"; - } - } + void Show() + { + for (int i = 0; i < top; i++) + { + cout << data[i] << "\t"; + } + } }; int main() { - list L; - int choice; - int x; - do - { - cout << "\n1.Insert"; - cout << "\n2.Delete"; - cout << "\n3.Search"; - cout << "\n4.Sort"; - cout << "\n5.Print"; - cout << "\n\nEnter Your Choice : "; - cin >> choice; - switch (choice) - { - case 1: - cout << "\nEnter the element to be inserted : "; - cin >> x; - L.insert(x); - break; - case 2: - cout << "\nEnter the element to be removed : "; - cin >> x; - L.Remove(x); - break; - case 3: - cout << "\nEnter the element to be searched : "; - cin >> x; - L.Search(x); - break; - case 4: - L.Sort(); - break; - case 5: - L.Show(); - break; - } - } while (choice != 0); - return 0; + list L; + int choice; + int x; + do + { + cout << "\n1.Insert"; + cout << "\n2.Delete"; + cout << "\n3.Search"; + cout << "\n4.Sort"; + cout << "\n5.Print"; + cout << "\n\nEnter Your Choice : "; + cin >> choice; + switch (choice) + { + case 1: + cout << "\nEnter the element to be inserted : "; + cin >> x; + L.insert(x); + break; + case 2: + cout << "\nEnter the element to be removed : "; + cin >> x; + L.Remove(x); + break; + case 3: + cout << "\nEnter the element to be searched : "; + cin >> x; + L.Search(x); + break; + case 4: + L.Sort(); + break; + case 5: + L.Show(); + break; + } + } while (choice != 0); + return 0; } diff --git a/data_structure/morrisinorder.cpp b/data_structure/morrisinorder.cpp index d3a2e9fd7..58f267907 100644 --- a/data_structure/morrisinorder.cpp +++ b/data_structure/morrisinorder.cpp @@ -2,107 +2,107 @@ #include /************************** - @author shrutisheoran + @author shrutisheoran **************************/ using namespace std; struct Btree { - int data; - struct Btree *left; //Pointer to left subtree - struct Btree *right; //Pointer to right subtree + int data; + struct Btree *left; // Pointer to left subtree + struct Btree *right; // Pointer to right subtree }; void insert(Btree **root, int d) { - Btree *nn = new Btree(); //Creating new node - nn->data = d; - nn->left = NULL; - nn->right = NULL; - if (*root == NULL) - { - *root = nn; - return; - } - else - { - queue q; - // Adding root node to queue - q.push(*root); - while (!q.empty()) - { - Btree *node = q.front(); - // Removing parent node from queue - q.pop(); - if (node->left) - // Adding left child of removed node to queue - q.push(node->left); - else - { - // Adding new node if no left child is present - node->left = nn; - return; - } - if (node->right) - // Adding right child of removed node to queue - q.push(node->right); - else - { - // Adding new node if no right child is present - node->right = nn; - return; - } - } - } + Btree *nn = new Btree(); // Creating new node + nn->data = d; + nn->left = NULL; + nn->right = NULL; + if (*root == NULL) + { + *root = nn; + return; + } + else + { + queue q; + // Adding root node to queue + q.push(*root); + while (!q.empty()) + { + Btree *node = q.front(); + // Removing parent node from queue + q.pop(); + if (node->left) + // Adding left child of removed node to queue + q.push(node->left); + else + { + // Adding new node if no left child is present + node->left = nn; + return; + } + if (node->right) + // Adding right child of removed node to queue + q.push(node->right); + else + { + // Adding new node if no right child is present + node->right = nn; + return; + } + } + } } void morrisInorder(Btree *root) { - Btree *curr = root; - Btree *temp; - while (curr) - { - if (curr->left == NULL) - { - cout << curr->data << " "; - // If left of current node is NULL then curr is shifted to right - curr = curr->right; - } - else - { - // Left of current node is stored in temp - temp = curr->left; - // Moving to extreme right of temp - while (temp->right && temp->right != curr) - temp = temp->right; - // If extreme right is null it is made to point to currrent node (will be used for backtracking) - if (temp->right == NULL) - { - temp->right = curr; - // current node is made to point its left subtree - curr = curr->left; - } - // If extreme right already points to currrent node it it set to null - else if (temp->right == curr) - { - cout << curr->data << " "; - temp->right = NULL; - // current node is made to point its right subtree - curr = curr->right; - } - } - } + Btree *curr = root; + Btree *temp; + while (curr) + { + if (curr->left == NULL) + { + cout << curr->data << " "; + // If left of current node is NULL then curr is shifted to right + curr = curr->right; + } + else + { + // Left of current node is stored in temp + temp = curr->left; + // Moving to extreme right of temp + while (temp->right && temp->right != curr) temp = temp->right; + // If extreme right is null it is made to point to currrent node + // (will be used for backtracking) + if (temp->right == NULL) + { + temp->right = curr; + // current node is made to point its left subtree + curr = curr->left; + } + // If extreme right already points to currrent node it it set to + // null + else if (temp->right == curr) + { + cout << curr->data << " "; + temp->right = NULL; + // current node is made to point its right subtree + curr = curr->right; + } + } + } } int main() { - // Testing morrisInorder funtion - Btree *root = NULL; - int i; - for (i = 1; i <= 7; i++) - insert(&root, i); - cout << "Morris Inorder: "; - morrisInorder(root); - return 0; + // Testing morrisInorder funtion + Btree *root = NULL; + int i; + for (i = 1; i <= 7; i++) insert(&root, i); + cout << "Morris Inorder: "; + morrisInorder(root); + return 0; } diff --git a/data_structure/queue/queue.cpp b/data_structure/queue/queue.cpp index 728adfc18..e8ff8966c 100644 --- a/data_structure/queue/queue.cpp +++ b/data_structure/queue/queue.cpp @@ -1,6 +1,6 @@ -#include -#include #include "queue.h" +#include +#include using namespace std; @@ -25,11 +25,12 @@ void queue::display() { node *current = queueFront; cout << "Front --> "; - while(current != NULL) { - cout<data<< " "; - current = current -> next; + while (current != NULL) + { + cout << current->data << " "; + current = current->next; } - cout <::enQueue(Kind item) newNode = new node; newNode->data = item; newNode->next = NULL; - if (queueFront == NULL) { + if (queueFront == NULL) + { queueFront = newNode; queueRear = newNode; - } else { + } + else + { queueRear->next = newNode; queueRear = queueRear->next; } @@ -78,13 +82,15 @@ template void queue::deQueue() { node *temp; - if(!isEmptyQueue()) { + if (!isEmptyQueue()) + { temp = queueFront; queueFront = queueFront->next; delete temp; size--; - } else { + } + else + { cout << "Queue is empty !" << endl; } } - diff --git a/data_structure/queue/queue.h b/data_structure/queue/queue.h index 715def1ef..7e9c44559 100644 --- a/data_structure/queue/queue.h +++ b/data_structure/queue/queue.h @@ -14,21 +14,20 @@ struct node template class queue { - public: - void display(); /* Show queue */ - queue(); /* Default constructor*/ - ~queue(); /* Destructor */ - bool isEmptyQueue(); /* Determine whether the queue is empty */ - void enQueue (Kind item); /* Add new item to the queue */ - Kind front(); /* Return the first element of the queue */ - void deQueue(); /* Remove the top element of the queue */ - void clear(); + public: + void display(); /* Show queue */ + queue(); /* Default constructor*/ + ~queue(); /* Destructor */ + bool isEmptyQueue(); /* Determine whether the queue is empty */ + void enQueue(Kind item); /* Add new item to the queue */ + Kind front(); /* Return the first element of the queue */ + void deQueue(); /* Remove the top element of the queue */ + void clear(); - private: - node *queueFront; /* Pointer to the front of the queue */ - node *queueRear; /* Pointer to the rear of the queue */ - int size; + private: + node *queueFront; /* Pointer to the front of the queue */ + node *queueRear; /* Pointer to the rear of the queue */ + int size; }; #endif - diff --git a/data_structure/queue/test_queue.cpp b/data_structure/queue/test_queue.cpp index caf80318c..d9308adcb 100644 --- a/data_structure/queue/test_queue.cpp +++ b/data_structure/queue/test_queue.cpp @@ -1,22 +1,25 @@ #include #include -#include "queue.h" #include "queue.cpp" +#include "queue.h" using namespace std; int main() { queue q; - cout << "---------------------- Test construct ----------------------" << endl; + cout << "---------------------- Test construct ----------------------" + << endl; q.display(); - cout << "---------------------- Test isEmptyQueue ----------------------" << endl; - if(q.isEmptyQueue()) - cout << "PASS" <> op; - if (op == 1) { + if (op == 1) + { std::cout << "Enter data "; std::cin >> data; ob.enqueue(data); - } else if (op == 2) { + } + else if (op == 2) + { data = ob.dequeue(); std::cout << "\ndequeue element is:\t" << data; - } else if (op == 3) { + } + else if (op == 3) + { ob.display(); - } else if (op == 4) { + } + else if (op == 4) + { exit(0); - } else { + } + else + { std::cout << "\nWrong choice "; } } diff --git a/data_structure/queue_using_array2.cpp b/data_structure/queue_using_array2.cpp index 3b79d06fc..7e1ada725 100644 --- a/data_structure/queue_using_array2.cpp +++ b/data_structure/queue_using_array2.cpp @@ -7,69 +7,68 @@ int rear = 0; void Enque(int x) { - if (rear == 10) - { - cout << "\nOverflow"; - } - else - { - queue[rear++] = x; - } + if (rear == 10) + { + cout << "\nOverflow"; + } + else + { + queue[rear++] = x; + } } void Deque() { - if (front == rear) - { - cout << "\nUnderflow"; - } + if (front == rear) + { + cout << "\nUnderflow"; + } - else - { - cout << "\n" - << queue[front++] << " deleted"; - for (int i = front; i < rear; i++) - { - queue[i - front] = queue[i]; - } - rear = rear - front; - front = 0; - } + else + { + cout << "\n" << queue[front++] << " deleted"; + for (int i = front; i < rear; i++) + { + queue[i - front] = queue[i]; + } + rear = rear - front; + front = 0; + } } void show() { - for (int i = front; i < rear; i++) - { - cout << queue[i] << "\t"; - } + for (int i = front; i < rear; i++) + { + cout << queue[i] << "\t"; + } } int main() { - int ch, x; - do - { - cout << "\n1. Enque"; - cout << "\n2. Deque"; - cout << "\n3. Print"; - cout << "\nEnter Your Choice : "; - cin >> ch; - if (ch == 1) - { - cout << "\nInsert : "; - cin >> x; - Enque(x); - } - else if (ch == 2) - { - Deque(); - } - else if (ch == 3) - { - show(); - } - } while (ch != 0); + int ch, x; + do + { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) + { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } + else if (ch == 2) + { + Deque(); + } + else if (ch == 3) + { + show(); + } + } while (ch != 0); - return 0; + return 0; } diff --git a/data_structure/queue_using_linked_list.cpp b/data_structure/queue_using_linked_list.cpp index 39d7a9ae3..9ddbdaa42 100644 --- a/data_structure/queue_using_linked_list.cpp +++ b/data_structure/queue_using_linked_list.cpp @@ -22,7 +22,6 @@ void Enque(int x) else { - node *n = new node; n->val = x; n->next = NULL; @@ -40,8 +39,7 @@ void Deque() else { node *t = front; - cout << "\n" - << t->val << " deleted"; + cout << "\n" << t->val << " deleted"; front = front->next; delete t; if (front == NULL) diff --git a/data_structure/queue_using_linkedlist.cpp b/data_structure/queue_using_linkedlist.cpp index 8bc130c27..21ff0cfcf 100644 --- a/data_structure/queue_using_linkedlist.cpp +++ b/data_structure/queue_using_linkedlist.cpp @@ -1,98 +1,99 @@ /* Write a program to implement Queue using linkedlist. */ -#include - - -struct linkedlist{ - int data; - linkedlist *next; +#include +struct linkedlist +{ + int data; + linkedlist *next; }; -class stack_linkedList{ - public: +class stack_linkedList +{ + public: linkedlist *front; linkedlist *rear; - - stack_linkedList(){ - front=rear=NULL; - } + + stack_linkedList() { front = rear = NULL; } void enqueue(int); int dequeue(); void display(); - }; -void stack_linkedList::enqueue(int ele){ - - linkedlist *temp=new linkedlist(); - temp->data=ele; - temp->next=NULL; +void stack_linkedList::enqueue(int ele) +{ + linkedlist *temp = new linkedlist(); + temp->data = ele; + temp->next = NULL; - if(front==NULL) - front=rear=temp; - else{ - rear->next=temp; - rear=temp; + if (front == NULL) + front = rear = temp; + else + { + rear->next = temp; + rear = temp; } } -int stack_linkedList::dequeue(){ +int stack_linkedList::dequeue() +{ linkedlist *temp; int ele; - if(front==NULL) - std::cout<<"\nStack is empty"; - else{ - temp=front; - ele=temp->data; - if(front==rear) //if length of queue is 1; - rear=rear->next; - front=front->next; - delete(temp); + if (front == NULL) + std::cout << "\nStack is empty"; + else + { + temp = front; + ele = temp->data; + if (front == rear) // if length of queue is 1; + rear = rear->next; + front = front->next; + delete (temp); } return ele; } -void stack_linkedList::display(){ - - if(front==NULL) - std::cout<<"\nStack is empty"; - - else { - +void stack_linkedList::display() +{ + if (front == NULL) + std::cout << "\nStack is empty"; + + else + { linkedlist *temp; - temp=front; - while(temp!=NULL){ - std::cout<data<<" "; - temp=temp->next; + temp = front; + while (temp != NULL) + { + std::cout << temp->data << " "; + temp = temp->next; } } } -int main(){ - - int op,data; +int main() +{ + int op, data; stack_linkedList ob; - std::cout<<"\n1. enqueue(Insertion) "; - std::cout<<"\n2. dequeue(Deletion)"; - std::cout<<"\n3. Display"; - std::cout<<"\n4. Exit"; - - while(1){ - std::cout<<"\nEnter your choice "; - std::cin>>op; - if(op==1) + std::cout << "\n1. enqueue(Insertion) "; + std::cout << "\n2. dequeue(Deletion)"; + std::cout << "\n3. Display"; + std::cout << "\n4. Exit"; + + while (1) + { + std::cout << "\nEnter your choice "; + std::cin >> op; + if (op == 1) { - std::cout<<"Enter data "; - std::cin>>data; + std::cout << "Enter data "; + std::cin >> data; ob.enqueue(data); } - else if(op==2) - data=ob.dequeue(); - else if(op==3) + else if (op == 2) + data = ob.dequeue(); + else if (op == 3) ob.display(); - else if(op==4) + else if (op == 4) exit(0); else - std::cout<<"\nWrong choice "; - + std::cout << "\nWrong choice "; } return 0; } diff --git a/data_structure/stack_using_array.cpp b/data_structure/stack_using_array.cpp index af1d57c46..dd0709ff2 100644 --- a/data_structure/stack_using_array.cpp +++ b/data_structure/stack_using_array.cpp @@ -6,74 +6,70 @@ int top = 0, size; void push(int x) { - if (top == size) - { - cout << "\nOverflow"; - } - else - { - stack[top++] = x; - } + if (top == size) + { + cout << "\nOverflow"; + } + else + { + stack[top++] = x; + } } void pop() { - if (top == 0) - { - cout << "\nUnderflow"; - } - else - { - cout << "\n" - << stack[--top] << " deleted"; - } + if (top == 0) + { + cout << "\nUnderflow"; + } + else + { + cout << "\n" << stack[--top] << " deleted"; + } } void show() { - for (int i = 0; i < top; i++) - { - cout << stack[i] << "\n"; - } + for (int i = 0; i < top; i++) + { + cout << stack[i] << "\n"; + } } -void topmost() -{ - cout << "\nTopmost element: " << stack[top - 1]; -} +void topmost() { cout << "\nTopmost element: " << stack[top - 1]; } int main() { - cout << "\nEnter Size of stack : "; - cin >> size; - stack = new int[size]; - int ch, x; - do - { - cout << "\n1. Push"; - cout << "\n2. Pop"; - cout << "\n3. Print"; - cout << "\n4. Print topmost element:"; - cout << "\nEnter Your Choice : "; - cin >> ch; - if (ch == 1) - { - cout << "\nInsert : "; - cin >> x; - push(x); - } - else if (ch == 2) - { - pop(); - } - else if (ch == 3) - { - show(); - } - else if (ch == 4) - { - topmost(); - } - } while (ch != 0); + cout << "\nEnter Size of stack : "; + cin >> size; + stack = new int[size]; + int ch, x; + do + { + cout << "\n1. Push"; + cout << "\n2. Pop"; + cout << "\n3. Print"; + cout << "\n4. Print topmost element:"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) + { + cout << "\nInsert : "; + cin >> x; + push(x); + } + else if (ch == 2) + { + pop(); + } + else if (ch == 3) + { + show(); + } + else if (ch == 4) + { + topmost(); + } + } while (ch != 0); - return 0; + return 0; } diff --git a/data_structure/stack_using_linked_list.cpp b/data_structure/stack_using_linked_list.cpp index 6925cf10c..89a15fe39 100644 --- a/data_structure/stack_using_linked_list.cpp +++ b/data_structure/stack_using_linked_list.cpp @@ -3,71 +3,70 @@ using namespace std; struct node { - int val; - node *next; + int val; + node *next; }; node *top; void push(int x) { - node *n = new node; - n->val = x; - n->next = top; - top = n; + node *n = new node; + n->val = x; + n->next = top; + top = n; } void pop() { - if (top == NULL) - { - cout << "\nUnderflow"; - } - else - { - node *t = top; - cout << "\n" - << t->val << " deleted"; - top = top->next; - delete t; - } + if (top == NULL) + { + cout << "\nUnderflow"; + } + else + { + node *t = top; + cout << "\n" << t->val << " deleted"; + top = top->next; + delete t; + } } void show() { - node *t = top; - while (t != NULL) - { - cout << t->val << "\n"; - t = t->next; - } + node *t = top; + while (t != NULL) + { + cout << t->val << "\n"; + t = t->next; + } } int main() { - int ch, x; - do - { - cout << "\n1. Push"; - cout << "\n2. Pop"; - cout << "\n3. Print"; - cout << "\nEnter Your Choice : "; - cin >> ch; - if (ch == 1) - { - cout << "\nInsert : "; - cin >> x; - push(x); - } - else if (ch == 2) - { - pop(); - } - else if (ch == 3) - { - show(); - } - } while (ch != 0); + int ch, x; + do + { + cout << "\n1. Push"; + cout << "\n2. Pop"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) + { + cout << "\nInsert : "; + cin >> x; + push(x); + } + else if (ch == 2) + { + pop(); + } + else if (ch == 3) + { + show(); + } + } while (ch != 0); - return 0; + return 0; } diff --git a/data_structure/stk/main.cpp b/data_structure/stk/main.cpp index 2d6bbec56..ceac2ac8a 100644 --- a/data_structure/stk/main.cpp +++ b/data_structure/stk/main.cpp @@ -8,18 +8,19 @@ * ./main student.txt ************************************************************ * */ -#include -#include -#include -#include #include +#include +#include +#include +#include -#include "stack.h" #include "stack.cpp" +#include "stack.h" using namespace std; -int main(int argc, char * argv[]) { +int main(int argc, char* argv[]) +{ double GPA; double highestGPA; string name; @@ -34,19 +35,24 @@ int main(int argc, char * argv[]) { infile >> GPA >> name; highestGPA = GPA; - while (infile) { - if (GPA > highestGPA) { + while (infile) + { + if (GPA > highestGPA) + { stk.clear(); stk.push(name); highestGPA = GPA; - } else if (GPA == highestGPA) { + } + else if (GPA == highestGPA) + { stk.push(name); } infile >> GPA >> name; } - cout << "Highest GPA: " << highestGPA < -#include #include "stack.h" +#include +#include using namespace std; @@ -24,11 +24,12 @@ void stack::display() { node *current = stackTop; cout << "Top --> "; - while(current != NULL) { - cout<data<< " "; - current = current -> next; + while (current != NULL) + { + cout << current->data << " "; + current = current->next; } - cout < void stack::pop() { node *temp; - if(!isEmptyStack()) { + if (!isEmptyStack()) + { temp = stackTop; stackTop = stackTop->next; delete temp; size--; - } else { + } + else + { cout << "Stack is empty !" << endl; } } /* Operator "=" */ template -stack stack::operator=(stack & otherStack) +stack stack::operator=(stack &otherStack) { node *newNode, *current, *last; @@ -91,13 +95,14 @@ stack stack::operator=(stack & otherStack) stackTop = NULL; if (otherStack.stackTop == NULL) stackTop = NULL; - else { + else + { current = otherStack.stackTop; stackTop = new node; stackTop->data = current->data; stackTop->next = NULL; last = stackTop; - current = current ->next; + current = current->next; /* Copy the remaining stack */ while (current != NULL) { diff --git a/data_structure/stk/stack.h b/data_structure/stk/stack.h index a93669482..39b455ac0 100644 --- a/data_structure/stk/stack.h +++ b/data_structure/stk/stack.h @@ -14,22 +14,21 @@ struct node template class stack { - public: - void display(); /* Show stack */ - stack(); /* Default constructor*/ - ~stack(); /* Destructor */ - bool isEmptyStack(); /* Determine whether the stack is empty */ - void push (Type item); /* Add new item to the stack */ - Type top(); /* Return the top element of the stack */ - void pop(); /* Remove the top element of the stack */ - void clear(); + public: + void display(); /* Show stack */ + stack(); /* Default constructor*/ + ~stack(); /* Destructor */ + bool isEmptyStack(); /* Determine whether the stack is empty */ + void push(Type item); /* Add new item to the stack */ + Type top(); /* Return the top element of the stack */ + void pop(); /* Remove the top element of the stack */ + void clear(); - stack operator=(stack & otherStack); - // Overload "=" the assignment operator. - private: - node *stackTop; /* Pointer to the stack */ - int size; + stack operator=(stack &otherStack); + // Overload "=" the assignment operator. + private: + node *stackTop; /* Pointer to the stack */ + int size; }; #endif - diff --git a/data_structure/stk/test_stack.cpp b/data_structure/stk/test_stack.cpp index 4703fc906..8839fdfa3 100644 --- a/data_structure/stk/test_stack.cpp +++ b/data_structure/stk/test_stack.cpp @@ -1,21 +1,23 @@ #include -#include "stack.h" #include "stack.cpp" +#include "stack.h" using namespace std; int main() { stack stk; - cout << "---------------------- Test construct ----------------------" << endl; + cout << "---------------------- Test construct ----------------------" + << endl; stk.display(); - cout << "---------------------- Test isEmptyStack ----------------------" << endl; - if(stk.isEmptyStack()) - cout << "PASS" < stk1; - cout << "stk current: "<< endl; + cout << "stk current: " << endl; stk.display(); - cout << endl << "Assign stk1 = stk "<< endl; + cout << endl << "Assign stk1 = stk " << endl; stk1 = stk; stk1.display(); - cout << endl<< "After pushing 8 9 10 into stk1:" <val << " : "; - cin >> ch; - if (ch == 'l') - CreateTree(n, n->left, x, ch); - else if (ch == 'r') - CreateTree(n, n->right, x, ch); + cout << "\nLeft or Right of " << n->val << " : "; + cin >> ch; + if (ch == 'l') + CreateTree(n, n->left, x, ch); + else if (ch == 'r') + CreateTree(n, n->right, x, ch); } else { @@ -40,19 +40,19 @@ void CreateTree(node *curr, node *n, int x, char pos) void BFT(node *n) { - list queue; + list queue; queue.push_back(n); - while(!queue.empty()) + while (!queue.empty()) { n = queue.front(); cout << n->val << " "; queue.pop_front(); - if(n->left != NULL) + if (n->left != NULL) queue.push_back(n->left); - if(n->right != NULL) + if (n->right != NULL) queue.push_back(n->right); } } diff --git a/data_structure/trie_tree.cpp b/data_structure/trie_tree.cpp index 2b84099e8..d34dd2dbc 100644 --- a/data_structure/trie_tree.cpp +++ b/data_structure/trie_tree.cpp @@ -1,86 +1,99 @@ -#include #include +#include #include #include // structure definition -typedef struct trie { - struct trie * arr[26]; +typedef struct trie +{ + struct trie* arr[26]; bool isEndofWord; } trie; // create a new node for trie -trie * createNode() { - trie * nn = new trie(); - for (int i = 0; i < 26; i++) - nn -> arr[i] = NULL; - nn -> isEndofWord = false; +trie* createNode() +{ + trie* nn = new trie(); + for (int i = 0; i < 26; i++) nn->arr[i] = NULL; + nn->isEndofWord = false; return nn; } // insert string into the trie -void insert(trie * root, std::string str) { - for (int i = 0; i < str.length(); i++) { +void insert(trie* root, std::string str) +{ + for (int i = 0; i < str.length(); i++) + { int j = str[i] - 'a'; - if (root -> arr[j]) { - root = root -> arr[j]; - } else { - root -> arr[j] = createNode(); - root = root -> arr[j]; + if (root->arr[j]) + { + root = root->arr[j]; + } + else + { + root->arr[j] = createNode(); + root = root->arr[j]; } } - root -> isEndofWord = true; + root->isEndofWord = true; } // search a string exists inside the trie -bool search(trie * root, std::string str, int index) { - if (index == str.length()) { - if (!root -> isEndofWord) +bool search(trie* root, std::string str, int index) +{ + if (index == str.length()) + { + if (!root->isEndofWord) return false; return true; } int j = str[index] - 'a'; - if (!root -> arr[j]) + if (!root->arr[j]) return false; - return search(root -> arr[j], str, index + 1); + return search(root->arr[j], str, index + 1); } /* -removes the string if it is not a prefix of any other -string, if it is then just sets the endofword to false, else +removes the string if it is not a prefix of any other +string, if it is then just sets the endofword to false, else removes the given string */ -bool deleteString(trie * root, std::string str, int index) { - if (index == str.length()) { - if (!root -> isEndofWord) - return false; - root -> isEndofWord = false; - for (int i = 0; i < 26; i++) +bool deleteString(trie* root, std::string str, int index) +{ + if (index == str.length()) + { + if (!root->isEndofWord) return false; + root->isEndofWord = false; + for (int i = 0; i < 26; i++) return false; return true; } int j = str[index] - 'a'; - if (!root -> arr[j]) + if (!root->arr[j]) return false; - bool - var = deleteString(root, str, index + 1); - if (var) { - root -> arr[j] = NULL; - if (root -> isEndofWord) { + bool var = deleteString(root, str, index + 1); + if (var) + { + root->arr[j] = NULL; + if (root->isEndofWord) + { return false; - } else { + } + else + { int i; for (i = 0; i < 26; i++) - if (root -> arr[i]) + if (root->arr[i]) return false; return true; } } } -int main() { - trie * root = createNode(); +int main() +{ + trie* root = createNode(); insert(root, "hello"); insert(root, "world"); int a = search(root, "hello", 0); diff --git a/dynamic_programming/0_1_knapsack.cpp b/dynamic_programming/0_1_knapsack.cpp index 9348372b2..0ce40ca0a 100644 --- a/dynamic_programming/0_1_knapsack.cpp +++ b/dynamic_programming/0_1_knapsack.cpp @@ -1,9 +1,9 @@ -//0-1 Knapsack problem - Dynamic programming +// 0-1 Knapsack problem - Dynamic programming //#include #include using namespace std; -//void Print(int res[20][20], int i, int j, int capacity) +// void Print(int res[20][20], int i, int j, int capacity) //{ // if(i==0 || j==0) // { @@ -30,42 +30,43 @@ using namespace std; int Knapsack(int capacity, int n, int weight[], int value[]) { - int res[20][20]; - for (int i = 0; i < n + 1; ++i) - { - for (int j = 0; j < capacity + 1; ++j) - { - if (i == 0 || j == 0) - res[i][j] = 0; - else if (weight[i - 1] <= j) - res[i][j] = max(value[i - 1] + res[i - 1][j - weight[i - 1]], res[i - 1][j]); - else - res[i][j] = res[i - 1][j]; - } - } - // Print(res, n, capacity, capacity); - // cout<<"\n"; - return res[n][capacity]; + int res[20][20]; + for (int i = 0; i < n + 1; ++i) + { + for (int j = 0; j < capacity + 1; ++j) + { + if (i == 0 || j == 0) + res[i][j] = 0; + else if (weight[i - 1] <= j) + res[i][j] = max(value[i - 1] + res[i - 1][j - weight[i - 1]], + res[i - 1][j]); + else + res[i][j] = res[i - 1][j]; + } + } + // Print(res, n, capacity, capacity); + // cout<<"\n"; + return res[n][capacity]; } int main() { - int n; - cout << "Enter number of items: "; - cin >> n; - int weight[n], value[n]; - cout << "Enter weights: "; - for (int i = 0; i < n; ++i) - { - cin >> weight[i]; - } - cout << "Enter values: "; - for (int i = 0; i < n; ++i) - { - cin >> value[i]; - } - int capacity; - cout << "Enter capacity: "; - cin >> capacity; - cout << Knapsack(capacity, n, weight, value); - return 0; + int n; + cout << "Enter number of items: "; + cin >> n; + int weight[n], value[n]; + cout << "Enter weights: "; + for (int i = 0; i < n; ++i) + { + cin >> weight[i]; + } + cout << "Enter values: "; + for (int i = 0; i < n; ++i) + { + cin >> value[i]; + } + int capacity; + cout << "Enter capacity: "; + cin >> capacity; + cout << Knapsack(capacity, n, weight, value); + return 0; } diff --git a/dynamic_programming/armstrong_number.cpp b/dynamic_programming/armstrong_number.cpp index 4dba89a27..218d6365d 100644 --- a/dynamic_programming/armstrong_number.cpp +++ b/dynamic_programming/armstrong_number.cpp @@ -1,21 +1,23 @@ // Program to check whether a number is an armstrong number or not #include -using std::cout; using std::cin; +using std::cout; -int main() { - int n, k, d, s = 0; - cout << "Enter a number:"; - cin >> n; - k = n; - while (k != 0) { - d = k % 10; - s += d * d * d; - k /= 10; - } - if (s == n) - cout << n << "is an armstrong number"; - else - cout << n << "is not an armstrong number"; +int main() +{ + int n, k, d, s = 0; + cout << "Enter a number:"; + cin >> n; + k = n; + while (k != 0) + { + d = k % 10; + s += d * d * d; + k /= 10; + } + if (s == n) + cout << n << "is an armstrong number"; + else + cout << n << "is not an armstrong number"; } diff --git a/dynamic_programming/bellman_ford.cpp b/dynamic_programming/bellman_ford.cpp index 7c36d96df..85d3bff06 100644 --- a/dynamic_programming/bellman_ford.cpp +++ b/dynamic_programming/bellman_ford.cpp @@ -1,128 +1,129 @@ -#include #include +#include using namespace std; -//Wrapper class for storing an edge +// Wrapper class for storing an edge class Edge { -public: - int src, dst, weight; + public: + int src, dst, weight; }; -//Wrapper class for storing a graph +// Wrapper class for storing a graph class Graph { -public: - int vertexNum, edgeNum; - Edge *edges; + public: + int vertexNum, edgeNum; + Edge *edges; - //Constructs a graph with V vertices and E edges - Graph(int V, int E) - { - this->vertexNum = V; - this->edgeNum = E; - this->edges = (Edge *)malloc(E * sizeof(Edge)); - } + // Constructs a graph with V vertices and E edges + Graph(int V, int E) + { + this->vertexNum = V; + this->edgeNum = E; + this->edges = (Edge *)malloc(E * sizeof(Edge)); + } - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { - static int edgeInd = 0; - if (edgeInd < this->edgeNum) - { - Edge newEdge; - newEdge.src = src; - newEdge.dst = dst; - newEdge.weight = weight; - this->edges[edgeInd++] = newEdge; - } - } + // Adds the given edge to the graph + void addEdge(int src, int dst, int weight) + { + static int edgeInd = 0; + if (edgeInd < this->edgeNum) + { + Edge newEdge; + newEdge.src = src; + newEdge.dst = dst; + newEdge.weight = weight; + this->edges[edgeInd++] = newEdge; + } + } }; -//Utility function to print distances +// Utility function to print distances void print(int dist[], int V) { - cout << "\nVertex Distance" << endl; - for (int i = 0; i < V; i++) - { - if (dist[i] != INT_MAX) - cout << i << "\t" << dist[i] << endl; - else - cout << i << "\tINF" << endl; - } + cout << "\nVertex Distance" << endl; + for (int i = 0; i < V; i++) + { + if (dist[i] != INT_MAX) + cout << i << "\t" << dist[i] << endl; + else + cout << i << "\tINF" << endl; + } } -//The main function that finds the shortest path from given source -//to all other vertices using Bellman-Ford.It also detects negative -//weight cycle +// The main function that finds the shortest path from given source +// to all other vertices using Bellman-Ford.It also detects negative +// weight cycle void BellmanFord(Graph graph, int src) { - int V = graph.vertexNum; - int E = graph.edgeNum; - int dist[V]; + int V = graph.vertexNum; + int E = graph.edgeNum; + int dist[V]; - //Initialize distances array as INF for all except source - //Intialize source as zero - for (int i = 0; i < V; i++) - dist[i] = INT_MAX; - dist[src] = 0; + // Initialize distances array as INF for all except source + // Intialize source as zero + for (int i = 0; i < V; i++) dist[i] = INT_MAX; + dist[src] = 0; - //Calculate shortest path distance from source to all edges - //A path can contain maximum (|V|-1) edges - for (int i = 0; i <= V - 1; i++) - for (int j = 0; j < E; j++) - { - int u = graph.edges[j].src; - int v = graph.edges[j].dst; - int w = graph.edges[j].weight; + // Calculate shortest path distance from source to all edges + // A path can contain maximum (|V|-1) edges + for (int i = 0; i <= V - 1; i++) + for (int j = 0; j < E; j++) + { + int u = graph.edges[j].src; + int v = graph.edges[j].dst; + int w = graph.edges[j].weight; - if (dist[u] != INT_MAX && dist[u] + w < dist[v]) - dist[v] = dist[u] + w; - } + if (dist[u] != INT_MAX && dist[u] + w < dist[v]) + dist[v] = dist[u] + w; + } - //Iterate inner loop once more to check for negative cycle - for (int j = 0; j < E; j++) - { - int u = graph.edges[j].src; - int v = graph.edges[j].dst; - int w = graph.edges[j].weight; + // Iterate inner loop once more to check for negative cycle + for (int j = 0; j < E; j++) + { + int u = graph.edges[j].src; + int v = graph.edges[j].dst; + int w = graph.edges[j].weight; - if (dist[u] != INT_MAX && dist[u] + w < dist[v]) - { - cout << "Graph contains negative weight cycle. Hence, shortest distance not guaranteed." << endl; - return; - } - } + if (dist[u] != INT_MAX && dist[u] + w < dist[v]) + { + cout << "Graph contains negative weight cycle. Hence, shortest " + "distance not guaranteed." + << endl; + return; + } + } - print(dist, V); + print(dist, V); - return; + return; } -//Driver Function +// Driver Function int main() { - int V, E, gsrc; - int src, dst, weight; - cout << "Enter number of vertices: "; - cin >> V; - cout << "Enter number of edges: "; - cin >> E; - Graph G(V, E); - for (int i = 0; i < E; i++) - { - cout << "\nEdge " << i + 1 << "\nEnter source: "; - cin >> src; - cout << "Enter destination: "; - cin >> dst; - cout << "Enter weight: "; - cin >> weight; - G.addEdge(src, dst, weight); - } - cout << "\nEnter source: "; - cin >> gsrc; - BellmanFord(G, gsrc); + int V, E, gsrc; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; + Graph G(V, E); + for (int i = 0; i < E; i++) + { + cout << "\nEdge " << i + 1 << "\nEnter source: "; + cin >> src; + cout << "Enter destination: "; + cin >> dst; + cout << "Enter weight: "; + cin >> weight; + G.addEdge(src, dst, weight); + } + cout << "\nEnter source: "; + cin >> gsrc; + BellmanFord(G, gsrc); - return 0; + return 0; } diff --git a/dynamic_programming/catalan_numbers.cpp b/dynamic_programming/catalan_numbers.cpp index 4d73cd51a..0107b9f20 100644 --- a/dynamic_programming/catalan_numbers.cpp +++ b/dynamic_programming/catalan_numbers.cpp @@ -9,7 +9,7 @@ #include using namespace std; -int *cat; // global array to hold catalan numbers +int *cat; // global array to hold catalan numbers unsigned long int catalan_dp(int n) { @@ -33,7 +33,7 @@ unsigned long int catalan_dp(int n) { cat[i] = 0; for (int j = 0; j < i; j++) - cat[i] += cat[j] * cat[i - j - 1]; // applying the definition here + cat[i] += cat[j] * cat[i - j - 1]; // applying the definition here } // Return the result diff --git a/dynamic_programming/coin_change.cpp b/dynamic_programming/coin_change.cpp index c8acad48e..f43d4fa18 100644 --- a/dynamic_programming/coin_change.cpp +++ b/dynamic_programming/coin_change.cpp @@ -1,50 +1,52 @@ -#include #include +#include using namespace std; // Function to find the Minimum number of coins required to get Sum S int findMinCoins(int arr[], int n, int N) { - // dp[i] = no of coins required to get a total of i - int dp[N + 1]; + // dp[i] = no of coins required to get a total of i + int dp[N + 1]; - // 0 coins are needed for 0 sum + // 0 coins are needed for 0 sum - dp[0] = 0; + dp[0] = 0; - for (int i = 1; i <= N; i++) - { - // initialize minimum number of coins needed to infinity - dp[i] = INT_MAX; - int res = INT_MAX; + for (int i = 1; i <= N; i++) + { + // initialize minimum number of coins needed to infinity + dp[i] = INT_MAX; + int res = INT_MAX; - // do for each coin - for (int c = 0; c < n; c++) - { - if (i - arr[c] >= 0) // check if coins doesn't become negative by including it - res = dp[i - arr[c]]; + // do for each coin + for (int c = 0; c < n; c++) + { + if (i - arr[c] >= + 0) // check if coins doesn't become negative by including it + res = dp[i - arr[c]]; - // if total can be reached by including current coin c, - // update minimum number of coins needed dp[i] - if (res != INT_MAX) - dp[i] = min(dp[i], res + 1); - } - } + // if total can be reached by including current coin c, + // update minimum number of coins needed dp[i] + if (res != INT_MAX) + dp[i] = min(dp[i], res + 1); + } + } - // The Minimum No of Coins Required for N = dp[N] - return dp[N]; + // The Minimum No of Coins Required for N = dp[N] + return dp[N]; } int main() { - // No of Coins We Have - int arr[] = {1, 2, 3, 4}; - int n = sizeof(arr) / sizeof(arr[0]); + // No of Coins We Have + int arr[] = {1, 2, 3, 4}; + int n = sizeof(arr) / sizeof(arr[0]); - // Total Change Required - int N = 15; + // Total Change Required + int N = 15; - cout << "Minimum Number of Coins Required " << findMinCoins(arr, n, N) << "\n"; + cout << "Minimum Number of Coins Required " << findMinCoins(arr, n, N) + << "\n"; - return 0; + return 0; } \ No newline at end of file diff --git a/dynamic_programming/cut_rod.cpp b/dynamic_programming/cut_rod.cpp index afca3dced..3df0a9fbe 100644 --- a/dynamic_programming/cut_rod.cpp +++ b/dynamic_programming/cut_rod.cpp @@ -1,6 +1,6 @@ -/*Given a rod of length n inches and an array of prices that -contains prices of all pieces of size smaller than n. Determine -the maximum value obtainable by cutting up the rod and selling +/*Given a rod of length n inches and an array of prices that +contains prices of all pieces of size smaller than n. Determine +the maximum value obtainable by cutting up the rod and selling the pieces.*/ #include @@ -22,7 +22,8 @@ int cutrod(int p[], int n) } int main() { - int price[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}; + int price[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 31, 32, 33, 34, 35, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}; cout << cutrod(price, 30); return 0; } diff --git a/dynamic_programming/edit_distance.cpp b/dynamic_programming/edit_distance.cpp index 996d3272c..da613b238 100644 --- a/dynamic_programming/edit_distance.cpp +++ b/dynamic_programming/edit_distance.cpp @@ -7,7 +7,7 @@ * a. Insert * b. Remove * c. Replace - * All of the above operations are + * All of the above operations are * of equal cost */ @@ -15,10 +15,7 @@ #include using namespace std; -int min(int x, int y, int z) -{ - return min(min(x, y), z); -} +int min(int x, int y, int z) { return min(min(x, y), z); } /* A Naive recursive C++ program to find * minimum number of operations to convert @@ -32,14 +29,14 @@ int editDist(string str1, string str2, int m, int n) if (n == 0) return m; - //If last characters are same then continue - //for the rest of them. + // If last characters are same then continue + // for the rest of them. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); - //If last not same, then 3 possibilities - //a.Insert b.Remove c. Replace - //Get min of three and continue for rest. + // If last not same, then 3 possibilities + // a.Insert b.Remove c. Replace + // Get min of three and continue for rest. return 1 + min(editDist(str1, str2, m, n - 1), editDist(str1, str2, m - 1, n), editDist(str1, str2, m - 1, n - 1)); @@ -50,31 +47,30 @@ int editDist(string str1, string str2, int m, int n) */ int editDistDP(string str1, string str2, int m, int n) { - - //Create Table for SubProblems + // Create Table for SubProblems int dp[m + 1][n + 1]; - //Fill d[][] in bottom up manner + // Fill d[][] in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { - //If str1 empty. Then add all of str2 + // If str1 empty. Then add all of str2 if (i == 0) dp[i][j] = j; - //If str2 empty. Then add all of str1 + // If str2 empty. Then add all of str1 else if (j == 0) dp[i][j] = i; - //If character same. Recur for remaining + // If character same. Recur for remaining else if (str1[i - 1] == str2[j - 1]) dp[i][j] = dp[i - 1][j - 1]; else - dp[i][j] = 1 + min(dp[i][j - 1], //Insert - dp[i - 1][j], //Remove - dp[i - 1][j - 1] //Replace + dp[i][j] = 1 + min(dp[i][j - 1], // Insert + dp[i - 1][j], // Remove + dp[i - 1][j - 1] // Replace ); } } diff --git a/dynamic_programming/egg_dropping_puzzle.cpp b/dynamic_programming/egg_dropping_puzzle.cpp index a441f29cb..79de4cc22 100644 --- a/dynamic_programming/egg_dropping_puzzle.cpp +++ b/dynamic_programming/egg_dropping_puzzle.cpp @@ -1,9 +1,9 @@ -/* Function to get minimun number of trials needed - * in worst case with n eggs and k floors +/* Function to get minimun number of trials needed + * in worst case with n eggs and k floors */ -#include #include +#include using namespace std; int eggDrop(int n, int k) @@ -13,8 +13,8 @@ int eggDrop(int n, int k) for (int i = 1; i <= n; i++) { - eggFloor[i][1] = 1; //n eggs..1 Floor - eggFloor[i][0] = 0; //n eggs..0 Floor + eggFloor[i][1] = 1; // n eggs..1 Floor + eggFloor[i][0] = 0; // n eggs..0 Floor } // Only one egg available diff --git a/dynamic_programming/fibonacci_bottom_up.cpp b/dynamic_programming/fibonacci_bottom_up.cpp index ab5b5b41f..3a9669fa9 100644 --- a/dynamic_programming/fibonacci_bottom_up.cpp +++ b/dynamic_programming/fibonacci_bottom_up.cpp @@ -2,23 +2,23 @@ using namespace std; int fib(int n) { - int res[3]; - res[0] = 0; - res[1] = 1; - for (int i = 2; i <= n; i++) - { - res[2] = res[1] + res[0]; - res[0] = res[1]; - res[1] = res[2]; - } - return res[1]; + int res[3]; + res[0] = 0; + res[1] = 1; + for (int i = 2; i <= n; i++) + { + res[2] = res[1] + res[0]; + res[0] = res[1]; + res[1] = res[2]; + } + return res[1]; } int main(int argc, char const *argv[]) { - int n; - cout << "Enter n: "; - cin >> n; - cout << "Fibonacci number is "; - cout << fib(n) << endl; - return 0; + int n; + cout << "Enter n: "; + cin >> n; + cout << "Fibonacci number is "; + cout << fib(n) << endl; + return 0; } diff --git a/dynamic_programming/fibonacci_top_down.cpp b/dynamic_programming/fibonacci_top_down.cpp index 9d76366f7..3ac3fdb40 100644 --- a/dynamic_programming/fibonacci_top_down.cpp +++ b/dynamic_programming/fibonacci_top_down.cpp @@ -3,24 +3,24 @@ using namespace std; int arr[1000000]; int fib(int n) { - if (arr[n] == -1) - { - if (n <= 1) - arr[n] = n; - else - arr[n] = fib(n - 1) + fib(n - 2); - } - return arr[n]; + if (arr[n] == -1) + { + if (n <= 1) + arr[n] = n; + else + arr[n] = fib(n - 1) + fib(n - 2); + } + return arr[n]; } int main(int argc, char const *argv[]) { - int n; - cout << "Enter n: "; - cin >> n; - for (int i = 0; i < n + 1; ++i) - { - arr[i] = -1; - } - cout << "Fibonacci number is " << fib(n) << endl; - return 0; + int n; + cout << "Enter n: "; + cin >> n; + for (int i = 0; i < n + 1; ++i) + { + arr[i] = -1; + } + cout << "Fibonacci number is " << fib(n) << endl; + return 0; } \ No newline at end of file diff --git a/dynamic_programming/floyd_warshall.cpp b/dynamic_programming/floyd_warshall.cpp index 93ccff62f..e3b0c66d3 100644 --- a/dynamic_programming/floyd_warshall.cpp +++ b/dynamic_programming/floyd_warshall.cpp @@ -1,112 +1,110 @@ -#include #include #include +#include using namespace std; -//Wrapper class for storing a graph +// Wrapper class for storing a graph class Graph { -public: - int vertexNum; - int **edges; + public: + int vertexNum; + int **edges; - //Constructs a graph with V vertices and E edges - Graph(int V) - { - this->vertexNum = V; - this->edges = (int **)malloc(V * sizeof(int *)); - for (int i = 0; i < V; i++) - { - this->edges[i] = (int *)malloc(V * sizeof(int)); - for (int j = 0; j < V; j++) - this->edges[i][j] = INT_MAX; - this->edges[i][i] = 0; - } - } + // Constructs a graph with V vertices and E edges + Graph(int V) + { + this->vertexNum = V; + this->edges = (int **)malloc(V * sizeof(int *)); + for (int i = 0; i < V; i++) + { + this->edges[i] = (int *)malloc(V * sizeof(int)); + for (int j = 0; j < V; j++) this->edges[i][j] = INT_MAX; + this->edges[i][i] = 0; + } + } - //Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { - this->edges[src][dst] = weight; - } + // Adds the given edge to the graph + void addEdge(int src, int dst, int weight) + { + this->edges[src][dst] = weight; + } }; -//Utility function to print distances +// Utility function to print distances void print(int dist[], int V) { - cout << "\nThe Distance matrix for Floyd - Warshall" << endl; - for (int i = 0; i < V; i++) - { - for (int j = 0; j < V; j++) - { - - if (dist[i * V + j] != INT_MAX) - cout << dist[i * V + j] << "\t"; - else - cout << "INF" - << "\t"; - } - cout << endl; - } + cout << "\nThe Distance matrix for Floyd - Warshall" << endl; + for (int i = 0; i < V; i++) + { + for (int j = 0; j < V; j++) + { + if (dist[i * V + j] != INT_MAX) + cout << dist[i * V + j] << "\t"; + else + cout << "INF" + << "\t"; + } + cout << endl; + } } -//The main function that finds the shortest path from a vertex -//to all other vertices using Floyd-Warshall Algorithm. +// The main function that finds the shortest path from a vertex +// to all other vertices using Floyd-Warshall Algorithm. void FloydWarshall(Graph graph) { - int V = graph.vertexNum; - int dist[V][V]; + int V = graph.vertexNum; + int dist[V][V]; - //Initialise distance array - for (int i = 0; i < V; i++) - for (int j = 0; j < V; j++) - dist[i][j] = graph.edges[i][j]; + // Initialise distance array + for (int i = 0; i < V; i++) + for (int j = 0; j < V; j++) dist[i][j] = graph.edges[i][j]; - //Calculate distances - for (int k = 0; k < V; k++) - //Choose an intermediate vertex + // Calculate distances + for (int k = 0; k < V; k++) + // Choose an intermediate vertex - for (int i = 0; i < V; i++) - //Choose a source vertex for given intermediate + for (int i = 0; i < V; i++) + // Choose a source vertex for given intermediate - for (int j = 0; j < V; j++) - //Choose a destination vertex for above source vertex + for (int j = 0; j < V; j++) + // Choose a destination vertex for above source vertex - if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && dist[i][k] + dist[k][j] < dist[i][j]) - //If the distance through intermediate vertex is less than direct edge then update value in distance array - dist[i][j] = dist[i][k] + dist[k][j]; + if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && + dist[i][k] + dist[k][j] < dist[i][j]) + // If the distance through intermediate vertex is less than + // direct edge then update value in distance array + dist[i][j] = dist[i][k] + dist[k][j]; - //Convert 2d array to 1d array for print - int dist1d[V * V]; - for (int i = 0; i < V; i++) - for (int j = 0; j < V; j++) - dist1d[i * V + j] = dist[i][j]; + // Convert 2d array to 1d array for print + int dist1d[V * V]; + for (int i = 0; i < V; i++) + for (int j = 0; j < V; j++) dist1d[i * V + j] = dist[i][j]; - print(dist1d, V); + print(dist1d, V); } -//Driver Function +// Driver Function int main() { - int V, E; - int src, dst, weight; - cout << "Enter number of vertices: "; - cin >> V; - cout << "Enter number of edges: "; - cin >> E; - Graph G(V); - for (int i = 0; i < E; i++) - { - cout << "\nEdge " << i + 1 << "\nEnter source: "; - cin >> src; - cout << "Enter destination: "; - cin >> dst; - cout << "Enter weight: "; - cin >> weight; - G.addEdge(src, dst, weight); - } - FloydWarshall(G); + int V, E; + int src, dst, weight; + cout << "Enter number of vertices: "; + cin >> V; + cout << "Enter number of edges: "; + cin >> E; + Graph G(V); + for (int i = 0; i < E; i++) + { + cout << "\nEdge " << i + 1 << "\nEnter source: "; + cin >> src; + cout << "Enter destination: "; + cin >> dst; + cout << "Enter weight: "; + cin >> weight; + G.addEdge(src, dst, weight); + } + FloydWarshall(G); - return 0; + return 0; } diff --git a/dynamic_programming/kadane.cpp b/dynamic_programming/kadane.cpp index bf2aa76ac..31d17ae9e 100644 --- a/dynamic_programming/kadane.cpp +++ b/dynamic_programming/kadane.cpp @@ -1,10 +1,12 @@ -#include -#include +#include +#include -int maxSubArraySum(int a[], int size) { +int maxSubArraySum(int a[], int size) +{ int max_so_far = INT_MIN, max_ending_here = 0; - for (int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) + { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; @@ -15,13 +17,14 @@ int maxSubArraySum(int a[], int size) { return max_so_far; } - -int main() { +int main() +{ int n, i; std::cout << "Enter the number of elements \n"; std::cin >> n; int a[n]; // NOLINT - for (i = 0; i < n; i++) { + for (i = 0; i < n; i++) + { std::cin >> a[i]; } int max_sum = maxSubArraySum(a, n); diff --git a/dynamic_programming/longest_common_string.cpp b/dynamic_programming/longest_common_string.cpp index c1e89d6db..e33489cb1 100644 --- a/dynamic_programming/longest_common_string.cpp +++ b/dynamic_programming/longest_common_string.cpp @@ -1,65 +1,59 @@ #include using namespace std; -int max(int a,int b) -{ - return (a > b) ? a : b; -} +int max(int a, int b) { return (a > b) ? a : b; } int main() { - char str1[]="DEFBCD"; - char str2[]="ABDEFJ"; - int i,j,k; - int n=strlen(str1)+1; - int m=strlen(str2)+1; - //cout<ma) + for(j=0;j ma) { - ma=a[i][j]; - indi=i; - indj=j; + ma = a[i][j]; + indi = i; + indj = j; } } } - cout< using namespace std; @@ -52,19 +52,22 @@ int lcs(string a, string b) else if (a[i - 1] == b[j - 1]) { res[i][j] = 1 + res[i - 1][j - 1]; - trace[i][j] = 1; // 1 means trace the matrix in upper left diagonal direction. + trace[i][j] = 1; // 1 means trace the matrix in upper left + // diagonal direction. } else { if (res[i - 1][j] > res[i][j - 1]) { res[i][j] = res[i - 1][j]; - trace[i][j] = 2; // 2 means trace the matrix in upwards direction. + trace[i][j] = + 2; // 2 means trace the matrix in upwards direction. } else { res[i][j] = res[i][j - 1]; - trace[i][j] = 3; // means trace the matrix in left direction. + trace[i][j] = + 3; // means trace the matrix in left direction. } } } diff --git a/dynamic_programming/longest_increasing_subsequence.cpp b/dynamic_programming/longest_increasing_subsequence.cpp index 49c54a941..573db34a5 100644 --- a/dynamic_programming/longest_increasing_subsequence.cpp +++ b/dynamic_programming/longest_increasing_subsequence.cpp @@ -1,39 +1,39 @@ -//Program to calculate length of longest increasing subsequence in an array +// Program to calculate length of longest increasing subsequence in an array #include using namespace std; int LIS(int a[], int n) { - int lis[n]; - for (int i = 0; i < n; ++i) - { - lis[i] = 1; - } - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < i; ++j) - { - if (a[i] > a[j] && lis[i] < lis[j] + 1) - lis[i] = lis[j] + 1; - } - } - int res = 0; - for (int i = 0; i < n; ++i) - { - res = max(res, lis[i]); - } - return res; + int lis[n]; + for (int i = 0; i < n; ++i) + { + lis[i] = 1; + } + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < i; ++j) + { + if (a[i] > a[j] && lis[i] < lis[j] + 1) + lis[i] = lis[j] + 1; + } + } + int res = 0; + for (int i = 0; i < n; ++i) + { + res = max(res, lis[i]); + } + return res; } int main(int argc, char const *argv[]) { - int n; - cout << "Enter size of array: "; - cin >> n; - int a[n]; - cout << "Enter array elements: "; - for (int i = 0; i < n; ++i) - { - cin >> a[i]; - } - cout << LIS(a, n) << endl; - return 0; + int n; + cout << "Enter size of array: "; + cin >> n; + int a[n]; + cout << "Enter array elements: "; + for (int i = 0; i < n; ++i) + { + cin >> a[i]; + } + cout << LIS(a, n) << endl; + return 0; } \ No newline at end of file diff --git a/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp b/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp index 5ee24e6a7..2471b701f 100644 --- a/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp +++ b/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp @@ -1,4 +1,4 @@ -//Program to calculate length of longest increasing subsequence in an array +// Program to calculate length of longest increasing subsequence in an array // in O(n log n) // tested on : https://cses.fi/problemset/task/1145/ @@ -7,30 +7,32 @@ using namespace std; int LIS(int arr[], int n) { - set < int > active; // The current built LIS. + set active; // The current built LIS. active.insert(arr[0]); // Loop through every element. for (int i = 1; i < n; ++i) { auto get = active.lower_bound(arr[i]); if (get == active.end()) - { + { active.insert(arr[i]); - } // current element is the greatest so LIS increases by 1. + } // current element is the greatest so LIS increases by 1. else - { - int val = * get; // we find the position where arr[i] will be in the LIS. If it is in the LIS already we do nothing + { + int val = *get; // we find the position where arr[i] will be in the + // LIS. If it is in the LIS already we do nothing if (val > arr[i]) - { - // else we remove the bigger element and add a smaller element (which is arr[i]) and continue; + { + // else we remove the bigger element and add a smaller element + // (which is arr[i]) and continue; active.erase(get); active.insert(arr[i]); } } } - return active.size(); // size of the LIS. + return active.size(); // size of the LIS. } -int main(int argc, char const * argv[]) +int main(int argc, char const* argv[]) { int n; cout << "Enter size of array: "; diff --git a/dynamic_programming/matrix_chain_multiplication.cpp b/dynamic_programming/matrix_chain_multiplication.cpp index 1e885bd7e..378edcc7f 100644 --- a/dynamic_programming/matrix_chain_multiplication.cpp +++ b/dynamic_programming/matrix_chain_multiplication.cpp @@ -1,5 +1,5 @@ -#include #include +#include using namespace std; #define MAX 10 @@ -7,56 +7,59 @@ using namespace std; // dp table to store the solution for already computed sub problems int dp[MAX][MAX]; -// Function to find the most efficient way to multiply the given sequence of matrices +// Function to find the most efficient way to multiply the given sequence of +// matrices int MatrixChainMultiplication(int dim[], int i, int j) { - // base case: one matrix - if (j <= i + 1) - return 0; + // base case: one matrix + if (j <= i + 1) + return 0; - // stores minimum number of scalar multiplications (i.e., cost) - // needed to compute the matrix M[i+1]...M[j] = M[i..j] - int min = INT_MAX; + // stores minimum number of scalar multiplications (i.e., cost) + // needed to compute the matrix M[i+1]...M[j] = M[i..j] + int min = INT_MAX; - // if dp[i][j] is not calculated (calculate it!!) + // if dp[i][j] is not calculated (calculate it!!) - if (dp[i][j] == 0) - { - // take the minimum over each possible position at which the - // sequence of matrices can be split + if (dp[i][j] == 0) + { + // take the minimum over each possible position at which the + // sequence of matrices can be split - for (int k = i + 1; k <= j - 1; k++) - { - // recur for M[i+1]..M[k] to get a i x k matrix - int cost = MatrixChainMultiplication(dim, i, k); + for (int k = i + 1; k <= j - 1; k++) + { + // recur for M[i+1]..M[k] to get a i x k matrix + int cost = MatrixChainMultiplication(dim, i, k); - // recur for M[k+1]..M[j] to get a k x j matrix - cost += MatrixChainMultiplication(dim, k, j); + // recur for M[k+1]..M[j] to get a k x j matrix + cost += MatrixChainMultiplication(dim, k, j); - // cost to multiply two (i x k) and (k x j) matrix - cost += dim[i] * dim[k] * dim[j]; + // cost to multiply two (i x k) and (k x j) matrix + cost += dim[i] * dim[k] * dim[j]; - if (cost < min) - min = cost; // store the minimum cost - } - dp[i][j] = min; - } + if (cost < min) + min = cost; // store the minimum cost + } + dp[i][j] = min; + } - // return min cost to multiply M[j+1]..M[j] - return dp[i][j]; + // return min cost to multiply M[j+1]..M[j] + return dp[i][j]; } // main function int main() { - // Matrix i has Dimensions dim[i-1] & dim[i] for i=1..n - // input is 10 x 30 matrix, 30 x 5 matrix, 5 x 60 matrix - int dim[] = {10, 30, 5, 60}; - int n = sizeof(dim) / sizeof(dim[0]); + // Matrix i has Dimensions dim[i-1] & dim[i] for i=1..n + // input is 10 x 30 matrix, 30 x 5 matrix, 5 x 60 matrix + int dim[] = {10, 30, 5, 60}; + int n = sizeof(dim) / sizeof(dim[0]); - // Function Calling: MatrixChainMultiplications(dimensions_array, starting, ending); + // Function Calling: MatrixChainMultiplications(dimensions_array, starting, + // ending); - cout << "Minimum cost is " << MatrixChainMultiplication(dim, 0, n - 1) << "\n"; + cout << "Minimum cost is " << MatrixChainMultiplication(dim, 0, n - 1) + << "\n"; - return 0; + return 0; } \ No newline at end of file diff --git a/dynamic_programming/searching_of_element_in_dynamic_array.cpp b/dynamic_programming/searching_of_element_in_dynamic_array.cpp index 9ee48dded..3dea46bf4 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_array.cpp @@ -1,41 +1,42 @@ /* -*this program is use to find any elemet in any row with variable array size -*aplication of pointer is use in it -*important point start from here to: -*the index value of array can be go to 1 to 100000 -*check till array[1000] -*end here -*how to work example: -**Question: -***number of array 2 -***quarry 3 -***array 1 is {1 2 3 4 5} -***array 2 is {6 7} -****i) what is 2nd element in 1st array -****ii) what is 1st element in 2nd array -****iii) what is 5th element in 1st array -*****output: -*****Enter Number of array you want to Store : 2 -*****Enter Number of Question or Quary you want to do Related to Array : 3 -*****Enter number of element in 1 rows : 5 -*****Enter the element of Array 1 2 3 4 5 -*****Enter number of element in 2 rows : 2 -*****Enter the element of Array 6 7 -*****enter the number of row which element You want to find : 1 -*****enter the position of element which You want to find : 2 -*****The element is 2 -*****enter the number of row which element You want to find : 2 -*****enter the position of element which You want to find : 1 -*****The element is 6 -*****enter the number of row which element You want to find : 1 -*****enter the position of element which You want to find : 5 -*****The element is 5 -*/ + *this program is use to find any elemet in any row with variable array size + *aplication of pointer is use in it + *important point start from here to: + *the index value of array can be go to 1 to 100000 + *check till array[1000] + *end here + *how to work example: + **Question: + ***number of array 2 + ***quarry 3 + ***array 1 is {1 2 3 4 5} + ***array 2 is {6 7} + ****i) what is 2nd element in 1st array + ****ii) what is 1st element in 2nd array + ****iii) what is 5th element in 1st array + *****output: + *****Enter Number of array you want to Store : 2 + *****Enter Number of Question or Quary you want to do Related to Array : 3 + *****Enter number of element in 1 rows : 5 + *****Enter the element of Array 1 2 3 4 5 + *****Enter number of element in 2 rows : 2 + *****Enter the element of Array 6 7 + *****enter the number of row which element You want to find : 1 + *****enter the position of element which You want to find : 2 + *****The element is 2 + *****enter the number of row which element You want to find : 2 + *****enter the position of element which You want to find : 1 + *****The element is 6 + *****enter the number of row which element You want to find : 1 + *****enter the position of element which You want to find : 5 + *****The element is 5 + */ #include // this is main fuction // *** -int main() { +int main() +{ int64_t r, mr = 0, x, q, i, z; std::cout << "Enter Number of array you want to Store :"; std::cin >> x; @@ -46,10 +47,11 @@ int main() { // create a Array in run time because use can // change the size of each array which he/she is going to store // create a 2D array - int** ar = new int* [x](); + int** ar = new int*[x](); // this for loop is use for entering different variable size array // *** - for (r = 0; r < x; r++) { + for (r = 0; r < x; r++) + { std::cout << "Enter number of element in " << r + 1 << " rows :"; std::cin >> mr; // creating a 1D array @@ -57,7 +59,8 @@ int main() { std::cout << "Enter the element of Array "; // this for loop is use for storing values in array // *** - for (i = 0; i < mr; i++) { + for (i = 0; i < mr; i++) + { // entering the value of rows in array in Horizontal std::cin >> ac[i]; } @@ -66,7 +69,8 @@ int main() { } // this for loop is use for display result of querry // *** - for (z = 0; z < q; z++) { + for (z = 0; z < q; z++) + { int64_t r1 = 0, q1 = 0; std::cout << "enter the number of row which element you want to find :"; std::cin >> r1; @@ -75,6 +79,6 @@ int main() { std::cin >> q1; q1 = q1 - 1; // use this to find desire position of element in desire array - std::cout <<"The element is "<< ar[r1][q1] < -#include +#include +#include // global declarations // no of nodes max limit. @@ -29,22 +29,26 @@ std::vector adj[MAX]; std::vector visited; std::vector dp; -void depth_first_search(int u) { +void depth_first_search(int u) +{ visited[u] = true; int child_height = 1; - for (int v : adj[u]) { - if (!visited[v]) { + for (int v : adj[u]) + { + if (!visited[v]) + { depth_first_search(v); // select maximum sub-tree height from all children. - child_height = std::max(child_height, dp[v]+1); + child_height = std::max(child_height, dp[v] + 1); } } // assigned the max child height to current visited node. dp[u] = child_height; } -int main() { +int main() +{ // number of nodes int number_of_nodes; std::cout << "Enter number of nodes of the tree : " << std::endl; @@ -54,16 +58,17 @@ int main() { int u, v; // Tree contains exactly n-1 edges where n denotes the number of nodes. std::cout << "Enter edges of the tree : " << std::endl; - for (int i = 0; i < number_of_nodes - 1; i++) { + for (int i = 0; i < number_of_nodes - 1; i++) + { std::cin >> u >> v; // undirected tree u -> v and v -> u. adj[u].push_back(v); adj[v].push_back(u); } // initialize all nodes as unvisited. - visited.assign(number_of_nodes+1, false); + visited.assign(number_of_nodes + 1, false); // initialize depth of all nodes to 0. - dp.assign(number_of_nodes+1, 0); + dp.assign(number_of_nodes + 1, 0); // function call which will initialize the height of all nodes. depth_first_search(1); std::cout << "Height of the Tree : " << dp[1] << std::endl; diff --git a/graph/bfs.cpp b/graph/bfs.cpp index e4e12886b..f5d372134 100644 --- a/graph/bfs.cpp +++ b/graph/bfs.cpp @@ -2,72 +2,72 @@ using namespace std; class graph { - int v; - list *adj; + int v; + list *adj; -public: - graph(int v); - void addedge(int src, int dest); - void printgraph(); - void bfs(int s); + public: + graph(int v); + void addedge(int src, int dest); + void printgraph(); + void bfs(int s); }; graph::graph(int v) { - this->v = v; - this->adj = new list[v]; + this->v = v; + this->adj = new list[v]; } void graph::addedge(int src, int dest) { - src--; - dest--; - adj[src].push_back(dest); - //adj[dest].push_back(src); + src--; + dest--; + adj[src].push_back(dest); + // adj[dest].push_back(src); } void graph::printgraph() { - for (int i = 0; i < this->v; i++) - { - cout << "Adjacency list of vertex " << i + 1 << " is \n"; - list::iterator it; - for (it = adj[i].begin(); it != adj[i].end(); ++it) - { - cout << *it + 1 << " "; - } - cout << endl; - } + for (int i = 0; i < this->v; i++) + { + cout << "Adjacency list of vertex " << i + 1 << " is \n"; + list::iterator it; + for (it = adj[i].begin(); it != adj[i].end(); ++it) + { + cout << *it + 1 << " "; + } + cout << endl; + } } void graph::bfs(int s) { - bool *visited = new bool[this->v + 1]; - memset(visited, false, sizeof(bool) * (this->v + 1)); - visited[s] = true; - list q; - q.push_back(s); - list::iterator it; - while (!q.empty()) - { - int u = q.front(); - cout << u << " "; - q.pop_front(); - for (it = adj[u].begin(); it != adj[u].end(); ++it) - { - if (visited[*it] == false) - { - visited[*it] = true; - q.push_back(*it); - } - } - } + bool *visited = new bool[this->v + 1]; + memset(visited, false, sizeof(bool) * (this->v + 1)); + visited[s] = true; + list q; + q.push_back(s); + list::iterator it; + while (!q.empty()) + { + int u = q.front(); + cout << u << " "; + q.pop_front(); + for (it = adj[u].begin(); it != adj[u].end(); ++it) + { + if (visited[*it] == false) + { + visited[*it] = true; + q.push_back(*it); + } + } + } } int main() { - graph g(4); - g.addedge(1, 2); - g.addedge(2, 3); - g.addedge(3, 4); - g.addedge(1, 4); - g.addedge(1, 3); - //g.printgraph(); - g.bfs(2); - return 0; + graph g(4); + g.addedge(1, 2); + g.addedge(2, 3); + g.addedge(3, 4); + g.addedge(1, 4); + g.addedge(1, 3); + // g.printgraph(); + g.bfs(2); + return 0; } diff --git a/graph/bridge_finding_with_tarjan_algorithm.cpp b/graph/bridge_finding_with_tarjan_algorithm.cpp index ca124f512..a283a7c91 100644 --- a/graph/bridge_finding_with_tarjan_algorithm.cpp +++ b/graph/bridge_finding_with_tarjan_algorithm.cpp @@ -4,28 +4,34 @@ * Last Modified Date: May 24, 2020 * */ -#include // for std::vector #include // for min & max -#include // for cout -using std::vector; +#include // for cout +#include // for std::vector using std::cout; using std::min; -class Solution { - vector < vector < int > > graph; - vectorin_time , out_time; +using std::vector; +class Solution +{ + vector> graph; + vector in_time, out_time; int timer; - vector < vector < int > > bridge; - vectorvisited; - void dfs(int current_node , int parent) { + vector> bridge; + vector visited; + void dfs(int current_node, int parent) + { visited.at(current_node) = true; in_time[current_node] = out_time[current_node] = timer++; - for ( auto&itr : graph[current_node] ) { - if (itr == parent) { + for (auto& itr : graph[current_node]) + { + if (itr == parent) + { continue; } - if (!visited[itr]) { - dfs(itr , current_node); - if (out_time[itr] > in_time[current_node]) { + if (!visited[itr]) + { + dfs(itr, current_node); + if (out_time[itr] > in_time[current_node]) + { bridge.push_back({itr, current_node}); } } @@ -34,14 +40,16 @@ class Solution { } public: - vector > search_bridges(int n, - const vector>& connections) { + vector> search_bridges(int n, + const vector>& connections) + { timer = 0; graph.resize(n); in_time.assign(n, 0); visited.assign(n, false); out_time.assign(n, 0); - for (auto&itr : connections) { + for (auto& itr : connections) + { graph.at(itr[0]).push_back(itr[1]); graph.at(itr[1]).push_back(itr[0]); } @@ -49,10 +57,11 @@ class Solution { return bridge; } }; -int main(void) { +int main(void) +{ Solution s1; int number_of_node = 5; - vector< vector >node; + vector> node; node.push_back({0, 1}); node.push_back({1, 3}); node.push_back({1, 2}); @@ -66,13 +75,14 @@ int main(void) { * 3 4 * * In this graph there are 4 bridges [0,2] , [2,4] , [3,5] , [1,2] - * + * * I assumed that the graph is bi-directional and connected. * */ - vector< vector > bridges = s1.search_bridges(number_of_node , node); + vector> bridges = s1.search_bridges(number_of_node, node); cout << bridges.size() << " bridges found!\n"; - for (auto&itr : bridges) { + for (auto& itr : bridges) + { cout << itr[0] << " --> " << itr[1] << '\n'; } return 0; diff --git a/graph/connected_components.cpp b/graph/connected_components.cpp index 9c22cc35e..f78ef011e 100644 --- a/graph/connected_components.cpp +++ b/graph/connected_components.cpp @@ -3,53 +3,62 @@ using std::vector; -class graph { +class graph +{ private: vector> adj; int connected_components; void depth_first_search(); - void explore(int, vector&); + void explore(int, vector &); + public: - explicit graph(int n): adj(n, vector()) { - connected_components = 0; - } + explicit graph(int n) : adj(n, vector()) { connected_components = 0; } void addEdge(int, int); - int getConnectedComponents() { - depth_first_search(); - return connected_components; + int getConnectedComponents() + { + depth_first_search(); + return connected_components; } }; -void graph::addEdge(int u, int v) { - adj[u-1].push_back(v-1); - adj[v-1].push_back(u-1); +void graph::addEdge(int u, int v) +{ + adj[u - 1].push_back(v - 1); + adj[v - 1].push_back(u - 1); } -void graph::depth_first_search() { - int n = adj.size(); - vector visited(n, false); +void graph::depth_first_search() +{ + int n = adj.size(); + vector visited(n, false); - for (int i = 0 ; i < n ; i++) { - if (!visited[i]) { - explore(i, visited); - connected_components++; + for (int i = 0; i < n; i++) + { + if (!visited[i]) + { + explore(i, visited); + connected_components++; + } } - } } -void graph::explore(int u, vector &visited) { - visited[u] = true; - for (auto v : adj[u]) { - if (!visited[v]) { - explore(v, visited); +void graph::explore(int u, vector &visited) +{ + visited[u] = true; + for (auto v : adj[u]) + { + if (!visited[v]) + { + explore(v, visited); + } } - } } -int main() { - graph g(4); - g.addEdge(1, 2); - g.addEdge(3, 2); - std::cout << g.getConnectedComponents(); - return 0; +int main() +{ + graph g(4); + g.addEdge(1, 2); + g.addEdge(3, 2); + std::cout << g.getConnectedComponents(); + return 0; } diff --git a/graph/connected_components_with_dsu.cpp b/graph/connected_components_with_dsu.cpp index 2c5c6dab5..07fda5d27 100644 --- a/graph/connected_components_with_dsu.cpp +++ b/graph/connected_components_with_dsu.cpp @@ -1,27 +1,32 @@ #include -#include #include +#include int N; // denotes number of nodes; std::vector parent; std::vector siz; -void make_set() { // function the initialize every node as it's own parent - for (int i = 1; i <= N; i++) { +void make_set() +{ // function the initialize every node as it's own parent + for (int i = 1; i <= N; i++) + { parent[i] = i; siz[i] = 1; } } // To find the component where following node belongs to -int find_set(int v) { +int find_set(int v) +{ if (v == parent[v]) return v; return parent[v] = find_set(parent[v]); } -void union_sets(int a, int b) { // To join 2 components to belong to one +void union_sets(int a, int b) +{ // To join 2 components to belong to one a = find_set(a); b = find_set(b); - if (a != b) { + if (a != b) + { if (siz[a] < siz[b]) std::swap(a, b); parent[b] = a; @@ -29,23 +34,25 @@ void union_sets(int a, int b) { // To join 2 components to belong to one } } -int no_of_connected_components() { // To find total no of connected components +int no_of_connected_components() +{ // To find total no of connected components std::set temp; // temp set to count number of connected components - for (int i = 1; i <= N; i++) - temp.insert(find_set(i)); + for (int i = 1; i <= N; i++) temp.insert(find_set(i)); return temp.size(); } // All critical/corner cases have been taken care of. // Input your required values: (not hardcoded) -int main() { +int main() +{ std::cin >> N; parent.resize(N + 1); siz.resize(N + 1); make_set(); int edges; std::cin >> edges; // no of edges in the graph - while (edges--) { + while (edges--) + { int node_a, node_b; std::cin >> node_a >> node_b; union_sets(node_a, node_b); diff --git a/graph/dfs.cpp b/graph/dfs.cpp index 656711ac8..7c7ec7761 100644 --- a/graph/dfs.cpp +++ b/graph/dfs.cpp @@ -3,29 +3,29 @@ using namespace std; int v = 4; void DFSUtil_(int graph[4][4], bool visited[], int s) { - visited[s] = true; - cout << s << " "; - for (int i = 0; i < v; i++) - { - if (graph[s][i] == 1 && visited[i] == false) - { - DFSUtil_(graph, visited, i); - } - } + visited[s] = true; + cout << s << " "; + for (int i = 0; i < v; i++) + { + if (graph[s][i] == 1 && visited[i] == false) + { + DFSUtil_(graph, visited, i); + } + } } void DFS_(int graph[4][4], int s) { - bool visited[v]; - memset(visited, 0, sizeof(visited)); - DFSUtil_(graph, visited, s); + bool visited[v]; + memset(visited, 0, sizeof(visited)); + DFSUtil_(graph, visited, s); } int main() { - int graph[4][4] = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 1}}; - cout << "DFS: "; - DFS_(graph, 2); - cout << endl; - return 0; + int graph[4][4] = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 1}}; + cout << "DFS: "; + DFS_(graph, 2); + cout << endl; + return 0; } \ No newline at end of file diff --git a/graph/dijkstra.cpp b/graph/dijkstra.cpp index b3ee44c41..f25510935 100644 --- a/graph/dijkstra.cpp +++ b/graph/dijkstra.cpp @@ -1,14 +1,16 @@ -#include -#include #include #include +#include +#include using namespace std; #define INF 10000010 vector> graph[5 * 100001]; int dis[5 * 100001]; int dij(vector> *v, int s, int *dis) { - priority_queue, vector>, greater>> pq; + priority_queue, vector>, + greater>> + pq; // source distance to zero. pq.push(make_pair(0, s)); dis[s] = 0; @@ -17,7 +19,8 @@ int dij(vector> *v, int s, int *dis) { u = (pq.top()).second; pq.pop(); - for (vector>::iterator it = v[u].begin(); it != v[u].end(); it++) + for (vector>::iterator it = v[u].begin(); + it != v[u].end(); it++) { if (dis[u] + it->first < dis[it->second]) { @@ -37,13 +40,13 @@ int main() // input edges. scanf("%d%d%d", &x, &y, &l); graph[x].push_back(make_pair(l, y)); - graph[y].push_back(make_pair(l, x)); // comment this line for directed graph + graph[y].push_back( + make_pair(l, x)); // comment this line for directed graph } // start node. scanf("%d", &s); // intialise all distances to infinity. - for (int i = 1; i <= n; i++) - dis[i] = INF; + for (int i = 1; i <= n; i++) dis[i] = INF; dij(graph, s, dis); for (int i = 1; i <= n; i++) diff --git a/graph/kosaraju.cpp b/graph/kosaraju.cpp index 2e66f131f..0efa291bc 100644 --- a/graph/kosaraju.cpp +++ b/graph/kosaraju.cpp @@ -1,134 +1,135 @@ -/* Implementation of Kosaraju's Algorithm to find out the strongly connected components (SCCs) in a graph. - Author:Anirban166 -*/ +/* Implementation of Kosaraju's Algorithm to find out the strongly connected + components (SCCs) in a graph. Author:Anirban166 +*/ -#include -#include +#include +#include using namespace std; /** -* Iterative function/method to print graph: -* @param a[] : array of vectors (2D) -* @param V : vertices -* @return void -**/ -void print(vector a[],int V) + * Iterative function/method to print graph: + * @param a[] : array of vectors (2D) + * @param V : vertices + * @return void + **/ +void print(vector a[], int V) { - for(int i=0;i"; - for(int j=0;j"; + for (int j = 0; j < a[i].size(); j++) cout << a[i][j] << " "; + if (!a[i].empty()) + cout << endl; } } /** -* //Recursive function/method to push vertices into stack passed as parameter: -* @param v : vertices -* @param &st : stack passed by reference -* @param vis[] : array to keep track of visited nodes (boolean type) -* @param adj[] : array of vectors to represent graph -* @return void -**/ -void push_vertex(int v,stack &st,bool vis[],vector adj[]) + * //Recursive function/method to push vertices into stack passed as parameter: + * @param v : vertices + * @param &st : stack passed by reference + * @param vis[] : array to keep track of visited nodes (boolean type) + * @param adj[] : array of vectors to represent graph + * @return void + **/ +void push_vertex(int v, stack &st, bool vis[], vector adj[]) { - vis[v]=true; - for(auto i=adj[v].begin();i!=adj[v].end();i++) + vis[v] = true; + for (auto i = adj[v].begin(); i != adj[v].end(); i++) { - if(vis[*i]==false) - push_vertex(*i,st,vis,adj); + if (vis[*i] == false) + push_vertex(*i, st, vis, adj); } st.push(v); } - /** -* //Recursive function/method to implement depth first traversal(dfs): -* @param v : vertices -* @param vis[] : array to keep track of visited nodes (boolean type) -* @param grev[] : graph with reversed edges -* @return void -**/ -void dfs(int v,bool vis[],vector grev[]) + * //Recursive function/method to implement depth first traversal(dfs): + * @param v : vertices + * @param vis[] : array to keep track of visited nodes (boolean type) + * @param grev[] : graph with reversed edges + * @return void + **/ +void dfs(int v, bool vis[], vector grev[]) { - vis[v]=true; + vis[v] = true; // cout<0)) - i.e. it returns the count of (number of) strongly connected components (SCCs) in the graph. (variable 'count_scc' within function) +* @return int ( 0, 1, 2..and so on, only unsigned values as either there can be +no SCCs i.e. none(0) or there will be x no. of SCCs (x>0)) i.e. it returns the +count of (number of) strongly connected components (SCCs) in the graph. +(variable 'count_scc' within function) **/ int kosaraju(int V, vector adj[]) { - bool vis[V]={}; + bool vis[V] = {}; stack st; - for(int v=0;v grev[V]; - for(int i=0;i 57) && c != '-'); c = gc()) - ; - if (c == '-') - { - neg = 1; - c = gc(); - } - for (; c > 47 && c < 58; c = gc()) - { - x = (x << 1) + (x << 3) + c - 48; - } - if (neg) - x = -x; + register int c = gc(); + x = 0; + int neg = 0; + for (; ((c < 48 || c > 57) && c != '-'); c = gc()) + ; + if (c == '-') + { + neg = 1; + c = gc(); + } + for (; c > 47 && c < 58; c = gc()) + { + x = (x << 1) + (x << 3) + c - 48; + } + if (neg) + x = -x; } void out(int n) { - int N = n, rev, count = 0; - rev = N; - if (N == 0) - { - pc('0'); - return; - } - while ((rev % 10) == 0) - { - count++; - rev /= 10; - } - rev = 0; - while (N != 0) - { - rev = (rev << 3) + (rev << 1) + N % 10; - N /= 10; - } - while (rev != 0) - { - pc(rev % 10 + '0'); - rev /= 10; - } - while (count--) - pc('0'); + int N = n, rev, count = 0; + rev = N; + if (N == 0) + { + pc('0'); + return; + } + while ((rev % 10) == 0) + { + count++; + rev /= 10; + } + rev = 0; + while (N != 0) + { + rev = (rev << 3) + (rev << 1) + N % 10; + N /= 10; + } + while (rev != 0) + { + pc(rev % 10 + '0'); + rev /= 10; + } + while (count--) pc('0'); } ll parent[mx], arr[mx], node, edge; vector>> v; void initial() { - int i; - rep(i, node + edge) - parent[i] = i; + int i; + rep(i, node + edge) parent[i] = i; } int root(int i) { - while (parent[i] != i) - { - parent[i] = parent[parent[i]]; - i = parent[i]; - } - return i; + while (parent[i] != i) + { + parent[i] = parent[parent[i]]; + i = parent[i]; + } + return i; } void join(int x, int y) { - int root_x = root(x); //Disjoint set union by rank - int root_y = root(y); - parent[root_x] = root_y; + int root_x = root(x); // Disjoint set union by rank + int root_y = root(y); + parent[root_x] = root_y; } ll kruskal() { - ll mincost = 0, i, x, y; - rep(i, edge) - { - x = v[i].second.first; - y = v[i].second.second; - if (root(x) != root(y)) - { - mincost += v[i].first; - join(x, y); - } - } - return mincost; + ll mincost = 0, i, x, y; + rep(i, edge) + { + x = v[i].second.first; + y = v[i].second.second; + if (root(x) != root(y)) + { + mincost += v[i].first; + join(x, y); + } + } + return mincost; } int main() { - fast; - while (1) - { - int i, j, from, to, cost, totalcost = 0; - cin >> node >> edge; //Enter the nodes and edges - if (node == 0 && edge == 0) - break; //Enter 0 0 to break out - initial(); //Initialise the parent array - rep(i, edge) - { - cin >> from >> to >> cost; - v.pb(mp(cost, mp(from, to))); - totalcost += cost; - } - sort(v.begin(), v.end()); - // rep(i,v.size()) - // cout<> node >> edge; // Enter the nodes and edges + if (node == 0 && edge == 0) + break; // Enter 0 0 to break out + initial(); // Initialise the parent array + rep(i, edge) + { + cin >> from >> to >> cost; + v.pb(mp(cost, mp(from, to))); + totalcost += cost; + } + sort(v.begin(), v.end()); + // rep(i,v.size()) + // cout< adj[N]; // Graph - int up[LG][N]; // build this table - int level[N]; // get the levels of all of them + vector adj[N]; // Graph + int up[LG][N]; // build this table + int level[N]; // get the levels of all of them - lca(int n_): n(n_) + lca(int n_) : n(n_) { memset(up, -1, sizeof(up)); memset(level, 0, sizeof(level)); for (int i = 0; i < n - 1; ++i) - { + { int a, b; cin >> a >> b; a--; @@ -34,15 +34,15 @@ struct lca void verify() { for (int i = 0; i < n; ++i) - { + { cout << i << " : level: " << level[i] << endl; } cout << endl; for (int i = 0; i < LG; ++i) - { + { cout << "Power:" << i << ": "; for (int j = 0; j < n; ++j) - { + { cout << up[i][j] << " "; } cout << endl; @@ -52,11 +52,11 @@ struct lca void build() { for (int i = 1; i < LG; ++i) - { + { for (int j = 0; j < n; ++j) - { + { if (up[i - 1][j] != -1) - { + { up[i][j] = up[i - 1][up[i - 1][j]]; } } @@ -66,10 +66,10 @@ struct lca void dfs(int node, int par) { up[0][node] = par; - for (auto i: adj[node]) - { + for (auto i : adj[node]) + { if (i != par) - { + { level[i] = level[node] + 1; dfs(i, node); } @@ -80,28 +80,28 @@ struct lca u--; v--; if (level[v] > level[u]) - { + { swap(u, v); } // u is at the bottom. int dist = level[u] - level[v]; // Go up this much distance for (int i = LG - 1; i >= 0; --i) - { + { if (dist & (1 << i)) - { + { u = up[i][u]; } } if (u == v) - { + { return u; } assert(level[u] == level[v]); for (int i = LG - 1; i >= 0; --i) - { + { if (up[i][u] != up[i][v]) - { + { u = up[i][u]; v = up[i][v]; } @@ -113,8 +113,8 @@ struct lca int main() { - int n; // number of nodes in the tree. - lca l(n); // will take the input in the format given + int n; // number of nodes in the tree. + lca l(n); // will take the input in the format given // n-1 edges of the form // a b // Use verify function to see. diff --git a/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp b/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp index ee394d9f0..f02a48e01 100644 --- a/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp +++ b/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp @@ -4,41 +4,47 @@ * Copyright: 2020, Open-Source * Last Modified: May 25, 2020 */ -#include -#include -#include #include #include -#include #include -#include +#include +#include +#include +#include #include +#include // std::max capacity of node in graph const int MAXN = 505; -class Graph { +class Graph +{ int residual_capacity[MAXN][MAXN]; int capacity[MAXN][MAXN]; // used while checking the flow of edge int total_nodes; int total_edges, source, sink; int parent[MAXN]; - std::vector >edge_participated; - std::bitset visited; + std::vector > edge_participated; + std::bitset visited; int max_flow = 0; - bool bfs(int source, int sink) { // to find the augmented - path + bool bfs(int source, int sink) + { // to find the augmented - path memset(parent, -1, sizeof(parent)); visited.reset(); - std::queueq; + std::queue q; q.push(source); bool is_path_found = false; - while (q.empty() == false && is_path_found == false) { + while (q.empty() == false && is_path_found == false) + { int current_node = q.front(); visited.set(current_node); q.pop(); - for (int i = 0; i < total_nodes; ++i) { - if (residual_capacity[current_node][i] > 0 && !visited[i]) { + for (int i = 0; i < total_nodes; ++i) + { + if (residual_capacity[current_node][i] > 0 && !visited[i]) + { visited.set(i); parent[i] = current_node; - if (i == sink) { + if (i == sink) + { return true; } q.push(i); @@ -49,29 +55,33 @@ class Graph { } public: - Graph() { - memset(residual_capacity, 0, sizeof(residual_capacity)); - } - void set_graph(void) { + Graph() { memset(residual_capacity, 0, sizeof(residual_capacity)); } + void set_graph(void) + { std::cin >> total_nodes >> total_edges >> source >> sink; - for (int start, destination, capacity_, i = 0; i < total_edges; ++i) { + for (int start, destination, capacity_, i = 0; i < total_edges; ++i) + { std::cin >> start >> destination >> capacity_; residual_capacity[start][destination] = capacity_; capacity[start][destination] = capacity_; } } - void ford_fulkerson(void) { - while (bfs(source, sink)) { + void ford_fulkerson(void) + { + while (bfs(source, sink)) + { int current_node = sink; int flow = std::numeric_limits::max(); - while (current_node != source) { + while (current_node != source) + { int parent_ = parent[current_node]; flow = std::min(flow, residual_capacity[parent_][current_node]); current_node = parent_; } current_node = sink; max_flow += flow; - while ( current_node != source ) { + while (current_node != source) + { int parent_ = parent[current_node]; residual_capacity[parent_][current_node] -= flow; residual_capacity[current_node][parent_] += flow; @@ -79,31 +89,34 @@ class Graph { } } } - void print_flow_info(void) { - for (int i = 0; i < total_nodes; ++i) { - for (int j = 0; j < total_nodes; ++j) { - if (capacity[i][j] && - residual_capacity[i][j] < capacity[i][j]) { - edge_participated.push_back( - std::make_tuple(i, j, - capacity[i][j]-residual_capacity[i][j])); + void print_flow_info(void) + { + for (int i = 0; i < total_nodes; ++i) + { + for (int j = 0; j < total_nodes; ++j) + { + if (capacity[i][j] && residual_capacity[i][j] < capacity[i][j]) + { + edge_participated.push_back(std::make_tuple( + i, j, capacity[i][j] - residual_capacity[i][j])); } } } - std::cout << "\nNodes : " << total_nodes - << "\nMax flow: " << max_flow - << "\nEdge present in flow: " << edge_participated.size() - << '\n'; - std::cout<< "\nSource\tDestination\tCapacity\total_nodes"; - for (auto&edge_data : edge_participated) { + std::cout << "\nNodes : " << total_nodes << "\nMax flow: " << max_flow + << "\nEdge present in flow: " << edge_participated.size() + << '\n'; + std::cout << "\nSource\tDestination\tCapacity\total_nodes"; + for (auto& edge_data : edge_participated) + { int source, destination, capacity_; std::tie(source, destination, capacity_) = edge_data; - std::cout << source << "\t" << destination << "\t\t" - << capacity_ <<'\t'; + std::cout << source << "\t" << destination << "\t\t" << capacity_ + << '\t'; } } }; -int main(void) { +int main(void) +{ /* Input Graph: (for testing ) 4 5 0 3 @@ -119,4 +132,3 @@ int main(void) { graph.print_flow_info(); return 0; } - diff --git a/graph/prim.cpp b/graph/prim.cpp index 2923b5b25..8332bdb36 100644 --- a/graph/prim.cpp +++ b/graph/prim.cpp @@ -1,23 +1,25 @@ // C++ program to implement Prim's Algorithm #include -#include #include +#include const int MAX = 1e4 + 5; -typedef std:: pair PII; +typedef std::pair PII; bool marked[MAX]; -std:: vector adj[MAX]; +std::vector adj[MAX]; -int prim(int x) { +int prim(int x) +{ // priority queue to maintain edges with respect to weights - std:: priority_queue, std:: greater > Q; + std::priority_queue, std::greater > Q; int y; int minimumCost = 0; PII p; - Q.push(std:: make_pair(0, x)); - while (!Q.empty()) { + Q.push(std::make_pair(0, x)); + while (!Q.empty()) + { // Select the edge with minimum weight p = Q.top(); Q.pop(); @@ -27,7 +29,8 @@ int prim(int x) { continue; minimumCost += p.first; marked[x] = true; - for (int i = 0; i < adj[x].size(); ++i) { + for (int i = 0; i < adj[x].size(); ++i) + { y = adj[x][i].second; if (marked[y] == false) Q.push(adj[x][i]); @@ -36,23 +39,25 @@ int prim(int x) { return minimumCost; } -int main() { +int main() +{ int nodes, edges, x, y; int weight, minimumCost; - std:: cin >> nodes >> edges; // number of nodes & edges in graph + std::cin >> nodes >> edges; // number of nodes & edges in graph if (nodes == 0 || edges == 0) return 0; // Edges with their nodes & weight - for (int i = 0; i < edges; ++i) { + for (int i = 0; i < edges; ++i) + { std::cin >> x >> y >> weight; - adj[x].push_back(std:: make_pair(weight, y)); - adj[y].push_back(std:: make_pair(weight, x)); + adj[x].push_back(std::make_pair(weight, y)); + adj[y].push_back(std::make_pair(weight, x)); } // Selecting 1 as the starting node minimumCost = prim(1); - std:: cout << minimumCost << std:: endl; + std::cout << minimumCost << std::endl; return 0; } diff --git a/graph/topological_sort.cpp b/graph/topological_sort.cpp index 2203231ae..d863c6993 100644 --- a/graph/topological_sort.cpp +++ b/graph/topological_sort.cpp @@ -1,53 +1,54 @@ +#include #include #include -#include using namespace std; -int n, m; // For number of Vertices (V) and number of edges (E) +int n, m; // For number of Vertices (V) and number of edges (E) vector> G; vector visited; vector ans; void dfs(int v) { - visited[v] = true; - for (int u : G[v]) - { - if (!visited[u]) - dfs(u); - } - ans.push_back(v); + visited[v] = true; + for (int u : G[v]) + { + if (!visited[u]) + dfs(u); + } + ans.push_back(v); } void topological_sort() { - visited.assign(n, false); - ans.clear(); - for (int i = 0; i < n; ++i) - { - if (!visited[i]) - dfs(i); - } - reverse(ans.begin(), ans.end()); + visited.assign(n, false); + ans.clear(); + for (int i = 0; i < n; ++i) + { + if (!visited[i]) + dfs(i); + } + reverse(ans.begin(), ans.end()); } int main() { - cout << "Enter the number of vertices and the number of directed edges\n"; - cin >> n >> m; - int x, y; - G.resize(n, vector()); - for (int i = 0; i < n; ++i) - { - cin >> x >> y; - x--, y--; // to convert 1-indexed to 0-indexed - G[x].push_back(y); - } - topological_sort(); - cout << "Topological Order : \n"; - for (int v : ans) - { - cout << v + 1 << ' '; // converting zero based indexing back to one based. - } - cout << '\n'; - return 0; + cout << "Enter the number of vertices and the number of directed edges\n"; + cin >> n >> m; + int x, y; + G.resize(n, vector()); + for (int i = 0; i < n; ++i) + { + cin >> x >> y; + x--, y--; // to convert 1-indexed to 0-indexed + G[x].push_back(y); + } + topological_sort(); + cout << "Topological Order : \n"; + for (int v : ans) + { + cout << v + 1 + << ' '; // converting zero based indexing back to one based. + } + cout << '\n'; + return 0; } diff --git a/graph/topological_sort_by_kahns_algo.cpp b/graph/topological_sort_by_kahns_algo.cpp index eda2a74bc..b56ae5651 100644 --- a/graph/topological_sort_by_kahns_algo.cpp +++ b/graph/topological_sort_by_kahns_algo.cpp @@ -1,63 +1,75 @@ #include #include #include -#include #include +#include int *topoSortKahn(int N, std::vector adj[]); -int main() { +int main() +{ int nodes, edges; std::cin >> edges >> nodes; if (edges == 0 || nodes == 0) return 0; int u, v; - std::vectorgraph[nodes]; + std::vector graph[nodes]; // create graph // example // 6 6 // 5 0 5 2 2 3 4 0 4 1 1 3 - for (int i = 0; i < edges; i++) { + for (int i = 0; i < edges; i++) + { std::cin >> u >> v; graph[u].push_back(v); } int *topo = topoSortKahn(nodes, graph); // topologically sorted nodes - for (int i = 0; i < nodes; i++) { + for (int i = 0; i < nodes; i++) + { std::cout << topo[i] << " "; } } -int* topoSortKahn(int V, std::vector adj[]) { - std::vectorvis(V+1, false); - std::vectordeg(V+1, 0); - for (int i = 0; i < V; i++) { - for (int j = 0; j < adj[i].size(); j++) { +int *topoSortKahn(int V, std::vector adj[]) +{ + std::vector vis(V + 1, false); + std::vector deg(V + 1, 0); + for (int i = 0; i < V; i++) + { + for (int j = 0; j < adj[i].size(); j++) + { deg[adj[i][j]]++; } } - std::queueq; - for (int i = 0; i < V; i++) { - if (deg[i] == 0) { + std::queue q; + for (int i = 0; i < V; i++) + { + if (deg[i] == 0) + { q.push(i); vis[i] = true; } } - int *arr = new int[V+1]; - memset(arr, 0, V+1); + int *arr = new int[V + 1]; + memset(arr, 0, V + 1); int count = 0; - while (!q.empty()) { + while (!q.empty()) + { int cur = q.front(); q.pop(); arr[count] = cur; count++; - for (int i = 0; i < adj[cur].size(); i++) { - if (!vis[adj[cur][i]]) { + for (int i = 0; i < adj[cur].size(); i++) + { + if (!vis[adj[cur][i]]) + { deg[adj[cur][i]]--; - if (deg[adj[cur][i]] == 0) { + if (deg[adj[cur][i]] == 0) + { q.push(adj[cur][i]); vis[adj[cur][i]] = true; } diff --git a/greedy_algorithms/dijkstra.cpp b/greedy_algorithms/dijkstra.cpp index 0c7fffc8c..b87b4ab10 100644 --- a/greedy_algorithms/dijkstra.cpp +++ b/greedy_algorithms/dijkstra.cpp @@ -1,19 +1,18 @@ -#include #include +#include using namespace std; -//Wrapper class for storing a graph +// Wrapper class for storing a graph class Graph { -public: + public: int vertexNum; int **edges; - //Constructs a graph with V vertices and E edges + // Constructs a graph with V vertices and E edges Graph(const int V) { - // initializes the array edges. this->edges = new int *[V]; for (int i = 0; i < V; i++) @@ -33,13 +32,13 @@ public: this->vertexNum = V; } - //Adds the given edge to the graph + // Adds the given edge to the graph void addEdge(int src, int dst, int weight) { this->edges[src][dst] = weight; } }; -//Utility function to find minimum distance vertex in mdist +// Utility function to find minimum distance vertex in mdist int minDistance(int mdist[], bool vset[], int V) { int minVal = INT_MAX, minInd = 0; @@ -55,7 +54,7 @@ int minDistance(int mdist[], bool vset[], int V) return minInd; } -//Utility function to print distances +// Utility function to print distances void print(int dist[], int V) { cout << "\nVertex Distance" << endl; @@ -68,17 +67,17 @@ void print(int dist[], int V) } } -//The main function that finds the shortest path from given source -//to all other vertices using Dijkstra's Algorithm.It doesn't work on negative -//weights +// The main function that finds the shortest path from given source +// to all other vertices using Dijkstra's Algorithm.It doesn't work on negative +// weights void Dijkstra(Graph graph, int src) { int V = graph.vertexNum; - int mdist[V]; //Stores updated distances to vertex - bool vset[V]; // vset[i] is true if the vertex i included + int mdist[V]; // Stores updated distances to vertex + bool vset[V]; // vset[i] is true if the vertex i included // in the shortest path tree - //Initialise mdist and vset. Set distance of source as zero + // Initialise mdist and vset. Set distance of source as zero for (int i = 0; i < V; i++) { mdist[i] = INT_MAX; @@ -87,7 +86,7 @@ void Dijkstra(Graph graph, int src) mdist[src] = 0; - //iterate to find shortest path + // iterate to find shortest path for (int count = 0; count < V - 1; count++) { int u = minDistance(mdist, vset, V); @@ -96,7 +95,8 @@ void Dijkstra(Graph graph, int src) for (int v = 0; v < V; v++) { - if (!vset[v] && graph.edges[u][v] && mdist[u] + graph.edges[u][v] < mdist[v]) + if (!vset[v] && graph.edges[u][v] && + mdist[u] + graph.edges[u][v] < mdist[v]) { mdist[v] = mdist[u] + graph.edges[u][v]; } @@ -106,7 +106,7 @@ void Dijkstra(Graph graph, int src) print(mdist, V); } -//Driver Function +// Driver Function int main() { int V, E, gsrc; diff --git a/greedy_algorithms/huffman.cpp b/greedy_algorithms/huffman.cpp index 253d8d0b5..bf3d9ff9a 100644 --- a/greedy_algorithms/huffman.cpp +++ b/greedy_algorithms/huffman.cpp @@ -1,109 +1,106 @@ -// C++ program for Huffman Coding +// C++ program for Huffman Coding #include -#include -using namespace std; - -// A Huffman tree node -struct MinHeapNode { - - // One of the input characters - char data; - - // Frequency of the character - unsigned freq; - - // Left and right child - MinHeapNode *left, *right; - - MinHeapNode(char data, unsigned freq) - - { - - left = right = NULL; - this->data = data; - this->freq = freq; - } -}; - -// For comparison of -// two heap nodes (needed in min heap) -struct compare { - - bool operator()(MinHeapNode* l, MinHeapNode* r) - - { - return (l->freq > r->freq); - } -}; - -// Prints huffman codes from -// the root of Huffman Tree. -void printCodes(struct MinHeapNode* root, string str) -{ - - if (!root) - return; - - if (root->data != '$') - cout << root->data << ": " << str << "\n"; - - printCodes(root->left, str + "0"); - printCodes(root->right, str + "1"); -} - -// The main function that builds a Huffman Tree and -// print codes by traversing the built Huffman Tree -void HuffmanCodes(char data[], int freq[], int size) -{ - struct MinHeapNode *left, *right, *top; - - // Create a min heap & inserts all characters of data[] - priority_queue, compare> minHeap; - - for (int i = 0; i < size; ++i) - minHeap.push(new MinHeapNode(data[i], freq[i])); - - // Iterate while size of heap doesn't become 1 - while (minHeap.size() != 1) { - - // Extract the two minimum - // freq items from min heap - left = minHeap.top(); - minHeap.pop(); - - right = minHeap.top(); - minHeap.pop(); - - // Create a new internal node with - // frequency equal to the sum of the - // two nodes frequencies. Make the - // two extracted node as left and right children - // of this new node. Add this node - // to the min heap '$' is a special value - // for internal nodes, not used - top = new MinHeapNode('$', left->freq + right->freq); - - top->left = left; - top->right = right; - - minHeap.push(top); - } - - // Print Huffman codes using - // the Huffman tree built above - printCodes(minHeap.top(), ""); -} - -// Driver program to test above functions -int main() -{ - - char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; - int freq[] = { 5, 9, 12, 13, 16, 45 }; - - int size = sizeof(arr) / sizeof(arr[0]); - - HuffmanCodes(arr, freq, size); - - return 0; -} +#include +using namespace std; + +// A Huffman tree node +struct MinHeapNode +{ + // One of the input characters + char data; + + // Frequency of the character + unsigned freq; + + // Left and right child + MinHeapNode *left, *right; + + MinHeapNode(char data, unsigned freq) + + { + left = right = NULL; + this->data = data; + this->freq = freq; + } +}; + +// For comparison of +// two heap nodes (needed in min heap) +struct compare +{ + bool operator()(MinHeapNode* l, MinHeapNode* r) + + { + return (l->freq > r->freq); + } +}; + +// Prints huffman codes from +// the root of Huffman Tree. +void printCodes(struct MinHeapNode* root, string str) +{ + if (!root) + return; + + if (root->data != '$') + cout << root->data << ": " << str << "\n"; + + printCodes(root->left, str + "0"); + printCodes(root->right, str + "1"); +} + +// The main function that builds a Huffman Tree and +// print codes by traversing the built Huffman Tree +void HuffmanCodes(char data[], int freq[], int size) +{ + struct MinHeapNode *left, *right, *top; + + // Create a min heap & inserts all characters of data[] + priority_queue, compare> minHeap; + + for (int i = 0; i < size; ++i) + minHeap.push(new MinHeapNode(data[i], freq[i])); + + // Iterate while size of heap doesn't become 1 + while (minHeap.size() != 1) + { + // Extract the two minimum + // freq items from min heap + left = minHeap.top(); + minHeap.pop(); + + right = minHeap.top(); + minHeap.pop(); + + // Create a new internal node with + // frequency equal to the sum of the + // two nodes frequencies. Make the + // two extracted node as left and right children + // of this new node. Add this node + // to the min heap '$' is a special value + // for internal nodes, not used + top = new MinHeapNode('$', left->freq + right->freq); + + top->left = left; + top->right = right; + + minHeap.push(top); + } + + // Print Huffman codes using + // the Huffman tree built above + printCodes(minHeap.top(), ""); +} + +// Driver program to test above functions +int main() +{ + char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'}; + int freq[] = {5, 9, 12, 13, 16, 45}; + + int size = sizeof(arr) / sizeof(arr[0]); + + HuffmanCodes(arr, freq, size); + + return 0; +} diff --git a/greedy_algorithms/knapsack.cpp b/greedy_algorithms/knapsack.cpp index 2135bd1eb..81fd879de 100644 --- a/greedy_algorithms/knapsack.cpp +++ b/greedy_algorithms/knapsack.cpp @@ -3,90 +3,88 @@ using namespace std; struct Item { - int weight; - int profit; + int weight; + int profit; }; -float profitPerUnit(Item x) -{ - return (float)x.profit / (float)x.weight; -} +float profitPerUnit(Item x) { return (float)x.profit / (float)x.weight; } int partition(Item arr[], int low, int high) { - Item pivot = arr[high]; // pivot - int i = (low - 1); // Index of smaller element + Item pivot = arr[high]; // pivot + int i = (low - 1); // Index of smaller element - for (int j = low; j < high; j++) - { - // If current element is smaller than or - // equal to pivot - if (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) - { - i++; // increment index of smaller element - Item temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; - } - } - Item temp = arr[i + 1]; - arr[i + 1] = arr[high]; - arr[high] = temp; - return (i + 1); + for (int j = low; j < high; j++) + { + // If current element is smaller than or + // equal to pivot + if (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) + { + i++; // increment index of smaller element + Item temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + Item temp = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp; + return (i + 1); } void quickSort(Item arr[], int low, int high) { - if (low < high) - { + if (low < high) + { + int p = partition(arr, low, high); - int p = partition(arr, low, high); - - quickSort(arr, low, p - 1); - quickSort(arr, p + 1, high); - } + quickSort(arr, low, p - 1); + quickSort(arr, p + 1, high); + } } int main() { - cout << "\nEnter the capacity of the knapsack : "; - float capacity; - cin >> capacity; - cout << "\n Enter the number of Items : "; - int n; - cin >> n; - Item itemArray[n]; - for (int i = 0; i < n; i++) - { - cout << "\nEnter the weight and profit of item " << i + 1 << " : "; - cin >> itemArray[i].weight; - cin >> itemArray[i].profit; - } + cout << "\nEnter the capacity of the knapsack : "; + float capacity; + cin >> capacity; + cout << "\n Enter the number of Items : "; + int n; + cin >> n; + Item itemArray[n]; + for (int i = 0; i < n; i++) + { + cout << "\nEnter the weight and profit of item " << i + 1 << " : "; + cin >> itemArray[i].weight; + cin >> itemArray[i].profit; + } - quickSort(itemArray, 0, n - 1); + quickSort(itemArray, 0, n - 1); - // show(itemArray, n); + // show(itemArray, n); - float maxProfit = 0; - int i = n; - while (capacity > 0 && --i >= 0) - { - if (capacity >= itemArray[i].weight) - { - maxProfit += itemArray[i].profit; - capacity -= itemArray[i].weight; - cout << "\n\t" << itemArray[i].weight << "\t" << itemArray[i].profit; - } - else - { - maxProfit += profitPerUnit(itemArray[i]) * capacity; - cout << "\n\t" << capacity << "\t" << profitPerUnit(itemArray[i]) * capacity; - capacity = 0; - break; - } - } + float maxProfit = 0; + int i = n; + while (capacity > 0 && --i >= 0) + { + if (capacity >= itemArray[i].weight) + { + maxProfit += itemArray[i].profit; + capacity -= itemArray[i].weight; + cout << "\n\t" << itemArray[i].weight << "\t" + << itemArray[i].profit; + } + else + { + maxProfit += profitPerUnit(itemArray[i]) * capacity; + cout << "\n\t" << capacity << "\t" + << profitPerUnit(itemArray[i]) * capacity; + capacity = 0; + break; + } + } - cout << "\nMax Profit : " << maxProfit; + cout << "\nMax Profit : " << maxProfit; - return 0; + return 0; } diff --git a/greedy_algorithms/kruskals_minimum_spanning_tree.cpp b/greedy_algorithms/kruskals_minimum_spanning_tree.cpp index 951d4a88a..feeaf0102 100644 --- a/greedy_algorithms/kruskals_minimum_spanning_tree.cpp +++ b/greedy_algorithms/kruskals_minimum_spanning_tree.cpp @@ -4,34 +4,33 @@ using namespace std; #define V 6 #define INFINITY 99999 -int graph[V][V] = { - {0, 4, 1, 4, INFINITY, INFINITY}, - {4, 0, 3, 8, 3, INFINITY}, - {1, 3, 0, INFINITY, 1, INFINITY}, - {4, 8, INFINITY, 0, 5, 7}, - {INFINITY, 3, 1, 5, 0, INFINITY}, - {INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}}; +int graph[V][V] = {{0, 4, 1, 4, INFINITY, INFINITY}, + {4, 0, 3, 8, 3, INFINITY}, + {1, 3, 0, INFINITY, 1, INFINITY}, + {4, 8, INFINITY, 0, 5, 7}, + {INFINITY, 3, 1, 5, 0, INFINITY}, + {INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}}; void findMinimumEdge() { - for (int i = 0; i < V; i++) - { - int min = INFINITY; - int minIndex = 0; - for (int j = 0; j < V; j++) - { - if (graph[i][j] != 0 && graph[i][j] < min) - { - min = graph[i][j]; - minIndex = j; - } - } - cout << i << " - " << minIndex << "\t" << graph[i][minIndex] << "\n"; - } + for (int i = 0; i < V; i++) + { + int min = INFINITY; + int minIndex = 0; + for (int j = 0; j < V; j++) + { + if (graph[i][j] != 0 && graph[i][j] < min) + { + min = graph[i][j]; + minIndex = j; + } + } + cout << i << " - " << minIndex << "\t" << graph[i][minIndex] << "\n"; + } } int main() { - findMinimumEdge(); - return 0; + findMinimumEdge(); + return 0; } diff --git a/greedy_algorithms/prims_minimum_spanning_tree.cpp b/greedy_algorithms/prims_minimum_spanning_tree.cpp index 769ca64e4..c1d3df669 100644 --- a/greedy_algorithms/prims_minimum_spanning_tree.cpp +++ b/greedy_algorithms/prims_minimum_spanning_tree.cpp @@ -4,76 +4,74 @@ using namespace std; #define V 4 #define INFINITY 99999 -int graph[V][V] = { - {0, 5, 1, 2}, - {5, 0, 3, 3}, - {1, 3, 0, 4}, - {2, 3, 4, 0}}; +int graph[V][V] = {{0, 5, 1, 2}, {5, 0, 3, 3}, {1, 3, 0, 4}, {2, 3, 4, 0}}; struct mst { - bool visited; - int key; - int near; + bool visited; + int key; + int near; }; mst MST_Array[V]; void initilize() { - for (int i = 0; i < V; i++) - { - MST_Array[i].visited = false; - MST_Array[i].key = INFINITY; // considering INFINITY as inifinity - MST_Array[i].near = i; - } + for (int i = 0; i < V; i++) + { + MST_Array[i].visited = false; + MST_Array[i].key = INFINITY; // considering INFINITY as inifinity + MST_Array[i].near = i; + } - MST_Array[0].key = 0; + MST_Array[0].key = 0; } void updateNear() { - for (int v = 0; v < V; v++) - { - int min = INFINITY; - int minIndex = 0; - for (int i = 0; i < V; i++) - { - if (MST_Array[i].key < min && MST_Array[i].visited == false && MST_Array[i].key != INFINITY) - { - min = MST_Array[i].key; - minIndex = i; - } - } + for (int v = 0; v < V; v++) + { + int min = INFINITY; + int minIndex = 0; + for (int i = 0; i < V; i++) + { + if (MST_Array[i].key < min && MST_Array[i].visited == false && + MST_Array[i].key != INFINITY) + { + min = MST_Array[i].key; + minIndex = i; + } + } - MST_Array[minIndex].visited = true; + MST_Array[minIndex].visited = true; - for (int i = 0; i < V; i++) - { - if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY) - { - if (graph[minIndex][i] < MST_Array[i].key) - { - MST_Array[i].key = graph[minIndex][i]; - MST_Array[i].near = minIndex; - } - } - } - } + for (int i = 0; i < V; i++) + { + if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY) + { + if (graph[minIndex][i] < MST_Array[i].key) + { + MST_Array[i].key = graph[minIndex][i]; + MST_Array[i].near = minIndex; + } + } + } + } } void show() { - for (int i = 0; i < V; i++) - { - cout << i << " - " << MST_Array[i].near << "\t" << graph[i][MST_Array[i].near] << "\n"; - } + for (int i = 0; i < V; i++) + { + cout << i << " - " << MST_Array[i].near << "\t" + << graph[i][MST_Array[i].near] << "\n"; + } } int main() { - initilize(); - updateNear(); - show(); - return 0; + initilize(); + updateNear(); + show(); + return 0; } diff --git a/hashing/chaining.cpp b/hashing/chaining.cpp index 55aa8961c..ae46aea59 100644 --- a/hashing/chaining.cpp +++ b/hashing/chaining.cpp @@ -1,140 +1,134 @@ -#include #include +#include using namespace std; struct Node { - int data; - struct Node *next; + int data; + struct Node *next; } * head[100], *curr; void init() { - for (int i = 0; i < 100; i++) - head[i] = NULL; + for (int i = 0; i < 100; i++) head[i] = NULL; } void add(int x, int h) { - struct Node *temp = new Node; - temp->data = x; - temp->next = NULL; - if (!head[h]) - { - head[h] = temp; - curr = head[h]; - } - else - { - curr = head[h]; - while (curr->next) - curr = curr->next; - curr->next = temp; - } + struct Node *temp = new Node; + temp->data = x; + temp->next = NULL; + if (!head[h]) + { + head[h] = temp; + curr = head[h]; + } + else + { + curr = head[h]; + while (curr->next) curr = curr->next; + curr->next = temp; + } } void display(int mod) { - struct Node *temp; - int i; - for (i = 0; i < mod; i++) - { - if (!head[i]) - { - cout << "Key " << i << " is empty" << endl; - } - else - { - cout << "Key " << i << " has values = "; - temp = head[i]; - while (temp->next) - { - cout << temp->data << " "; - temp = temp->next; - } - cout << temp->data; - cout << endl; - } - } + struct Node *temp; + int i; + for (i = 0; i < mod; i++) + { + if (!head[i]) + { + cout << "Key " << i << " is empty" << endl; + } + else + { + cout << "Key " << i << " has values = "; + temp = head[i]; + while (temp->next) + { + cout << temp->data << " "; + temp = temp->next; + } + cout << temp->data; + cout << endl; + } + } } -int hash(int x, int mod) -{ - return x % mod; -} +int hash(int x, int mod) { return x % mod; } void find(int x, int h) { - struct Node *temp = head[h]; - if (!head[h]) - { - cout << "Element not found"; - return; - } - while (temp->data != x && temp->next) - temp = temp->next; - if (temp->next) - cout << "Element found"; - else - { - if (temp->data == x) - cout << "Element found"; - else - cout << "Element not found"; - } + struct Node *temp = head[h]; + if (!head[h]) + { + cout << "Element not found"; + return; + } + while (temp->data != x && temp->next) temp = temp->next; + if (temp->next) + cout << "Element found"; + else + { + if (temp->data == x) + cout << "Element found"; + else + cout << "Element not found"; + } } int main(void) { - init(); - int c, x, mod, h; - cout << "Enter the size of Hash Table. = "; - cin >> mod; - bool loop = true; - while (loop) - { - cout << endl; - cout << "PLEASE CHOOSE -" << endl; - cout << "1. Add element." << endl; - cout << "2. Find element." << endl; - cout << "3. Generate Hash." << endl; - cout << "4. Display Hash table." << endl; - cout << "5. Exit." << endl; - cin >> c; - switch (c) - { - case 1: - cout << "Enter element to add = "; - cin >> x; - h = hash(x, mod); - h = fabs(h); - add(x, h); - break; - case 2: - cout << "Enter element to search = "; - cin >> x; - h = hash(x, mod); - find(x, h); - break; - case 3: - cout << "Enter element to generate hash = "; - cin >> x; - cout << "Hash of " << x << " is = " << hash(x, mod); - break; - case 4: - display(mod); - break; - default: - loop = false; - break; - } - cout << endl; - } - /*add(1,&head1); - add(2,&head1); - add(3,&head2); - add(5,&head1); - display(&head1); - display(&head2);*/ - return 0; + init(); + int c, x, mod, h; + cout << "Enter the size of Hash Table. = "; + cin >> mod; + bool loop = true; + while (loop) + { + cout << endl; + cout << "PLEASE CHOOSE -" << endl; + cout << "1. Add element." << endl; + cout << "2. Find element." << endl; + cout << "3. Generate Hash." << endl; + cout << "4. Display Hash table." << endl; + cout << "5. Exit." << endl; + cin >> c; + switch (c) + { + case 1: + cout << "Enter element to add = "; + cin >> x; + h = hash(x, mod); + h = fabs(h); + add(x, h); + break; + case 2: + cout << "Enter element to search = "; + cin >> x; + h = hash(x, mod); + find(x, h); + break; + case 3: + cout << "Enter element to generate hash = "; + cin >> x; + cout << "Hash of " << x << " is = " << hash(x, mod); + break; + case 4: + display(mod); + break; + default: + loop = false; + break; + } + cout << endl; + } + /*add(1,&head1); + add(2,&head1); + add(3,&head2); + add(5,&head1); + display(&head1); + display(&head2);*/ + return 0; } \ No newline at end of file diff --git a/hashing/double_hash_hash_table.cpp b/hashing/double_hash_hash_table.cpp index 6030b7ff3..842f383c5 100644 --- a/hashing/double_hash_hash_table.cpp +++ b/hashing/double_hash_hash_table.cpp @@ -1,13 +1,13 @@ // Copyright 2019 -#include -#include -#include -#include +#include +#include +#include +#include -using std::endl; -using std::cout; using std::cin; +using std::cout; +using std::endl; using std::string; // fwd declarations @@ -25,53 +25,70 @@ int size; bool rehashing; // Node that holds key -struct Entry { +struct Entry +{ explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key -int hashFxn(int key) { +int hashFxn(int key) +{ std::hash hash; return hash(key); } // Used for second hash function -int otherHashFxn(int key) { +int otherHashFxn(int key) +{ std::hash hash; return 1 + (7 - (hash(key) % 7)); } // Performs double hashing to resolve collisions -int doubleHash(int key, bool searching) { +int doubleHash(int key, bool searching) +{ int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; - do { - int index = static_cast(fabs((hash + - (i * otherHashFxn(key))))) % totalSize; + do + { + int index = static_cast(fabs((hash + (i * otherHashFxn(key))))) % + totalSize; entry = table[index]; - if (searching) { - if (entry.key == notPresent) { + if (searching) + { + if (entry.key == notPresent) + { return notPresent; } - if (searchingProber(entry, key)) { + if (searchingProber(entry, key)) + { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; - } else { - if (putProber(entry, key)) { - if (!rehashing) cout << "Spot found!" << endl; + } + else + { + if (putProber(entry, key)) + { + if (!rehashing) + cout << "Spot found!" << endl; return index; } - if (!rehashing) cout << "Spot taken, looking at next (next index:" - << " " << static_cast(fabs((hash + - (i * otherHashFxn(key))))) % totalSize << ")" << endl; + if (!rehashing) + cout << "Spot taken, looking at next (next index:" + << " " + << static_cast( + fabs((hash + (i * otherHashFxn(key))))) % + totalSize + << ")" << endl; i++; } - if (i == totalSize * 100) { + if (i == totalSize * 100) + { cout << "DoubleHash probe failed" << endl; return notPresent; } @@ -80,27 +97,38 @@ int doubleHash(int key, bool searching) { } // Finds empty spot -bool putProber(Entry entry, int key) { - if (entry.key == notPresent || entry.key == tomb) { +bool putProber(Entry entry, int key) +{ + if (entry.key == notPresent || entry.key == tomb) + { return true; } return false; } // Looks for a matching key -bool searchingProber(Entry entry, int key) { - if (entry.key == key) return true; +bool searchingProber(Entry entry, int key) +{ + if (entry.key == key) + return true; return false; } // Displays the table -void display() { - for (int i = 0; i < totalSize; i++) { - if (table[i].key == notPresent) { +void display() +{ + for (int i = 0; i < totalSize; i++) + { + if (table[i].key == notPresent) + { cout << " Empty "; - } else if (table[i].key == tomb) { + } + else if (table[i].key == tomb) + { cout << " Tomb "; - } else { + } + else + { cout << " "; cout << table[i].key; cout << " "; @@ -110,7 +138,8 @@ void display() { } // Rehashes the table into a bigger table -void rehash() { +void rehash() +{ // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; @@ -118,8 +147,10 @@ void rehash() { // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; - for (int i = 0; i < oldSize; i++) { - if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { + for (int i = 0; i < oldSize; i++) + { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) + { size--; // Size stays the same (add increments size) add(oldTable[i].key); } @@ -130,21 +161,25 @@ void rehash() { } // Checks for load factor here -void add(int key) { - Entry * entry = new Entry(); +void add(int key) +{ + Entry* entry = new Entry(); entry->key = key; int index = doubleHash(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size/ static_cast(totalSize) >= 0.5) { + if (++size / static_cast(totalSize) >= 0.5) + { rehash(); } } // Removes key. Leaves tombstone upon removal. -void remove(int key) { +void remove(int key) +{ int index = doubleHash(key, true); - if (index == notPresent) { + if (index == notPresent) + { cout << "key not found" << endl; } table[index].key = tomb; @@ -153,12 +188,13 @@ void remove(int key) { } // Information about the adding process -void addInfo(int key) { +void addInfo(int key) +{ cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) - << " % " << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << fabs(hashFxn(key) % totalSize); cout << endl; add(key); cout << "New table: "; @@ -166,12 +202,13 @@ void addInfo(int key) { } // Information about removal process -void removalInfo(int key) { +void removalInfo(int key) +{ cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) - << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << hashFxn(key) % totalSize; cout << endl; remove(key); cout << "New table: "; @@ -179,13 +216,15 @@ void removalInfo(int key) { } // I/O -int main(void) { +int main(void) +{ int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; - while (loop) { + while (loop) + { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; @@ -196,7 +235,8 @@ int main(void) { cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; - switch (cmd) { + switch (cmd) + { case 1: cout << "Enter key to add = "; cin >> key; @@ -207,11 +247,13 @@ int main(void) { cin >> key; removalInfo(key); break; - case 3: { + case 3: + { cout << "Enter key to search = "; cin >> key; Entry entry = table[doubleHash(key, true)]; - if (entry.key == notPresent) { + if (entry.key == notPresent) + { cout << "Key not present"; } break; diff --git a/hashing/linear_probing_hash_table.cpp b/hashing/linear_probing_hash_table.cpp index b00eb8641..0d4b5b0e1 100644 --- a/hashing/linear_probing_hash_table.cpp +++ b/hashing/linear_probing_hash_table.cpp @@ -1,13 +1,13 @@ // Copyright 2019 -#include -#include -#include -#include +#include +#include +#include +#include -using std::endl; -using std::cout; using std::cin; +using std::cout; +using std::endl; using std::string; // fwd declarations @@ -25,44 +25,57 @@ int size; bool rehashing; // Node that holds key -struct Entry { +struct Entry +{ explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key -int hashFxn(int key) { +int hashFxn(int key) +{ std::hash hash; return hash(key); } // Performs linear probing to resolve collisions -int linearProbe(int key, bool searching) { +int linearProbe(int key, bool searching) +{ int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; - do { + do + { int index = static_cast(fabs((hash + i) % totalSize)); entry = table[index]; - if (searching) { - if (entry.key == notPresent) { + if (searching) + { + if (entry.key == notPresent) + { return notPresent; } - if (searchingProber(entry, key)) { + if (searchingProber(entry, key)) + { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; - } else { - if (putProber(entry, key)) { - if (!rehashing) cout << "Spot found!" << endl; + } + else + { + if (putProber(entry, key)) + { + if (!rehashing) + cout << "Spot found!" << endl; return index; } - if (!rehashing) cout << "Spot taken, looking at next" << endl; + if (!rehashing) + cout << "Spot taken, looking at next" << endl; i++; } - if (i == totalSize) { + if (i == totalSize) + { cout << "Linear probe failed" << endl; return notPresent; } @@ -71,27 +84,38 @@ int linearProbe(int key, bool searching) { } // Finds empty spot -bool putProber(Entry entry, int key) { - if (entry.key == notPresent || entry.key == tomb) { +bool putProber(Entry entry, int key) +{ + if (entry.key == notPresent || entry.key == tomb) + { return true; } return false; } // Looks for a matching key -bool searchingProber(Entry entry, int key) { - if (entry.key == key) return true; +bool searchingProber(Entry entry, int key) +{ + if (entry.key == key) + return true; return false; } // Displays the table -void display() { - for (int i = 0; i < totalSize; i++) { - if (table[i].key == notPresent) { +void display() +{ + for (int i = 0; i < totalSize; i++) + { + if (table[i].key == notPresent) + { cout << " Empty "; - } else if (table[i].key == tomb) { + } + else if (table[i].key == tomb) + { cout << " Tomb "; - } else { + } + else + { cout << " "; cout << table[i].key; cout << " "; @@ -101,7 +125,8 @@ void display() { } // Rehashes the table into a bigger table -void rehash() { +void rehash() +{ // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; @@ -109,8 +134,10 @@ void rehash() { // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; - for (int i = 0; i < oldSize; i++) { - if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { + for (int i = 0; i < oldSize; i++) + { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) + { size--; // Size stays the same (add increments size) add(oldTable[i].key); } @@ -121,21 +148,25 @@ void rehash() { } // Adds entry using linear probing. Checks for load factor here -void add(int key) { - Entry * entry = new Entry(); +void add(int key) +{ + Entry* entry = new Entry(); entry->key = key; int index = linearProbe(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size/ static_cast(totalSize) >= 0.5) { + if (++size / static_cast(totalSize) >= 0.5) + { rehash(); } } // Removes key. Leaves tombstone upon removal. -void remove(int key) { +void remove(int key) +{ int index = linearProbe(key, true); - if (index == notPresent) { + if (index == notPresent) + { cout << "key not found" << endl; } cout << "Removal Successful, leaving tomb" << endl; @@ -144,12 +175,13 @@ void remove(int key) { } // Information about the adding process -void addInfo(int key) { +void addInfo(int key) +{ cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) << " % " - << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << fabs(hashFxn(key) % totalSize); cout << endl; add(key); cout << "New table: "; @@ -157,12 +189,13 @@ void addInfo(int key) { } // Information about removal process -void removalInfo(int key) { +void removalInfo(int key) +{ cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) - << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << hashFxn(key) % totalSize; cout << endl; remove(key); cout << "New table: "; @@ -170,13 +203,15 @@ void removalInfo(int key) { } // I/O -int main(void) { +int main(void) +{ int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; - while (loop) { + while (loop) + { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; @@ -187,7 +222,8 @@ int main(void) { cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; - switch (cmd) { + switch (cmd) + { case 1: cout << "Enter key to add = "; cin >> key; @@ -198,11 +234,13 @@ int main(void) { cin >> key; removalInfo(key); break; - case 3: { + case 3: + { cout << "Enter key to search = "; cin >> key; Entry entry = table[linearProbe(key, true)]; - if (entry.key == notPresent) { + if (entry.key == notPresent) + { cout << "Key not present"; } break; diff --git a/hashing/quadratic_probing_hash_table.cpp b/hashing/quadratic_probing_hash_table.cpp index 44e2e3b9f..b549d057d 100644 --- a/hashing/quadratic_probing_hash_table.cpp +++ b/hashing/quadratic_probing_hash_table.cpp @@ -1,14 +1,14 @@ // Copyright 2019 -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include -using std::endl; -using std::cout; using std::cin; +using std::cout; +using std::endl; using std::string; // fwd declarations @@ -26,49 +26,64 @@ int size; bool rehashing; // Node that holds key -struct Entry { +struct Entry +{ explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key -int hashFxn(int key) { +int hashFxn(int key) +{ std::hash hash; return hash(key); } // Performs quadratic probing to resolve collisions -int quadraticProbe(int key, bool searching) { +int quadraticProbe(int key, bool searching) +{ int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; - do { - int index = std::round(fabs((hash + - static_cast(std::round(std::pow(i, 2)))) % totalSize)); + do + { + int index = std::round(fabs( + (hash + static_cast(std::round(std::pow(i, 2)))) % totalSize)); entry = table[index]; - if (searching) { - if (entry.key == notPresent) { + if (searching) + { + if (entry.key == notPresent) + { return notPresent; } - if (searchingProber(entry, key)) { + if (searchingProber(entry, key)) + { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; - } else { - if (putProber(entry, key)) { - if (!rehashing) cout << "Spot found!" << endl; + } + else + { + if (putProber(entry, key)) + { + if (!rehashing) + cout << "Spot found!" << endl; return index; } - if (!rehashing) { - cout << "Spot taken, looking at next (next index = " << - std::round(fabs((hash + static_cast(std::round( - std::pow(i + 1, 2)))) % totalSize)) << endl; + if (!rehashing) + { + cout << "Spot taken, looking at next (next index = " + << std::round(fabs((hash + static_cast(std::round( + std::pow(i + 1, 2)))) % + totalSize)) + << endl; } i++; } - if (i == totalSize * 100) { + if (i == totalSize * 100) + { cout << "Quadratic probe failed (infinite loop)" << endl; return notPresent; } @@ -77,34 +92,47 @@ int quadraticProbe(int key, bool searching) { } // Finds empty spot -bool putProber(Entry entry, int key) { - if (entry.key == notPresent || entry.key == tomb) { +bool putProber(Entry entry, int key) +{ + if (entry.key == notPresent || entry.key == tomb) + { return true; } return false; } // Looks for a matching key -bool searchingProber(Entry entry, int key) { - if (entry.key == key) return true; +bool searchingProber(Entry entry, int key) +{ + if (entry.key == key) + return true; return false; } // Helper -Entry find(int key) { +Entry find(int key) +{ int index = quadraticProbe(key, true); - if (index == notPresent) return Entry(); + if (index == notPresent) + return Entry(); return table[index]; } // Displays the table -void display() { - for (int i = 0; i < totalSize; i++) { - if (table[i].key == notPresent) { +void display() +{ + for (int i = 0; i < totalSize; i++) + { + if (table[i].key == notPresent) + { cout << " Empty "; - } else if (table[i].key == tomb) { + } + else if (table[i].key == tomb) + { cout << " Tomb "; - } else { + } + else + { cout << " "; cout << table[i].key; cout << " "; @@ -114,7 +142,8 @@ void display() { } // Rehashes the table into a bigger table -void rehash() { +void rehash() +{ // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; @@ -122,8 +151,10 @@ void rehash() { // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; - for (int i = 0; i < oldSize; i++) { - if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { + for (int i = 0; i < oldSize; i++) + { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) + { size--; // Size stays the same (add increments size) add(oldTable[i].key); } @@ -134,21 +165,25 @@ void rehash() { } // Checks for load factor here -void add(int key) { - Entry * entry = new Entry(); +void add(int key) +{ + Entry* entry = new Entry(); entry->key = key; int index = quadraticProbe(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size/ static_cast(totalSize) >= 0.5) { + if (++size / static_cast(totalSize) >= 0.5) + { rehash(); } } // Removes key. Leaves tombstone upon removal. -void remove(int key) { +void remove(int key) +{ int index = quadraticProbe(key, true); - if (index == notPresent) { + if (index == notPresent) + { cout << "key not found" << endl; } table[index].key = tomb; @@ -157,12 +192,13 @@ void remove(int key) { } // Information about the adding process -void addInfo(int key) { +void addInfo(int key) +{ cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) << " % " - << totalSize << " == " << fabs(hashFxn(key) % totalSize); + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << fabs(hashFxn(key) % totalSize); cout << endl; add(key); cout << "New table: "; @@ -170,12 +206,13 @@ void addInfo(int key) { } // Information about removal process -void removalInfo(int key) { +void removalInfo(int key) +{ cout << "Initial table: "; display(); cout << endl; - cout << "hash of " << key << " is " << hashFxn(key) - << " % " << totalSize << " == " << hashFxn(key) % totalSize; + cout << "hash of " << key << " is " << hashFxn(key) << " % " << totalSize + << " == " << hashFxn(key) % totalSize; cout << endl; remove(key); cout << "New table: "; @@ -183,13 +220,15 @@ void removalInfo(int key) { } // I/O -int main(void) { +int main(void) +{ int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; - while (loop) { + while (loop) + { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; @@ -200,7 +239,8 @@ int main(void) { cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; - switch (cmd) { + switch (cmd) + { case 1: cout << "Enter key to add = "; cin >> key; @@ -211,11 +251,13 @@ int main(void) { cin >> key; removalInfo(key); break; - case 3: { + case 3: + { cout << "Enter key to search = "; cin >> key; Entry entry = table[quadraticProbe(key, true)]; - if (entry.key == notPresent) { + if (entry.key == notPresent) + { cout << "Key not present"; } break; diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index 05e6f33f7..7bf3a34a1 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -25,24 +25,32 @@ /// Recursive function to calculate exponent in \f$O(\log(n))\f$ using binary /// exponent. -int binExpo(int a, int b) { - if (b == 0) { +int binExpo(int a, int b) +{ + if (b == 0) + { return 1; } int res = binExpo(a, b / 2); - if (b % 2) { + if (b % 2) + { return res * res * a; - } else { + } + else + { return res * res; } } /// Iterative function to calculate exponent in \f$O(\log(n))\f$ using binary /// exponent. -int binExpo_alt(int a, int b) { +int binExpo_alt(int a, int b) +{ int res = 1; - while (b > 0) { - if (b % 2) { + while (b > 0) + { + if (b % 2) + { res = res * a; } a = a * a; @@ -52,15 +60,21 @@ int binExpo_alt(int a, int b) { } /// Main function -int main() { +int main() +{ int a, b; /// Give two numbers a, b std::cin >> a >> b; - if (a == 0 && b == 0) { + if (a == 0 && b == 0) + { std::cout << "Math error" << std::endl; - } else if (b < 0) { + } + else if (b < 0) + { std::cout << "Exponent must be positive !!" << std::endl; - } else { + } + else + { int resRecurse = binExpo(a, b); /// int resIterate = binExpo_alt(a, b); diff --git a/math/double_factorial.cpp b/math/double_factorial.cpp index 37bd2052a..4909ad489 100644 --- a/math/double_factorial.cpp +++ b/math/double_factorial.cpp @@ -13,10 +13,13 @@ /** Compute double factorial using iterative method */ -uint64_t double_factorial_iterative(uint64_t n) { +uint64_t double_factorial_iterative(uint64_t n) +{ uint64_t res = 1; - for (uint64_t i = n;; i -= 2) { - if (i == 0 || i == 1) return res; + for (uint64_t i = n;; i -= 2) + { + if (i == 0 || i == 1) + return res; res *= i; } return res; @@ -25,13 +28,16 @@ uint64_t double_factorial_iterative(uint64_t n) { /** Compute double factorial using resursive method. *
Recursion can be costly for large numbers. */ -uint64_t double_factorial_recursive(uint64_t n) { - if (n <= 1) return 1; +uint64_t double_factorial_recursive(uint64_t n) +{ + if (n <= 1) + return 1; return n * double_factorial_recursive(n - 2); } /// main function -int main() { +int main() +{ uint64_t n; std::cin >> n; assert(n >= 0); diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp index e7f6fbf7f..283516b42 100644 --- a/math/eulers_totient_function.cpp +++ b/math/eulers_totient_function.cpp @@ -29,26 +29,35 @@ /** Function to caculate Euler's totient phi */ -uint64_t phiFunction(uint64_t n) { +uint64_t phiFunction(uint64_t n) +{ uint64_t result = n; - for (uint64_t i = 2; i * i <= n; i++) { - if (n % i == 0) { - while (n % i == 0) { + for (uint64_t i = 2; i * i <= n; i++) + { + if (n % i == 0) + { + while (n % i == 0) + { n /= i; } result -= result / i; } } - if (n > 1) result -= result / n; + if (n > 1) + result -= result / n; return result; } /// Main function -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ uint64_t n; - if (argc < 2) { + if (argc < 2) + { std::cout << "Enter the number: "; - } else { + } + else + { n = strtoull(argv[1], nullptr, 10); } std::cin >> n; diff --git a/math/extended_euclid_algorithm.cpp b/math/extended_euclid_algorithm.cpp index 3fdae25b5..8a79e0c78 100644 --- a/math/extended_euclid_algorithm.cpp +++ b/math/extended_euclid_algorithm.cpp @@ -21,7 +21,8 @@ * @param[in] quotient unsigned */ template -inline void update_step(T *r, T *r0, const T2 quotient) { +inline void update_step(T *r, T *r0, const T2 quotient) +{ T temp = *r; *r = *r0 - (quotient * temp); *r0 = temp; @@ -38,14 +39,17 @@ inline void update_step(T *r, T *r0, const T2 quotient) { * @param[out] y signed */ template -void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) { - if (B > A) std::swap(A, B); // Ensure that A >= B +void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) +{ + if (B > A) + std::swap(A, B); // Ensure that A >= B T2 s = 0, s0 = 1; T2 t = 1, t0 = 0; T1 r = B, r0 = A; - while (r != 0) { + while (r != 0) + { T1 quotient = r0 / r; update_step(&r, &r0, quotient); update_step(&s, &s0, quotient); @@ -66,14 +70,19 @@ void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) { * @param[in,out] y signed */ template -void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) { - if (B > A) std::swap(A, B); // Ensure that A >= B +void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) +{ + if (B > A) + std::swap(A, B); // Ensure that A >= B - if (B == 0) { + if (B == 0) + { *GCD = A; *x = 1; *y = 0; - } else { + } + else + { extendedEuclid(B, A % B, GCD, x, y); T2 temp = *x; *x = *y; @@ -82,7 +91,8 @@ void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) { } /// Main function -int main() { +int main() +{ uint32_t a, b, gcd; int32_t x, y; std::cin >> a >> b; diff --git a/math/factorial.cpp b/math/factorial.cpp index 353f0b16b..7f50544e2 100644 --- a/math/factorial.cpp +++ b/math/factorial.cpp @@ -5,14 +5,16 @@ #include /** function to find factorial of given number */ -unsigned int factorial(unsigned int n) { +unsigned int factorial(unsigned int n) +{ if (n == 0) return 1; return n * factorial(n - 1); } /** Main function */ -int main() { +int main() +{ int num = 5; std::cout << "Factorial of " << num << " is " << factorial(num) << std::endl; diff --git a/math/fast_power.cpp b/math/fast_power.cpp index d4de07460..8a0525ac1 100644 --- a/math/fast_power.cpp +++ b/math/fast_power.cpp @@ -23,11 +23,14 @@ * algorithm implementation for \f$a^b\f$ */ template -double fast_power_recursive(T a, T b) { +double fast_power_recursive(T a, T b) +{ // negative power. a^b = 1 / (a^-b) - if (b < 0) return 1.0 / fast_power_recursive(a, -b); + if (b < 0) + return 1.0 / fast_power_recursive(a, -b); - if (b == 0) return 1; + if (b == 0) + return 1; T bottom = fast_power_recursive(a, b >> 1); // Since it is integer division b/2 = (b-1)/2 where b is odd. // Therefore, case2 is easily solved by integer division. @@ -45,13 +48,17 @@ double fast_power_recursive(T a, T b) { It still calculates in \f$O(\log N)\f$ */ template -double fast_power_linear(T a, T b) { +double fast_power_linear(T a, T b) +{ // negative power. a^b = 1 / (a^-b) - if (b < 0) return 1.0 / fast_power_linear(a, -b); + if (b < 0) + return 1.0 / fast_power_linear(a, -b); double result = 1; - while (b) { - if (b & 1) result = result * a; + while (b) + { + if (b & 1) + result = result * a; a = a * a; b = b >> 1; } @@ -61,12 +68,14 @@ double fast_power_linear(T a, T b) { /** * Main function */ -int main() { +int main() +{ std::srand(std::time(nullptr)); std::ios_base::sync_with_stdio(false); std::cout << "Testing..." << std::endl; - for (int i = 0; i < 20; i++) { + for (int i = 0; i < 20; i++) + { int a = std::rand() % 20 - 10; int b = std::rand() % 20 - 10; std::cout << std::endl << "Calculating " << a << "^" << b << std::endl; diff --git a/math/fibonacci.cpp b/math/fibonacci.cpp index e15cfc0cc..5a219bbf9 100644 --- a/math/fibonacci.cpp +++ b/math/fibonacci.cpp @@ -14,7 +14,8 @@ /** * Recursively compute sequences */ -int fibonacci(unsigned int n) { +int fibonacci(unsigned int n) +{ /* If the input is 0 or 1 just return the same This will set the first 2 values of the sequence */ if (n <= 1) @@ -25,7 +26,8 @@ int fibonacci(unsigned int n) { } /// Main function -int main() { +int main() +{ int n; std::cin >> n; assert(n >= 0); diff --git a/math/fibonacci_fast.cpp b/math/fibonacci_fast.cpp index 08cced351..3b3a3ca38 100644 --- a/math/fibonacci_fast.cpp +++ b/math/fibonacci_fast.cpp @@ -26,7 +26,8 @@ const uint64_t MAX = 93; uint64_t f[MAX] = {0}; /** Algorithm */ -uint64_t fib(uint64_t n) { +uint64_t fib(uint64_t n) +{ if (n == 0) return 0; if (n == 1 || n == 2) @@ -43,9 +44,11 @@ uint64_t fib(uint64_t n) { } /** Main function */ -int main() { +int main() +{ // Main Function - for (uint64_t i = 1; i < 93; i++) { + for (uint64_t i = 1; i < 93; i++) + { std::cout << i << " th fibonacci number is " << fib(i) << std::endl; } return 0; diff --git a/math/fibonacci_large.cpp b/math/fibonacci_large.cpp index d9dbff799..edc513750 100644 --- a/math/fibonacci_large.cpp +++ b/math/fibonacci_large.cpp @@ -20,11 +20,13 @@ * \f[f(n)=f(n-1)+f(n-2)\f] * and returns the result as a large_number type. */ -large_number fib(uint64_t n) { +large_number fib(uint64_t n) +{ large_number f0(1); large_number f1(1); - do { + do + { large_number f2 = f1; f1 += f0; f0 = f2; @@ -34,11 +36,15 @@ large_number fib(uint64_t n) { return f1; } -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ uint64_t N; - if (argc == 2) { + if (argc == 2) + { N = strtoull(argv[1], NULL, 10); - } else { + } + else + { std::cout << "Enter N: "; std::cin >> N; } diff --git a/math/gcd_iterative_euclidean.cpp b/math/gcd_iterative_euclidean.cpp index 2c0651ad7..e832605d7 100644 --- a/math/gcd_iterative_euclidean.cpp +++ b/math/gcd_iterative_euclidean.cpp @@ -12,27 +12,34 @@ /** * algorithm */ -int gcd(int num1, int num2) { - if (num1 <= 0 | num2 <= 0) { +int gcd(int num1, int num2) +{ + if (num1 <= 0 | num2 <= 0) + { throw std::domain_error("Euclidean algorithm domain is for ints > 0"); } - if (num1 == num2) { + if (num1 == num2) + { return num1; } int base_num = 0; int previous_remainder = 1; - if (num1 > num2) { + if (num1 > num2) + { base_num = num1; previous_remainder = num2; - } else { + } + else + { base_num = num2; previous_remainder = num1; } - while ((base_num % previous_remainder) != 0) { + while ((base_num % previous_remainder) != 0) + { int old_base = base_num; base_num = previous_remainder; previous_remainder = old_base % previous_remainder; @@ -44,11 +51,15 @@ int gcd(int num1, int num2) { /** * Main function */ -int main() { +int main() +{ std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; - try { + try + { std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl; - } catch (const std::domain_error &e) { + } + catch (const std::domain_error &e) + { std::cout << "Error handling was successful" << std::endl; } std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl; diff --git a/math/gcd_of_n_numbers.cpp b/math/gcd_of_n_numbers.cpp index 92968ff12..cd81e6025 100644 --- a/math/gcd_of_n_numbers.cpp +++ b/math/gcd_of_n_numbers.cpp @@ -12,10 +12,12 @@ * @param[in] a array of integers to compute GCD for * @param[in] n number of integers in array `a` */ -int gcd(int *a, int n) { +int gcd(int *a, int n) +{ int j = 1; // to access all elements of the array starting from 1 int gcd = a[0]; - while (j < n) { + while (j < n) + { if (a[j] % gcd == 0) // value of gcd is as needed so far j++; // so we check for next element else @@ -25,7 +27,8 @@ int gcd(int *a, int n) { } /** Main function */ -int main() { +int main() +{ int n; std::cout << "Enter value of n:" << std::endl; std::cin >> n; diff --git a/math/gcd_recursive_euclidean.cpp b/math/gcd_recursive_euclidean.cpp index 2a3d2183c..d16fb1190 100644 --- a/math/gcd_recursive_euclidean.cpp +++ b/math/gcd_recursive_euclidean.cpp @@ -11,12 +11,15 @@ /** * algorithm */ -int gcd(int num1, int num2) { - if (num1 <= 0 | num2 <= 0) { +int gcd(int num1, int num2) +{ + if (num1 <= 0 | num2 <= 0) + { throw std::domain_error("Euclidean algorithm domain is for ints > 0"); } - if (num1 == num2) { + if (num1 == num2) + { return num1; } @@ -39,11 +42,15 @@ int gcd(int num1, int num2) { /** * Main function */ -int main() { +int main() +{ std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; - try { + try + { std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl; - } catch (const std::domain_error &e) { + } + catch (const std::domain_error &e) + { std::cout << "Error handling was successful" << std::endl; } std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl; diff --git a/math/large_factorial.cpp b/math/large_factorial.cpp index 1027f41ab..0a54f620b 100644 --- a/math/large_factorial.cpp +++ b/math/large_factorial.cpp @@ -13,7 +13,8 @@ /** Test implementation for 10! Result must be 3628800. * @returns True if test pass else False */ -bool test1() { +bool test1() +{ std::cout << "---- Check 1\t"; unsigned int i, number = 10; large_number result; @@ -23,15 +24,18 @@ bool test1() { const char *known_reslt = "3628800"; /* check 1 */ - if (strlen(known_reslt) != result.num_digits()) { + if (strlen(known_reslt) != result.num_digits()) + { std::cerr << "Result lengths dont match! " << strlen(known_reslt) << " != " << result.num_digits() << std::endl; return false; } const size_t N = result.num_digits(); - for (i = 0; i < N; i++) { - if (known_reslt[i] != result.digit_char(i)) { + for (i = 0; i < N; i++) + { + if (known_reslt[i] != result.digit_char(i)) + { std::cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result.digit_char(i) << std::endl; return false; @@ -50,7 +54,8 @@ bool test1() { * ``` * @returns True if test pass else False */ -bool test2() { +bool test2() +{ std::cout << "---- Check 2\t"; unsigned int i, number = 100; large_number result; @@ -63,15 +68,18 @@ bool test2() { "000000000000000000"; /* check 1 */ - if (strlen(known_reslt) != result.num_digits()) { + if (strlen(known_reslt) != result.num_digits()) + { std::cerr << "Result lengths dont match! " << strlen(known_reslt) << " != " << result.num_digits() << std::endl; return false; } const size_t N = result.num_digits(); - for (i = 0; i < N; i++) { - if (known_reslt[i] != result.digit_char(i)) { + for (i = 0; i < N; i++) + { + if (known_reslt[i] != result.digit_char(i)) + { std::cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result.digit_char(i) << std::endl; return false; @@ -85,12 +93,16 @@ bool test2() { /** * Main program **/ -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ int number, i; - if (argc == 2) { + if (argc == 2) + { number = atoi(argv[1]); - } else { + } + else + { std::cout << "Enter the value of n(n starts from 0 ): "; std::cin >> number; } diff --git a/math/large_number.h b/math/large_number.h index c1a3665e4..88e3ba802 100644 --- a/math/large_number.h +++ b/math/large_number.h @@ -20,7 +20,8 @@ * digit to the number, perform multiplication of * large number with long unsigned integers. **/ -class large_number { +class large_number +{ public: /**< initializer with value = 1 */ large_number() { _digits.push_back(1); } @@ -35,9 +36,11 @@ class large_number { // } /**< initializer from an integer */ - explicit large_number(int n) { + explicit large_number(int n) + { int carry = n; - do { + do + { add_digit(carry % 10); carry /= 10; } while (carry != 0); @@ -50,8 +53,10 @@ class large_number { explicit large_number(std::vector &vec) : _digits(vec) {} /**< initializer from a string */ - explicit large_number(char const *number_str) { - for (size_t i = strlen(number_str); i > 0; i--) { + explicit large_number(char const *number_str) + { + for (size_t i = strlen(number_str); i > 0; i--) + { unsigned char a = number_str[i - 1] - '0'; if (a >= 0 && a <= 9) _digits.push_back(a); @@ -61,48 +66,55 @@ class large_number { /** * Function to check implementation **/ - static bool test() { + static bool test() + { std::cout << "------ Checking `large_number` class implementations\t" << std::endl; large_number a(40); // 1. test multiplication a *= 10; - if (a != large_number(400)) { + if (a != large_number(400)) + { std::cerr << "\tFailed 1/6 (" << a << "!=400)" << std::endl; return false; } std::cout << "\tPassed 1/6..."; // 2. test compound addition with integer a += 120; - if (a != large_number(520)) { + if (a != large_number(520)) + { std::cerr << "\tFailed 2/6 (" << a << "!=520)" << std::endl; return false; } std::cout << "\tPassed 2/6..."; // 3. test compound multiplication again a *= 10; - if (a != large_number(5200)) { + if (a != large_number(5200)) + { std::cerr << "\tFailed 3/6 (" << a << "!=5200)" << std::endl; return false; } std::cout << "\tPassed 3/6..."; // 4. test increment (prefix) ++a; - if (a != large_number(5201)) { + if (a != large_number(5201)) + { std::cerr << "\tFailed 4/6 (" << a << "!=5201)" << std::endl; return false; } std::cout << "\tPassed 4/6..."; // 5. test increment (postfix) a++; - if (a != large_number(5202)) { + if (a != large_number(5202)) + { std::cerr << "\tFailed 5/6 (" << a << "!=5202)" << std::endl; return false; } std::cout << "\tPassed 5/6..."; // 6. test addition with another large number a = a + large_number("7000000000000000000000000000000"); - if (a != large_number("7000000000000000000000000005202")) { + if (a != large_number("7000000000000000000000000005202")) + { std::cerr << "\tFailed 6/6 (" << a << "!=7000000000000000000000000005202)" << std::endl; return false; @@ -114,8 +126,10 @@ class large_number { /** * add a digit at MSB to the large number **/ - void add_digit(unsigned int value) { - if (value > 9) { + void add_digit(unsigned int value) + { + if (value > 9) + { std::cerr << "digit > 9!!\n"; exit(EXIT_FAILURE); } @@ -135,14 +149,16 @@ class large_number { **/ inline unsigned char &operator[](size_t n) { return this->_digits[n]; } - inline const unsigned char &operator[](size_t n) const { + inline const unsigned char &operator[](size_t n) const + { return this->_digits[n]; } /** * operator overload to compare two numbers **/ - friend std::ostream &operator<<(std::ostream &out, const large_number &a) { + friend std::ostream &operator<<(std::ostream &out, const large_number &a) + { for (size_t i = a.num_digits(); i > 0; i--) out << static_cast(a[i - 1]); return out; @@ -151,7 +167,8 @@ class large_number { /** * operator overload to compare two numbers **/ - friend bool operator==(large_number const &a, large_number const &b) { + friend bool operator==(large_number const &a, large_number const &b) + { size_t N = a.num_digits(); if (N != b.num_digits()) return false; @@ -164,14 +181,16 @@ class large_number { /** * operator overload to compare two numbers **/ - friend bool operator!=(large_number const &a, large_number const &b) { + friend bool operator!=(large_number const &a, large_number const &b) + { return !(a == b); } /** * operator overload to increment (prefix) **/ - large_number &operator++() { + large_number &operator++() + { (*this) += 1; return *this; } @@ -179,7 +198,8 @@ class large_number { /** * operator overload to increment (postfix) **/ - large_number &operator++(int) { + large_number &operator++(int) + { static large_number tmp(_digits); ++(*this); return tmp; @@ -188,13 +208,15 @@ class large_number { /** * operator overload to add **/ - large_number &operator+=(large_number n) { + large_number &operator+=(large_number n) + { // if adding with another large_number large_number *b = reinterpret_cast(&n); const size_t max_L = std::max(this->num_digits(), b->num_digits()); unsigned int carry = 0; size_t i; - for (i = 0; i < max_L || carry != 0; i++) { + for (i = 0; i < max_L || carry != 0; i++) + { if (i < b->num_digits()) carry += (*b)[i]; if (i < this->num_digits()) @@ -216,7 +238,8 @@ class large_number { * operator overload to perform addition **/ template - friend large_number &operator+(const large_number &a, const T &b) { + friend large_number &operator+(const large_number &a, const T &b) + { static large_number c = a; c += b; return c; @@ -225,7 +248,8 @@ class large_number { /** * assignment operator **/ - large_number &operator=(const large_number &b) { + large_number &operator=(const large_number &b) + { this->_digits = b._digits; return *this; } @@ -234,7 +258,8 @@ class large_number { * operator overload to increment **/ template - large_number &operator*=(const T n) { + large_number &operator*=(const T n) + { static_assert(std::is_integral::value, "Must be integer addition unsigned integer types."); this->multiply(n); @@ -244,7 +269,8 @@ class large_number { /** * returns i^th digit as an ASCII character **/ - const char digit_char(size_t i) const { + const char digit_char(size_t i) const + { return _digits[num_digits() - i - 1] + '0'; } @@ -254,7 +280,8 @@ class large_number { * store the result in the same large number **/ template - void multiply(const T n) { + void multiply(const T n) + { static_assert(std::is_integral::value, "Can only have integer types."); // assert(!(std::is_signed::value)); //, "Implemented only for @@ -262,19 +289,24 @@ class large_number { size_t i; uint64_t carry = 0, temp; - for (i = 0; i < this->num_digits(); i++) { + for (i = 0; i < this->num_digits(); i++) + { temp = (*this)[i] * n; temp += carry; - if (temp < 10) { + if (temp < 10) + { carry = 0; - } else { + } + else + { carry = temp / 10; temp = temp % 10; } (*this)[i] = temp; } - while (carry != 0) { + while (carry != 0) + { this->add_digit(carry % 10); carry /= 10; } diff --git a/math/modular_inverse_fermat_little_theorem.cpp b/math/modular_inverse_fermat_little_theorem.cpp index 7550e14bf..6895cafbb 100644 --- a/math/modular_inverse_fermat_little_theorem.cpp +++ b/math/modular_inverse_fermat_little_theorem.cpp @@ -49,11 +49,14 @@ /** Recursive function to calculate exponent in \f$O(\log n)\f$ using binary * exponent. */ -int64_t binExpo(int64_t a, int64_t b, int64_t m) { +int64_t binExpo(int64_t a, int64_t b, int64_t m) +{ a %= m; int64_t res = 1; - while (b > 0) { - if (b % 2) { + while (b > 0) + { + if (b % 2) + { res = res * a % m; } a = a * a % m; @@ -65,12 +68,18 @@ int64_t binExpo(int64_t a, int64_t b, int64_t m) { /** Prime check in \f$O(\sqrt{m})\f$ time. */ -bool isPrime(int64_t m) { - if (m <= 1) { +bool isPrime(int64_t m) +{ + if (m <= 1) + { return false; - } else { - for (int64_t i = 2; i * i <= m; i++) { - if (m % i == 0) { + } + else + { + for (int64_t i = 2; i * i <= m; i++) + { + if (m % i == 0) + { return false; } } @@ -81,17 +90,21 @@ bool isPrime(int64_t m) { /** * Main function */ -int main() { +int main() +{ int64_t a, m; // Take input of a and m. std::cout << "Computing ((a^(-1))%(m)) using Fermat's Little Theorem"; std::cout << std::endl << std::endl; std::cout << "Give input 'a' and 'm' space separated : "; std::cin >> a >> m; - if (isPrime(m)) { + if (isPrime(m)) + { std::cout << "The modular inverse of a with mod m is (a^(m-2)) : "; std::cout << binExpo(a, m - 2, m) << std::endl; - } else { + } + else + { std::cout << "m must be a prime number."; std::cout << std::endl; } diff --git a/math/number_of_positive_divisors.cpp b/math/number_of_positive_divisors.cpp index f157f7b41..beb459943 100644 --- a/math/number_of_positive_divisors.cpp +++ b/math/number_of_positive_divisors.cpp @@ -31,25 +31,31 @@ respectively. /** * Algorithm */ -int number_of_positive_divisors(int n) { +int number_of_positive_divisors(int n) +{ std::vector prime_exponent_count; - for (int i = 2; i * i <= n; i++) { + for (int i = 2; i * i <= n; i++) + { int prime_count = 0; - while (n % i == 0) { + while (n % i == 0) + { prime_count += 1; n /= i; } - if (prime_count != 0) { + if (prime_count != 0) + { prime_exponent_count.push_back(prime_count); } } - if (n > 1) { + if (n > 1) + { prime_exponent_count.push_back(1); } int divisors_count = 1; - for (int i = 0; i < prime_exponent_count.size(); i++) { + for (int i = 0; i < prime_exponent_count.size(); i++) + { divisors_count = divisors_count * (prime_exponent_count[i] + 1); } @@ -59,15 +65,20 @@ int number_of_positive_divisors(int n) { /** * Main function */ -int main() { +int main() +{ int n; std::cin >> n; - if (n < 0) { + if (n < 0) + { n = -n; } - if (n == 0) { + if (n == 0) + { std::cout << "All non-zero numbers are divisors of 0 !" << std::endl; - } else { + } + else + { std::cout << "Number of positive divisors is : "; std::cout << number_of_positive_divisors(n) << std::endl; } diff --git a/math/power_for_huge_numbers.cpp b/math/power_for_huge_numbers.cpp index 301767d66..1f969f89d 100644 --- a/math/power_for_huge_numbers.cpp +++ b/math/power_for_huge_numbers.cpp @@ -22,13 +22,15 @@ * @param res large number representation using array * @param res_size number of digits in `res` */ -int multiply(int x, int res[], int res_size) { +int multiply(int x, int res[], int res_size) +{ // Initialize carry int carry = 0; // One by one multiply n with // individual digits of res[] - for (int i = 0; i < res_size; i++) { + for (int i = 0; i < res_size; i++) + { int prod = res[i] * x + carry; // Store last digit of @@ -41,7 +43,8 @@ int multiply(int x, int res[], int res_size) { // Put carry in res and // increase result size - while (carry) { + while (carry) + { res[res_size] = carry % 10; carry = carry / 10; res_size++; @@ -53,9 +56,11 @@ int multiply(int x, int res[], int res_size) { * @param x base * @param n exponent */ -void power(int x, int n) { +void power(int x, int n) +{ // printing value "1" for power = 0 - if (n == 0) { + if (n == 0) + { std::cout << "1"; return; } @@ -65,7 +70,8 @@ void power(int x, int n) { int temp = x; // Initialize result - while (temp != 0) { + while (temp != 0) + { res[res_size++] = temp % 10; temp = temp / 10; } @@ -79,7 +85,8 @@ void power(int x, int n) { } /** Main function */ -int main() { +int main() +{ int exponent, base; std::cout << "Enter base "; std::cin >> base; diff --git a/math/prime_factorization.cpp b/math/prime_factorization.cpp index d0e05cb4c..c650497e2 100644 --- a/math/prime_factorization.cpp +++ b/math/prime_factorization.cpp @@ -20,44 +20,55 @@ std::vector> factors; /** Calculating prime number upto a given range */ -void SieveOfEratosthenes(int N) { +void SieveOfEratosthenes(int N) +{ // initializes the array isprime memset(isprime, true, sizeof isprime); - for (int i = 2; i <= N; i++) { - if (isprime[i]) { + for (int i = 2; i <= N; i++) + { + if (isprime[i]) + { for (int j = 2 * i; j <= N; j += i) isprime[j] = false; } } - for (int i = 2; i <= N; i++) { - if (isprime[i]) prime_numbers.push_back(i); + for (int i = 2; i <= N; i++) + { + if (isprime[i]) + prime_numbers.push_back(i); } } /** Prime factorization of a number */ -void prime_factorization(int num) { +void prime_factorization(int num) +{ int number = num; - for (int i = 0; prime_numbers[i] <= num; i++) { + for (int i = 0; prime_numbers[i] <= num; i++) + { int count = 0; // termination condition - if (number == 1) { + if (number == 1) + { break; } - while (number % prime_numbers[i] == 0) { + while (number % prime_numbers[i] == 0) + { count++; number = number / prime_numbers[i]; } - if (count) factors.push_back(std::make_pair(prime_numbers[i], count)); + if (count) + factors.push_back(std::make_pair(prime_numbers[i], count)); } } /** Main program */ -int main() { +int main() +{ int num; std::cout << "\t\tComputes the prime factorization\n\n"; std::cout << "Type in a number: "; @@ -68,7 +79,8 @@ int main() { prime_factorization(num); // Prime factors with their powers in the given number in new line - for (auto it : factors) { + for (auto it : factors) + { std::cout << it.first << " " << it.second << std::endl; } diff --git a/math/prime_numbers.cpp b/math/prime_numbers.cpp index 4dd54f136..b3a52a104 100644 --- a/math/prime_numbers.cpp +++ b/math/prime_numbers.cpp @@ -9,12 +9,15 @@ /** Generate an increasingly large number of primes * and store in a list */ -std::vector primes(int max) { +std::vector primes(int max) +{ max++; std::vector res; std::vector numbers(max, false); - for (int i = 2; i < max; i++) { - if (!numbers[i]) { + for (int i = 2; i < max; i++) + { + if (!numbers[i]) + { for (int j = i; j < max; j += i) numbers[j] = true; res.push_back(i); } @@ -23,7 +26,8 @@ std::vector primes(int max) { } /** main function */ -int main() { +int main() +{ std::cout << "Calculate primes up to:\n>> "; int n; std::cin >> n; diff --git a/math/primes_up_to_billion.cpp b/math/primes_up_to_billion.cpp index 4fb79a15e..6c02b9089 100644 --- a/math/primes_up_to_billion.cpp +++ b/math/primes_up_to_billion.cpp @@ -10,12 +10,15 @@ char prime[100000000]; /** Perform Sieve algorithm */ -void Sieve(int64_t n) { +void Sieve(int64_t n) +{ memset(prime, '1', sizeof(prime)); // intitize '1' to every index prime[0] = '0'; // 0 is not prime prime[1] = '0'; // 1 is not prime - for (int p = 2; p * p <= n; p++) { - if (prime[p] == '1') { + for (int p = 2; p * p <= n; p++) + { + if (prime[p] == '1') + { for (int i = p * p; i <= n; i += p) prime[i] = '0'; // set all multiples of p to false } @@ -23,7 +26,8 @@ void Sieve(int64_t n) { } /** Main function */ -int main() { +int main() +{ Sieve(100000000); int64_t n; std::cin >> n; // 10006187 diff --git a/math/sieve_of_eratosthenes.cpp b/math/sieve_of_eratosthenes.cpp index d8fa70531..90ad8bc40 100644 --- a/math/sieve_of_eratosthenes.cpp +++ b/math/sieve_of_eratosthenes.cpp @@ -22,12 +22,16 @@ bool isprime[MAX]; * This is the function that finds the primes and eliminates * the multiples. */ -void sieve(uint32_t N) { +void sieve(uint32_t N) +{ isprime[0] = false; isprime[1] = false; - for (uint32_t i = 2; i <= N; i++) { - if (isprime[i]) { - for (uint32_t j = (i << 1); j <= N; j += i) { + for (uint32_t i = 2; i <= N; i++) + { + if (isprime[i]) + { + for (uint32_t j = (i << 1); j <= N; j += i) + { isprime[j] = false; } } @@ -37,9 +41,12 @@ void sieve(uint32_t N) { /** * This function prints out the primes to STDOUT */ -void print(uint32_t N) { - for (uint32_t i = 1; i <= N; i++) { - if (isprime[i]) { +void print(uint32_t N) +{ + for (uint32_t i = 1; i <= N; i++) + { + if (isprime[i]) + { std::cout << i << ' '; } } @@ -49,14 +56,17 @@ void print(uint32_t N) { /** * Initialize the array */ -void init() { - for (uint32_t i = 1; i < MAX; i++) { +void init() +{ + for (uint32_t i = 1; i < MAX; i++) + { isprime[i] = true; } } /** main function */ -int main() { +int main() +{ uint32_t N = 100; init(); sieve(N); diff --git a/math/sqrt_double.cpp b/math/sqrt_double.cpp index 1521b500a..ffc83998a 100644 --- a/math/sqrt_double.cpp +++ b/math/sqrt_double.cpp @@ -13,8 +13,10 @@ /** Bisection method implemented for the function \f$x^2-a=0\f$ * whose roots are \f$\pm\sqrt{a}\f$ and only the positive root is returned. */ -double Sqrt(double a) { - if (a > 0 && a < 1) { +double Sqrt(double a) +{ + if (a > 0 && a < 1) + { return 1 / Sqrt(1 / a); } double l = 0, r = a; @@ -24,12 +26,17 @@ double Sqrt(double a) { double epsilon = 1e-12; */ double epsilon = 1e-12; - while (l <= r) { + while (l <= r) + { double mid = (l + r) / 2; - if (mid * mid > a) { + if (mid * mid > a) + { r = mid; - } else { - if (a - mid * mid < epsilon) { + } + else + { + if (a - mid * mid < epsilon) + { return mid; } l = mid; @@ -39,7 +46,8 @@ double Sqrt(double a) { } /** main function */ -int main() { +int main() +{ double n{}; std::cin >> n; assert(n >= 0); diff --git a/math/string_fibonacci.cpp b/math/string_fibonacci.cpp index eb9b6d7e1..401b04d2d 100644 --- a/math/string_fibonacci.cpp +++ b/math/string_fibonacci.cpp @@ -21,41 +21,50 @@ * \param [in] b second number in string to add * \returns sum as a std::string */ -std::string add(std::string a, std::string b) { +std::string add(std::string a, std::string b) +{ std::string temp = ""; // carry flag int carry = 0; // fills up with zeros - while (a.length() < b.length()) { + while (a.length() < b.length()) + { a = "0" + a; } // fills up with zeros - while (b.length() < a.length()) { + while (b.length() < a.length()) + { b = "0" + b; } // adds the numbers a and b - for (int i = a.length() - 1; i >= 0; i--) { + for (int i = a.length() - 1; i >= 0; i--) + { char val = static_cast(((a[i] - 48) + (b[i] - 48)) + 48 + carry); - if (val > 57) { + if (val > 57) + { carry = 1; val -= 10; - } else { + } + else + { carry = 0; } temp = val + temp; } // processes the carry flag - if (carry == 1) { + if (carry == 1) + { temp = "1" + temp; } // removes leading zeros. - while (temp[0] == '0' && temp.length() > 1) { + while (temp[0] == '0' && temp.length() > 1) + { temp = temp.substr(1); } @@ -65,11 +74,13 @@ std::string add(std::string a, std::string b) { /** Fibonacci iterator * \param [in] n n^th Fibonacci number */ -void fib_Accurate(uint64_t n) { +void fib_Accurate(uint64_t n) +{ std::string tmp = ""; std::string fibMinus1 = "1"; std::string fibMinus2 = "0"; - for (uint64_t i = 0; i < n; i++) { + for (uint64_t i = 0; i < n; i++) + { tmp = add(fibMinus1, fibMinus2); fibMinus2 = fibMinus1; fibMinus1 = tmp; @@ -78,7 +89,8 @@ void fib_Accurate(uint64_t n) { } /** main function */ -int main() { +int main() +{ int n; std::cout << "Enter whatever number N you want to find the fibonacci of\n"; std::cin >> n; diff --git a/operations_on_datastructures/array_left_rotation.cpp b/operations_on_datastructures/array_left_rotation.cpp index 9eb5d4e50..444738360 100644 --- a/operations_on_datastructures/array_left_rotation.cpp +++ b/operations_on_datastructures/array_left_rotation.cpp @@ -2,38 +2,38 @@ using namespace std; int main() { - int n, k; - cout << "Enter size of array=\t"; - cin >> n; - cout << "Enter Number of indeces u want to rotate the array to left=\t"; - cin >> k; - int a[n]; - cout << "Enter elements of array=\t"; - for (int i = 0; i < n; i++) - { - cin >> a[i]; - } - int temp = 0; - for (int i = 0; i < k; i++) - { - temp = a[0]; - for (int j = 0; j < n; j++) - { - if (j == n - 1) - { - a[n - 1] = temp; - } - else - { - a[j] = a[j + 1]; - } - } - } - cout << "Your rotated array is=\t"; - for (int j = 0; j < n; j++) - { - cout << a[j] << " "; - } - getchar(); - return 0; + int n, k; + cout << "Enter size of array=\t"; + cin >> n; + cout << "Enter Number of indeces u want to rotate the array to left=\t"; + cin >> k; + int a[n]; + cout << "Enter elements of array=\t"; + for (int i = 0; i < n; i++) + { + cin >> a[i]; + } + int temp = 0; + for (int i = 0; i < k; i++) + { + temp = a[0]; + for (int j = 0; j < n; j++) + { + if (j == n - 1) + { + a[n - 1] = temp; + } + else + { + a[j] = a[j + 1]; + } + } + } + cout << "Your rotated array is=\t"; + for (int j = 0; j < n; j++) + { + cout << a[j] << " "; + } + getchar(); + return 0; } diff --git a/operations_on_datastructures/array_right_rotation.cpp b/operations_on_datastructures/array_right_rotation.cpp index 81875766c..5077d2d74 100644 --- a/operations_on_datastructures/array_right_rotation.cpp +++ b/operations_on_datastructures/array_right_rotation.cpp @@ -9,8 +9,7 @@ int main() cin >> k; int a[n]; cout << "Enter elements of array=\t"; - for (int i = 0; i < n; i++) - cin >> a[i]; + for (int i = 0; i < n; i++) cin >> a[i]; int temp = 0; for (int i = 0; i < k; i++) { diff --git a/operations_on_datastructures/circular_linked_list.cpp b/operations_on_datastructures/circular_linked_list.cpp index d360f6cd7..2fddd3b7b 100644 --- a/operations_on_datastructures/circular_linked_list.cpp +++ b/operations_on_datastructures/circular_linked_list.cpp @@ -3,112 +3,112 @@ using namespace std; struct node { - int val; - node *next; + int val; + node *next; }; node *start; void insert(int x) { - node *t = start; + node *t = start; - if (start != NULL) - { - while (t->next != start) - { - t = t->next; - } - node *n = new node; - t->next = n; - n->val = x; - n->next = start; - } - else - { - node *n = new node; - n->val = x; - start = n; - n->next = start; - } + if (start != NULL) + { + while (t->next != start) + { + t = t->next; + } + node *n = new node; + t->next = n; + n->val = x; + n->next = start; + } + else + { + node *n = new node; + n->val = x; + start = n; + n->next = start; + } } void remove(int x) { - node *t = start; - node *p; - while (t->val != x) - { - p = t; - t = t->next; - } - p->next = t->next; - delete t; + node *t = start; + node *p; + while (t->val != x) + { + p = t; + t = t->next; + } + p->next = t->next; + delete t; } void search(int x) { - node *t = start; - int found = 0; - while (t->next != start) - { - if (t->val == x) - { - cout << "\nFound"; - found = 1; - break; - } - t = t->next; - } - if (found == 0) - { - cout << "\nNot Found"; - } + node *t = start; + int found = 0; + while (t->next != start) + { + if (t->val == x) + { + cout << "\nFound"; + found = 1; + break; + } + t = t->next; + } + if (found == 0) + { + cout << "\nNot Found"; + } } void show() { - node *t = start; - do - { - cout << t->val << "\t"; - t = t->next; - } while (t != start); + node *t = start; + do + { + cout << t->val << "\t"; + t = t->next; + } while (t != start); } int main() { - int choice, x; - do - { - cout << "\n1. Insert"; - cout << "\n2. Delete"; - cout << "\n3. Search"; - cout << "\n4. Print"; - cout << "\n\nEnter you choice : "; - cin >> choice; - switch (choice) - { - case 1: - cout << "\nEnter the element to be inserted : "; - cin >> x; - insert(x); - break; - case 2: - cout << "\nEnter the element to be removed : "; - cin >> x; - remove(x); - break; - case 3: - cout << "\nEnter the element to be searched : "; - cin >> x; - search(x); - break; - case 4: - show(); - break; - } - } while (choice != 0); + int choice, x; + do + { + cout << "\n1. Insert"; + cout << "\n2. Delete"; + cout << "\n3. Search"; + cout << "\n4. Print"; + cout << "\n\nEnter you choice : "; + cin >> choice; + switch (choice) + { + case 1: + cout << "\nEnter the element to be inserted : "; + cin >> x; + insert(x); + break; + case 2: + cout << "\nEnter the element to be removed : "; + cin >> x; + remove(x); + break; + case 3: + cout << "\nEnter the element to be searched : "; + cin >> x; + search(x); + break; + case 4: + show(); + break; + } + } while (choice != 0); - return 0; + return 0; } diff --git a/operations_on_datastructures/circular_queue_using_array.cpp b/operations_on_datastructures/circular_queue_using_array.cpp index 36d7e22c3..cf6e39dd5 100644 --- a/operations_on_datastructures/circular_queue_using_array.cpp +++ b/operations_on_datastructures/circular_queue_using_array.cpp @@ -8,67 +8,66 @@ int count = 0; void Enque(int x) { - if (count == 10) - { - cout << "\nOverflow"; - } - else - { - queue[rear] = x; - rear = (rear + 1) % 10; - count++; - } + if (count == 10) + { + cout << "\nOverflow"; + } + else + { + queue[rear] = x; + rear = (rear + 1) % 10; + count++; + } } void Deque() { - if (front == rear) - { - cout << "\nUnderflow"; - } + if (front == rear) + { + cout << "\nUnderflow"; + } - else - { - cout << "\n" - << queue[front] << " deleted"; - front = (front + 1) % 10; - count--; - } + else + { + cout << "\n" << queue[front] << " deleted"; + front = (front + 1) % 10; + count--; + } } void show() { - for (int i = 0; i < count; i++) - { - cout << queue[(i + front) % 10] << "\t"; - } + for (int i = 0; i < count; i++) + { + cout << queue[(i + front) % 10] << "\t"; + } } int main() { - int ch, x; - do - { - cout << "\n1. Enque"; - cout << "\n2. Deque"; - cout << "\n3. Print"; - cout << "\nEnter Your Choice : "; - cin >> ch; - if (ch == 1) - { - cout << "\nInsert : "; - cin >> x; - Enque(x); - } - else if (ch == 2) - { - Deque(); - } - else if (ch == 3) - { - show(); - } - } while (ch != 0); + int ch, x; + do + { + cout << "\n1. Enque"; + cout << "\n2. Deque"; + cout << "\n3. Print"; + cout << "\nEnter Your Choice : "; + cin >> ch; + if (ch == 1) + { + cout << "\nInsert : "; + cin >> x; + Enque(x); + } + else if (ch == 2) + { + Deque(); + } + else if (ch == 3) + { + show(); + } + } while (ch != 0); - return 0; + return 0; } diff --git a/operations_on_datastructures/get_size_of_linked_list.cpp b/operations_on_datastructures/get_size_of_linked_list.cpp index 84f8db07f..0f22967c2 100644 --- a/operations_on_datastructures/get_size_of_linked_list.cpp +++ b/operations_on_datastructures/get_size_of_linked_list.cpp @@ -1,6 +1,7 @@ #include -class Node { +class Node +{ public: int val; Node *next; @@ -8,19 +9,23 @@ class Node { Node(int v, Node *n) : val(v), next(n) {} // Default constructor for Node }; -int getSize(Node *root) { - if (root == NULL) { +int getSize(Node *root) +{ + if (root == NULL) + { return 0; } // Each node will return 1 so the total adds up to be the size return 1 + getSize(root->next); } -int main() { +int main() +{ Node *myList = new Node(0, NULL); // Initializes the LinkedList Node *temp = myList; // Creates a linked lists of total size 10, numbered 1 - 10 - for (int i = 1; i < 10; i++) { + for (int i = 1; i < 10; i++) + { temp->next = new Node(i, NULL); temp = temp->next; } diff --git a/operations_on_datastructures/intersection_of_2_arrays.cpp b/operations_on_datastructures/intersection_of_2_arrays.cpp index 05652811f..df83c9f21 100644 --- a/operations_on_datastructures/intersection_of_2_arrays.cpp +++ b/operations_on_datastructures/intersection_of_2_arrays.cpp @@ -1,31 +1,29 @@ #include int main() { - int i, j, m, n; - cout << "Enter size of array 1:"; - cin >> m; - cout << "Enter size of array 2:"; - cin >> n; - int a[m]; - int b[n]; - cout << "Enter elements of array 1:"; - for (i = 0; i < m; i++) - cin >> a[i]; - for (i = 0; i < n; i++) - cin >> b[i]; - i = 0; - j = 0; - while ((i < m) && (j < n)) - { - if (a[i] < b[j]) - i++; - else if (a[i] > b[j]) - j++; - else + int i, j, m, n; + cout << "Enter size of array 1:"; + cin >> m; + cout << "Enter size of array 2:"; + cin >> n; + int a[m]; + int b[n]; + cout << "Enter elements of array 1:"; + for (i = 0; i < m; i++) cin >> a[i]; + for (i = 0; i < n; i++) cin >> b[i]; + i = 0; + j = 0; + while ((i < m) && (j < n)) { - cout << a[i++] << " "; - j++; + if (a[i] < b[j]) + i++; + else if (a[i] > b[j]) + j++; + else + { + cout << a[i++] << " "; + j++; + } } - } - return 0; + return 0; } diff --git a/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp b/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp index 0908080cc..4fe6d2915 100644 --- a/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp +++ b/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp @@ -3,74 +3,74 @@ using namespace std; struct node { - int val; - node *next; + int val; + node *next; }; node *start; void insert(int x) { - node *t = start; - if (start != NULL) - { - while (t->next != NULL) - { - t = t->next; - } - node *n = new node; - t->next = n; - n->val = x; - n->next = NULL; - } - else - { - node *n = new node; - n->val = x; - n->next = NULL; - start = n; - } + node *t = start; + if (start != NULL) + { + while (t->next != NULL) + { + t = t->next; + } + node *n = new node; + t->next = n; + n->val = x; + n->next = NULL; + } + else + { + node *n = new node; + n->val = x; + n->next = NULL; + start = n; + } } void reverse(node *p, node *q) { - if (q->next == NULL) - { - q->next = p; - p->next = NULL; - start = q; - return; - } - else - { - reverse(q, q->next); - q->next = p; - p->next = NULL; - } + if (q->next == NULL) + { + q->next = p; + p->next = NULL; + start = q; + return; + } + else + { + reverse(q, q->next); + q->next = p; + p->next = NULL; + } } void show() { - node *t = start; - while (t != NULL) - { - cout << t->val << "\t"; - t = t->next; - } + node *t = start; + while (t != NULL) + { + cout << t->val << "\t"; + t = t->next; + } } int main() { - insert(1); - insert(2); - insert(3); - insert(4); - insert(5); - insert(6); + insert(1); + insert(2); + insert(3); + insert(4); + insert(5); + insert(6); - reverse(start, start->next); + reverse(start, start->next); - show(); + show(); - return 0; + return 0; } diff --git a/operations_on_datastructures/selectionsortlinkedlist.cpp b/operations_on_datastructures/selectionsortlinkedlist.cpp index 52363ceff..550928d01 100644 --- a/operations_on_datastructures/selectionsortlinkedlist.cpp +++ b/operations_on_datastructures/selectionsortlinkedlist.cpp @@ -1,10 +1,10 @@ #include using namespace std; -//node defined +// node defined class node { -public: + public: int data; node *link; node(int d) @@ -14,7 +14,7 @@ public: } }; -//printing the linked list +// printing the linked list void print(node *head) { node *current = head; @@ -26,7 +26,7 @@ void print(node *head) cout << endl; } -//creating the linked list with 'n' nodes +// creating the linked list with 'n' nodes node *createlist(int n) { node *head = NULL; @@ -50,51 +50,71 @@ node *createlist(int n) return head; } -//performing selection sort on the linked list in an iterative manner +// performing selection sort on the linked list in an iterative manner void my_selection_sort_linked_list(node *&head) { - node *min = head; //throughout the algorithm 'min' is used to denote the node with min value out of all the nodes left for scanning - //while scanning if we find a node 'X' with value lesser than min, - //then we update the pointers in such a way that 'X' becomes the predecessor of 'min' - node *current = min->link; // 'current' refers to the current node we are scanning - node *previous = min; //'previous' refers to the node that is previous to the current node - node *temp = NULL; // 'temp' in this algo is used to point to the last node of the sorted part of the linked list. - //eg. If at any time instance the state of the linked list is suppose 1->2->5->3->8->NULL - //then, we see that "1->2" is the sorted part of the LL, and therefore temp will be pointing to the last node of the sorted part,i.e,'2' - //We keep on arranging the Linked list in such a way that after each iteration the node with 'min' value is placed at its correct position. - //Eg. Let suppose initially we have 5->4->1->3->2->NULL - //After 1st iteration : 1->4->5->3->2->NULL and so on + node *min = head; // throughout the algorithm 'min' is used to denote the + // node with min value out of all the nodes left for + // scanning while scanning if we find a node 'X' with + // value lesser than min, then we update the pointers in + // such a way that 'X' becomes the predecessor of 'min' + node *current = + min->link; // 'current' refers to the current node we are scanning + node *previous = min; //'previous' refers to the node that is previous to + //the current node + node *temp = + NULL; // 'temp' in this algo is used to point to the last node of the + // sorted part of the linked list. + // eg. If at any time instance the state of the linked list is + // suppose 1->2->5->3->8->NULL then, we see that "1->2" is the + // sorted part of the LL, and therefore temp will be pointing to + // the last node of the sorted part,i.e,'2' We keep on arranging + // the Linked list in such a way that after each iteration the + // node with 'min' value is placed at its correct position. Eg. + // Let suppose initially we have 5->4->1->3->2->NULL After 1st + // iteration : 1->4->5->3->2->NULL and so on - while (min->link != NULL) //so that all the nodes are scanned or until there exists a node + while ( + min->link != + NULL) // so that all the nodes are scanned or until there exists a node { - //pick the first node from the unsorted part and assume that it is the minimum and then start scanning from the next node + // pick the first node from the unsorted part and assume that it is the + // minimum and then start scanning from the next node - while (current != NULL) //suppose you choose the min node to be X, then scan starts from the (X+1)th node until its NULL. current = (X+1)th node and min = X + while (current != NULL) // suppose you choose the min node to be X, + // then scan starts from the (X+1)th node until + // its NULL. current = (X+1)th node and min = X { - if (current->data < min->data) //if the current node is smaller than the presumed node 'min' + if (current->data < min->data) // if the current node is smaller + // than the presumed node 'min' { - if (temp == NULL) //temp stays null for the first iteration, therefore it symbolizes that we are scanning for the first time + if (temp == NULL) // temp stays null for the first iteration, + // therefore it symbolizes that we are + // scanning for the first time { - if (previous == min) //if the 'previous' is pointing to the 'min' node + if (previous == + min) // if the 'previous' is pointing to the 'min' node { - //Update the pointers - head = current; //update the head pointer with the current node + // Update the pointers + head = current; // update the head pointer with the + // current node min->link = current->link; current->link = previous; min = current; current = previous->link; } - else //if the 'previous' is not pointing to the 'min' node + else // if the 'previous' is not pointing to the 'min' node { - //Update the pointers - head = current; //update the head pointer with the current node + // Update the pointers + head = current; // update the head pointer with the + // current node previous->link = current->link; current->link = min; min = current; current = previous->link; } } - else //if 'temp' is not NULL, i.e., its not the 1st iteration + else // if 'temp' is not NULL, i.e., its not the 1st iteration { temp->link = current; previous->link = current->link; @@ -103,15 +123,17 @@ void my_selection_sort_linked_list(node *&head) current = previous->link; } } - else //if the current node is greater than min, just move the previous and the current pointer a step further + else // if the current node is greater than min, just move the + // previous and the current pointer a step further { previous = previous->link; current = current->link; } } - //update the pointers. Set 'temp' to the last node in the sorted part. Make 'min' move a step further so that 'min' points to the 1st node of the unsorted part - //start the iteration again + // update the pointers. Set 'temp' to the last node in the sorted part. + // Make 'min' move a step further so that 'min' points to the 1st node of + // the unsorted part start the iteration again temp = min; min = min->link; previous = min; @@ -145,15 +167,16 @@ int main() { node *head = NULL; int n; - cout << "enter the no. of nodes : "; //taking input from user about the number of nodes in linked list + cout << "enter the no. of nodes : "; // taking input from user about the + // number of nodes in linked list cin >> n; if (n == 0) return 0; - head = createlist(n); //creating the list + head = createlist(n); // creating the list cout << "original list is : "; - print(head); //printing the original linked list - my_selection_sort_linked_list(head); //applying selection sort + print(head); // printing the original linked list + my_selection_sort_linked_list(head); // applying selection sort cout << "sorted list is : "; - print(head); //printing the sorted linked list + print(head); // printing the sorted linked list return 0; } \ No newline at end of file diff --git a/operations_on_datastructures/union_of_2_arrays.cpp b/operations_on_datastructures/union_of_2_arrays.cpp index aaaeb8378..45845f341 100644 --- a/operations_on_datastructures/union_of_2_arrays.cpp +++ b/operations_on_datastructures/union_of_2_arrays.cpp @@ -1,34 +1,30 @@ #include int main() { - int m, n, i = 0, j = 0; - cout << "Enter size of both arrays:"; - cin >> m >> n; - int a[m]; - int b[n]; - cout << "Enter elements of array 1:"; - for (i = 0; i < m; i++) - cin >> a[i]; - cout << "Enter elements of array 2:"; - for (i = 0; i < n; i++) - cin >> b[i]; - i = 0; - j = 0; - while ((i < m) && (j < n)) - { - if (a[i] < b[j]) - cout << a[i++] << " "; - else if (a[i] > b[j]) - cout << b[j++] << " "; - else + int m, n, i = 0, j = 0; + cout << "Enter size of both arrays:"; + cin >> m >> n; + int a[m]; + int b[n]; + cout << "Enter elements of array 1:"; + for (i = 0; i < m; i++) cin >> a[i]; + cout << "Enter elements of array 2:"; + for (i = 0; i < n; i++) cin >> b[i]; + i = 0; + j = 0; + while ((i < m) && (j < n)) { - cout << a[i++]; - j++; + if (a[i] < b[j]) + cout << a[i++] << " "; + else if (a[i] > b[j]) + cout << b[j++] << " "; + else + { + cout << a[i++]; + j++; + } } - } - while (i < m) - cout << a[i++] << " "; - while (j < n) - cout << b[j++] << " "; - return 0; + while (i < m) cout << a[i++] << " "; + while (j < n) cout << b[j++] << " "; + return 0; } diff --git a/others/buzz_number.cpp b/others/buzz_number.cpp index ed9fc5f28..712b79401 100644 --- a/others/buzz_number.cpp +++ b/others/buzz_number.cpp @@ -6,10 +6,12 @@ #include /** main function */ -int main() { +int main() +{ int n, t; std::cin >> t; - while (t--) { + while (t--) + { std::cin >> n; if ((n % 7 == 0) || (n % 10 == 7)) std::cout << n << " is a buzz number" << std::endl; diff --git a/others/decimal_to_binary.cpp b/others/decimal_to_binary.cpp index 11ce064a5..32616944f 100644 --- a/others/decimal_to_binary.cpp +++ b/others/decimal_to_binary.cpp @@ -8,10 +8,12 @@ * This method converts the bit representation and stores it as a decimal * number. */ -void method1(int number) { +void method1(int number) +{ int remainder, binary = 0, var = 1; - do { + do + { remainder = number % 2; number = number / 2; binary = binary + (remainder * var); @@ -24,11 +26,13 @@ void method1(int number) { * This method stores each bit value from LSB to MSB and then prints them back * from MSB to LSB */ -void method2(int number) { +void method2(int number) +{ int num_bits = 0; char bit_string[50]; - do { + do + { bool bit = number & 0x01; // get last bit if (bit) bit_string[num_bits++] = '1'; @@ -43,7 +47,8 @@ void method2(int number) { std::cout << std::endl; } -int main() { +int main() +{ int number; std::cout << "Enter a number:"; std::cin >> number; diff --git a/others/decimal_to_hexadecimal.cpp b/others/decimal_to_hexadecimal.cpp index a3e544f49..f0a521db6 100644 --- a/others/decimal_to_hexadecimal.cpp +++ b/others/decimal_to_hexadecimal.cpp @@ -8,7 +8,8 @@ /** * Main program */ -int main(void) { +int main(void) +{ int valueToConvert = 0; // Holds user input int hexArray[8]; // Contains hex values backwards int i = 0; // counter @@ -19,7 +20,8 @@ int main(void) { std::cin >> valueToConvert; // Stores value into valueToConvert via user input - while (valueToConvert > 15) { // Dec to Hex Algorithm + while (valueToConvert > 15) + { // Dec to Hex Algorithm hexArray[i++] = valueToConvert % 16; // Gets remainder valueToConvert /= 16; // valueToConvert >>= 4; // This will divide by 2^4=16 and is faster diff --git a/others/decimal_to_roman_numeral.cpp b/others/decimal_to_roman_numeral.cpp index 6bd1be395..fbcbaa232 100644 --- a/others/decimal_to_roman_numeral.cpp +++ b/others/decimal_to_roman_numeral.cpp @@ -12,7 +12,8 @@ /** This functions fills a string with character c, n times and returns it * @note This can probably be replace by `memcpy` function. */ -std::string fill(char c, int n) { +std::string fill(char c, int n) +{ std::string s = ""; while (n--) s += c; return s; @@ -21,51 +22,76 @@ std::string fill(char c, int n) { /** to convert to lowercase Roman Numeral * the function works recursively */ -std::string tolowerRoman(int n) { - if (n < 4) return fill('i', n); - if (n < 6) return fill('i', 5 - n) + "v"; - if (n < 9) return std::string("v") + fill('i', n - 5); - if (n < 11) return fill('i', 10 - n) + "x"; - if (n < 40) return fill('x', n / 10) + tolowerRoman(n % 10); - if (n < 60) return fill('x', 5 - n / 10) + 'l' + tolowerRoman(n % 10); +std::string tolowerRoman(int n) +{ + if (n < 4) + return fill('i', n); + if (n < 6) + return fill('i', 5 - n) + "v"; + if (n < 9) + return std::string("v") + fill('i', n - 5); + if (n < 11) + return fill('i', 10 - n) + "x"; + if (n < 40) + return fill('x', n / 10) + tolowerRoman(n % 10); + if (n < 60) + return fill('x', 5 - n / 10) + 'l' + tolowerRoman(n % 10); if (n < 90) return std::string("l") + fill('x', n / 10 - 5) + tolowerRoman(n % 10); - if (n < 110) return fill('x', 10 - n / 10) + "c" + tolowerRoman(n % 10); - if (n < 400) return fill('c', n / 100) + tolowerRoman(n % 100); - if (n < 600) return fill('c', 5 - n / 100) + 'd' + tolowerRoman(n % 100); + if (n < 110) + return fill('x', 10 - n / 10) + "c" + tolowerRoman(n % 10); + if (n < 400) + return fill('c', n / 100) + tolowerRoman(n % 100); + if (n < 600) + return fill('c', 5 - n / 100) + 'd' + tolowerRoman(n % 100); if (n < 900) return std::string("d") + fill('c', n / 100 - 5) + tolowerRoman(n % 100); - if (n < 1100) return fill('c', 10 - n / 100) + "m" + tolowerRoman(n % 100); - if (n < 4000) return fill('m', n / 1000) + tolowerRoman(n % 1000); + if (n < 1100) + return fill('c', 10 - n / 100) + "m" + tolowerRoman(n % 100); + if (n < 4000) + return fill('m', n / 1000) + tolowerRoman(n % 1000); return "?"; } /** to convert to uppercase Roman Numeral * the function works recursively */ -std::string toupperRoman(int n) { - if (n < 4) return fill('I', n); - if (n < 6) return fill('I', 5 - n) + "V"; - if (n < 9) return std::string("V") + fill('I', n - 5); - if (n < 11) return fill('I', 10 - n) + "X"; - if (n < 40) return fill('X', n / 10) + toupperRoman(n % 10); - if (n < 60) return fill('X', 5 - n / 10) + 'L' + toupperRoman(n % 10); +std::string toupperRoman(int n) +{ + if (n < 4) + return fill('I', n); + if (n < 6) + return fill('I', 5 - n) + "V"; + if (n < 9) + return std::string("V") + fill('I', n - 5); + if (n < 11) + return fill('I', 10 - n) + "X"; + if (n < 40) + return fill('X', n / 10) + toupperRoman(n % 10); + if (n < 60) + return fill('X', 5 - n / 10) + 'L' + toupperRoman(n % 10); if (n < 90) return std::string("L") + fill('X', n / 10 - 5) + toupperRoman(n % 10); - if (n < 110) return fill('X', 10 - n / 10) + "C" + toupperRoman(n % 10); - if (n < 400) return fill('C', n / 100) + toupperRoman(n % 100); - if (n < 600) return fill('C', 5 - n / 100) + 'D' + toupperRoman(n % 100); + if (n < 110) + return fill('X', 10 - n / 10) + "C" + toupperRoman(n % 10); + if (n < 400) + return fill('C', n / 100) + toupperRoman(n % 100); + if (n < 600) + return fill('C', 5 - n / 100) + 'D' + toupperRoman(n % 100); if (n < 900) return std::string("D") + fill('C', n / 100 - 5) + toupperRoman(n % 100); - if (n < 1100) return fill('C', 10 - n / 100) + "M" + toupperRoman(n % 100); - if (n < 4000) return fill('M', n / 1000) + toupperRoman(n % 1000); + if (n < 1100) + return fill('C', 10 - n / 100) + "M" + toupperRoman(n % 100); + if (n < 4000) + return fill('M', n / 1000) + toupperRoman(n % 1000); return "?"; } /** main function */ -int main() { +int main() +{ int n; std::cout << "\t\tRoman numbers converter\n\n"; std::cout << "Type in decimal number between 0 up to 4000 (exclusive): "; diff --git a/others/fast_interger_input.cpp b/others/fast_interger_input.cpp index 5e7bcb99d..a71e807dd 100644 --- a/others/fast_interger_input.cpp +++ b/others/fast_interger_input.cpp @@ -8,7 +8,8 @@ /** Function to read the number from stdin. The function reads input until a non * numeric character is entered. */ -void fastinput(int *number) { +void fastinput(int *number) +{ // variable to indicate sign of input integer bool negative = false; register int c; @@ -16,7 +17,8 @@ void fastinput(int *number) { // extract current character from buffer c = std::getchar(); - if (c == '-') { + if (c == '-') + { // number is negative negative = true; @@ -31,11 +33,13 @@ void fastinput(int *number) { // if scanned input has a negative sign, negate the // value of the input number - if (negative) *(number) *= -1; + if (negative) + *(number) *= -1; } /** Main function */ -int main() { +int main() +{ int number; fastinput(&number); std::cout << number << std::endl; diff --git a/others/happy_number.cpp b/others/happy_number.cpp index b1debaa54..494891e3b 100644 --- a/others/happy_number.cpp +++ b/others/happy_number.cpp @@ -11,10 +11,13 @@ * \returns true if happy else false */ template -bool is_happy(T n) { - T s = 0; // stores sum of digits - while (n > 9) { // while number is > 9, there are more than 1 digit - while (n != 0) { // get digit +bool is_happy(T n) +{ + T s = 0; // stores sum of digits + while (n > 9) + { // while number is > 9, there are more than 1 digit + while (n != 0) + { // get digit T d = n % 10; s += d; n /= 10; @@ -26,7 +29,8 @@ bool is_happy(T n) { } /** Main function */ -int main() { +int main() +{ int n; std::cout << "Enter a number:"; std::cin >> n; diff --git a/others/matrix_exponentiation.cpp b/others/matrix_exponentiation.cpp index d44d22593..78daca8ec 100644 --- a/others/matrix_exponentiation.cpp +++ b/others/matrix_exponentiation.cpp @@ -58,11 +58,15 @@ vector a, b, c; * \result matrix of dimension (m\f$\times\f$q) */ vector> multiply(const vector> &A, - const vector> &B) { + const vector> &B) +{ vector> C(k + 1, vector(k + 1)); - for (ll i = 1; i <= k; i++) { - for (ll j = 1; j <= k; j++) { - for (ll z = 1; z <= k; z++) { + for (ll i = 1; i <= k; i++) + { + for (ll j = 1; j <= k; j++) + { + for (ll z = 1; z <= k; z++) + { C[i][j] = (C[i][j] + (A[i][z] * B[z][j]) % MOD) % MOD; } } @@ -76,12 +80,16 @@ vector> multiply(const vector> &A, * \param [in] p exponent * \return matrix of same dimension as A */ -vector> power(const vector> &A, ll p) { +vector> power(const vector> &A, ll p) +{ if (p == 1) return A; - if (p % 2 == 1) { + if (p % 2 == 1) + { return multiply(A, power(A, p - 1)); - } else { + } + else + { vector> X = power(A, p / 2); return multiply(X, X); } @@ -91,7 +99,8 @@ vector> power(const vector> &A, ll p) { * \param[in] n \f$n^\text{th}\f$ Fibonacci number * \return \f$n^\text{th}\f$ Fibonacci number */ -ll ans(ll n) { +ll ans(ll n) +{ if (n == 0) return 0; if (n <= k) @@ -102,9 +111,12 @@ ll ans(ll n) { // Transpose matrix vector> T(k + 1, vector(k + 1)); - for (ll i = 1; i <= k; i++) { - for (ll j = 1; j <= k; j++) { - if (i < k) { + for (ll i = 1; i <= k; i++) + { + for (ll j = 1; j <= k; j++) + { + if (i < k) + { if (j == i + 1) T[i][j] = 1; else @@ -119,26 +131,31 @@ ll ans(ll n) { // T*F1 ll res = 0; - for (ll i = 1; i <= k; i++) { + for (ll i = 1; i <= k; i++) + { res = (res + (T[1][i] * F1[i]) % MOD) % MOD; } return res; } /** Main function */ -int main() { +int main() +{ cin.tie(0); cout.tie(0); ll t; cin >> t; ll i, j, x; - while (t--) { + while (t--) + { cin >> k; - for (i = 0; i < k; i++) { + for (i = 0; i < k; i++) + { cin >> x; b.pb(x); } - for (i = 0; i < k; i++) { + for (i = 0; i < k; i++) + { cin >> x; c.pb(x); } diff --git a/others/palindrome_of_number.cpp b/others/palindrome_of_number.cpp index 66401ff96..d6ed3fc70 100644 --- a/others/palindrome_of_number.cpp +++ b/others/palindrome_of_number.cpp @@ -16,7 +16,8 @@ #endif /** Main function */ -int main() { +int main() +{ int num; std::cout << "Enter number = "; std::cin >> num; diff --git a/others/paranthesis_matching.cpp b/others/paranthesis_matching.cpp index ef5da6e47..95a9e1100 100644 --- a/others/paranthesis_matching.cpp +++ b/others/paranthesis_matching.cpp @@ -33,41 +33,53 @@ char pop() { return stack[top--]; } /** return opening paranthesis corresponding to the close paranthesis * @param[in] ch closed paranthesis character */ -char opening(char ch) { - switch (ch) { - case '}': - return '{'; - case ']': - return '['; - case ')': - return '('; - case '>': - return '<'; +char opening(char ch) +{ + switch (ch) + { + case '}': + return '{'; + case ']': + return '['; + case ')': + return '('; + case '>': + return '<'; } return '\0'; } -int main() { +int main() +{ std::string exp; int valid = 1, i = 0; std::cout << "Enter The Expression : "; std::cin >> exp; - while (valid == 1 && i < exp.length()) { - if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<') { + while (valid == 1 && i < exp.length()) + { + if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<') + { push(exp[i]); - } else if (top >= 0 && stack[top] == opening(exp[i])) { + } + else if (top >= 0 && stack[top] == opening(exp[i])) + { pop(); - } else { + } + else + { valid = 0; } i++; } // makes sure the stack is empty after processsing (above) - if (valid == 1 && top == -1) { + if (valid == 1 && top == -1) + { std::cout << "\nCorrect Expression"; - } else { + } + else + { std::cout << "\nWrong Expression"; } diff --git a/others/pascal_triangle.cpp b/others/pascal_triangle.cpp index 4ea58f3f1..814b9a142 100644 --- a/others/pascal_triangle.cpp +++ b/others/pascal_triangle.cpp @@ -15,9 +15,12 @@ * \param [in] arr 2D-array containing Pascal numbers * \param [in] n depth of Pascal triangle to print */ -void show_pascal(int **arr, int n) { - for (int i = 0; i < n; ++i) { - for (int j = 0; j < n + i; ++j) { +void show_pascal(int **arr, int n) +{ + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < n + i; ++j) + { if (arr[i][j] == 0) std::cout << std::setw(4) << " "; else @@ -33,9 +36,12 @@ void show_pascal(int **arr, int n) { * \param [in] n depth of Pascal triangle to print * \result arr pointer returned */ -int **pascal_triangle(int **arr, int n) { - for (int i = 0; i < n; ++i) { - for (int j = n - i - 1; j < n + i; ++j) { +int **pascal_triangle(int **arr, int n) +{ + for (int i = 0; i < n; ++i) + { + for (int j = n - i - 1; j < n + i; ++j) + { if (j == n - i - 1 || j == n + i - 1) arr[i][j] = 1; // The edge of the Pascal triangle goes in 1 else @@ -49,7 +55,8 @@ int **pascal_triangle(int **arr, int n) { /** * main function */ -int main() { +int main() +{ int n = 0; std::cout << "Set Pascal's Triangle Height" << std::endl; @@ -57,7 +64,8 @@ int main() { // memory allocation (Assign two-dimensional array to store Pascal triangle) int **arr = new int *[n]; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { arr[i] = new int[2 * n - 1]; memset(arr[i], 0, sizeof(int) * (2 * n - 1)); } @@ -66,7 +74,8 @@ int main() { show_pascal(arr, n); // deallocation - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { delete[] arr[i]; } delete[] arr; diff --git a/others/primality_test.cpp b/others/primality_test.cpp index faec6589c..16700ec4a 100644 --- a/others/primality_test.cpp +++ b/others/primality_test.cpp @@ -15,12 +15,14 @@ * \param[in] number number to check * \returns true if prime else false */ -bool IsPrime(int number) { +bool IsPrime(int number) +{ if (((!(number & 1)) && number != 2) || (number < 2) || (number % 3 == 0 && number != 3)) return false; - for (int k = 1; 36 * k * k - 12 * k < number; ++k) { + for (int k = 1; 36 * k * k - 12 * k < number; ++k) + { if ((number % (6 * k + 1) == 0) || (number % (6 * k - 1) == 0)) return false; } @@ -28,7 +30,8 @@ bool IsPrime(int number) { } /** main function */ -int main() { +int main() +{ // Main Function std::cout << "Enter the value of n to check if Prime\n"; int n; diff --git a/others/smallest_circle.cpp b/others/smallest_circle.cpp index 9ee4353eb..5842a33c8 100644 --- a/others/smallest_circle.cpp +++ b/others/smallest_circle.cpp @@ -12,7 +12,8 @@ #include /** Define a point */ -struct Point { +struct Point +{ double x, /**< abscissa */ y; /**< ordinate */ @@ -20,7 +21,8 @@ struct Point { * \param [in] a absicca (default = 0.0) * \param [in] b ordinate (default = 0.0) */ - explicit Point(double a = 0.f, double b = 0.f) { + explicit Point(double a = 0.f, double b = 0.f) + { x = a; y = b; } @@ -34,7 +36,8 @@ struct Point { * \param [in] B point B * \return ditance */ -double LenghtLine(const Point &A, const Point &B) { +double LenghtLine(const Point &A, const Point &B) +{ double dx = B.x - A.x; double dy = B.y - A.y; return std::sqrt((dx * dx) + (dy * dy)); @@ -51,7 +54,8 @@ double LenghtLine(const Point &A, const Point &B) { * \param [in] C vertex C * \returns area of triangle */ -double TriangleArea(const Point &A, const Point &B, const Point &C) { +double TriangleArea(const Point &A, const Point &B, const Point &C) +{ double a = LenghtLine(A, B); double b = LenghtLine(B, C); double c = LenghtLine(C, A); @@ -69,8 +73,10 @@ double TriangleArea(const Point &A, const Point &B, const Point &C) { * \returns True if P lies on or within the circle * \returns False if P lies outside the circle */ -bool PointInCircle(const std::vector &P, const Point &Center, double R) { - for (size_t i = 0; i < P.size(); i++) { +bool PointInCircle(const std::vector &P, const Point &Center, double R) +{ + for (size_t i = 0; i < P.size(); i++) + { if (LenghtLine(P[i], Center) > R) return false; } @@ -84,7 +90,8 @@ bool PointInCircle(const std::vector &P, const Point &Center, double R) { * \param [in] P vector of points * \returns radius of the circle */ -double circle(const std::vector &P) { +double circle(const std::vector &P) +{ double minR = INFINITY; double R; Point C; @@ -96,7 +103,8 @@ double circle(const std::vector &P) { // for every subsequent point in the list for (size_t j = i + 1; j < P.size(); j++) // for every subsequent point in the list - for (size_t k = j + 1; k < P.size(); k++) { + for (size_t k = j + 1; k < P.size(); k++) + { // here, we now have picked three points from the given set of // points that we can use // viz., P[i], P[j] and P[k] @@ -121,10 +129,12 @@ double circle(const std::vector &P) { R = (LenghtLine(P[i], P[j]) * LenghtLine(P[j], P[k]) * LenghtLine(P[k], P[i])) / (4 * TriangleArea(P[i], P[j], P[k])); - if (!PointInCircle(P, C, R)) { + if (!PointInCircle(P, C, R)) + { continue; } - if (R <= minR) { + if (R <= minR) + { minR = R; minC = C; } @@ -133,15 +143,18 @@ double circle(const std::vector &P) { // for each point in the list for (size_t i = 0; i < P.size() - 1; i++) // for every subsequent point in the list - for (size_t j = i + 1; j < P.size(); j++) { + for (size_t j = i + 1; j < P.size(); j++) + { // check for diameterically opposite points C.x = (P[i].x + P[j].x) / 2; C.y = (P[i].y + P[j].y) / 2; R = LenghtLine(C, P[i]); - if (!PointInCircle(P, C, R)) { + if (!PointInCircle(P, C, R)) + { continue; } - if (R <= minR) { + if (R <= minR) + { minR = R; minC = C; } @@ -155,7 +168,8 @@ double circle(const std::vector &P) { * \n radius 3.318493136080724 * \n centre at (3.0454545454545454, 1.3181818181818181) */ -void test() { +void test() +{ std::vector Pv; Pv.push_back(Point(0, 0)); Pv.push_back(Point(5, 4)); @@ -170,7 +184,8 @@ void test() { * \n radius 1.4142135623730951 * \n centre at (1.0, 1.0) */ -void test2() { +void test2() +{ std::vector Pv; Pv.push_back(Point(0, 0)); Pv.push_back(Point(0, 2)); @@ -185,7 +200,8 @@ void test2() { * \n centre at (2.142857142857143, 1.7857142857142856) * @todo This test fails */ -void test3() { +void test3() +{ std::vector Pv; Pv.push_back(Point(0.5, 1)); Pv.push_back(Point(3.5, 3)); @@ -195,7 +211,8 @@ void test3() { } /** Main program */ -int main() { +int main() +{ test(); std::cout << std::endl; test2(); diff --git a/others/sparse_matrix.cpp b/others/sparse_matrix.cpp index a358f0da4..5662e065d 100644 --- a/others/sparse_matrix.cpp +++ b/others/sparse_matrix.cpp @@ -6,7 +6,8 @@ #include /** main function */ -int main() { +int main() +{ int m, n; int counterZeros = 0; @@ -21,16 +22,20 @@ int main() { std::cout << "\n"; // reads the matrix from stdin - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { std::cout << "element? "; std::cin >> a[i][j]; } } // counts the zero's - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { if (a[i][j] == 0) counterZeros++; // Counting number of zeroes } diff --git a/others/spiral_print.cpp b/others/spiral_print.cpp index 02dc3183a..da92e6937 100644 --- a/others/spiral_print.cpp +++ b/others/spiral_print.cpp @@ -9,10 +9,13 @@ * \param [in] r number of rows * \param [in] c number of columns */ -void genArray(int **a, int r, int c) { +void genArray(int **a, int r, int c) +{ int value = 1; - for (int i = 0; i < r; i++) { - for (int j = 0; j < c; j++) { + for (int i = 0; i < r; i++) + { + for (int j = 0; j < c; j++) + { a[i][j] = value; std::cout << a[i][j] << " "; value++; @@ -26,39 +29,47 @@ void genArray(int **a, int r, int c) { * \param [in] r number of rows * \param [in] c number of columns */ -void spiralPrint(int **a, int r, int c) { +void spiralPrint(int **a, int r, int c) +{ int startRow = 0, endRow = r - 1; int startCol = 0, endCol = c - 1; int cnt = 0; - while (startRow <= endRow && startCol <= endCol) { + while (startRow <= endRow && startCol <= endCol) + { /// Print start row - for (int i = startCol; i <= endCol; i++, cnt++) { + for (int i = startCol; i <= endCol; i++, cnt++) + { std::cout << a[startRow][i] << " "; } startRow++; /// Print the end col - for (int i = startRow; i <= endRow; i++, cnt++) { + for (int i = startRow; i <= endRow; i++, cnt++) + { std::cout << a[i][endCol] << " "; } endCol--; /// Print the end row - if (cnt == r * c) { + if (cnt == r * c) + { break; } - for (int i = endCol; i >= startCol; i--, cnt++) { + for (int i = endCol; i >= startCol; i--, cnt++) + { std::cout << a[endRow][i] << " "; } endRow--; /// Print the start Col - if (cnt == r * c) { + if (cnt == r * c) + { break; } - for (int i = endRow; i >= startRow; i--, cnt++) { + for (int i = endRow; i >= startRow; i--, cnt++) + { std::cout << a[i][startCol] << " "; } startCol++; @@ -66,7 +77,8 @@ void spiralPrint(int **a, int r, int c) { } /** main function */ -int main() { +int main() +{ int r, c; std::cin >> r >> c; int **a = new int *[r]; diff --git a/others/stairs_pattern.cpp b/others/stairs_pattern.cpp index a3b8b0a44..bfd90dd10 100644 --- a/others/stairs_pattern.cpp +++ b/others/stairs_pattern.cpp @@ -14,18 +14,23 @@ where number of pairs line is given by user #include /** main function */ -int main() { +int main() +{ int l, st = 2, x, r, z, n, sp; std::cout << "enter Index "; std::cin >> x; z = x; - for (r = 1; r <= x; r++) { + for (r = 1; r <= x; r++) + { z = z - 1; - for (n = 1; n <= 2; n++) { - for (sp = 1; sp <= z; sp++) { + for (n = 1; n <= 2; n++) + { + for (sp = 1; sp <= z; sp++) + { std::cout << " "; } - for (l = 1; l <= st; l++) { + for (l = 1; l <= st; l++) + { std::cout << "*"; } std::cout << std::endl; diff --git a/others/tower_of_hanoi.cpp b/others/tower_of_hanoi.cpp index 323b2e424..3a832248f 100644 --- a/others/tower_of_hanoi.cpp +++ b/others/tower_of_hanoi.cpp @@ -8,7 +8,8 @@ /** * Define the state of tower */ -struct tower { +struct tower +{ //! Values in the tower int values[10]; //! top tower ID @@ -17,17 +18,21 @@ struct tower { /** Display the towers */ void show(const struct tower *const F, const struct tower *const T, - const struct tower *const U) { + const struct tower *const U) +{ std::cout << "\n\n\tF : "; - for (int i = 0; i < F->top; i++) { + for (int i = 0; i < F->top; i++) + { std::cout << F->values[i] << "\t"; } std::cout << "\n\tU : "; - for (int i = 0; i < U->top; i++) { + for (int i = 0; i < U->top; i++) + { std::cout << U->values[i] << "\t"; } std::cout << "\n\tT : "; - for (int i = 0; i < T->top; i++) { + for (int i = 0; i < T->top; i++) + { std::cout << T->values[i] << "\t"; } } @@ -36,7 +41,8 @@ void show(const struct tower *const F, const struct tower *const T, * \param [in,out] From tower to move disk *from* * \param [in,out] To tower to move disk *to* */ -void mov(tower *From, tower *To) { +void mov(tower *From, tower *To) +{ --From->top; To->values[To->top] = From->values[From->top]; ++To->top; @@ -49,11 +55,15 @@ void mov(tower *From, tower *To) { * \param [in,out] Using temporary tower for the puzzle * \param [in,out] To tower to move disk to */ -void TH(int n, tower *From, tower *Using, tower *To) { - if (n == 1) { +void TH(int n, tower *From, tower *Using, tower *To) +{ + if (n == 1) + { mov(From, To); show(From, To, Using); - } else { + } + else + { TH(n - 1, From, To, Using); mov(From, To); show(From, To, Using); @@ -62,7 +72,8 @@ void TH(int n, tower *From, tower *Using, tower *To) { } /** Main function */ -int main() { +int main() +{ struct tower F, U, T; F.top = 0; @@ -74,7 +85,8 @@ int main() { std::cout << "\nEnter number of discs : "; std::cin >> no; - for (int i = no; i > 0; i--) { + for (int i = no; i > 0; i--) + { F.values[F.top++] = i; } diff --git a/others/vector_important_functions.cpp b/others/vector_important_functions.cpp index d23ff9c97..765f6a8e5 100644 --- a/others/vector_important_functions.cpp +++ b/others/vector_important_functions.cpp @@ -8,7 +8,8 @@ #include /** Main function */ -int main() { +int main() +{ // Initializing vector with array values int arr[] = {10, 20, 5, 23, 42, 15}; int n = sizeof(arr) / sizeof(arr[0]); diff --git a/probability/addition_rule.cpp b/probability/addition_rule.cpp index 780951489..0666b29e6 100644 --- a/probability/addition_rule.cpp +++ b/probability/addition_rule.cpp @@ -11,7 +11,8 @@ * \parama [in] B probability of event B * \returns probability of A and B */ -double addition_rule_independent(double A, double B) { +double addition_rule_independent(double A, double B) +{ return (A + B) - (A * B); } @@ -22,12 +23,14 @@ double addition_rule_independent(double A, double B) { * \parama [in] B_given_A probability of event B condition A * \returns probability of A and B */ -double addition_rule_dependent(double A, double B, double B_given_A) { +double addition_rule_dependent(double A, double B, double B_given_A) +{ return (A + B) - (A * B_given_A); } /** Main function */ -int main() { +int main() +{ double A = 0.5; double B = 0.25; double B_given_A = 0.05; diff --git a/probability/bayes_theorem.cpp b/probability/bayes_theorem.cpp index aaa557a94..632611fe5 100644 --- a/probability/bayes_theorem.cpp +++ b/probability/bayes_theorem.cpp @@ -11,19 +11,22 @@ /** returns P(A|B) */ -double bayes_AgivenB(double BgivenA, double A, double B) { +double bayes_AgivenB(double BgivenA, double A, double B) +{ return (BgivenA * A) / B; } /** returns P(B|A) */ -double bayes_BgivenA(double AgivenB, double A, double B) { +double bayes_BgivenA(double AgivenB, double A, double B) +{ return (AgivenB * B) / A; } /** Main function */ -int main() { +int main() +{ double A = 0.01; double B = 0.1; double BgivenA = 0.9; diff --git a/probability/binomial_dist.cpp b/probability/binomial_dist.cpp index 1f30c5048..4d2e90842 100644 --- a/probability/binomial_dist.cpp +++ b/probability/binomial_dist.cpp @@ -33,7 +33,8 @@ double binomial_variance(double n, double p) { return n * p * (1 - p); } * \param [in] p * \returns \f$\sigma = \sqrt{\sigma^2} = \sqrt{n\cdot p\cdot (1-p)}\f$ */ -double binomial_standard_deviation(double n, double p) { +double binomial_standard_deviation(double n, double p) +{ return std::sqrt(binomial_variance(n, p)); } @@ -44,15 +45,18 @@ double binomial_standard_deviation(double n, double p) { * \frac{n!}{r!(n-r)!} = \frac{n\times(n-1)\times(n-2)\times\cdots(n-r)}{r!} * \f$ */ -double nCr(double n, double r) { +double nCr(double n, double r) +{ double numerator = n; double denominator = r; - for (int i = n - 1; i >= ((n - r) + 1); i--) { + for (int i = n - 1; i >= ((n - r) + 1); i--) + { numerator *= i; } - for (int i = 1; i < r; i++) { + for (int i = 1; i < r; i++) + { denominator *= i; } @@ -62,7 +66,8 @@ double nCr(double n, double r) { /** calculates the probability of exactly x successes * \returns \f$\displaystyle P(n,p,x) = {n\choose x} p^x (1-p)^{n-x}\f$ */ -double binomial_x_successes(double n, double p, double x) { +double binomial_x_successes(double n, double p, double x) +{ return nCr(n, x) * std::pow(p, x) * std::pow(1 - p, n - x); } @@ -72,16 +77,19 @@ double binomial_x_successes(double n, double p, double x) { * =\sum_{i=x_0}^{x_1} {n\choose i} p^i (1-p)^{n-i}\f$ */ double binomial_range_successes(double n, double p, double lower_bound, - double upper_bound) { + double upper_bound) +{ double probability = 0; - for (int i = lower_bound; i <= upper_bound; i++) { + for (int i = lower_bound; i <= upper_bound; i++) + { probability += nCr(n, i) * std::pow(p, i) * std::pow(1 - p, n - i); } return probability; } /** main function */ -int main() { +int main() +{ std::cout << "expected value : " << binomial_expected(100, 0.5) << std::endl; diff --git a/probability/poisson_dist.cpp b/probability/poisson_dist.cpp index 6a2a377c3..428ee903f 100644 --- a/probability/poisson_dist.cpp +++ b/probability/poisson_dist.cpp @@ -14,7 +14,8 @@ * calculate the events per unit time\n * e.g 5 dollars every 2 mins = 5 / 2 = 2.5 */ -double poisson_rate(double events, double timeframe) { +double poisson_rate(double events, double timeframe) +{ return events / timeframe; } @@ -27,13 +28,16 @@ double poisson_expected(double rate, double time) { return rate * time; } /** * Compute factorial of a given number */ -double fact(double x) { +double fact(double x) +{ double x_fact = x; - for (int i = x - 1; i > 0; i--) { + for (int i = x - 1; i > 0; i--) + { x_fact *= i; } - if (x_fact <= 0) { + if (x_fact <= 0) + { x_fact = 1; } return x_fact; @@ -43,7 +47,8 @@ double fact(double x) { * Find the probability of x successes in a Poisson dist. * \f[p(\mu,x) = \frac{\mu^x e^{-\mu}}{x!}\f] */ -double poisson_x_successes(double expected, double x) { +double poisson_x_successes(double expected, double x) +{ return (std::pow(expected, x) * std::exp(-expected)) / fact(x); } @@ -51,9 +56,11 @@ double poisson_x_successes(double expected, double x) { * probability of a success in range for Poisson dist (inclusive, inclusive) * \f[P = \sum_i p(\mu,i)\f] */ -double poisson_range_successes(double expected, double lower, double upper) { +double poisson_range_successes(double expected, double lower, double upper) +{ double probability = 0; - for (int i = lower; i <= upper; i++) { + for (int i = lower; i <= upper; i++) + { probability += poisson_x_successes(expected, i); } return probability; @@ -62,7 +69,8 @@ double poisson_range_successes(double expected, double lower, double upper) { /** * main function */ -int main() { +int main() +{ double rate, expected; rate = poisson_rate(3, 1); std::cout << "Poisson rate : " << rate << std::endl; diff --git a/range_queries/bit.cpp b/range_queries/bit.cpp index e5e36ed24..19141b7f5 100644 --- a/range_queries/bit.cpp +++ b/range_queries/bit.cpp @@ -7,22 +7,18 @@ class Bit { int n; vector bit; - inline int offset(int x) + inline int offset(int x) { return (x & (-x)); } + + public: + Bit(vector& arr) { - return (x & (-x)); - } - - public: - - Bit(vector& arr) - { - n = arr.size(); - bit.assign(n + 1, 0); - for (int i = 0; i < n; ++i) - { - update(i, arr[i]); - } + n = arr.size(); + bit.assign(n + 1, 0); + for (int i = 0; i < n; ++i) + { + update(i, arr[i]); } + } Bit(int x) { n = x; @@ -34,7 +30,7 @@ class Bit // Add val at id id++; while (id <= n) - { + { bit[id] += val; id += offset(id); } @@ -46,23 +42,20 @@ class Bit id++; int res = 0; while (id > 0) - { + { res += bit[id]; id -= offset(id); } return res; } - int sum_range(int l, int r) - { - return sum(r) - sum(l - 1); - } + int sum_range(int l, int r) { return sum(r) - sum(l - 1); } }; int main() { int n = 5; - vector arr = { 1, 2, 3, 4, 5 }; + vector arr = {1, 2, 3, 4, 5}; Bit x(arr); assert(x.sum_range(0, 0) == 1); @@ -72,5 +65,5 @@ int main() assert(x.sum_range(0, 0) == 6); assert(x.sum_range(0, 1) == 8); assert(x.sum_range(0, 2) == 11); - return 0; + return 0; } diff --git a/range_queries/fenwicktree.cpp b/range_queries/fenwicktree.cpp index a4d1a02de..d78cb0d48 100644 --- a/range_queries/fenwicktree.cpp +++ b/range_queries/fenwicktree.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; /** @@ -6,47 +6,55 @@ using namespace std; * twos complement works good on this * also using ` x - (x & (x - 1)) ` */ -#define lowbit(x) (x & (-x) ) +#define lowbit(x) (x & (-x)) const int maxn = 1e5 + 7; int tree[maxn] = {0}, - range; // segement of [1...range], notice it must be less than `maxn` + range; // segement of [1...range], notice it must be less than `maxn` -void update(int x, int c) { - while(x <= range) { +void update(int x, int c) +{ + while (x <= range) + { tree[x] += c; x += lowbit(x); } } -int query(int x) { +int query(int x) +{ int ans = 0; - while(x) { + while (x) + { ans += tree[x]; x -= lowbit(x); } return ans; } -int query_segement(int l, int r) { - return query(r) - query(l - 1); -} +int query_segement(int l, int r) { return query(r) - query(l - 1); } -int main() { +int main() +{ cin >> range; - for(int i = 1; i <= range; i++) { + for (int i = 1; i <= range; i++) + { int num; cin >> num; update(i, num); } int q; cin >> q; - while(q--) { + while (q--) + { int op; cin >> op; - if(op == 0) { + if (op == 0) + { int l, r; cin >> l >> r; cout << query_segement(l, r) << endl; - } else { + } + else + { int x, c; cin >> x >> c; update(x, c); diff --git a/range_queries/mo.cpp b/range_queries/mo.cpp index 7172bd632..4cdcdf30d 100644 --- a/range_queries/mo.cpp +++ b/range_queries/mo.cpp @@ -5,73 +5,71 @@ int a[N], bucket[N], cnt[N]; int bucket_size; struct query { - int l, r, i; + int l, r, i; } q[N]; int ans = 0; void add(int index) { - cnt[a[index]]++; - if (cnt[a[index]] == 1) - ans++; + cnt[a[index]]++; + if (cnt[a[index]] == 1) + ans++; } void remove(int index) { - cnt[a[index]]--; - if (cnt[a[index]] == 0) - ans--; + cnt[a[index]]--; + if (cnt[a[index]] == 0) + ans--; } bool mycmp(query x, query y) { - if (x.l / bucket_size != y.l / bucket_size) - return x.l / bucket_size < y.l / bucket_size; - return x.r < y.r; + if (x.l / bucket_size != y.l / bucket_size) + return x.l / bucket_size < y.l / bucket_size; + return x.r < y.r; } int main() { - int n, t, i, j, k = 0; - scanf("%d", &n); - for (i = 0; i < n; i++) - scanf("%d", &a[i]); - bucket_size = ceil(sqrt(n)); - scanf("%d", &t); - for (i = 0; i < t; i++) - { - scanf("%d %d", &q[i].l, &q[i].r); - q[i].l--; - q[i].r--; - q[i].i = i; - } - sort(q, q + t, mycmp); - int left = 0, right = 0; - for (i = 0; i < t; i++) - { - int L = q[i].l, R = q[i].r; - while (left < L) - { - remove(left); - left++; - } - while (left > L) - { - add(left - 1); - left--; - } - while (right <= R) - { - add(right); - right++; - } - while (right > R + 1) - { - remove(right - 1); - right--; - } - bucket[q[i].i] = ans; - } - for (i = 0; i < t; i++) - printf("%d\n", bucket[i]); - return 0; + int n, t, i, j, k = 0; + scanf("%d", &n); + for (i = 0; i < n; i++) scanf("%d", &a[i]); + bucket_size = ceil(sqrt(n)); + scanf("%d", &t); + for (i = 0; i < t; i++) + { + scanf("%d %d", &q[i].l, &q[i].r); + q[i].l--; + q[i].r--; + q[i].i = i; + } + sort(q, q + t, mycmp); + int left = 0, right = 0; + for (i = 0; i < t; i++) + { + int L = q[i].l, R = q[i].r; + while (left < L) + { + remove(left); + left++; + } + while (left > L) + { + add(left - 1); + left--; + } + while (right <= R) + { + add(right); + right++; + } + while (right > R + 1) + { + remove(right - 1); + right--; + } + bucket[q[i].i] = ans; + } + for (i = 0; i < t; i++) printf("%d\n", bucket[i]); + return 0; } diff --git a/range_queries/segtree.cpp b/range_queries/segtree.cpp index ee81453e1..fb2bbab13 100644 --- a/range_queries/segtree.cpp +++ b/range_queries/segtree.cpp @@ -1,92 +1,94 @@ //#include -#incldue +#incldue < iostream > #define MAX 4000000 using namespace std; typedef long long ll; void ConsTree(ll arr[], ll segtree[], ll low, ll high, ll pos) { - if (low == high) - { - segtree[pos] = arr[low]; - return; - } - ll mid = (low + high) / 2; - ConsTree(arr, segtree, low, mid, 2 * pos + 1); - ConsTree(arr, segtree, mid + 1, high, 2 * pos + 2); - segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; + if (low == high) + { + segtree[pos] = arr[low]; + return; + } + ll mid = (low + high) / 2; + ConsTree(arr, segtree, low, mid, 2 * pos + 1); + ConsTree(arr, segtree, mid + 1, high, 2 * pos + 2); + segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; } ll query(ll segtree[], ll lazy[], ll qlow, ll qhigh, ll low, ll high, ll pos) { - if (low > high) - return 0; - if (qlow > high || qhigh < low) - return 0; - if (lazy[pos] != 0) - { - segtree[pos] += lazy[pos] * (high - low + 1); - if (low != high) - { - lazy[2 * pos + 1] += lazy[pos]; - lazy[2 * pos + 2] += lazy[pos]; - } - lazy[pos] = 0; - } - if (qlow <= low && qhigh >= high) - return segtree[pos]; - ll mid = (low + high) / 2; - return query(segtree, lazy, qlow, qhigh, low, mid, 2 * pos + 1) + query(segtree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2); + if (low > high) + return 0; + if (qlow > high || qhigh < low) + return 0; + if (lazy[pos] != 0) + { + segtree[pos] += lazy[pos] * (high - low + 1); + if (low != high) + { + lazy[2 * pos + 1] += lazy[pos]; + lazy[2 * pos + 2] += lazy[pos]; + } + lazy[pos] = 0; + } + if (qlow <= low && qhigh >= high) + return segtree[pos]; + ll mid = (low + high) / 2; + return query(segtree, lazy, qlow, qhigh, low, mid, 2 * pos + 1) + + query(segtree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2); } -void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, ll high, ll pos) +void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, + ll high, ll pos) { - if (low > high) - return; - if (lazy[pos] != 0) - { - segtree[pos] += lazy[pos] * (high - low + 1); - if (low != high) - { - lazy[2 * pos + 1] += lazy[pos]; - lazy[2 * pos + 2] += lazy[pos]; - } - lazy[pos] = 0; - } - if (start > high || end < low) - return; - if (start <= low && end >= high) - { - segtree[pos] += delta * (high - low + 1); - if (low != high) - { - lazy[2 * pos + 1] += delta; - lazy[2 * pos + 2] += delta; - } - return; - } - ll mid = (low + high) / 2; - update(segtree, lazy, start, end, delta, low, mid, 2 * pos + 1); - update(segtree, lazy, start, end, delta, mid + 1, high, 2 * pos + 2); - segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; + if (low > high) + return; + if (lazy[pos] != 0) + { + segtree[pos] += lazy[pos] * (high - low + 1); + if (low != high) + { + lazy[2 * pos + 1] += lazy[pos]; + lazy[2 * pos + 2] += lazy[pos]; + } + lazy[pos] = 0; + } + if (start > high || end < low) + return; + if (start <= low && end >= high) + { + segtree[pos] += delta * (high - low + 1); + if (low != high) + { + lazy[2 * pos + 1] += delta; + lazy[2 * pos + 2] += delta; + } + return; + } + ll mid = (low + high) / 2; + update(segtree, lazy, start, end, delta, low, mid, 2 * pos + 1); + update(segtree, lazy, start, end, delta, mid + 1, high, 2 * pos + 2); + segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; } int main() { - ll n, c; - scanf("%lld %lld", &n, &c); - ll arr[n] = {0}, p, q, v, choice; - ll segtree[MAX], lazy[MAX] = {0}; - ConsTree(arr, segtree, 0, n - 1, 0); - while (c--) - { - scanf("%lld", &choice); - if (choice == 0) - { - scanf("%lld %lld %lld", &p, &q, &v); - update(segtree, lazy, p - 1, q - 1, v, 0, n - 1, 0); - } - else - { - scanf("%lld %lld", &p, &q); - printf("%lld\n", query(segtree, lazy, p - 1, q - 1, 0, n - 1, 0)); - } - } - return 0; + ll n, c; + scanf("%lld %lld", &n, &c); + ll arr[n] = {0}, p, q, v, choice; + ll segtree[MAX], lazy[MAX] = {0}; + ConsTree(arr, segtree, 0, n - 1, 0); + while (c--) + { + scanf("%lld", &choice); + if (choice == 0) + { + scanf("%lld %lld %lld", &p, &q, &v); + update(segtree, lazy, p - 1, q - 1, v, 0, n - 1, 0); + } + else + { + scanf("%lld %lld", &p, &q); + printf("%lld\n", query(segtree, lazy, p - 1, q - 1, 0, n - 1, 0)); + } + } + return 0; } diff --git a/search/binary_search.cpp b/search/binary_search.cpp index 66da31d7f..ba0ce7644 100644 --- a/search/binary_search.cpp +++ b/search/binary_search.cpp @@ -12,10 +12,12 @@ * \returns index if T is found * \return -1 if T is not found */ -int binary_search(int a[], int r, int key) { +int binary_search(int a[], int r, int key) +{ int l = 0; - while (l <= r) { + while (l <= r) + { int m = l + (r - l) / 2; if (key == a[m]) return m; @@ -28,7 +30,8 @@ int binary_search(int a[], int r, int key) { } /** main function */ -int main(int argc, char const* argv[]) { +int main(int argc, char const* argv[]) +{ int n, key; std::cout << "Enter size of array: "; std::cin >> n; @@ -37,7 +40,8 @@ int main(int argc, char const* argv[]) { int* a = new int[n]; // this loop use for store value in Array - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { std::cin >> a[i]; } diff --git a/search/exponential_search.cpp b/search/exponential_search.cpp index f57cbf96b..276d03246 100644 --- a/search/exponential_search.cpp +++ b/search/exponential_search.cpp @@ -31,10 +31,12 @@ * \returns `nullptr` if value not found */ template -inline Type* binary_s(Type* array, size_t size, Type key) { +inline Type* binary_s(Type* array, size_t size, Type key) +{ int32_t lower_index(0), upper_index(size - 1), middle_index; - while (lower_index <= upper_index) { + while (lower_index <= upper_index) + { middle_index = std::floor((lower_index + upper_index) / 2); if (*(array + middle_index) < key) @@ -56,10 +58,13 @@ inline Type* binary_s(Type* array, size_t size, Type key) { * * Auxiliary Space Complexity O(1) */ template -Type* struzik_search(Type* array, size_t size, Type key) { +Type* struzik_search(Type* array, size_t size, Type key) +{ uint32_t block_front(0), block_size = size == 0 ? 0 : 1; - while (block_front != block_size) { - if (*(array + block_size - 1) < key) { + while (block_front != block_size) + { + if (*(array + block_size - 1) < key) + { block_front = block_size; (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size; continue; @@ -71,7 +76,8 @@ Type* struzik_search(Type* array, size_t size, Type key) { } /** Main function */ -int main() { +int main() +{ // TEST CASES int* sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; assert(struzik_search(sorted_array, 7, 0) == nullptr); diff --git a/search/hash_search.cpp b/search/hash_search.cpp index 6e4caffc3..c417c114b 100644 --- a/search/hash_search.cpp +++ b/search/hash_search.cpp @@ -26,7 +26,8 @@ int data[MAX] = {1, 10, 15, 5, 8, 7}; //!< test data /** * a one-way linked list */ -typedef struct list { +typedef struct list +{ int key; //!< key value for node struct list* next; //!< pointer to next link in the chain } node, /**< define node as one item list */ @@ -52,7 +53,8 @@ int h(int key) { return key % HASHMAX; } * \warning dynamic memory allocated to `n` never gets freed. * \todo fix memory leak */ -void create_list(int key) { // Construct hash table +void create_list(int key) +{ // Construct hash table link p, n; int index; n = (link)malloc(sizeof(node)); @@ -60,10 +62,13 @@ void create_list(int key) { // Construct hash table n->next = NULL; index = h(key); p = hashtab[index].next; - if (p != NULL) { + if (p != NULL) + { n->next = p; hashtab[index].next = n; - } else { + } + else + { hashtab[index].next = n; } } @@ -73,7 +78,8 @@ void create_list(int key) { // Construct hash table * (int key) function, then one-dimensional linear search. If found @return * element depth and number of searches If not found @return -1 */ -int hash_search(int key, int* counter) { // Hash lookup function +int hash_search(int key, int* counter) +{ // Hash lookup function link pointer; int index; @@ -83,7 +89,8 @@ int hash_search(int key, int* counter) { // Hash lookup function std::cout << "data[" << index << "]:"; - while (pointer != NULL) { + while (pointer != NULL) + { counter[0]++; std::cout << "data[" << pointer->key << "]:"; if (pointer->key == key) @@ -96,23 +103,27 @@ int hash_search(int key, int* counter) { // Hash lookup function } /** main function */ -int main() { +int main() +{ link p; int key, index, i, counter; // Key is the value to be found index = 0; // You can write the input mode here - while (index < MAX) { // Construct hash table + while (index < MAX) + { // Construct hash table create_list(data[index]); index++; } - for (i = 0; i < HASHMAX; i++) { // Output hash table + for (i = 0; i < HASHMAX; i++) + { // Output hash table std::cout << "hashtab [" << i << "]\n"; p = hashtab[i].next; - while (p != NULL) { + while (p != NULL) + { std::cout << "please int key:"; if (p->key > 0) std::cout << "[" << p->key << "]"; @@ -121,7 +132,8 @@ int main() { std::cout << std::endl; } - while (key != -1) { + while (key != -1) + { // You can write the input mode here // test key = 10 key = 10; diff --git a/search/interpolation_search.cpp b/search/interpolation_search.cpp index 4339dc366..0b356b119 100644 --- a/search/interpolation_search.cpp +++ b/search/interpolation_search.cpp @@ -12,11 +12,13 @@ * \returns index where the value is found * \returns 0 if not found */ -int interpolation_search(int arr[], int value, int len) { +int interpolation_search(int arr[], int value, int len) +{ int low = 0, high, mid; high = len - 1; - while (arr[low] <= value && arr[high] >= value) { + while (arr[low] <= value && arr[high] >= value) + { mid = (low + ((value - arr[low]) * (high - low)) / (arr[high] - arr[low])); if (arr[mid] > value) @@ -34,7 +36,8 @@ int interpolation_search(int arr[], int value, int len) { } /** main function */ -int main() { +int main() +{ int n, value, re; std::cout << "Enter the size of array(less than 100) : "; diff --git a/search/interpolation_search2.cpp b/search/interpolation_search2.cpp index 93fa6cd83..9400c5f96 100644 --- a/search/interpolation_search2.cpp +++ b/search/interpolation_search2.cpp @@ -12,10 +12,12 @@ * \returns index where the value is found * \returns -1 if not found */ -int InterpolationSearch(int A[], int n, int x) { +int InterpolationSearch(int A[], int n, int x) +{ int low = 0; int high = n - 1; - while (low <= high) { + while (low <= high) + { int mid = low + (((high - 1) * (x - A[low])) / (A[high] - A[low])); if (x == A[mid]) return mid; // Found x, return (exit) @@ -29,7 +31,8 @@ int InterpolationSearch(int A[], int n, int x) { } /** main function */ -int main() { +int main() +{ int A[] = {2, 4, 5, 7, 13, 14, 15, 23}; int x = 17; diff --git a/search/jump_search.cpp b/search/jump_search.cpp index f7b100a4e..b854ac6f9 100644 --- a/search/jump_search.cpp +++ b/search/jump_search.cpp @@ -9,14 +9,16 @@ /** jump search implementation */ -int jumpSearch(int arr[], int x, int n) { +int jumpSearch(int arr[], int x, int n) +{ // Finding block size to be jumped int step = std::sqrt(n); // Finding the block where element is // present (if it is present) int prev = 0; - while (arr[std::min(step, n) - 1] < x) { + while (arr[std::min(step, n) - 1] < x) + { prev = step; step += std::sqrt(n); if (prev >= n) @@ -25,7 +27,8 @@ int jumpSearch(int arr[], int x, int n) { // Doing a linear search for x in block // beginning with prev. - while (arr[prev] < x) { + while (arr[prev] < x) + { prev++; // If we reached next block or end of @@ -41,7 +44,8 @@ int jumpSearch(int arr[], int x, int n) { } // Driver program to test function -int main() { +int main() +{ int arr[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}; int x = 55; int n = sizeof(arr) / sizeof(arr[0]); diff --git a/search/linear_search.cpp b/search/linear_search.cpp index 142506951..b8fd798a7 100644 --- a/search/linear_search.cpp +++ b/search/linear_search.cpp @@ -13,9 +13,12 @@ * \returns index where the key-value occurs in the array * \returns -1 if key-value not found */ -int LinearSearch(int *array, int size, int key) { - for (int i = 0; i < size; ++i) { - if (array[i] == key) { +int LinearSearch(int *array, int size, int key) +{ + for (int i = 0; i < size; ++i) + { + if (array[i] == key) + { return i; } } @@ -24,7 +27,8 @@ int LinearSearch(int *array, int size, int key) { } /** main function */ -int main() { +int main() +{ int size; std::cout << "\nEnter the size of the Array : "; std::cin >> size; @@ -34,7 +38,8 @@ int main() { // Input array std::cout << "\nEnter the Array of " << size << " numbers : "; - for (int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) + { std::cin >> array[i]; } @@ -42,9 +47,12 @@ int main() { std::cin >> key; int index = LinearSearch(array, size, key); - if (index != -1) { + if (index != -1) + { std::cout << "\nNumber found at index : " << index; - } else { + } + else + { std::cout << "\nNot found"; } diff --git a/search/median_search.cpp b/search/median_search.cpp index 7379cad26..433ffc1f7 100644 --- a/search/median_search.cpp +++ b/search/median_search.cpp @@ -14,18 +14,25 @@ * @todo add documentation */ template -void comp(X x, std::vector *s1, std::vector *s2, - std::vector *s3) { - if (s1->size() >= x && s1->size() + s2->size() < x) { +void comp(X x, std::vector *s1, std::vector *s2, std::vector *s3) +{ + if (s1->size() >= x && s1->size() + s2->size() < x) + { std::cout << (*s2)[0] << " is the " << x + 1 << "th element from front"; - } else if (s1->size() > x) { + } + else if (s1->size() > x) + { std::sort(s1->begin(), s1->end()); std::cout << (*s1)[x] << " is the " << x + 1 << "th element from front"; - } else if (s1->size() + s2->size() <= x && s3->size() > x) { + } + else if (s1->size() + s2->size() <= x && s3->size() > x) + { std::sort(s3->begin(), s3->end()); std::cout << (*s3)[x - s1->size() - s2->size()] << " is the " << x + 1 << "th element from front"; - } else { + } + else + { std::cout << x + 1 << " is invalid location"; } } @@ -35,7 +42,8 @@ void comp(X x, std::vector *s1, std::vector *s2, /** * Main function */ -int main() { +int main() +{ std::vector v{25, 21, 98, 100, 76, 22, 43, 60, 89, 87}; std::vector s1; std::vector s2; @@ -54,14 +62,20 @@ int main() { std::cout << "\nmedian=" << median << std::endl; int avg1, avg2, avg3, sum1 = 0, sum2 = 0, sum3 = 0; - for (int i = 0; i < v.size(); i++) { // iterate through all numbers - if (v.back() == v[median]) { + for (int i = 0; i < v.size(); i++) + { // iterate through all numbers + if (v.back() == v[median]) + { avg1 = sum1 + v.back(); s2.push_back(v.back()); - } else if (v.back() < v[median]) { + } + else if (v.back() < v[median]) + { avg2 = sum2 + v.back(); s1.push_back(v.back()); - } else { + } + else + { avg3 = sum3 + v.back(); s3.push_back(v.back()); } diff --git a/search/ternary_search.cpp b/search/ternary_search.cpp index 73b89da7a..f1e2eccf0 100644 --- a/search/ternary_search.cpp +++ b/search/ternary_search.cpp @@ -45,10 +45,14 @@ void get_input() {} * \returns index where the target value was found * \returns -1 if target value not found */ -int it_ternary_search(int left, int right, int A[], int target) { - while (1) { - if (left < right) { - if (right - left < absolutePrecision) { +int it_ternary_search(int left, int right, int A[], int target) +{ + while (1) + { + if (left < right) + { + if (right - left < absolutePrecision) + { for (int i = left; i <= right; i++) if (A[i] == target) return i; @@ -71,7 +75,9 @@ int it_ternary_search(int left, int right, int A[], int target) { else left = oneThird + 1, right = twoThird - 1; - } else { + } + else + { return -1; } } @@ -87,9 +93,12 @@ int it_ternary_search(int left, int right, int A[], int target) { * \returns index where the target value was found * \returns -1 if target value not found */ -int rec_ternary_search(int left, int right, int A[], int target) { - if (left < right) { - if (right - left < absolutePrecision) { +int rec_ternary_search(int left, int right, int A[], int target) +{ + if (left < right) + { + if (right - left < absolutePrecision) + { for (int i = left; i <= right; i++) if (A[i] == target) return i; @@ -111,7 +120,9 @@ int rec_ternary_search(int left, int right, int A[], int target) { return rec_ternary_search(twoThird + 1, right, A, target); return rec_ternary_search(oneThird + 1, twoThird - 1, A, target); - } else { + } + else + { return -1; } } @@ -124,14 +135,16 @@ int rec_ternary_search(int left, int right, int A[], int target) { * \param[in] A array to search in * \param[in] target value to search for */ -void ternary_search(int N, int A[], int target) { +void ternary_search(int N, int A[], int target) +{ std::cout << it_ternary_search(0, N - 1, A, target) << '\t'; std::cout << rec_ternary_search(0, N - 1, A, target) << '\t'; std::cout << std::endl; } /** Main function */ -int main() { +int main() +{ int N = 21; int A[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 10}; get_input(); diff --git a/search/text_search.cpp b/search/text_search.cpp index ee66a506a..a228d23b2 100644 --- a/search/text_search.cpp +++ b/search/text_search.cpp @@ -12,7 +12,8 @@ /** Main function */ -int main() { +int main() +{ std::string paragraph; std::cout << "Please enter your paragraph: \n"; std::getline(std::cin, paragraph); @@ -20,18 +21,25 @@ int main() { std::cout << "\nThe size of your paragraph = " << paragraph.size() << " characters. \n\n"; - if (paragraph.empty()) { + if (paragraph.empty()) + { std::cout << "\nThe paragraph is empty" << std::endl; - } else { - while (true) { + } + else + { + while (true) + { std::string word; std::cout << "Please enter the word you are searching for: "; std::getline(std::cin, word); std::cout << "Hello, your word is " << word << "!\n"; - if (paragraph.find(word) == std::string::npos) { + if (paragraph.find(word) == std::string::npos) + { std::cout << word << " does not exist in the sentence" << std::endl; - } else { + } + else + { std::cout << "The word " << word << " is now found at location " << paragraph.find(word) << std::endl << std::endl; diff --git a/sorting/bead_sort.cpp b/sorting/bead_sort.cpp index a1a54c1e0..0215fc769 100644 --- a/sorting/bead_sort.cpp +++ b/sorting/bead_sort.cpp @@ -5,11 +5,13 @@ #define BEAD(i, j) beads[i * max + j] // function to perform the above algorithm -void beadSort(int *a, int len) { +void beadSort(int *a, int len) +{ // Find the maximum element int max = a[0]; for (int i = 1; i < len; i++) - if (a[i] > max) max = a[i]; + if (a[i] > max) + max = a[i]; // allocating memory unsigned char *beads = new unsigned char[max * len]; @@ -19,10 +21,12 @@ void beadSort(int *a, int len) { for (int i = 0; i < len; i++) for (int j = 0; j < a[i]; j++) BEAD(i, j) = 1; - for (int j = 0; j < max; j++) { + for (int j = 0; j < max; j++) + { // count how many beads are on each post int sum = 0; - for (int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) + { sum += BEAD(i, j); BEAD(i, j) = 0; } @@ -32,9 +36,11 @@ void beadSort(int *a, int len) { } // Put sorted values in array using beads - for (int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) + { int j; - for (j = 0; j < max && BEAD(i, j); j++) { + for (j = 0; j < max && BEAD(i, j); j++) + { } a[i] = j; @@ -43,7 +49,8 @@ void beadSort(int *a, int len) { } // driver function to test the algorithm -int main() { +int main() +{ int a[] = {5, 3, 1, 7, 4, 1, 1, 20}; int len = sizeof(a) / sizeof(a[0]); diff --git a/sorting/bitonic_sort.cpp b/sorting/bitonic_sort.cpp index 4d0981056..7f47cbac6 100644 --- a/sorting/bitonic_sort.cpp +++ b/sorting/bitonic_sort.cpp @@ -9,16 +9,20 @@ /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/ -void compAndSwap(int a[], int i, int j, int dir) { - if (dir == (a[i] > a[j])) std::swap(a[i], a[j]); +void compAndSwap(int a[], int i, int j, int dir) +{ + if (dir == (a[i] > a[j])) + std::swap(a[i], a[j]); } /*It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ -void bitonicMerge(int a[], int low, int cnt, int dir) { - if (cnt > 1) { +void bitonicMerge(int a[], int low, int cnt, int dir) +{ + if (cnt > 1) + { int k = cnt / 2; for (int i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir); bitonicMerge(a, low, k, dir); @@ -29,8 +33,10 @@ void bitonicMerge(int a[], int low, int cnt, int dir) { /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */ -void bitonicSort(int a[], int low, int cnt, int dir) { - if (cnt > 1) { +void bitonicSort(int a[], int low, int cnt, int dir) +{ + if (cnt > 1) + { int k = cnt / 2; // sort in ascending order since dir here is 1 @@ -50,7 +56,8 @@ void bitonicSort(int a[], int low, int cnt, int dir) { void sort(int a[], int N, int up) { bitonicSort(a, 0, N, up); } // Driver code -int main() { +int main() +{ int a[] = {3, 7, 4, 8, 6, 2, 1, 5}; int N = sizeof(a) / sizeof(a[0]); diff --git a/sorting/bubble_sort.cpp b/sorting/bubble_sort.cpp index c43e425fc..8d2a33dcd 100644 --- a/sorting/bubble_sort.cpp +++ b/sorting/bubble_sort.cpp @@ -40,7 +40,8 @@ optimized bubble sort algorithm. It's right down there. #include #include -int main() { +int main() +{ int n; bool swap_check = true; std::cout << "Enter the amount of numbers to sort: "; @@ -50,16 +51,20 @@ int main() { int num; // Input - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { std::cin >> num; numbers.push_back(num); } // Bubble Sorting - for (int i = 0; (i < n) && (swap_check); i++) { + for (int i = 0; (i < n) && (swap_check); i++) + { swap_check = false; - for (int j = 0; j < n - 1 - i; j++) { - if (numbers[j] > numbers[j + 1]) { + for (int j = 0; j < n - 1 - i; j++) + { + if (numbers[j] > numbers[j + 1]) + { swap_check = true; std::swap(numbers[j], numbers[j + 1]); // by changing swap location. @@ -72,10 +77,14 @@ int main() { // Output std::cout << "\nSorted Array : "; - for (int i = 0; i < numbers.size(); i++) { - if (i != numbers.size() - 1) { + for (int i = 0; i < numbers.size(); i++) + { + if (i != numbers.size() - 1) + { std::cout << numbers[i] << ", "; - } else { + } + else + { std::cout << numbers[i] << std::endl; } } diff --git a/sorting/bucket_sort.cpp b/sorting/bucket_sort.cpp index c43865281..ee945627c 100644 --- a/sorting/bucket_sort.cpp +++ b/sorting/bucket_sort.cpp @@ -4,12 +4,14 @@ #include // Function to sort arr[] of size n using bucket sort -void bucketSort(float arr[], int n) { +void bucketSort(float arr[], int n) +{ // 1) Create n empty buckets std::vector *b = new std::vector[n]; // 2) Put array elements in different buckets - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { int bi = n * arr[i]; // Index in bucket b[bi].push_back(arr[i]); } @@ -25,7 +27,8 @@ void bucketSort(float arr[], int n) { } /* Driver program to test above funtion */ -int main() { +int main() +{ float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434}; int n = sizeof(arr) / sizeof(arr[0]); bucketSort(arr, n); diff --git a/sorting/cocktail_selection_sort.cpp b/sorting/cocktail_selection_sort.cpp index ab6229996..ef3d30752 100644 --- a/sorting/cocktail_selection_sort.cpp +++ b/sorting/cocktail_selection_sort.cpp @@ -9,27 +9,35 @@ // Iterative Version -void CocktailSelectionSort(std::vector *vec, int low, int high) { - while (low <= high) { +void CocktailSelectionSort(std::vector *vec, int low, int high) +{ + while (low <= high) + { int minimum = (*vec)[low]; int minimumindex = low; int maximum = (*vec)[high]; int maximumindex = high; - for (int i = low; i <= high; i++) { - if ((*vec)[i] >= maximum) { + for (int i = low; i <= high; i++) + { + if ((*vec)[i] >= maximum) + { maximum = (*vec)[i]; maximumindex = i; } - if ((*vec)[i] <= minimum) { + if ((*vec)[i] <= minimum) + { minimum = (*vec)[i]; minimumindex = i; } } - if (low != maximumindex || high != minimumindex) { + if (low != maximumindex || high != minimumindex) + { std::swap((*vec)[low], (*vec)[minimumindex]); std::swap((*vec)[high], (*vec)[maximumindex]); - } else { + } + else + { std::swap((*vec)[low], (*vec)[high]); } @@ -40,28 +48,36 @@ void CocktailSelectionSort(std::vector *vec, int low, int high) { // Recursive Version -void CocktailSelectionSort_v2(std::vector *vec, int low, int high) { - if (low >= high) return; +void CocktailSelectionSort_v2(std::vector *vec, int low, int high) +{ + if (low >= high) + return; int minimum = (*vec)[low]; int minimumindex = low; int maximum = (*vec)[high]; int maximumindex = high; - for (int i = low; i <= high; i++) { - if ((*vec)[i] >= maximum) { + for (int i = low; i <= high; i++) + { + if ((*vec)[i] >= maximum) + { maximum = (*vec)[i]; maximumindex = i; } - if ((*vec)[i] <= minimum) { + if ((*vec)[i] <= minimum) + { minimum = (*vec)[i]; minimumindex = i; } } - if (low != maximumindex || high != minimumindex) { + if (low != maximumindex || high != minimumindex) + { std::swap((*vec)[low], (*vec)[minimumindex]); std::swap((*vec)[high], (*vec)[maximumindex]); - } else { + } + else + { std::swap((*vec)[low], (*vec)[high]); } @@ -70,13 +86,15 @@ void CocktailSelectionSort_v2(std::vector *vec, int low, int high) { // main function, select any one of iterative or recursive version -int main() { +int main() +{ int n; std::cout << "Enter number of elements\n"; std::cin >> n; std::vector v(n); std::cout << "Enter all the elements\n"; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { std::cin >> v[i]; } @@ -84,16 +102,22 @@ int main() { std::cout << "Enter method: \n\t0: iterative\n\t1: recursive:\t"; std::cin >> method; - if (method == 0) { + if (method == 0) + { CocktailSelectionSort(&v, 0, n - 1); - } else if (method == 1) { + } + else if (method == 1) + { CocktailSelectionSort_v2(&v, 0, n - 1); - } else { + } + else + { std::cerr << "Unknown method" << std::endl; return -1; } std::cout << "Sorted elements are\n"; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { std::cout << v[i] << " "; } diff --git a/sorting/comb_sort.cpp b/sorting/comb_sort.cpp index 1b0a4d706..d554ac757 100644 --- a/sorting/comb_sort.cpp +++ b/sorting/comb_sort.cpp @@ -8,13 +8,15 @@ int a[100005]; int n; -int FindNextGap(int x) { +int FindNextGap(int x) +{ x = (x * 10) / 13; return std::max(1, x); } -void CombSort(int a[], int l, int r) { +void CombSort(int a[], int l, int r) +{ // Init gap int gap = n; @@ -22,15 +24,18 @@ void CombSort(int a[], int l, int r) { bool swapped = true; // Keep running until gap = 1 or none elements were swapped - while (gap != 1 || swapped) { + while (gap != 1 || swapped) + { // Find next gap gap = FindNextGap(gap); swapped = false; // Compare all elements with current gap - for (int i = l; i <= r - gap; ++i) { - if (a[i] > a[i + gap]) { + for (int i = l; i <= r - gap; ++i) + { + if (a[i] > a[i + gap]) + { std::swap(a[i], a[i + gap]); swapped = true; } @@ -38,7 +43,8 @@ void CombSort(int a[], int l, int r) { } } -int main() { +int main() +{ std::cin >> n; for (int i = 1; i <= n; ++i) std::cin >> a[i]; diff --git a/sorting/counting_sort.cpp b/sorting/counting_sort.cpp index bda37bbd8..9dadd48cc 100644 --- a/sorting/counting_sort.cpp +++ b/sorting/counting_sort.cpp @@ -3,64 +3,61 @@ using namespace std; int Max(int Arr[], int N) { - int max = Arr[0]; - for (int i = 1; i < N; i++) - if (Arr[i] > max) - max = Arr[i]; - return max; + int max = Arr[0]; + for (int i = 1; i < N; i++) + if (Arr[i] > max) + max = Arr[i]; + return max; } int Min(int Arr[], int N) { - int min = Arr[0]; - for (int i = 1; i < N; i++) - if (Arr[i] < min) - min = Arr[i]; - return min; + int min = Arr[0]; + for (int i = 1; i < N; i++) + if (Arr[i] < min) + min = Arr[i]; + return min; } void Print(int Arr[], int N) { - for (int i = 0; i < N; i++) - cout << Arr[i] << ", "; + for (int i = 0; i < N; i++) cout << Arr[i] << ", "; } int *Counting_Sort(int Arr[], int N) { + int max = Max(Arr, N); + int min = Min(Arr, N); + int *Sorted_Arr = new int[N]; - int max = Max(Arr, N); - int min = Min(Arr, N); - int *Sorted_Arr = new int[N]; + int *Count = new int[max - min + 1]; - int *Count = new int[max - min + 1]; + for (int i = 0; i < N; i++) Count[Arr[i] - min]++; - for (int i = 0; i < N; i++) - Count[Arr[i] - min]++; + for (int i = 1; i < (max - min + 1); i++) Count[i] += Count[i - 1]; - for (int i = 1; i < (max - min + 1); i++) - Count[i] += Count[i - 1]; + for (int i = N - 1; i >= 0; i--) + { + Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i]; + Count[Arr[i] - min]--; + } - for (int i = N - 1; i >= 0; i--) - { - Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i]; - Count[Arr[i] - min]--; - } - - return Sorted_Arr; + return Sorted_Arr; } int main() { + int Arr[] = {47, 65, 20, 66, 25, 53, 64, 69, 72, 22, + 74, 25, 53, 15, 42, 36, 4, 69, 86, 19}, + N = 20; + int *Sorted_Arr; - int Arr[] = {47, 65, 20, 66, 25, 53, 64, 69, 72, 22, 74, 25, 53, 15, 42, 36, 4, 69, 86, 19}, N = 20; - int *Sorted_Arr; + cout << "\n\tOrignal Array = "; + Print(Arr, N); + Sorted_Arr = Counting_Sort(Arr, N); + cout << "\n\t Sorted Array = "; + Print(Sorted_Arr, N); + cout << endl; - cout << "\n\tOrignal Array = "; - Print(Arr, N); - Sorted_Arr = Counting_Sort(Arr, N); - cout << "\n\t Sorted Array = "; - Print(Sorted_Arr, N); - cout << endl; - - return 0; + return 0; } diff --git a/sorting/counting_sort_string.cpp b/sorting/counting_sort_string.cpp index 6179e5d11..77e8cdf89 100644 --- a/sorting/counting_sort_string.cpp +++ b/sorting/counting_sort_string.cpp @@ -5,18 +5,14 @@ using namespace std; void countSort(string arr) { - string output; int count[256], i; - for (int i = 0; i < 256; i++) - count[i] = 0; + for (int i = 0; i < 256; i++) count[i] = 0; - for (i = 0; arr[i]; ++i) - ++count[arr[i]]; + for (i = 0; arr[i]; ++i) ++count[arr[i]]; - for (i = 1; i <= 256; ++i) - count[i] += count[i - 1]; + for (i = 1; i <= 256; ++i) count[i] += count[i - 1]; for (i = 0; arr[i]; ++i) { @@ -24,8 +20,7 @@ void countSort(string arr) --count[arr[i]]; } - for (i = 0; arr[i]; ++i) - arr[i] = output[i]; + for (i = 0; arr[i]; ++i) arr[i] = output[i]; cout << "Sorted character array is " << arr; } diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index 9948bb821..b9b62a5f6 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -1,7 +1,8 @@ #include #include -void heapify(int *a, int i, int n) { +void heapify(int *a, int i, int n) +{ int largest = i; const int l = 2 * i + 1; const int r = 2 * i + 2; @@ -12,31 +13,38 @@ void heapify(int *a, int i, int n) { if (r < n && a[r] > a[largest]) largest = r; - if (largest != i) { + if (largest != i) + { std::swap(a[i], a[largest]); heapify(a, n, largest); } } -void heapsort(int *a, int n) { - for (int i = n - 1; i >= 0; --i) { +void heapsort(int *a, int n) +{ + for (int i = n - 1; i >= 0; --i) + { std::swap(a[0], a[i]); heapify(a, 0, i); } } -void build_maxheap(int *a, int n) { - for (int i = n / 2 - 1; i >= 0; --i) { +void build_maxheap(int *a, int n) +{ + for (int i = n / 2 - 1; i >= 0; --i) + { heapify(a, i, n); } } -int main() { +int main() +{ int n; std::cout << "Enter number of elements of array\n"; std::cin >> n; int a[20]; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { std::cout << "Enter Element " << i << std::endl; std::cin >> a[i]; } @@ -44,7 +52,8 @@ int main() { build_maxheap(a, n); heapsort(a, n); std::cout << "Sorted Output\n"; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { std::cout << a[i] << std::endl; } diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index fe920ca59..b96a44c47 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -2,7 +2,8 @@ #include -int main() { +int main() +{ int n; std::cout << "\nEnter the length of your array : "; std::cin >> n; @@ -10,15 +11,18 @@ int main() { std::cout << "\nEnter any " << n << " Numbers for Unsorted Array : "; // Input - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { std::cin >> Array[i]; } // Sorting - for (int i = 1; i < n; i++) { + for (int i = 1; i < n; i++) + { int temp = Array[i]; int j = i - 1; - while (j >= 0 && temp < Array[j]) { + while (j >= 0 && temp < Array[j]) + { Array[j + 1] = Array[j]; j--; } @@ -27,7 +31,8 @@ int main() { // Output std::cout << "\nSorted Array : "; - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { std::cout << Array[i] << "\t"; } diff --git a/sorting/library_sort.cpp b/sorting/library_sort.cpp index 6f1ab6245..c0fa857e7 100644 --- a/sorting/library_sort.cpp +++ b/sorting/library_sort.cpp @@ -1,15 +1,15 @@ #include #include -void librarySort(int *index, int n) { +void librarySort(int *index, int n) +{ int lib_size, index_pos, *gaps, // gaps *library[2]; // libraries bool target_lib, *numbered; - for (int i = 0; i < 2; i++) - library[i] = new int[n]; + for (int i = 0; i < 2; i++) library[i] = new int[n]; gaps = new int[n + 1]; numbered = new bool[n + 1]; @@ -19,7 +19,8 @@ void librarySort(int *index, int n) { target_lib = 0; library[target_lib][0] = index[0]; - while (index_pos < n) { + while (index_pos < n) + { // binary search int insert = std::distance( library[target_lib], @@ -28,19 +29,23 @@ void librarySort(int *index, int n) { // if there is no gap to insert a new index ... - if (numbered[insert] == true) { + if (numbered[insert] == true) + { int prov_size = 0, next_target_lib = !target_lib; // update library and clear gaps - for (int i = 0; i <= n; i++) { - if (numbered[i] == true) { + for (int i = 0; i <= n; i++) + { + if (numbered[i] == true) + { library[next_target_lib][prov_size] = gaps[i]; prov_size++; numbered[i] = false; } - if (i <= lib_size) { + if (i <= lib_size) + { library[next_target_lib][prov_size] = library[target_lib][i]; prov_size++; @@ -49,7 +54,9 @@ void librarySort(int *index, int n) { target_lib = next_target_lib; lib_size = prov_size - 1; - } else { + } + else + { numbered[insert] = true; gaps[insert] = index[index_pos]; index_pos++; @@ -57,14 +64,17 @@ void librarySort(int *index, int n) { } int index_pos_for_output = 0; - for (int i = 0; index_pos_for_output < n; i++) { - if (numbered[i] == true) { + for (int i = 0; index_pos_for_output < n; i++) + { + if (numbered[i] == true) + { // std::cout << gaps[i] << std::endl; index[index_pos_for_output] = gaps[i]; index_pos_for_output++; } - if (i < lib_size) { + if (i < lib_size) + { // std::cout << library[target_lib][i] << std::endl; index[index_pos_for_output] = library[target_lib][i]; index_pos_for_output++; @@ -72,15 +82,15 @@ void librarySort(int *index, int n) { } } -int main() { +int main() +{ // ---example-- int index_ex[] = {-6, 5, 9, 1, 9, 1, 0, 1, -8, 4, -12}; int n_ex = sizeof(index_ex) / sizeof(index_ex[0]); librarySort(index_ex, n_ex); std::cout << "sorted array :" << std::endl; - for (int i = 0; i < n_ex; i++) - std::cout << index_ex[i] << " "; + for (int i = 0; i < n_ex; i++) std::cout << index_ex[i] << " "; std::cout << std::endl; /* --output-- diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index 82ab869cd..1a394ded9 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -1,6 +1,7 @@ #include -void merge(int arr[], int l, int m, int r) { +void merge(int arr[], int l, int m, int r) +{ int i, j, k; int n1 = m - l + 1; int n2 = r - m; @@ -13,24 +14,30 @@ void merge(int arr[], int l, int m, int r) { i = 0; j = 0; k = l; - while (i < n1 && j < n2) { - if (L[i] <= R[j]) { + while (i < n1 && j < n2) + { + if (L[i] <= R[j]) + { arr[k] = L[i]; i++; - } else { + } + else + { arr[k] = R[j]; j++; } k++; } - while (i < n1) { + while (i < n1) + { arr[k] = L[i]; i++; k++; } - while (j < n2) { + while (j < n2) + { arr[k] = R[j]; j++; k++; @@ -40,8 +47,10 @@ void merge(int arr[], int l, int m, int r) { delete[] R; } -void mergeSort(int arr[], int l, int r) { - if (l < r) { +void mergeSort(int arr[], int l, int r) +{ + if (l < r) + { int m = l + (r - l) / 2; mergeSort(arr, l, m); @@ -51,12 +60,14 @@ void mergeSort(int arr[], int l, int r) { } } -void show(int A[], int size) { +void show(int A[], int size) +{ int i; for (i = 0; i < size; i++) std::cout << A[i] << "\n"; } -int main() { +int main() +{ int size; std::cout << "\nEnter the number of elements : "; @@ -66,7 +77,8 @@ int main() { std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size; ++i) + { std::cout << "\n"; std::cin >> arr[i]; } diff --git a/sorting/non_recursive_merge_sort.cpp b/sorting/non_recursive_merge_sort.cpp index 9d4e95f2f..9086ec0ed 100644 --- a/sorting/non_recursive_merge_sort.cpp +++ b/sorting/non_recursive_merge_sort.cpp @@ -22,17 +22,20 @@ void merge(Iterator, Iterator, const Iterator, char[]); */ template void non_recursive_merge_sort(const Iterator first, const Iterator last, - const size_t n) { + const size_t n) +{ // create a buffer large enough to store all elements // dynamically allocated to comply with cpplint char* buffer = new char[n * sizeof(*first)]; // buffer size can be optimized to largest power of 2 less than n elements // divide the container into equally-sized segments whose length start at 1 // and keeps increasing by factors of 2 - for (size_t length(1); length < n; length <<= 1) { + for (size_t length(1); length < n; length <<= 1) + { // merge adjacent segments whose number is n / (length * 2) Iterator left(first); - for (size_t counter(n / (length << 1)); counter; --counter) { + for (size_t counter(n / (length << 1)); counter; --counter) + { Iterator right(left + length), end(right + length); merge(left, right, end, buffer); left = end; @@ -53,7 +56,8 @@ void non_recursive_merge_sort(const Iterator first, const Iterator last, * @param b points at the buffer */ template -void merge(Iterator l, Iterator r, const Iterator e, char b[]) { +void merge(Iterator l, Iterator r, const Iterator e, char b[]) +{ // create 2 pointers to point at the buffer auto p(reinterpret_cast*>(b)), c(p); // move the left part of the segment @@ -73,7 +77,8 @@ void merge(Iterator l, Iterator r, const Iterator e, char b[]) { * @param n the number of elements */ template -void non_recursive_merge_sort(const Iterator first, const size_t n) { +void non_recursive_merge_sort(const Iterator first, const size_t n) +{ non_recursive_merge_sort(first, first + n, n); } /// bottom-up merge sort which sorts elements in a non-decreasing order @@ -82,16 +87,19 @@ void non_recursive_merge_sort(const Iterator first, const size_t n) { * @param last points to 1-step past the last element */ template -void non_recursive_merge_sort(const Iterator first, const Iterator last) { +void non_recursive_merge_sort(const Iterator first, const Iterator last) +{ non_recursive_merge_sort(first, last, last - first); } -int main(int argc, char** argv) { +int main(int argc, char** argv) +{ int size; std::cout << "Enter the number of elements : "; std::cin >> size; int* arr = new int[size]; - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size; ++i) + { std::cout << "arr[" << i << "] = "; std::cin >> arr[i]; } diff --git a/sorting/numeric_string_sort.cpp b/sorting/numeric_string_sort.cpp index 8b86bb29d..358cc63e3 100644 --- a/sorting/numeric_string_sort.cpp +++ b/sorting/numeric_string_sort.cpp @@ -13,40 +13,48 @@ #include #include -bool NumericSort(std::string a, std::string b) { - while (a[0] == '0') { +bool NumericSort(std::string a, std::string b) +{ + while (a[0] == '0') + { a.erase(a.begin()); } - while (b[0] == '0') { + while (b[0] == '0') + { b.erase(b.begin()); } int n = a.length(); int m = b.length(); - if (n == m) return a < b; + if (n == m) + return a < b; return n < m; } -int main() { +int main() +{ int n; std::cout << "Enter number of elements to be sorted Numerically\n"; std::cin >> n; std::vector v(n); std::cout << "Enter the string of Numbers\n"; - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { std::cin >> v[i]; } sort(v.begin(), v.end()); std::cout << "Elements sorted normally \n"; - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { std::cout << v[i] << " "; } std::cout << "\n"; std::sort(v.begin(), v.end(), NumericSort); std::cout << "Elements sorted Numerically \n"; - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { std::cout << v[i] << " "; } diff --git a/sorting/odd_even_sort.cpp b/sorting/odd_even_sort.cpp index 62842c174..274f3033b 100644 --- a/sorting/odd_even_sort.cpp +++ b/sorting/odd_even_sort.cpp @@ -6,56 +6,55 @@ using namespace std; void oddEven(vector &arr, int size) { - bool sorted = false; - while (!sorted) - { - sorted = true; - for (int i = 1; i < size - 1; i += 2) //Odd - { - if (arr[i] > arr[i + 1]) - { - swap(arr[i], arr[i + 1]); - sorted = false; - } - } + bool sorted = false; + while (!sorted) + { + sorted = true; + for (int i = 1; i < size - 1; i += 2) // Odd + { + if (arr[i] > arr[i + 1]) + { + swap(arr[i], arr[i + 1]); + sorted = false; + } + } - for (int i = 0; i < size - 1; i += 2) //Even - { - if (arr[i] > arr[i + 1]) - { - swap(arr[i], arr[i + 1]); - sorted = false; - } - } - } + for (int i = 0; i < size - 1; i += 2) // Even + { + if (arr[i] > arr[i + 1]) + { + swap(arr[i], arr[i + 1]); + sorted = false; + } + } + } } void show(vector A, int size) { - int i; - for (i = 0; i < size; i++) - cout << A[i] << "\n"; + int i; + for (i = 0; i < size; i++) cout << A[i] << "\n"; } int main() { - int size, temp; - cout << "\nEnter the number of elements : "; - cin >> size; + int size, temp; + cout << "\nEnter the number of elements : "; + cin >> size; - vector arr; + vector arr; - cout << "\nEnter the unsorted elements : \n"; + cout << "\nEnter the unsorted elements : \n"; - for (int i = 0; i < size; ++i) - { - cin >> temp; - arr.push_back(temp); - } + for (int i = 0; i < size; ++i) + { + cin >> temp; + arr.push_back(temp); + } - oddEven(arr, size); + oddEven(arr, size); - cout << "Sorted array\n"; - show(arr, size); - return 0; + cout << "Sorted array\n"; + show(arr, size); + return 0; } diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index 1db6b014e..8bb376b24 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -33,14 +33,17 @@ * */ -int partition(int arr[], int low, int high) { +int partition(int arr[], int low, int high) +{ int pivot = arr[high]; // taking the last element as pivot int i = (low - 1); // Index of smaller element - for (int j = low; j < high; j++) { + for (int j = low; j < high; j++) + { // If current element is smaller than or // equal to pivot - if (arr[j] <= pivot) { + if (arr[j] <= pivot) + { i++; // increment index of smaller element int temp = arr[i]; arr[i] = arr[j]; @@ -59,8 +62,10 @@ int partition(int arr[], int low, int high) { * low --> Starting index, * high --> Ending index */ -void quickSort(int arr[], int low, int high) { - if (low < high) { +void quickSort(int arr[], int low, int high) +{ + if (low < high) + { int p = partition(arr, low, high); quickSort(arr, low, p - 1); quickSort(arr, p + 1, high); @@ -68,13 +73,15 @@ void quickSort(int arr[], int low, int high) { } // prints the array after sorting -void show(int arr[], int size) { +void show(int arr[], int size) +{ for (int i = 0; i < size; i++) std::cout << arr[i] << " "; std::cout << "\n"; } /** Driver program to test above functions */ -int main() { +int main() +{ int size; std::cout << "\nEnter the number of elements : "; @@ -84,7 +91,8 @@ int main() { std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size; ++i) + { std::cout << "\n"; std::cin >> arr[i]; } diff --git a/sorting/radix_sort.cpp b/sorting/radix_sort.cpp index a0fbfe99e..c3b5b1629 100644 --- a/sorting/radix_sort.cpp +++ b/sorting/radix_sort.cpp @@ -3,53 +3,66 @@ #include #include -void radixsort(int a[], int n) { +void radixsort(int a[], int n) +{ int count[10]; int* output = new int[n]; memset(output, 0, n * sizeof(*output)); memset(count, 0, sizeof(count)); int max = 0; - for (int i = 0; i < n; ++i) { - if (a[i] > max) { + for (int i = 0; i < n; ++i) + { + if (a[i] > max) + { max = a[i]; } } int maxdigits = 0; - while (max) { + while (max) + { maxdigits++; max /= 10; } - for (int j = 0; j < maxdigits; j++) { - for (int i = 0; i < n; i++) { + for (int j = 0; j < maxdigits; j++) + { + for (int i = 0; i < n; i++) + { int t = std::pow(10, j); count[(a[i] % (10 * t)) / t]++; } int k = 0; - for (int p = 0; p < 10; p++) { - for (int i = 0; i < n; i++) { + for (int p = 0; p < 10; p++) + { + for (int i = 0; i < n; i++) + { int t = std::pow(10, j); - if ((a[i] % (10 * t)) / t == p) { + if ((a[i] % (10 * t)) / t == p) + { output[k] = a[i]; k++; } } } memset(count, 0, sizeof(count)); - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { a[i] = output[i]; } } delete[] output; } -void print(int a[], int n) { - for (int i = 0; i < n; ++i) { +void print(int a[], int n) +{ + for (int i = 0; i < n; ++i) + { std::cout << a[i] << " "; } std::cout << std::endl; } -int main(int argc, char const* argv[]) { +int main(int argc, char const* argv[]) +{ int a[] = {170, 45, 75, 90, 802, 24, 2, 66}; int n = sizeof(a) / sizeof(a[0]); radixsort(a, n); diff --git a/sorting/selection_sort.cpp b/sorting/selection_sort.cpp index 5b8724141..7e8b0678c 100644 --- a/sorting/selection_sort.cpp +++ b/sorting/selection_sort.cpp @@ -1,39 +1,39 @@ -//Selection Sort +// Selection Sort #include using namespace std; int main() { - int Array[6]; - cout << "\nEnter any 6 Numbers for Unsorted Array : "; + int Array[6]; + cout << "\nEnter any 6 Numbers for Unsorted Array : "; - //Input - for (int i = 0; i < 6; i++) - { - cin >> Array[i]; - } + // Input + for (int i = 0; i < 6; i++) + { + cin >> Array[i]; + } - //Selection Sorting - for (int i = 0; i < 6; i++) - { - int min = i; - for (int j = i + 1; j < 6; j++) - { - if (Array[j] < Array[min]) - { - min = j; //Finding the smallest number in Array - } - } - int temp = Array[i]; - Array[i] = Array[min]; - Array[min] = temp; - } + // Selection Sorting + for (int i = 0; i < 6; i++) + { + int min = i; + for (int j = i + 1; j < 6; j++) + { + if (Array[j] < Array[min]) + { + min = j; // Finding the smallest number in Array + } + } + int temp = Array[i]; + Array[i] = Array[min]; + Array[min] = temp; + } - //Output - cout << "\nSorted Array : "; - for (int i = 0; i < 6; i++) - { - cout << Array[i] << "\t"; - } + // Output + cout << "\nSorted Array : "; + for (int i = 0; i < 6; i++) + { + cout << Array[i] << "\t"; + } } diff --git a/sorting/shell_sort.cpp b/sorting/shell_sort.cpp index eb701478d..af783eb24 100644 --- a/sorting/shell_sort.cpp +++ b/sorting/shell_sort.cpp @@ -1,23 +1,31 @@ #include -int main() { +int main() +{ int size = 10; int* array = new int[size]; // Input std::cout << "\nHow many numbers do want to enter in unsorted array : "; std::cin >> size; std::cout << "\nEnter the numbers for unsorted array : "; - for (int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) + { std::cin >> array[i]; } // Sorting - for (int i = size / 2; i > 0; i = i / 2) { - for (int j = i; j < size; j++) { - for (int k = j - i; k >= 0; k = k - i) { - if (array[k] < array[k + i]) { + for (int i = size / 2; i > 0; i = i / 2) + { + for (int j = i; j < size; j++) + { + for (int k = j - i; k >= 0; k = k - i) + { + if (array[k] < array[k + i]) + { break; - } else { + } + else + { int temp = array[k + i]; array[k + i] = array[k]; array[k] = temp; @@ -28,7 +36,8 @@ int main() { // Output std::cout << "\nSorted array : "; - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size; ++i) + { std::cout << array[i] << "\t"; } diff --git a/sorting/shell_sort2.cpp b/sorting/shell_sort2.cpp index 1268c7a50..dee8cecd7 100644 --- a/sorting/shell_sort2.cpp +++ b/sorting/shell_sort2.cpp @@ -6,100 +6,113 @@ // for std::swap #include -template void show_data(T *arr, size_t LEN) { - size_t i; +template +void show_data(T *arr, size_t LEN) +{ + size_t i; - for (i = 0; i < LEN; i++) - std::cout << arr[i] << ", "; - std::cout << std::endl; + for (i = 0; i < LEN; i++) std::cout << arr[i] << ", "; + std::cout << std::endl; } -template void show_data(T (&arr)[N]) { show_data(arr, N); } +template +void show_data(T (&arr)[N]) +{ + show_data(arr, N); +} /** * Optimized algorithm - takes half the time by utilizing * Mar **/ -template void shell_sort(T *arr, size_t LEN) { - const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; - const unsigned int gap_len = 8; - size_t i, j, g; +template +void shell_sort(T *arr, size_t LEN) +{ + const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; + const unsigned int gap_len = 8; + size_t i, j, g; - for (g = 0; g < gap_len; g++) { - unsigned int gap = gaps[g]; - for (i = gap; i < LEN; i++) { - T tmp = arr[i]; + for (g = 0; g < gap_len; g++) + { + unsigned int gap = gaps[g]; + for (i = gap; i < LEN; i++) + { + T tmp = arr[i]; - for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) - arr[j] = arr[j - gap]; + for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) + arr[j] = arr[j - gap]; - arr[j] = tmp; + arr[j] = tmp; + } } - } } -template void shell_sort(T (&arr)[N]) { - shell_sort(arr, N); +template +void shell_sort(T (&arr)[N]) +{ + shell_sort(arr, N); } /** * function to compare sorting using cstdlib's qsort **/ -int compare(const void *a, const void *b) { - int arg1 = *static_cast(a); - int arg2 = *static_cast(b); +int compare(const void *a, const void *b) +{ + int arg1 = *static_cast(a); + int arg2 = *static_cast(b); - if (arg1 < arg2) - return -1; - if (arg1 > arg2) - return 1; - return 0; + if (arg1 < arg2) + return -1; + if (arg1 > arg2) + return 1; + return 0; - // return (arg1 > arg2) - (arg1 < arg2); // possible shortcut - // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present) + // return (arg1 > arg2) - (arg1 < arg2); // possible shortcut + // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present) } -int main(int argc, char *argv[]) { - int i, NUM_DATA; +int main(int argc, char *argv[]) +{ + int i, NUM_DATA; - if (argc == 2) - NUM_DATA = atoi(argv[1]); - else - NUM_DATA = 200; + if (argc == 2) + NUM_DATA = atoi(argv[1]); + else + NUM_DATA = 200; - // int array = new int[NUM_DATA]; - int *data = new int[NUM_DATA]; - int *data2 = new int[NUM_DATA]; - // int array2 = new int[NUM_DATA]; - int range = 1800; + // int array = new int[NUM_DATA]; + int *data = new int[NUM_DATA]; + int *data2 = new int[NUM_DATA]; + // int array2 = new int[NUM_DATA]; + int range = 1800; - std::srand(time(NULL)); - for (i = 0; i < NUM_DATA; i++) - data[i] = data2[i] = (std::rand() % range) - (range >> 1); + std::srand(time(NULL)); + for (i = 0; i < NUM_DATA; i++) + data[i] = data2[i] = (std::rand() % range) - (range >> 1); - std::cout << "Unsorted original data: " << std::endl; - show_data(data, NUM_DATA); - std::clock_t start = std::clock(); - shell_sort(data, NUM_DATA); - std::clock_t end = std::clock(); + std::cout << "Unsorted original data: " << std::endl; + show_data(data, NUM_DATA); + std::clock_t start = std::clock(); + shell_sort(data, NUM_DATA); + std::clock_t end = std::clock(); - std::cout << std::endl - << "Data Sorted using custom implementation: " << std::endl; - show_data(data, NUM_DATA); + std::cout << std::endl + << "Data Sorted using custom implementation: " << std::endl; + show_data(data, NUM_DATA); - double elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; - std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; + double elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; + std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; - start = std::clock(); - qsort(data2, NUM_DATA, sizeof(data2[0]), compare); - end = std::clock(); - std::cout << "Data Sorted using cstdlib qsort: " << std::endl; - show_data(data2, NUM_DATA); + start = std::clock(); + qsort(data2, NUM_DATA, sizeof(data2[0]), compare); + end = std::clock(); + std::cout << "Data Sorted using cstdlib qsort: " << std::endl; + show_data(data2, NUM_DATA); - elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; - std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; + elapsed_time = (end - start) * 1.f / CLOCKS_PER_SEC; + std::cout << "Time spent sorting: " << elapsed_time << "s\n" << std::endl; - free(data); - free(data2); - return 0; + free(data); + free(data2); + return 0; } diff --git a/sorting/slow_sort.cpp b/sorting/slow_sort.cpp index b2627d12f..e4f175af6 100644 --- a/sorting/slow_sort.cpp +++ b/sorting/slow_sort.cpp @@ -10,14 +10,17 @@ #include -void SlowSort(int a[], int i, int j) { - if (i >= j) return; +void SlowSort(int a[], int i, int j) +{ + if (i >= j) + return; int m = i + (j - i) / 2; // midpoint, implemented this way to avoid // overflow int temp; SlowSort(a, i, m); SlowSort(a, m + 1, j); - if (a[j] < a[m]) { + if (a[j] < a[m]) + { temp = a[j]; // swapping a[j] & a[m] a[j] = a[m]; a[m] = temp; @@ -27,7 +30,8 @@ void SlowSort(int a[], int i, int j) { // Sample Main function -int main() { +int main() +{ int size; std::cout << "\nEnter the number of elements : "; @@ -37,7 +41,8 @@ int main() { std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size; ++i) + { std::cout << "\n"; std::cin >> arr[i]; } @@ -46,7 +51,8 @@ int main() { std::cout << "Sorted array\n"; - for (int i = 0; i < size; ++i) { + for (int i = 0; i < size; ++i) + { std::cout << arr[i] << " "; } diff --git a/sorting/swap_sort.cpp b/sorting/swap_sort.cpp index 2e59e2fb3..7d391d8a1 100644 --- a/sorting/swap_sort.cpp +++ b/sorting/swap_sort.cpp @@ -6,12 +6,14 @@ // Function returns the minimum number of swaps // required to sort the array -int minSwaps(int arr[], int n) { +int minSwaps(int arr[], int n) +{ // Create an array of pairs where first // element is array element and second element // is position of first element std::pair *arrPos = new std::pair[n]; - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { arrPos[i].first = arr[i]; arrPos[i].second = i; } @@ -29,16 +31,19 @@ int minSwaps(int arr[], int n) { int ans = 0; // Traverse array elements - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { // already swapped and corrected or // already present at correct pos - if (vis[i] || arrPos[i].second == i) continue; + if (vis[i] || arrPos[i].second == i) + continue; // find out the number of node in // this cycle and add in ans int cycle_size = 0; int j = i; - while (!vis[j]) { + while (!vis[j]) + { vis[j] = 1; // move to next node @@ -47,7 +52,8 @@ int minSwaps(int arr[], int n) { } // Update answer by adding current cycle. - if (cycle_size > 0) { + if (cycle_size > 0) + { ans += (cycle_size - 1); } } @@ -59,7 +65,8 @@ int minSwaps(int arr[], int n) { } // program to test -int main() { +int main() +{ int arr[] = {6, 7, 8, 1, 2, 3, 9, 12}; int n = (sizeof(arr) / sizeof(int)); std::cout << minSwaps(arr, n); diff --git a/sorting/tim_sort.cpp b/sorting/tim_sort.cpp index 94f5aa230..9645a60b1 100644 --- a/sorting/tim_sort.cpp +++ b/sorting/tim_sort.cpp @@ -6,11 +6,14 @@ const int RUN = 32; // this function sorts array from left index to to right index which is of size // atmost RUN -void insertionSort(int arr[], int left, int right) { - for (int i = left + 1; i <= right; i++) { +void insertionSort(int arr[], int left, int right) +{ + for (int i = left + 1; i <= right; i++) + { int temp = arr[i]; int j = i - 1; - while (arr[j] > temp && j >= left) { + while (arr[j] > temp && j >= left) + { arr[j + 1] = arr[j]; j--; } @@ -19,7 +22,8 @@ void insertionSort(int arr[], int left, int right) { } // merge function merges the sorted runs -void merge(int arr[], int l, int m, int r) { +void merge(int arr[], int l, int m, int r) +{ // original array is broken in two parts, left and right array int len1 = m - l + 1, len2 = r - m; int *left = new int[len1], *right = new int[len2]; @@ -31,11 +35,15 @@ void merge(int arr[], int l, int m, int r) { int k = l; // after comparing, we merge those two array in larger sub array - while (i < len1 && j < len2) { - if (left[i] <= right[j]) { + while (i < len1 && j < len2) + { + if (left[i] <= right[j]) + { arr[k] = left[i]; i++; - } else { + } + else + { arr[k] = right[j]; j++; } @@ -43,14 +51,16 @@ void merge(int arr[], int l, int m, int r) { } // copy remaining elements of left, if any - while (i < len1) { + while (i < len1) + { arr[k] = left[i]; k++; i++; } // copy remaining element of right, if any - while (j < len2) { + while (j < len2) + { arr[k] = right[j]; k++; j++; @@ -60,18 +70,21 @@ void merge(int arr[], int l, int m, int r) { } // iterative Timsort function to sort the array[0...n-1] (similar to merge sort) -void timSort(int arr[], int n) { +void timSort(int arr[], int n) +{ // Sort individual subarrays of size RUN for (int i = 0; i < n; i += RUN) insertionSort(arr, i, std::min((i + 31), (n - 1))); // start merging from size RUN (or 32). It will merge to form size 64, then // 128, 256 and so on .... - for (int size = RUN; size < n; size = 2 * size) { + for (int size = RUN; size < n; size = 2 * size) + { // pick starting point of left sub array. We are going to merge // arr[left..left+size-1] and arr[left+size, left+2*size-1] After every // merge, we increase left by 2*size - for (int left = 0; left < n; left += 2 * size) { + for (int left = 0; left < n; left += 2 * size) + { // find ending point of left sub array // mid+1 is starting point of right sub array int mid = left + size - 1; @@ -84,13 +97,15 @@ void timSort(int arr[], int n) { } // utility function to print the Array -void printArray(int arr[], int n) { +void printArray(int arr[], int n) +{ for (int i = 0; i < n; i++) printf("%d ", arr[i]); std::cout << std::endl; } // Driver program to test above function -int main() { +int main() +{ int arr[] = {5, 21, 7, 23, 19}; int n = sizeof(arr) / sizeof(arr[0]); printf("Given Array is\n"); diff --git a/strings/brute_force_string_searching.cpp b/strings/brute_force_string_searching.cpp index 9a2b5327a..5f6116e1b 100644 --- a/strings/brute_force_string_searching.cpp +++ b/strings/brute_force_string_searching.cpp @@ -17,14 +17,18 @@ * @return Index where the pattern starts in the text * @return -1 if the pattern was not found. */ -int brute_force(const std::string &text, const std::string &pattern) { +int brute_force(const std::string &text, const std::string &pattern) +{ size_t pat_l = pattern.length(); size_t txt_l = text.length(); int index = -1; - if (pat_l <= txt_l) { - for (size_t i = 0; i < txt_l - pat_l + 1; i++) { + if (pat_l <= txt_l) + { + for (size_t i = 0; i < txt_l - pat_l + 1; i++) + { std::string s = text.substr(i, pat_l); - if (s == pattern) { + if (s == pattern) + { index = i; break; } @@ -40,8 +44,10 @@ const std::vector> test_set = { {"bba", "bb", "0"}, {"bbca", "c", "2"}, {"ab", "b", "1"}}; /** Main function */ -int main() { - for (size_t i = 0; i < test_set.size(); i++) { +int main() +{ + for (size_t i = 0; i < test_set.size(); i++) + { int output = brute_force(test_set[i][0], test_set[i][1]); if (std::to_string(output) == test_set[i][2]) diff --git a/strings/knuth_morris_pratt.cpp b/strings/knuth_morris_pratt.cpp index b83cab966..29e6ef834 100644 --- a/strings/knuth_morris_pratt.cpp +++ b/strings/knuth_morris_pratt.cpp @@ -26,14 +26,17 @@ * \param[in] pattern text for which to create the partial match table * \returns the partial match table as a vector array */ -std::vector getFailureArray(const std::string &pattern) { +std::vector getFailureArray(const std::string &pattern) +{ int pattern_length = pattern.size(); std::vector failure(pattern_length + 1); failure[0] = -1; int j = -1; - for (int i = 0; i < pattern_length; i++) { - while (j != -1 && pattern[j] != pattern[i]) { + for (int i = 0; i < pattern_length; i++) + { + while (j != -1 && pattern[j] != pattern[i]) + { j = failure[j]; } j++; @@ -49,13 +52,16 @@ std::vector getFailureArray(const std::string &pattern) { * \returns `true` if pattern was found * \returns `false` if pattern was not found */ -bool kmp(const std::string &pattern, const std::string &text) { +bool kmp(const std::string &pattern, const std::string &text) +{ int text_length = text.size(), pattern_length = pattern.size(); std::vector failure = getFailureArray(pattern); int k = 0; - for (int j = 0; j < text_length; j++) { - while (k != -1 && pattern[k] != text[j]) { + for (int j = 0; j < text_length; j++) + { + while (k != -1 && pattern[k] != text[j]) + { k = failure[k]; } k++; @@ -66,21 +72,28 @@ bool kmp(const std::string &pattern, const std::string &text) { } /** Main function */ -int main() { +int main() +{ std::string text = "alskfjaldsabc1abc1abc12k23adsfabcabc"; std::string pattern = "abc1abc12l"; - if (kmp(pattern, text) == true) { + if (kmp(pattern, text) == true) + { std::cout << "Found" << std::endl; - } else { + } + else + { std::cout << "Not Found" << std::endl; } text = "abcabc"; pattern = "bca"; - if (kmp(pattern, text) == true) { + if (kmp(pattern, text) == true) + { std::cout << "Found" << std::endl; - } else { + } + else + { std::cout << "Not Found" << std::endl; } diff --git a/strings/rabin_karp.cpp b/strings/rabin_karp.cpp index 018ff5632..5baaaf615 100644 --- a/strings/rabin_karp.cpp +++ b/strings/rabin_karp.cpp @@ -21,9 +21,11 @@ * \param[in] n length of substring to hash * \returns hash integer */ -int64_t create_hash(const std::string& s, int n) { +int64_t create_hash(const std::string& s, int n) +{ int64_t result = 0; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) + { result += (int64_t)(s[i] * (int64_t)pow(PRIME, i)); } return result; @@ -39,7 +41,8 @@ int64_t create_hash(const std::string& s, int n) { * \returns new hash integer */ int64_t recalculate_hash(const std::string& s, int old_index, int new_index, - int64_t old_hash, int patLength) { + int64_t old_hash, int patLength) +{ int64_t new_hash = old_hash - s[old_index]; new_hash /= PRIME; new_hash += (int64_t)(s[new_index] * (int64_t)pow(PRIME, patLength - 1)); @@ -57,12 +60,16 @@ int64_t recalculate_hash(const std::string& s, int old_index, int new_index, * @note can this be replaced by std::string::compare? */ bool check_if_equal(const std::string& str1, const std::string& str2, - int start1, int end1, int start2, int end2) { - if (end1 - start1 != end2 - start2) { + int start1, int end1, int start2, int end2) +{ + if (end1 - start1 != end2 - start2) + { return false; } - while (start1 <= end1 && start2 <= end2) { - if (str1[start1] != str2[start2]) { + while (start1 <= end1 && start2 <= end2) + { + if (str1[start1] != str2[start2]) + { return false; } start1++; @@ -79,16 +86,19 @@ bool check_if_equal(const std::string& str1, const std::string& str2, * @return -1 if pattern not found */ -int rabin_karp(const std::string& str, const std::string& pat) { +int rabin_karp(const std::string& str, const std::string& pat) +{ int64_t pat_hash = create_hash(pat, pat.size()); int64_t str_hash = create_hash(str, pat.size()); - for (int i = 0; i <= str.size() - pat.size(); ++i) { + for (int i = 0; i <= str.size() - pat.size(); ++i) + { if (pat_hash == str_hash && - check_if_equal(str, pat, i, i + pat.size() - 1, 0, - pat.size() - 1)) { + check_if_equal(str, pat, i, i + pat.size() - 1, 0, pat.size() - 1)) + { return i; } - if (i < str.size() - pat.size()) { + if (i < str.size() - pat.size()) + { str_hash = recalculate_hash(str, i, i + pat.size(), str_hash, pat.size()); } @@ -97,7 +107,8 @@ int rabin_karp(const std::string& str, const std::string& pat) { } /** Main function */ -int main(void) { +int main(void) +{ assert(rabin_karp("helloWorld", "world") == -1); assert(rabin_karp("helloWorld", "World") == 5); assert(rabin_karp("this_is_c++", "c++") == 8); From 7e634c2cb34442e73892a6764dc601f25008f7c4 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 19:30:10 -0400 Subject: [PATCH 39/57] remove allman break before braces --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index a8d61e423..94cd125bb 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -50,7 +50,7 @@ jobs: git commit -am "formatting source-code for $GITHUB_SHA" || true env: line1: "{ BasedOnStyle: Google, UseTab: Never," - line2: "IndentWidth: 4, TabWidth: 4, BreakBeforeBraces: Allman," + line2: "IndentWidth: 4, TabWidth: 4" line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - name: Git Push From 5c40942257209da5889985da12be758b10269317 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Fri, 29 May 2020 23:30:37 +0000 Subject: [PATCH 40/57] updating DIRECTORY.md --- DIRECTORY.md | 96 ++++++++++++++++++++++++++-------------------------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index d90326050..334538685 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -18,10 +18,10 @@ * [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/successive_approximation.cpp) ## Data Structure - * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/AVLtree.cpp) - * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Binary%20Search%20Tree.cpp) - * [Binaryheap](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Binaryheap.cpp) - * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/circular_Queue_using_Linked_List.cpp) + * [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/avltree.cpp) + * [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/binary_search_tree.cpp) + * [Binaryheap](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/binaryheap.cpp) + * [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/circular_queue_using_linked_list.cpp) * Cll * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.cpp) * [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.h) @@ -29,73 +29,73 @@ * [Disjoint Set](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/disjoint_set.cpp) * [Doubly Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/doubly_linked_list.cpp) * [Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linked_list.cpp) - * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedList_implentation_usingArray.cpp) - * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/List%20Array.cpp) - * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/MorrisInorder.cpp) - * [Queue Using Array2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Array2.cpp) - * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Linked%20List.cpp) + * [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedlist_implentation_usingarray.cpp) + * [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/list_array.cpp) + * [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/morrisinorder.cpp) * Queue * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.cpp) * [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.h) * [Test Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/test_queue.cpp) * [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_array.cpp) + * [Queue Using Array2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_array2.cpp) + * [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_linked_list.cpp) * [Queue Using Linkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_linkedlist.cpp) - * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Array.cpp) - * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Linked%20List.cpp) + * [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stack_using_array.cpp) + * [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stack_using_linked_list.cpp) * Stk * [Main](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/main.cpp) * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.cpp) * [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.h) * [Test Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/test_stack.cpp) - * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Tree.cpp) + * [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/tree.cpp) * [Trie Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/trie_tree.cpp) ## Dynamic Programming - * [0-1 Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/0-1%20Knapsack.cpp) + * [0 1 Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/0_1_knapsack.cpp) * [Armstrong Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/armstrong_number.cpp) - * [Bellman-Ford](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Bellman-Ford.cpp) - * [Catalan-Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Catalan-Numbers.cpp) - * [Coin-Change](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Coin-Change.cpp) - * [Cut Rod](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Cut%20Rod.cpp) - * [Edit Distance](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Edit%20Distance.cpp) - * [Egg-Dropping-Puzzle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Egg-Dropping-Puzzle.cpp) - * [Fibonacci Bottom Up](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Fibonacci_Bottom_Up.cpp) - * [Fibonacci Top Down](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Fibonacci_Top_Down.cpp) - * [Floyd-Warshall](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Floyd-Warshall.cpp) + * [Bellman Ford](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/bellman_ford.cpp) + * [Catalan Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/catalan_numbers.cpp) + * [Coin Change](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/coin_change.cpp) + * [Cut Rod](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/cut_rod.cpp) + * [Edit Distance](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/edit_distance.cpp) + * [Egg Dropping Puzzle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/egg_dropping_puzzle.cpp) + * [Fibonacci Bottom Up](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/fibonacci_bottom_up.cpp) + * [Fibonacci Top Down](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/fibonacci_top_down.cpp) + * [Floyd Warshall](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/floyd_warshall.cpp) * [Kadane](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/kadane.cpp) - * [Longest Common Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Common%20Subsequence.cpp) - * [Longest Increasing Subsequence (Nlogn)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence%20(nlogn).cpp) - * [Longest Increasing Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence.cpp) * [Longest Common String](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_common_string.cpp) - * [Matrix-Chain-Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Matrix-Chain-Multiplication.cpp) + * [Longest Common Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_common_subsequence.cpp) + * [Longest Increasing Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_increasing_subsequence.cpp) + * [Longest Increasing Subsequence (Nlogn)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp) + * [Matrix Chain Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/matrix_chain_multiplication.cpp) * [Searching Of Element In Dynamic Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/searching_of_element_in_dynamic_array.cpp) * [Tree Height](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/tree_height.cpp) ## Graph - * [Bfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/BFS.cpp) + * [Bfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/bfs.cpp) * [Bridge Finding With Tarjan Algorithm](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/bridge_finding_with_tarjan_algorithm.cpp) * [Connected Components](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/connected_components.cpp) * [Connected Components With Dsu](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/connected_components_with_dsu.cpp) - * [Dfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/DFS.cpp) + * [Dfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dfs.cpp) * [Dfs With Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/DFS_with_stack.cc) - * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Dijkstra.cpp) + * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dijkstra.cpp) * [Kosaraju](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kosaraju.cpp) - * [Kruskal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Kruskal.cpp) + * [Kruskal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kruskal.cpp) * [Lca](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/lca.cpp) * [Max Flow With Ford Fulkerson And Edmond Karp Algo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp) * [Prim](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/prim.cpp) - * [Topological-Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Topological-Sort.cpp) + * [Topological Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/topological_sort.cpp) * [Topological Sort By Kahns Algo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/topological_sort_by_kahns_algo.cpp) ## Greedy Algorithms - * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Dijkstra.cpp) + * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/dijkstra.cpp) * [Huffman](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/huffman.cpp) - * [Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Knapsack.cpp) - * [Kruskals Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Kruskals%20Minimum%20Spanning%20Tree.cpp) - * [Prims Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Prims%20Minimum%20Spanning%20Tree.cpp) + * [Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/knapsack.cpp) + * [Kruskals Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/kruskals_minimum_spanning_tree.cpp) + * [Prims Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/prims_minimum_spanning_tree.cpp) ## Hashing - * [Chaining](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/Chaining.cpp) + * [Chaining](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/chaining.cpp) * [Double Hash Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/double_hash_hash_table.cpp) * [Linear Probing Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/linear_probing_hash_table.cpp) * [Quadratic Probing Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/quadratic_probing_hash_table.cpp) @@ -126,15 +126,15 @@ * [String Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/string_fibonacci.cpp) ## Operations On Datastructures - * [Array Left Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Array%20Left%20Rotation.cpp) - * [Array Right Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Array%20Right%20Rotation.cpp) - * [Circular Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Circular%20Linked%20List.cpp) - * [Circular Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Circular%20Queue%20Using%20Array.cpp) + * [Array Left Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/array_left_rotation.cpp) + * [Array Right Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/array_right_rotation.cpp) + * [Circular Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/circular_linked_list.cpp) + * [Circular Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/circular_queue_using_array.cpp) * [Get Size Of Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/get_size_of_linked_list.cpp) - * [Intersection Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Intersection_of_2_arrays.cpp) - * [Reverse A Linked List Using Recusion](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Reverse%20a%20Linked%20List%20using%20Recusion.cpp) - * [Selectionsortlinkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/selectionSortLinkedList.cpp) - * [Union Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Union_of_2_arrays.cpp) + * [Intersection Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/intersection_of_2_arrays.cpp) + * [Reverse A Linked List Using Recusion](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp) + * [Selectionsortlinkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/selectionsortlinkedlist.cpp) + * [Union Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/union_of_2_arrays.cpp) ## Others * [Buzz Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/buzz_number.cpp) @@ -163,9 +163,9 @@ ## Range Queries * [Bit](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/bit.cpp) - * [Fenwicktree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/FenwickTree.cpp) - * [Mo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/MO.cpp) - * [Segtree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/segTree.cpp) + * [Fenwicktree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/fenwicktree.cpp) + * [Mo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/mo.cpp) + * [Segtree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/segtree.cpp) ## Search * [Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/binary_search.cpp) @@ -186,7 +186,7 @@ * [Bucket Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bucket_sort.cpp) * [Cocktail Selection Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/cocktail_selection_sort.cpp) * [Comb Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/comb_sort.cpp) - * [Counting Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Counting_Sort.cpp) + * [Counting Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/counting_sort.cpp) * [Counting Sort String](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/counting_sort_string.cpp) * [Heap Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/heap_sort.cpp) * [Insertion Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/insertion_sort.cpp) From daca1b5715dc069e8f956b6256eeb0fc25713bca Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 19:31:48 -0400 Subject: [PATCH 41/57] added missing comma lost in previous commit --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 94cd125bb..191e121cd 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -50,7 +50,7 @@ jobs: git commit -am "formatting source-code for $GITHUB_SHA" || true env: line1: "{ BasedOnStyle: Google, UseTab: Never," - line2: "IndentWidth: 4, TabWidth: 4" + line2: "IndentWidth: 4, TabWidth: 4, " line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - name: Git Push From e9d29caf6b30ef54d2599e397eb0b309c2c70cf2 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 21:23:17 -0400 Subject: [PATCH 42/57] orchestrate all workflows --- .github/workflows/ccpp.yml | 23 ----- .github/workflows/clang-format.yml | 96 +++++++++++++++++++- .github/workflows/cpplint.yml | 13 --- .github/workflows/cpplint_modified_files.yml | 66 -------------- .github/workflows/update_directory_md.yml | 68 -------------- 5 files changed, 94 insertions(+), 172 deletions(-) delete mode 100644 .github/workflows/ccpp.yml delete mode 100644 .github/workflows/cpplint.yml delete mode 100644 .github/workflows/cpplint_modified_files.yml delete mode 100644 .github/workflows/update_directory_md.yml diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml deleted file mode 100644 index 34085cdec..000000000 --- a/.github/workflows/ccpp.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: C/C++ CI - -on: [push] -# push: -# branches: [ master ] -# pull_request: -# branches: [ master ] - -jobs: - build: - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest, windows-latest, macOS-latest] - - steps: - - uses: actions/checkout@master - with: - submodules: true - - name: configure - run: cmake -B ./build -S . - - name: build - run: cmake --build build diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 191e121cd..092564fc4 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -1,4 +1,4 @@ -name: Code Formatting +name: Long CI Workflow on: [push] # push: @@ -7,7 +7,8 @@ on: [push] # branches: [ master ] jobs: - build: + code_format: + name: Code Formatter runs-on: ubuntu-latest steps: - name: requirements @@ -55,3 +56,94 @@ jobs: line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - name: Git Push run: git pull && git push + + update_directory_md: + name: Update Directory.md + needs: code_format + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v1 + - name: update_directory_md + shell: python + run: | + import os + from typing import Iterator + + URL_BASE = "https://github.com/TheAlgorithms/C-Plus-Plus/blob/master" + g_output = [] + + + def good_filepaths(top_dir: str = ".") -> Iterator[str]: + cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) + for dirpath, dirnames, filenames in os.walk(top_dir): + dirnames[:] = [d for d in dirnames if d[0] not in "._"] + for filename in filenames: + if os.path.splitext(filename)[1].lower() in cpp_exts: + yield os.path.join(dirpath, filename).lstrip("./") + + + def md_prefix(i): + return f"{i * ' '}*" if i else "\n##" + + + def print_path(old_path: str, new_path: str) -> str: + global g_output + old_parts = old_path.split(os.sep) + for i, new_part in enumerate(new_path.split(os.sep)): + if i + 1 > len(old_parts) or old_parts[i] != new_part: + if new_part: + g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") + return new_path + + + def build_directory_md(top_dir: str = ".") -> str: + global g_output + old_path = "" + for filepath in sorted(good_filepaths(), key=str.lower): + filepath, filename = os.path.split(filepath) + if filepath != old_path: + old_path = print_path(old_path, filepath) + indent = (filepath.count(os.sep) + 1) if filepath else 0 + url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20") + filename = os.path.splitext(filename.replace("_", " ").title())[0] + g_output.append(f"{md_prefix(indent)} [{filename}]({url})") + return "\n".join(g_output) + + + with open("DIRECTORY.md", "w") as out_file: + out_file.write(build_directory_md(".") + "\n") + - name: Update DIRECTORY.md + run: | + cat DIRECTORY.md + git config --global user.name github-actions + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git add DIRECTORY.md + git commit -am "updating DIRECTORY.md" || true + git push --force origin HEAD:$GITHUB_REF || true + + cpplint: + name: CPPLINT + needs: code_format + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - uses: actions/setup-python@v1 + - run: pip install cpplint + - run: cpplint --filter=-legal --recursive . + + build: + runs-on: ${{ matrix.os }} + needs: [cpplint, update_directory_md] + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macOS-latest] + steps: + - uses: actions/checkout@master + with: + submodules: true + - name: configure + run: cmake -B ./build -S . + - name: build + run: cmake --build build diff --git a/.github/workflows/cpplint.yml b/.github/workflows/cpplint.yml deleted file mode 100644 index a6999e1f2..000000000 --- a/.github/workflows/cpplint.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: cpplint -on: [push, pull_request] -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - uses: actions/setup-python@v1 - - run: pip install cpplint - # - run: cpplint --filter= # print out all cpplint rules - - run: cpplint --recursive . || true # all issues to be fixed - # TODO: Remove each filter one at a time and fix those failures - - run: cpplint --filter=-build,-legal,-readability,-runtime,-whitespace --recursive . diff --git a/.github/workflows/cpplint_modified_files.yml b/.github/workflows/cpplint_modified_files.yml deleted file mode 100644 index a5aa6a652..000000000 --- a/.github/workflows/cpplint_modified_files.yml +++ /dev/null @@ -1,66 +0,0 @@ -# GitHub Action that enables a repo to achieve gradual compliance with cpplint by -# linting only those files that have been added or modified (vs. origin/master). -# 1. runs cpplint only on those files that have been modified vs. origin/master. -# 2. compiles with g++ only those files that have been modified vs. origin/master. -# 3. other optional filepath verifications may be commented out at the end of this file. -# From: https://github.com/cpplint/GitHub-Action-for-cpplint - -name: cpplint_modified_files -on: [push, pull_request] -jobs: - cpplint_modified_files: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 # v2 is broken for git diff - - uses: actions/setup-python@v1 - - run: python -m pip install cpplint - - run: git remote -v - - run: git branch - - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - - run: git diff --diff-filter=dr --name-only origin/master > git_diff.txt - - name: cpplint_modified_files - shell: python - run: | - import os - import subprocess - import sys - - print("Python {}.{}.{}".format(*sys.version_info)) # Python 3.8 - with open("git_diff.txt") as in_file: - modified_files = sorted(in_file.read().splitlines()) - print("{} files were modified.".format(len(modified_files))) - - cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) - cpp_files = [file for file in modified_files if file.lower().endswith(cpp_exts)] - print(f"{len(cpp_files)} C++ files were modified.") - if not cpp_files: - sys.exit(0) - - print("cpplint:") - for cpp_file in cpp_files: - subprocess.run(["cpplint", "--filter=-legal/copyright", cpp_file], check=True, text=True) - - print("g++:") - # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) - # compile_files = [file for file in cpp_files if file.lower().endswith(compile_exts)] - for cpp_file in cpp_files: - subprocess.run(["g++", cpp_file], check=True, text=True) - - upper_files = [file for file in cpp_files if file != file.lower()] - if upper_files: - print(f"{len(upper_files)} files contain uppercase characters:") - print("\n".join(upper_files) + "\n") - - space_files = [file for file in cpp_files if " " in file or "-" in file] - if space_files: - print(f"{len(space_files)} files contain space or dash characters:") - print("\n".join(space_files) + "\n") - - nodir_files = [file for file in cpp_files if file.count(os.sep) != 1] - if nodir_files: - print(f"{len(nodir_files)} files are not in one and only one directory:") - print("\n".join(nodir_files) + "\n") - - bad_files = len(upper_files + space_files + nodir_files) - if bad_files: - sys.exit(bad_files) diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml deleted file mode 100644 index 1d63374b0..000000000 --- a/.github/workflows/update_directory_md.yml +++ /dev/null @@ -1,68 +0,0 @@ -# This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push -name: update_directory_md -on: [push] -jobs: - update_directory_md: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-python@v1 - - name: update_directory_md - shell: python - run: | - import os - from typing import Iterator - - URL_BASE = "https://github.com/TheAlgorithms/C-Plus-Plus/blob/master" - g_output = [] - - - def good_filepaths(top_dir: str = ".") -> Iterator[str]: - cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) - for dirpath, dirnames, filenames in os.walk(top_dir): - dirnames[:] = [d for d in dirnames if d[0] not in "._"] - for filename in filenames: - if os.path.splitext(filename)[1].lower() in cpp_exts: - yield os.path.join(dirpath, filename).lstrip("./") - - - def md_prefix(i): - return f"{i * ' '}*" if i else "\n##" - - - def print_path(old_path: str, new_path: str) -> str: - global g_output - old_parts = old_path.split(os.sep) - for i, new_part in enumerate(new_path.split(os.sep)): - if i + 1 > len(old_parts) or old_parts[i] != new_part: - if new_part: - g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") - return new_path - - - def build_directory_md(top_dir: str = ".") -> str: - global g_output - old_path = "" - for filepath in sorted(good_filepaths(), key=str.lower): - filepath, filename = os.path.split(filepath) - if filepath != old_path: - old_path = print_path(old_path, filepath) - indent = (filepath.count(os.sep) + 1) if filepath else 0 - url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20") - filename = os.path.splitext(filename.replace("_", " ").title())[0] - g_output.append(f"{md_prefix(indent)} [{filename}]({url})") - return "\n".join(g_output) - - - with open("DIRECTORY.md", "w") as out_file: - out_file.write(build_directory_md(".") + "\n") - - - name: Update DIRECTORY.md - run: | - cat DIRECTORY.md - git config --global user.name github-actions - git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' - git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - git add DIRECTORY.md - git commit -am "updating DIRECTORY.md" || true - git push --force origin HEAD:$GITHUB_REF || true From 3496cf3fa19276cd2ae89a92d11944660c717bda Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 21:25:19 -0400 Subject: [PATCH 43/57] fix yml indentation --- .github/workflows/clang-format.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 092564fc4..57961b614 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -127,7 +127,7 @@ jobs: name: CPPLINT needs: code_format runs-on: ubuntu-latest - steps: + steps: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 - run: pip install cpplint From bc615f5bb9e1ba987ff87982664b690fb11aae86 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 21:38:46 -0400 Subject: [PATCH 44/57] force push format changes, add title to DIRECTORY.md --- .github/workflows/clang-format.yml | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 57961b614..ecccb1149 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -55,7 +55,7 @@ jobs: line3: "AllowShortIfStatementsOnASingleLine: false, IndentCaseLabels: false," line4: "ColumnLimit: 80, AccessModifierOffset: -3 }" - name: Git Push - run: git pull && git push + run: git push --force origin HEAD:$GITHUB_REF || true update_directory_md: name: Update Directory.md @@ -64,7 +64,7 @@ jobs: steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v1 - - name: update_directory_md + - name: Update DIRECTORY.md shell: python run: | import os @@ -73,7 +73,6 @@ jobs: URL_BASE = "https://github.com/TheAlgorithms/C-Plus-Plus/blob/master" g_output = [] - def good_filepaths(top_dir: str = ".") -> Iterator[str]: cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) for dirpath, dirnames, filenames in os.walk(top_dir): @@ -82,11 +81,9 @@ jobs: if os.path.splitext(filename)[1].lower() in cpp_exts: yield os.path.join(dirpath, filename).lstrip("./") - def md_prefix(i): return f"{i * ' '}*" if i else "\n##" - def print_path(old_path: str, new_path: str) -> str: global g_output old_parts = old_path.split(os.sep) @@ -96,7 +93,6 @@ jobs: g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") return new_path - def build_directory_md(top_dir: str = ".") -> str: global g_output old_path = "" @@ -108,8 +104,7 @@ jobs: url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20") filename = os.path.splitext(filename.replace("_", " ").title())[0] g_output.append(f"{md_prefix(indent)} [{filename}]({url})") - return "\n".join(g_output) - + return "# List of all files\n" + "\n".join(g_output) with open("DIRECTORY.md", "w") as out_file: out_file.write(build_directory_md(".") + "\n") @@ -134,6 +129,7 @@ jobs: - run: cpplint --filter=-legal --recursive . build: + name: Compile checks runs-on: ${{ matrix.os }} needs: [cpplint, update_directory_md] strategy: From 40af5a53a934a63bc5360f7f853572f0db1047cb Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 21:42:32 -0400 Subject: [PATCH 45/57] pull before proceeding --- .github/workflows/clang-format.yml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index ecccb1149..15a6ae647 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -64,6 +64,8 @@ jobs: steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v1 + - name: pull latest commit + run: git pull - name: Update DIRECTORY.md shell: python run: | @@ -125,7 +127,9 @@ jobs: steps: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 - - run: pip install cpplint + - run: | + pip install cpplint + git pull - run: cpplint --filter=-legal --recursive . build: @@ -139,6 +143,8 @@ jobs: - uses: actions/checkout@master with: submodules: true + - name: git pull + run: git pull - name: configure run: cmake -B ./build -S . - name: build From 388d06c8eecff6685b08bebbfc33020782495962 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 21:46:28 -0400 Subject: [PATCH 46/57] reorganize pull commands --- .github/workflows/clang-format.yml | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 15a6ae647..0cfa72e59 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -127,9 +127,8 @@ jobs: steps: - uses: actions/checkout@v1 - uses: actions/setup-python@v1 - - run: | - pip install cpplint - git pull + - run: pip install cpplint + - run: git pull - run: cpplint --filter=-legal --recursive . build: @@ -143,9 +142,6 @@ jobs: - uses: actions/checkout@master with: submodules: true - - name: git pull - run: git pull - - name: configure - run: cmake -B ./build -S . - - name: build - run: cmake --build build + - run: git pull + - run: cmake -B ./build -S . + - run: cmake --build build From 03d7fa8b67435b5c98135f250804f057b31f7822 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 21:50:07 -0400 Subject: [PATCH 47/57] use master branches for actions --- .github/workflows/clang-format.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 0cfa72e59..df40c4e28 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -1,4 +1,4 @@ -name: Long CI Workflow +name: Awesome CI Workflow on: [push] # push: @@ -125,8 +125,8 @@ jobs: needs: code_format runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 - - uses: actions/setup-python@v1 + - uses: actions/checkout@master + - uses: actions/setup-python@master - run: pip install cpplint - run: git pull - run: cpplint --filter=-legal --recursive . From b285d09d6a219f7ed22f57f403672e037f379eb8 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 22:20:34 -0400 Subject: [PATCH 48/57] rename .cc files to .cpp --- .github/workflows/clang-format.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index df40c4e28..121309d1e 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -26,7 +26,7 @@ jobs: - name: Filename Formatter run: | IFS=$'\n' - for fname in `find . -type f -name '*.cpp' -o -name '*.h'` + for fname in `find . -type f -name '*.cpp' -o -name '*.cc' -o -name '*.h'` do echo "${fname}" new_fname=`echo ${fname} | tr ' ' '_'` @@ -35,6 +35,8 @@ jobs: echo " ${new_fname}" new_fname=`echo ${new_fname} | tr '-' '_'` echo " ${new_fname}" + new_fname=${new_fname/.cc/.cpp} + echo " ${new_fname}" if [ ${fname} != ${new_fname} ] then echo " ${fname} --> ${new_fname}" From 231d5c48586f41050407a4a0b58e0aff5393ad11 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 23:15:28 -0400 Subject: [PATCH 49/57] added class destructor to clean up dynamic memory allocation --- dynamic_programming/floyd_warshall.cpp | 47 ++++++++++++-------------- 1 file changed, 22 insertions(+), 25 deletions(-) diff --git a/dynamic_programming/floyd_warshall.cpp b/dynamic_programming/floyd_warshall.cpp index e3b0c66d3..d193ebbd5 100644 --- a/dynamic_programming/floyd_warshall.cpp +++ b/dynamic_programming/floyd_warshall.cpp @@ -1,44 +1,44 @@ -#include -#include +#include #include +#include -using namespace std; +using std::cin; +using std::cout; +using std::endl; // Wrapper class for storing a graph -class Graph -{ +class Graph { public: int vertexNum; int **edges; // Constructs a graph with V vertices and E edges - Graph(int V) - { + Graph(int V) { this->vertexNum = V; - this->edges = (int **)malloc(V * sizeof(int *)); - for (int i = 0; i < V; i++) - { - this->edges[i] = (int *)malloc(V * sizeof(int)); + this->edges = new int *[V]; + for (int i = 0; i < V; i++) { + this->edges[i] = new int[V]; for (int j = 0; j < V; j++) this->edges[i][j] = INT_MAX; this->edges[i][i] = 0; } } + ~Graph() { + for (int i = 0; i < vertexNum; i++) delete[] edges[i]; + delete[] edges; + } + // Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { + void addEdge(int src, int dst, int weight) { this->edges[src][dst] = weight; } }; // Utility function to print distances -void print(int dist[], int V) -{ +void print(int dist[], int V) { cout << "\nThe Distance matrix for Floyd - Warshall" << endl; - for (int i = 0; i < V; i++) - { - for (int j = 0; j < V; j++) - { + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { if (dist[i * V + j] != INT_MAX) cout << dist[i * V + j] << "\t"; else @@ -51,8 +51,7 @@ void print(int dist[], int V) // The main function that finds the shortest path from a vertex // to all other vertices using Floyd-Warshall Algorithm. -void FloydWarshall(Graph graph) -{ +void FloydWarshall(Graph graph) { int V = graph.vertexNum; int dist[V][V]; @@ -85,8 +84,7 @@ void FloydWarshall(Graph graph) } // Driver Function -int main() -{ +int main() { int V, E; int src, dst, weight; cout << "Enter number of vertices: "; @@ -94,8 +92,7 @@ int main() cout << "Enter number of edges: "; cin >> E; Graph G(V); - for (int i = 0; i < E; i++) - { + for (int i = 0; i < E; i++) { cout << "\nEdge " << i + 1 << "\nEnter source: "; cin >> src; cout << "Enter destination: "; From b8a97780a70f86cd1527ac503e5c14466d24dbe0 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 23:42:29 -0400 Subject: [PATCH 50/57] rename to awesome workflow --- .github/workflows/{clang-format.yml => awesome_forkflow.yml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/workflows/{clang-format.yml => awesome_forkflow.yml} (100%) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/awesome_forkflow.yml similarity index 100% rename from .github/workflows/clang-format.yml rename to .github/workflows/awesome_forkflow.yml From cac95058297004870981c7e88948079f39e53696 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 23:48:29 -0400 Subject: [PATCH 51/57] commented whole repo cpplint - added modified files lint check --- .github/workflows/awesome_forkflow.yml | 77 +++++++++++++++++++++++--- 1 file changed, 69 insertions(+), 8 deletions(-) diff --git a/.github/workflows/awesome_forkflow.yml b/.github/workflows/awesome_forkflow.yml index 121309d1e..07bfb99dc 100644 --- a/.github/workflows/awesome_forkflow.yml +++ b/.github/workflows/awesome_forkflow.yml @@ -122,21 +122,82 @@ jobs: git commit -am "updating DIRECTORY.md" || true git push --force origin HEAD:$GITHUB_REF || true - cpplint: - name: CPPLINT - needs: code_format + # cpplint: + # name: CPPLINT + # needs: code_format + # runs-on: ubuntu-latest + # steps: + # - uses: actions/checkout@master + # - uses: actions/setup-python@master + # - run: pip install cpplint + # - run: git pull + # - run: cpplint --filter=-legal --recursive . + + cpplint_modified_files: runs-on: ubuntu-latest + needs: code_format + name: CPPLINT steps: - - uses: actions/checkout@master - - uses: actions/setup-python@master - - run: pip install cpplint + - uses: actions/checkout@v1 # v2 is broken for git diff + - uses: actions/setup-python@v1 + - run: python -m pip install cpplint + - run: git remote -v + - run: git branch + - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - run: git pull - - run: cpplint --filter=-legal --recursive . + - run: git diff --diff-filter=dr --name-only origin/master > git_diff.txt + - name: cpplint_modified_files + shell: python + run: | + import os + import subprocess + import sys + + print("Python {}.{}.{}".format(*sys.version_info)) # Python 3.8 + with open("git_diff.txt") as in_file: + modified_files = sorted(in_file.read().splitlines()) + print("{} files were modified.".format(len(modified_files))) + + cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split()) + cpp_files = [file for file in modified_files if file.lower().endswith(cpp_exts)] + print(f"{len(cpp_files)} C++ files were modified.") + if not cpp_files: + sys.exit(0) + + print("cpplint:") + for cpp_file in cpp_files: + subprocess.run(["cpplint", "--filter=-legal/copyright", cpp_file], check=True, text=True) + + print("g++:") + # compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split()) + # compile_files = [file for file in cpp_files if file.lower().endswith(compile_exts)] + for cpp_file in cpp_files: + subprocess.run(["g++", cpp_file], check=True, text=True) + + upper_files = [file for file in cpp_files if file != file.lower()] + if upper_files: + print(f"{len(upper_files)} files contain uppercase characters:") + print("\n".join(upper_files) + "\n") + + space_files = [file for file in cpp_files if " " in file or "-" in file] + if space_files: + print(f"{len(space_files)} files contain space or dash characters:") + print("\n".join(space_files) + "\n") + + nodir_files = [file for file in cpp_files if file.count(os.sep) != 1] + if nodir_files: + print(f"{len(nodir_files)} files are not in one and only one directory:") + print("\n".join(nodir_files) + "\n") + + bad_files = len(upper_files + space_files + nodir_files) + if bad_files: + sys.exit(bad_files) + build: name: Compile checks runs-on: ${{ matrix.os }} - needs: [cpplint, update_directory_md] + needs: [cpplint, update_directory_md, cpplint_modified_files] strategy: matrix: os: [ubuntu-latest, windows-latest, macOS-latest] From 5a737a725df4e46210e0bf31ad3c7d21944ebee6 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 23:50:46 -0400 Subject: [PATCH 52/57] removed need for cpplint --- .github/workflows/awesome_forkflow.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/awesome_forkflow.yml b/.github/workflows/awesome_forkflow.yml index 07bfb99dc..acd53f13c 100644 --- a/.github/workflows/awesome_forkflow.yml +++ b/.github/workflows/awesome_forkflow.yml @@ -132,7 +132,7 @@ jobs: # - run: pip install cpplint # - run: git pull # - run: cpplint --filter=-legal --recursive . - + cpplint_modified_files: runs-on: ubuntu-latest needs: code_format @@ -197,7 +197,8 @@ jobs: build: name: Compile checks runs-on: ${{ matrix.os }} - needs: [cpplint, update_directory_md, cpplint_modified_files] + # needs: [cpplint, update_directory_md, cpplint_modified_files] + needs: [update_directory_md, cpplint_modified_files] strategy: matrix: os: [ubuntu-latest, windows-latest, macOS-latest] From 2bf0c00e90adac5f3b1e0fca9711a7f1b1cee73a Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Fri, 29 May 2020 23:53:00 -0400 Subject: [PATCH 53/57] attempt to use actions/checkout@master --- .github/workflows/awesome_forkflow.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/awesome_forkflow.yml b/.github/workflows/awesome_forkflow.yml index acd53f13c..8d79e4b71 100644 --- a/.github/workflows/awesome_forkflow.yml +++ b/.github/workflows/awesome_forkflow.yml @@ -138,8 +138,8 @@ jobs: needs: code_format name: CPPLINT steps: - - uses: actions/checkout@v1 # v2 is broken for git diff - - uses: actions/setup-python@v1 + - uses: actions/checkout@master # v2 is broken for git diff + - uses: actions/setup-python@master - run: python -m pip install cpplint - run: git remote -v - run: git branch From 153fb7b8a572aaf4561ac3d22d47e89480f11318 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Sat, 30 May 2020 00:01:27 -0400 Subject: [PATCH 54/57] temporary: no dependency on cpplint --- .github/workflows/awesome_forkflow.yml | 4 ++-- backtracking/knight_tour.cpp | 25 ++++++++++--------------- 2 files changed, 12 insertions(+), 17 deletions(-) diff --git a/.github/workflows/awesome_forkflow.yml b/.github/workflows/awesome_forkflow.yml index 8d79e4b71..11e585dee 100644 --- a/.github/workflows/awesome_forkflow.yml +++ b/.github/workflows/awesome_forkflow.yml @@ -146,6 +146,7 @@ jobs: - run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY - run: git pull - run: git diff --diff-filter=dr --name-only origin/master > git_diff.txt + - run: echo "Files changed-- `cat diff.txt`" - name: cpplint_modified_files shell: python run: | @@ -193,12 +194,11 @@ jobs: if bad_files: sys.exit(bad_files) - build: name: Compile checks runs-on: ${{ matrix.os }} # needs: [cpplint, update_directory_md, cpplint_modified_files] - needs: [update_directory_md, cpplint_modified_files] + needs: [update_directory_md] strategy: matrix: os: [ubuntu-latest, windows-latest, macOS-latest] diff --git a/backtracking/knight_tour.cpp b/backtracking/knight_tour.cpp index 72b900376..c97523be7 100644 --- a/backtracking/knight_tour.cpp +++ b/backtracking/knight_tour.cpp @@ -9,25 +9,23 @@ square (so that it could tour the board again immediately, following the same path), the tour is closed; otherwise, it is open. **/ -using namespace std; -bool issafe(int x, int y, int sol[n][n]) -{ +using std::cin; +using std::cout; + +bool issafe(int x, int y, int sol[n][n]) { return (x < n && x >= 0 && y < n && y >= 0 && sol[x][y] == -1); } -bool solve(int x, int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) -{ +bool solve(int x, int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) { int k, xnext, ynext; if (mov == n * n) return true; - for (k = 0; k < 8; k++) - { + for (k = 0; k < 8; k++) { xnext = x + xmov[k]; ynext = y + ymov[k]; - if (issafe(xnext, ynext, sol)) - { + if (issafe(xnext, ynext, sol)) { sol[xnext][ynext] = mov; if (solve(xnext, ynext, mov + 1, sol, xmov, ymov) == true) @@ -38,8 +36,7 @@ bool solve(int x, int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) } return false; } -int main() -{ +int main() { // initialize(); int sol[n][n]; @@ -54,10 +51,8 @@ int main() bool flag = solve(0, 0, 1, sol, xmov, ymov); if (flag == false) cout << "solution doesnot exist \n"; - else - { - for (i = 0; i < n; i++) - { + else { + for (i = 0; i < n; i++) { for (j = 0; j < n; j++) cout << sol[i][j] << " "; cout << "\n"; } From 92fe9495ecefbdc8e3f70666a7a3c8a5c8cc40c1 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 30 May 2020 04:02:05 +0000 Subject: [PATCH 55/57] formatting filenames 153fb7b8a572aaf4561ac3d22d47e89480f11318 --- graph/{DFS_with_stack.cc => dfs_with_stack.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename graph/{DFS_with_stack.cc => dfs_with_stack.cpp} (100%) diff --git a/graph/DFS_with_stack.cc b/graph/dfs_with_stack.cpp similarity index 100% rename from graph/DFS_with_stack.cc rename to graph/dfs_with_stack.cpp From 8a2de9842baf9d6a4728de2267cb93bdcab81800 Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 30 May 2020 04:02:09 +0000 Subject: [PATCH 56/57] formatting source-code for 153fb7b8a572aaf4561ac3d22d47e89480f11318 --- backtracking/graph_coloring.cpp | 21 ++-- backtracking/minimax.cpp | 6 +- backtracking/n_queens.cpp | 24 ++-- .../n_queens_all_solution_optimised.cpp | 58 +++------ backtracking/nqueen_print_all_solutions.cpp | 36 ++---- backtracking/rat_maze.cpp | 31 ++--- backtracking/sudoku_solve.cpp | 57 +++------ .../bisection_method.cpp | 29 ++--- .../false_position.cpp | 25 ++-- .../gaussian_elimination.cpp | 33 ++--- .../newton_raphson_method.cpp | 12 +- .../ordinary_least_squares_regressor.cpp | 112 ++++++----------- .../successive_approximation.cpp | 9 +- data_structure/avltree.cpp | 50 +++----- data_structure/binary_search_tree.cpp | 119 ++++++------------ data_structure/binaryheap.cpp | 42 +++---- .../circular_queue_using_linked_list.cpp | 34 ++--- data_structure/cll/cll.cpp | 67 ++++------ data_structure/cll/cll.h | 6 +- data_structure/cll/main_cll.cpp | 3 +- data_structure/disjoint_set.cpp | 44 +++---- data_structure/doubly_linked_list.cpp | 82 ++++-------- data_structure/linked_list.cpp | 72 ++++------- .../linkedlist_implentation_usingarray.cpp | 30 ++--- data_structure/list_array.cpp | 95 +++++--------- data_structure/morrisinorder.cpp | 44 +++---- data_structure/queue/queue.cpp | 42 ++----- data_structure/queue/queue.h | 6 +- data_structure/queue/test_queue.cpp | 3 +- data_structure/queue_using_array.cpp | 69 +++------- data_structure/queue_using_array2.cpp | 45 +++---- data_structure/queue_using_linked_list.cpp | 45 +++---- data_structure/queue_using_linkedlist.cpp | 39 ++---- data_structure/stack_using_array.cpp | 47 +++---- data_structure/stack_using_linked_list.cpp | 39 ++---- data_structure/stk/main.cpp | 16 +-- data_structure/stk/stack.cpp | 44 +++---- data_structure/stk/stack.h | 6 +- data_structure/stk/test_stack.cpp | 3 +- data_structure/tree.cpp | 53 +++----- data_structure/trie_tree.cpp | 44 +++---- dynamic_programming/0_1_knapsack.cpp | 18 +-- dynamic_programming/armstrong_number.cpp | 6 +- dynamic_programming/bellman_ford.cpp | 39 ++---- dynamic_programming/catalan_numbers.cpp | 12 +- dynamic_programming/coin_change.cpp | 12 +- dynamic_programming/cut_rod.cpp | 12 +- dynamic_programming/edit_distance.cpp | 15 +-- dynamic_programming/egg_dropping_puzzle.cpp | 21 ++-- dynamic_programming/fibonacci_bottom_up.cpp | 9 +- dynamic_programming/fibonacci_top_down.cpp | 12 +- dynamic_programming/kadane.cpp | 12 +- dynamic_programming/longest_common_string.cpp | 18 +-- .../longest_common_subsequence.cpp | 52 +++----- .../longest_increasing_subsequence.cpp | 21 ++-- ...longest_increasing_subsequence_(nlogn).cpp | 21 ++-- .../matrix_chain_multiplication.cpp | 12 +- .../searching_of_element_in_dynamic_array.cpp | 12 +- dynamic_programming/tree_height.cpp | 15 +-- graph/bfs.cpp | 33 ++--- .../bridge_finding_with_tarjan_algorithm.cpp | 30 ++--- graph/connected_components.cpp | 30 ++--- graph/connected_components_with_dsu.cpp | 24 ++-- graph/dfs.cpp | 15 +-- graph/dfs_with_stack.cpp | 20 ++- graph/dijkstra.cpp | 18 +-- graph/kosaraju.cpp | 42 +++---- graph/kruskal.cpp | 54 +++----- graph/lca.cpp | 66 ++++------ ...th_ford_fulkerson_and_edmond_karp_algo.cpp | 55 +++----- graph/prim.cpp | 15 +-- graph/topological_sort.cpp | 21 ++-- graph/topological_sort_by_kahns_algo.cpp | 36 ++---- greedy_algorithms/dijkstra.cpp | 61 +++------ greedy_algorithms/huffman.cpp | 18 +-- greedy_algorithms/knapsack.cpp | 34 ++--- .../kruskals_minimum_spanning_tree.cpp | 15 +-- .../prims_minimum_spanning_tree.cpp | 39 ++---- hashing/chaining.cpp | 50 +++----- hashing/double_hash_hash_table.cpp | 102 +++++---------- hashing/linear_probing_hash_table.cpp | 99 +++++---------- hashing/quadratic_probing_hash_table.cpp | 105 +++++----------- math/binary_exponent.cpp | 36 ++---- math/double_factorial.cpp | 12 +- math/eulers_totient_function.cpp | 22 ++-- math/extended_euclid_algorithm.cpp | 22 ++-- math/factorial.cpp | 6 +- math/fast_power.cpp | 15 +-- math/fibonacci.cpp | 6 +- math/fibonacci_fast.cpp | 9 +- math/fibonacci_large.cpp | 16 +-- math/gcd_iterative_euclidean.cpp | 29 ++--- math/gcd_of_n_numbers.cpp | 9 +- math/gcd_recursive_euclidean.cpp | 19 +-- math/large_factorial.cpp | 34 ++--- math/large_number.h | 94 +++++--------- .../modular_inverse_fermat_little_theorem.cpp | 35 ++---- math/number_of_positive_divisors.cpp | 31 ++--- math/power_for_huge_numbers.cpp | 21 ++-- math/prime_factorization.cpp | 30 ++--- math/prime_numbers.cpp | 12 +- math/primes_up_to_billion.cpp | 12 +- math/sieve_of_eratosthenes.cpp | 30 ++--- math/sqrt_double.cpp | 22 ++-- math/string_fibonacci.cpp | 34 ++--- .../array_left_rotation.cpp | 22 ++-- .../array_right_rotation.cpp | 19 +-- .../circular_linked_list.cpp | 49 +++----- .../circular_queue_using_array.cpp | 42 ++----- .../get_size_of_linked_list.cpp | 15 +-- .../intersection_of_2_arrays.cpp | 9 +- .../reverse_a_linked_list_using_recusion.cpp | 35 ++---- .../selectionsortlinkedlist.cpp | 46 +++---- .../union_of_2_arrays.cpp | 9 +- others/buzz_number.cpp | 6 +- others/decimal_to_binary.cpp | 15 +-- others/decimal_to_hexadecimal.cpp | 6 +- others/decimal_to_roman_numeral.cpp | 12 +- others/fast_interger_input.cpp | 9 +- others/happy_number.cpp | 14 +-- others/matrix_exponentiation.cpp | 49 +++----- others/palindrome_of_number.cpp | 3 +- others/paranthesis_matching.cpp | 30 ++--- others/pascal_triangle.cpp | 27 ++-- others/primality_test.cpp | 9 +- others/smallest_circle.cpp | 51 +++----- others/sparse_matrix.cpp | 15 +-- others/spiral_print.cpp | 36 ++---- others/stairs_pattern.cpp | 15 +-- others/tower_of_hanoi.cpp | 34 ++--- others/vector_important_functions.cpp | 3 +- probability/addition_rule.cpp | 9 +- probability/bayes_theorem.cpp | 9 +- probability/binomial_dist.cpp | 24 ++-- probability/poisson_dist.cpp | 24 ++-- range_queries/bit.cpp | 27 ++-- range_queries/fenwicktree.cpp | 28 ++--- range_queries/mo.cpp | 33 ++--- range_queries/segtree.cpp | 43 +++---- search/binary_search.cpp | 12 +- search/exponential_search.cpp | 18 +-- search/hash_search.cpp | 34 ++--- search/interpolation_search.cpp | 9 +- search/interpolation_search2.cpp | 9 +- search/jump_search.cpp | 12 +- search/linear_search.cpp | 22 ++-- search/median_search.cpp | 36 ++---- search/ternary_search.cpp | 35 ++---- search/text_search.cpp | 20 +-- sorting/bead_sort.cpp | 18 +-- sorting/bitonic_sort.cpp | 18 +-- sorting/bubble_sort.cpp | 25 ++-- sorting/bucket_sort.cpp | 9 +- sorting/cocktail_selection_sort.cpp | 61 +++------ sorting/comb_sort.cpp | 18 +-- sorting/counting_sort.cpp | 18 +-- sorting/counting_sort_string.cpp | 9 +- sorting/heap_sort.cpp | 27 ++-- sorting/insertion_sort.cpp | 15 +-- sorting/library_sort.cpp | 34 ++--- sorting/merge_sort.cpp | 34 ++--- sorting/non_recursive_merge_sort.cpp | 24 ++-- sorting/numeric_string_sort.cpp | 21 ++-- sorting/odd_even_sort.cpp | 21 ++-- sorting/quick_sort.cpp | 24 ++-- sorting/radix_sort.cpp | 39 ++---- sorting/selection_sort.cpp | 18 +-- sorting/shell_sort.cpp | 25 ++-- sorting/shell_sort2.cpp | 24 ++-- sorting/slow_sort.cpp | 15 +-- sorting/swap_sort.cpp | 18 +-- sorting/tim_sort.cpp | 43 +++---- strings/brute_force_string_searching.cpp | 18 +-- strings/knuth_morris_pratt.cpp | 35 ++---- strings/rabin_karp.cpp | 37 ++---- 175 files changed, 1671 insertions(+), 3460 deletions(-) diff --git a/backtracking/graph_coloring.cpp b/backtracking/graph_coloring.cpp index 5d0049902..19a983019 100644 --- a/backtracking/graph_coloring.cpp +++ b/backtracking/graph_coloring.cpp @@ -7,8 +7,7 @@ void printSolution(int color[]); /* A utility function to check if the current color assignment is safe for vertex v */ -bool isSafe(int v, bool graph[V][V], int color[], int c) -{ +bool isSafe(int v, bool graph[V][V], int color[], int c) { for (int i = 0; i < V; i++) if (graph[v][i] && c == color[i]) return false; @@ -16,22 +15,18 @@ bool isSafe(int v, bool graph[V][V], int color[], int c) } /* A recursive utility function to solve m coloring problem */ -void graphColoring(bool graph[V][V], int m, int color[], int v) -{ +void graphColoring(bool graph[V][V], int m, int color[], int v) { /* base case: If all vertices are assigned a color then return true */ - if (v == V) - { + if (v == V) { printSolution(color); return; } /* Consider this vertex v and try different colors */ - for (int c = 1; c <= m; c++) - { + for (int c = 1; c <= m; c++) { /* Check if assignment of color c to v is fine*/ - if (isSafe(v, graph, color, c)) - { + if (isSafe(v, graph, color, c)) { color[v] = c; /* recur to assign colors to rest of the vertices */ @@ -45,16 +40,14 @@ void graphColoring(bool graph[V][V], int m, int color[], int v) } /* A utility function to print solution */ -void printSolution(int color[]) -{ +void printSolution(int color[]) { printf(" Following are the assigned colors \n"); for (int i = 0; i < V; i++) printf(" %d ", color[i]); printf("\n"); } // driver program to test above function -int main() -{ +int main() { /* Create following graph and test whether it is 3 colorable (3)---(2) | / | diff --git a/backtracking/minimax.cpp b/backtracking/minimax.cpp index 110e9e7ed..4e46a5fb2 100644 --- a/backtracking/minimax.cpp +++ b/backtracking/minimax.cpp @@ -9,8 +9,7 @@ using std::min; using std::vector; int minimax(int depth, int node_index, bool is_max, vector scores, - int height) -{ + int height) { if (depth == height) return scores[node_index]; @@ -20,8 +19,7 @@ int minimax(int depth, int node_index, bool is_max, vector scores, return is_max ? max(v1, v2) : min(v1, v2); } -int main() -{ +int main() { vector scores = {90, 23, 6, 33, 21, 65, 123, 34423}; int height = log2(scores.size()); diff --git a/backtracking/n_queens.cpp b/backtracking/n_queens.cpp index 45d6f436c..8aab5df7b 100644 --- a/backtracking/n_queens.cpp +++ b/backtracking/n_queens.cpp @@ -2,18 +2,15 @@ #define N 4 using namespace std; -void printSolution(int board[N][N]) -{ +void printSolution(int board[N][N]) { cout << "\n"; - for (int i = 0; i < N; i++) - { + for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << "" << board[i][j]; cout << "\n"; } } -bool isSafe(int board[N][N], int row, int col) -{ +bool isSafe(int board[N][N], int row, int col) { int i, j; /* Check this row on left side */ @@ -34,22 +31,18 @@ bool isSafe(int board[N][N], int row, int col) return true; } -void solveNQ(int board[N][N], int col) -{ - if (col >= N) - { +void solveNQ(int board[N][N], int col) { + if (col >= N) { printSolution(board); return; } /* Consider this column and try placing this queen in all rows one by one */ - for (int i = 0; i < N; i++) - { + for (int i = 0; i < N; i++) { /* Check if queen can be placed on board[i][col] */ - if (isSafe(board, i, col)) - { + if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ // cout<<"\n"<= stop; var--) -void PrintSol(int Board[n][n]) -{ - inc_loop(i, 0, n - 1) - { +void PrintSol(int Board[n][n]) { + inc_loop(i, 0, n - 1) { inc_loop(j, 0, n - 1) std::cout << Board[i][j] << " "; std::cout << std::endl; } std::cout << std::endl; - if (n % 2 == 0 || (n % 2 == 1 && Board[n / 2 + 1][0] != 1)) - { - inc_loop(i, 0, n - 1) - { + if (n % 2 == 0 || (n % 2 == 1 && Board[n / 2 + 1][0] != 1)) { + inc_loop(i, 0, n - 1) { dec_loop(j, n - 1, 0) std::cout << Board[i][j] << " "; std::cout << std::endl; } @@ -21,40 +17,32 @@ void PrintSol(int Board[n][n]) } } -bool CanIMove(int Board[n][n], int row, int col) -{ +bool CanIMove(int Board[n][n], int row, int col) { /// check in the row - inc_loop(i, 0, col - 1) - { + inc_loop(i, 0, col - 1) { if (Board[row][i] == 1) return false; } /// check the first diagonal - for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) - { + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { if (Board[i][j] == 1) return false; } /// check the second diagonal - for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) - { + for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) { if (Board[i][j] == 1) return false; } return true; } -void NQueenSol(int Board[n][n], int col) -{ - if (col >= n) - { +void NQueenSol(int Board[n][n], int col) { + if (col >= n) { PrintSol(Board); return; } - inc_loop(i, 0, n - 1) - { - if (CanIMove(Board, i, col)) - { + inc_loop(i, 0, n - 1) { + if (CanIMove(Board, i, col)) { Board[i][col] = 1; NQueenSol(Board, col + 1); Board[i][col] = 0; @@ -62,27 +50,19 @@ void NQueenSol(int Board[n][n], int col) } } -int main() -{ +int main() { int Board[n][n] = {0}; - if (n % 2 == 0) - { - inc_loop(i, 0, n / 2 - 1) - { - if (CanIMove(Board, i, 0)) - { + if (n % 2 == 0) { + inc_loop(i, 0, n / 2 - 1) { + if (CanIMove(Board, i, 0)) { Board[i][0] = 1; NQueenSol(Board, 1); Board[i][0] = 0; } } - } - else - { - inc_loop(i, 0, n / 2) - { - if (CanIMove(Board, i, 0)) - { + } else { + inc_loop(i, 0, n / 2) { + if (CanIMove(Board, i, 0)) { Board[i][0] = 1; NQueenSol(Board, 1); Board[i][0] = 0; diff --git a/backtracking/nqueen_print_all_solutions.cpp b/backtracking/nqueen_print_all_solutions.cpp index d3d50998d..e6736da1e 100644 --- a/backtracking/nqueen_print_all_solutions.cpp +++ b/backtracking/nqueen_print_all_solutions.cpp @@ -1,12 +1,9 @@ #include #define n 4 -void PrintSol(int Board[n][n]) -{ - for (int i = 0; i < n; i++) - { - for (int j = 0; j < n; j++) - { +void PrintSol(int Board[n][n]) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { std::cout << Board[i][j] << " "; } std::cout << std::endl; @@ -14,40 +11,32 @@ void PrintSol(int Board[n][n]) std::cout << std::endl; } -bool CanIMove(int Board[n][n], int row, int col) -{ +bool CanIMove(int Board[n][n], int row, int col) { /// check in the row - for (int i = 0; i < col; i++) - { + for (int i = 0; i < col; i++) { if (Board[row][i] == 1) return false; } /// check the first diagonal - for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) - { + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { if (Board[i][j] == 1) return false; } /// check the second diagonal - for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) - { + for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) { if (Board[i][j] == 1) return false; } return true; } -void NQueenSol(int Board[n][n], int col) -{ - if (col >= n) - { +void NQueenSol(int Board[n][n], int col) { + if (col >= n) { PrintSol(Board); return; } - for (int i = 0; i < n; i++) - { - if (CanIMove(Board, i, col)) - { + for (int i = 0; i < n; i++) { + if (CanIMove(Board, i, col)) { Board[i][col] = 1; NQueenSol(Board, col + 1); Board[i][col] = 0; @@ -55,8 +44,7 @@ void NQueenSol(int Board[n][n], int col) } } -int main() -{ +int main() { int Board[n][n] = {0}; NQueenSol(Board, 0); } diff --git a/backtracking/rat_maze.cpp b/backtracking/rat_maze.cpp index 5454a6c82..fb3be4451 100644 --- a/backtracking/rat_maze.cpp +++ b/backtracking/rat_maze.cpp @@ -12,36 +12,28 @@ using namespace std; int solveMaze(int currposrow, int currposcol, int maze[size][size], - int soln[size][size]) -{ - if ((currposrow == size - 1) && (currposcol == size - 1)) - { + int soln[size][size]) { + if ((currposrow == size - 1) && (currposcol == size - 1)) { soln[currposrow][currposcol] = 1; - for (int i = 0; i < size; ++i) - { - for (int j = 0; j < size; ++j) - { + for (int i = 0; i < size; ++i) { + for (int j = 0; j < size; ++j) { cout << soln[i][j]; } cout << endl; } return 1; - } - else - { + } else { soln[currposrow][currposcol] = 1; // if there exist a solution by moving one step ahead in a collumn if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 && - solveMaze(currposrow, currposcol + 1, maze, soln)) - { + solveMaze(currposrow, currposcol + 1, maze, soln)) { return 1; } // if there exists a solution by moving one step ahead in a row if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 && - solveMaze(currposrow + 1, currposcol, maze, soln)) - { + solveMaze(currposrow + 1, currposcol, maze, soln)) { return 1; } @@ -51,17 +43,14 @@ int solveMaze(int currposrow, int currposcol, int maze[size][size], } } -int main(int argc, char const *argv[]) -{ +int main(int argc, char const *argv[]) { int maze[size][size] = { {1, 0, 1, 0}, {1, 0, 1, 1}, {1, 0, 0, 1}, {1, 1, 1, 1}}; int soln[size][size]; - for (int i = 0; i < size; ++i) - { - for (int j = 0; j < size; ++j) - { + for (int i = 0; i < size; ++i) { + for (int j = 0; j < size; ++j) { soln[i][j] = 0; } } diff --git a/backtracking/sudoku_solve.cpp b/backtracking/sudoku_solve.cpp index c98040841..b712b6ec7 100644 --- a/backtracking/sudoku_solve.cpp +++ b/backtracking/sudoku_solve.cpp @@ -3,13 +3,10 @@ using namespace std; /// N=9; int n = 9; -bool isPossible(int mat[][9], int i, int j, int no) -{ +bool isPossible(int mat[][9], int i, int j, int no) { /// Row or col nahin hona chahiye - for (int x = 0; x < n; x++) - { - if (mat[x][j] == no || mat[i][x] == no) - { + for (int x = 0; x < n; x++) { + if (mat[x][j] == no || mat[i][x] == no) { return false; } } @@ -18,12 +15,9 @@ bool isPossible(int mat[][9], int i, int j, int no) int sx = (i / 3) * 3; int sy = (j / 3) * 3; - for (int x = sx; x < sx + 3; x++) - { - for (int y = sy; y < sy + 3; y++) - { - if (mat[x][y] == no) - { + for (int x = sx; x < sx + 3; x++) { + for (int y = sy; y < sy + 3; y++) { + if (mat[x][y] == no) { return false; } } @@ -31,58 +25,46 @@ bool isPossible(int mat[][9], int i, int j, int no) return true; } -void printMat(int mat[][9]) -{ - for (int i = 0; i < n; i++) - { - for (int j = 0; j < n; j++) - { +void printMat(int mat[][9]) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { cout << mat[i][j] << " "; - if ((j + 1) % 3 == 0) - { + if ((j + 1) % 3 == 0) { cout << '\t'; } } - if ((i + 1) % 3 == 0) - { + if ((i + 1) % 3 == 0) { cout << endl; } cout << endl; } } -bool solveSudoku(int mat[][9], int i, int j) -{ +bool solveSudoku(int mat[][9], int i, int j) { /// Base Case - if (i == 9) - { + if (i == 9) { /// Solve kr chuke hain for 9 rows already printMat(mat); return true; } /// Crossed the last Cell in the row - if (j == 9) - { + if (j == 9) { return solveSudoku(mat, i + 1, 0); } /// Blue Cell - Skip - if (mat[i][j] != 0) - { + if (mat[i][j] != 0) { return solveSudoku(mat, i, j + 1); } /// White Cell /// Try to place every possible no - for (int no = 1; no <= 9; no++) - { - if (isPossible(mat, i, j, no)) - { + for (int no = 1; no <= 9; no++) { + if (isPossible(mat, i, j, no)) { /// Place the no - assuming solution aa jayega mat[i][j] = no; bool aageKiSolveHui = solveSudoku(mat, i, j + 1); - if (aageKiSolveHui) - { + if (aageKiSolveHui) { return true; } /// Nahin solve hui @@ -94,8 +76,7 @@ bool solveSudoku(int mat[][9], int i, int j) return false; } -int main() -{ +int main() { int mat[9][9] = {{5, 3, 0, 0, 7, 0, 0, 0, 0}, {6, 0, 0, 1, 9, 5, 0, 0, 0}, {0, 9, 8, 0, 0, 0, 0, 6, 0}, {8, 0, 0, 0, 6, 0, 0, 0, 3}, {4, 0, 0, 8, 0, 3, 0, 0, 1}, {7, 0, 0, 0, 2, 0, 0, 0, 6}, diff --git a/computer_oriented_statistical_methods/bisection_method.cpp b/computer_oriented_statistical_methods/bisection_method.cpp index ea0a5e931..c93c529d2 100644 --- a/computer_oriented_statistical_methods/bisection_method.cpp +++ b/computer_oriented_statistical_methods/bisection_method.cpp @@ -23,36 +23,29 @@ /** define \f$f(x)\f$ to find root for */ -static double eq(double i) -{ +static double eq(double i) { return (std::pow(i, 3) - (4 * i) - 9); // original equation } /** get the sign of any given number */ template -int sgn(T val) -{ +int sgn(T val) { return (T(0) < val) - (val < T(0)); } /** main function */ -int main() -{ +int main() { double a = -1, b = 1, x, z; int i; // loop to find initial intervals a, b - for (int i = 0; i < MAX_ITERATIONS; i++) - { + for (int i = 0; i < MAX_ITERATIONS; i++) { z = eq(a); x = eq(b); - if (sgn(z) == sgn(x)) - { // same signs, increase interval + if (sgn(z) == sgn(x)) { // same signs, increase interval b++; a--; - } - else - { // if opposite signs, we got our interval + } else { // if opposite signs, we got our interval break; } } @@ -61,19 +54,15 @@ int main() std::cout << "\nSecond initial: " << b; // start iterations - for (i = 0; i < MAX_ITERATIONS; i++) - { + for (i = 0; i < MAX_ITERATIONS; i++) { x = (a + b) / 2; z = eq(x); std::cout << "\n\nz: " << z << "\t[" << a << " , " << b << " | Bisect: " << x << "]"; - if (z < 0) - { + if (z < 0) { a = x; - } - else - { + } else { b = x; } diff --git a/computer_oriented_statistical_methods/false_position.cpp b/computer_oriented_statistical_methods/false_position.cpp index 6bdc0cf67..aebd154bb 100644 --- a/computer_oriented_statistical_methods/false_position.cpp +++ b/computer_oriented_statistical_methods/false_position.cpp @@ -25,36 +25,29 @@ /** define \f$f(x)\f$ to find root for */ -static double eq(double i) -{ +static double eq(double i) { return (std::pow(i, 3) - (4 * i) - 9); // origial equation } /** get the sign of any given number */ template -int sgn(T val) -{ +int sgn(T val) { return (T(0) < val) - (val < T(0)); } /** main function */ -int main() -{ +int main() { double a = -1, b = 1, x, z, m, n, c; int i; // loop to find initial intervals a, b - for (int i = 0; i < MAX_ITERATIONS; i++) - { + for (int i = 0; i < MAX_ITERATIONS; i++) { z = eq(a); x = eq(b); - if (sgn(z) == sgn(x)) - { // same signs, increase interval + if (sgn(z) == sgn(x)) { // same signs, increase interval b++; a--; - } - else - { // if opposite signs, we got our interval + } else { // if opposite signs, we got our interval break; } } @@ -62,8 +55,7 @@ int main() std::cout << "\nFirst initial: " << a; std::cout << "\nSecond initial: " << b; - for (i = 0; i < MAX_ITERATIONS; i++) - { + for (i = 0; i < MAX_ITERATIONS; i++) { m = eq(a); n = eq(b); @@ -72,8 +64,7 @@ int main() a = c; z = eq(c); - if (std::abs(z) < EPSILON) - { // stoping criteria + if (std::abs(z) < EPSILON) { // stoping criteria break; } } diff --git a/computer_oriented_statistical_methods/gaussian_elimination.cpp b/computer_oriented_statistical_methods/gaussian_elimination.cpp index 01cb578b2..60b5648ec 100644 --- a/computer_oriented_statistical_methods/gaussian_elimination.cpp +++ b/computer_oriented_statistical_methods/gaussian_elimination.cpp @@ -6,8 +6,7 @@ #include /** Main function */ -int main() -{ +int main() { int mat_size, i, j, step; std::cout << "Matrix size: "; @@ -15,8 +14,7 @@ int main() // create a 2D matrix by dynamic memory allocation double **mat = new double *[mat_size + 1], **x = new double *[mat_size]; - for (i = 0; i <= mat_size; i++) - { + for (i = 0; i <= mat_size; i++) { mat[i] = new double[mat_size + 1]; if (i < mat_size) x[i] = new double[mat_size + 1]; @@ -24,20 +22,16 @@ int main() // get the matrix elements from user std::cout << std::endl << "Enter value of the matrix: " << std::endl; - for (i = 0; i < mat_size; i++) - { - for (j = 0; j <= mat_size; j++) - { + for (i = 0; i < mat_size; i++) { + for (j = 0; j <= mat_size; j++) { std::cin >> mat[i][j]; // Enter (mat_size*mat_size) value of the matrix. } } // perform Gaussian elimination - for (step = 0; step < mat_size - 1; step++) - { - for (i = step; i < mat_size - 1; i++) - { + for (step = 0; step < mat_size - 1; step++) { + for (i = step; i < mat_size - 1; i++) { double a = (mat[i + 1][step] / mat[step][step]); for (j = step; j <= mat_size; j++) @@ -47,10 +41,8 @@ int main() std::cout << std::endl << "Matrix using Gaussian Elimination method: " << std::endl; - for (i = 0; i < mat_size; i++) - { - for (j = 0; j <= mat_size; j++) - { + for (i = 0; i < mat_size; i++) { + for (j = 0; j <= mat_size; j++) { x[i][j] = mat[i][j]; std::cout << mat[i][j] << " "; } @@ -58,11 +50,9 @@ int main() } std::cout << std::endl << "Value of the Gaussian Elimination method: " << std::endl; - for (i = mat_size - 1; i >= 0; i--) - { + for (i = mat_size - 1; i >= 0; i--) { double sum = 0; - for (j = mat_size - 1; j > i; j--) - { + for (j = mat_size - 1; j > i; j--) { x[i][j] = x[j][j] * x[i][j]; sum = x[i][j] + sum; } @@ -74,8 +64,7 @@ int main() std::cout << "x" << i << "= " << x[i][i] << std::endl; } - for (i = 0; i <= mat_size; i++) - { + for (i = 0; i <= mat_size; i++) { delete[] mat[i]; if (i < mat_size) delete[] x[i]; diff --git a/computer_oriented_statistical_methods/newton_raphson_method.cpp b/computer_oriented_statistical_methods/newton_raphson_method.cpp index a93774b91..318363a39 100644 --- a/computer_oriented_statistical_methods/newton_raphson_method.cpp +++ b/computer_oriented_statistical_methods/newton_raphson_method.cpp @@ -21,21 +21,18 @@ /** define \f$f(x)\f$ to find root for */ -static double eq(double i) -{ +static double eq(double i) { return (std::pow(i, 3) - (4 * i) - 9); // original equation } /** define the derivative function \f$f'(x)\f$ */ -static double eq_der(double i) -{ +static double eq_der(double i) { return ((3 * std::pow(i, 2)) - 4); // derivative of equation } /** Main function */ -int main() -{ +int main() { std::srand(std::time(nullptr)); // initialize randomizer double z, c = std::rand() % 100, m, n; @@ -44,8 +41,7 @@ int main() std::cout << "\nInitial approximation: " << c; // start iterations - for (i = 0; i < MAX_ITERATIONS; i++) - { + for (i = 0; i < MAX_ITERATIONS; i++) { m = eq(c); n = eq_der(c); diff --git a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp index c3fe8be03..de02b27bb 100644 --- a/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp +++ b/computer_oriented_statistical_methods/ordinary_least_squares_regressor.cpp @@ -16,13 +16,11 @@ */ template std::ostream &operator<<(std::ostream &out, - std::vector> const &v) -{ + std::vector> const &v) { const int width = 10; const char separator = ' '; - for (size_t row = 0; row < v.size(); row++) - { + for (size_t row = 0; row < v.size(); row++) { for (size_t col = 0; col < v[row].size(); col++) out << std::left << std::setw(width) << std::setfill(separator) << v[row][col]; @@ -36,8 +34,7 @@ std::ostream &operator<<(std::ostream &out, * operator to print a vector */ template -std::ostream &operator<<(std::ostream &out, std::vector const &v) -{ +std::ostream &operator<<(std::ostream &out, std::vector const &v) { const int width = 15; const char separator = ' '; @@ -53,8 +50,7 @@ std::ostream &operator<<(std::ostream &out, std::vector const &v) * \returns 1 if true, 0 if false */ template -inline bool is_square(std::vector> const &A) -{ +inline bool is_square(std::vector> const &A) { // Assuming A is square matrix size_t N = A.size(); for (size_t i = 0; i < N; i++) @@ -72,8 +68,7 @@ inline bool is_square(std::vector> const &A) **/ template std::vector> operator*(std::vector> const &A, - std::vector> const &B) -{ + std::vector> const &B) { // Number of rows in A size_t N_A = A.size(); // Number of columns in B @@ -81,18 +76,15 @@ std::vector> operator*(std::vector> const &A, std::vector> result(N_A); - if (A[0].size() != B.size()) - { + if (A[0].size() != B.size()) { std::cerr << "Number of columns in A != Number of rows in B (" << A[0].size() << ", " << B.size() << ")" << std::endl; return result; } - for (size_t row = 0; row < N_A; row++) - { + for (size_t row = 0; row < N_A; row++) { std::vector v(N_B); - for (size_t col = 0; col < N_B; col++) - { + for (size_t col = 0; col < N_B; col++) { v[col] = static_cast(0); for (size_t j = 0; j < B.size(); j++) v[col] += A[row][j] * B[j][col]; @@ -109,22 +101,19 @@ std::vector> operator*(std::vector> const &A, */ template std::vector operator*(std::vector> const &A, - std::vector const &B) -{ + std::vector const &B) { // Number of rows in A size_t N_A = A.size(); std::vector result(N_A); - if (A[0].size() != B.size()) - { + if (A[0].size() != B.size()) { std::cerr << "Number of columns in A != Number of rows in B (" << A[0].size() << ", " << B.size() << ")" << std::endl; return result; } - for (size_t row = 0; row < N_A; row++) - { + for (size_t row = 0; row < N_A; row++) { result[row] = static_cast(0); for (size_t j = 0; j < B.size(); j++) result[row] += A[row][j] * B[j]; } @@ -137,15 +126,13 @@ std::vector operator*(std::vector> const &A, * \returns resultant vector */ template -std::vector operator*(float const scalar, std::vector const &A) -{ +std::vector operator*(float const scalar, std::vector const &A) { // Number of rows in A size_t N_A = A.size(); std::vector result(N_A); - for (size_t row = 0; row < N_A; row++) - { + for (size_t row = 0; row < N_A; row++) { result[row] += A[row] * static_cast(scalar); } @@ -157,8 +144,7 @@ std::vector operator*(float const scalar, std::vector const &A) * \returns resultant vector */ template -std::vector operator*(std::vector const &A, float const scalar) -{ +std::vector operator*(std::vector const &A, float const scalar) { // Number of rows in A size_t N_A = A.size(); @@ -175,8 +161,7 @@ std::vector operator*(std::vector const &A, float const scalar) * \returns resultant vector */ template -std::vector operator/(std::vector const &A, float const scalar) -{ +std::vector operator/(std::vector const &A, float const scalar) { return (1.f / scalar) * A; } @@ -185,15 +170,13 @@ std::vector operator/(std::vector const &A, float const scalar) * \returns resultant vector */ template -std::vector operator-(std::vector const &A, std::vector const &B) -{ +std::vector operator-(std::vector const &A, std::vector const &B) { // Number of rows in A size_t N = A.size(); std::vector result(N); - if (B.size() != N) - { + if (B.size() != N) { std::cerr << "Vector dimensions shouldbe identical!" << std::endl; return A; } @@ -208,15 +191,13 @@ std::vector operator-(std::vector const &A, std::vector const &B) * \returns resultant vector */ template -std::vector operator+(std::vector const &A, std::vector const &B) -{ +std::vector operator+(std::vector const &A, std::vector const &B) { // Number of rows in A size_t N = A.size(); std::vector result(N); - if (B.size() != N) - { + if (B.size() != N) { std::cerr << "Vector dimensions shouldbe identical!" << std::endl; return A; } @@ -233,30 +214,26 @@ std::vector operator+(std::vector const &A, std::vector const &B) **/ template std::vector> get_inverse( - std::vector> const &A) -{ + std::vector> const &A) { // Assuming A is square matrix size_t N = A.size(); std::vector> inverse(N); - for (size_t row = 0; row < N; row++) - { + for (size_t row = 0; row < N; row++) { // preallocatae a resultant identity matrix inverse[row] = std::vector(N); for (size_t col = 0; col < N; col++) inverse[row][col] = (row == col) ? 1.f : 0.f; } - if (!is_square(A)) - { + if (!is_square(A)) { std::cerr << "A must be a square matrix!" << std::endl; return inverse; } // preallocatae a temporary matrix identical to A std::vector> temp(N); - for (size_t row = 0; row < N; row++) - { + for (size_t row = 0; row < N; row++) { std::vector v(N); for (size_t col = 0; col < N; col++) v[col] = static_cast(A[row][col]); @@ -264,27 +241,22 @@ std::vector> get_inverse( } // start transformations - for (size_t row = 0; row < N; row++) - { - for (size_t row2 = row; row2 < N && temp[row][row] == 0; row2++) - { + for (size_t row = 0; row < N; row++) { + for (size_t row2 = row; row2 < N && temp[row][row] == 0; row2++) { // this to ensure diagonal elements are not 0 temp[row] = temp[row] + temp[row2]; inverse[row] = inverse[row] + inverse[row2]; } - for (size_t col2 = row; col2 < N && temp[row][row] == 0; col2++) - { + for (size_t col2 = row; col2 < N && temp[row][row] == 0; col2++) { // this to further ensure diagonal elements are not 0 - for (size_t row2 = 0; row2 < N; row2++) - { + for (size_t row2 = 0; row2 < N; row2++) { temp[row2][row] = temp[row2][row] + temp[row2][col2]; inverse[row2][row] = inverse[row2][row] + inverse[row2][col2]; } } - if (temp[row][row] == 0) - { + if (temp[row][row] == 0) { // Probably a low-rank matrix and hence singular std::cerr << "Low-rank matrix, no inverse!" << std::endl; return inverse; @@ -295,8 +267,7 @@ std::vector> get_inverse( temp[row] = temp[row] / divisor; inverse[row] = inverse[row] / divisor; // Row transformations - for (size_t row2 = 0; row2 < N; row2++) - { + for (size_t row2 = 0; row2 < N; row2++) { if (row2 == row) continue; float factor = temp[row2][row]; @@ -313,12 +284,11 @@ std::vector> get_inverse( * \returns resultant matrix **/ template -std::vector> get_transpose(std::vector> const &A) -{ +std::vector> get_transpose( + std::vector> const &A) { std::vector> result(A[0].size()); - for (size_t row = 0; row < A[0].size(); row++) - { + for (size_t row = 0; row < A[0].size(); row++) { std::vector v(A.size()); for (size_t col = 0; col < A.size(); col++) v[col] = A[col][row]; @@ -336,8 +306,7 @@ std::vector> get_transpose(std::vector> const &A) */ template std::vector fit_OLS_regressor(std::vector> const &X, - std::vector const &Y) -{ + std::vector const &Y) { // NxF std::vector> X2 = X; for (size_t i = 0; i < X2.size(); i++) @@ -368,12 +337,10 @@ std::vector fit_OLS_regressor(std::vector> const &X, template std::vector predict_OLS_regressor(std::vector> const &X, std::vector const &beta /**< */ -) -{ +) { std::vector result(X.size()); - for (size_t rows = 0; rows < X.size(); rows++) - { + for (size_t rows = 0; rows < X.size(); rows++) { // -> start with constant term result[rows] = beta[X[0].size()]; for (size_t cols = 0; cols < X[0].size(); cols++) @@ -386,8 +353,7 @@ std::vector predict_OLS_regressor(std::vector> const &X, /** * main function */ -int main() -{ +int main() { size_t N, F; std::cout << "Enter number of features: "; @@ -404,8 +370,7 @@ int main() << "Enter training data. Per sample, provide features ad one output." << std::endl; - for (size_t rows = 0; rows < N; rows++) - { + for (size_t rows = 0; rows < N; rows++) { std::vector v(F); std::cout << "Sample# " << rows + 1 << ": "; for (size_t cols = 0; cols < F; cols++) @@ -426,8 +391,7 @@ int main() std::vector> data2(T); // vector Y2(T); - for (size_t rows = 0; rows < T; rows++) - { + for (size_t rows = 0; rows < T; rows++) { std::cout << "Sample# " << rows + 1 << ": "; std::vector v(F); for (size_t cols = 0; cols < F; cols++) std::cin >> v[cols]; diff --git a/computer_oriented_statistical_methods/successive_approximation.cpp b/computer_oriented_statistical_methods/successive_approximation.cpp index 137933591..351382f24 100644 --- a/computer_oriented_statistical_methods/successive_approximation.cpp +++ b/computer_oriented_statistical_methods/successive_approximation.cpp @@ -17,13 +17,11 @@ static float eq(float y) { return (3 * y) - cos(y) - 2; } static float eqd(float y) { return 0.5 * (cos(y) + 2); } /** Main function */ -int main() -{ +int main() { float y, x1, x2, x3, sum, s, a, f1, f2, gd; int i, n; - for (i = 0; i < 10; i++) - { + for (i = 0; i < 10; i++) { sum = eq(y); std::cout << "value of equation at " << i << " " << sum << "\n"; y++; @@ -33,8 +31,7 @@ int main() std::cout << "enter the no iteration to perform->\n"; std::cin >> n; - for (i = 0; i <= n; i++) - { + for (i = 0; i <= n; i++) { x2 = eqd(x1); std::cout << "\nenter the x2->" << x2; x1 = x2; diff --git a/data_structure/avltree.cpp b/data_structure/avltree.cpp index dc96ad977..f38133c05 100644 --- a/data_structure/avltree.cpp +++ b/data_structure/avltree.cpp @@ -3,8 +3,7 @@ using namespace std; -typedef struct node -{ +typedef struct node { int data; int height; struct node *left; @@ -15,8 +14,7 @@ int max(int a, int b) { return a > b ? a : b; } // Returns a new Node -node *createNode(int data) -{ +node *createNode(int data) { node *nn = new node(); nn->data = data; nn->height = 0; @@ -27,8 +25,7 @@ node *createNode(int data) // Returns height of tree -int height(node *root) -{ +int height(node *root) { if (root == NULL) return 0; return 1 + max(height(root->left), height(root->right)); @@ -40,8 +37,7 @@ int getBalance(node *root) { return height(root->left) - height(root->right); } // Returns Node after Right Rotation -node *rightRotate(node *root) -{ +node *rightRotate(node *root) { node *t = root->left; node *u = t->right; t->right = root; @@ -51,8 +47,7 @@ node *rightRotate(node *root) // Returns Node after Left Rotation -node *leftRotate(node *root) -{ +node *leftRotate(node *root) { node *t = root->right; node *u = t->left; t->left = root; @@ -62,8 +57,7 @@ node *leftRotate(node *root) // Returns node with minimum value in the tree -node *minValue(node *root) -{ +node *minValue(node *root) { if (root->left == NULL) return root; return minValue(root->left); @@ -71,8 +65,7 @@ node *minValue(node *root) // Balanced Insertion -node *insert(node *root, int item) -{ +node *insert(node *root, int item) { node *nn = createNode(item); if (root == NULL) return nn; @@ -81,14 +74,11 @@ node *insert(node *root, int item) else root->right = insert(root->right, item); int b = getBalance(root); - if (b > 1) - { + if (b > 1) { if (getBalance(root->left) < 0) root->left = leftRotate(root->left); // Left-Right Case return rightRotate(root); // Left-Left Case - } - else if (b < -1) - { + } else if (b < -1) { if (getBalance(root->right) > 0) root->right = rightRotate(root->right); // Right-Left Case return leftRotate(root); // Right-Right Case @@ -98,8 +88,7 @@ node *insert(node *root, int item) // Balanced Deletion -node *deleteNode(node *root, int key) -{ +node *deleteNode(node *root, int key) { if (root == NULL) return root; if (key < root->data) @@ -107,18 +96,14 @@ node *deleteNode(node *root, int key) else if (key > root->data) root->right = deleteNode(root->right, key); - else - { + else { // Node to be deleted is leaf node or have only one Child - if (!root->right) - { + if (!root->right) { node *temp = root->left; delete (root); root = NULL; return temp; - } - else if (!root->left) - { + } else if (!root->left) { node *temp = root->right; delete (root); root = NULL; @@ -135,12 +120,10 @@ node *deleteNode(node *root, int key) // LevelOrder (Breadth First Search) -void levelOrder(node *root) -{ +void levelOrder(node *root) { queue q; q.push(root); - while (!q.empty()) - { + while (!q.empty()) { root = q.front(); cout << root->data << " "; q.pop(); @@ -151,8 +134,7 @@ void levelOrder(node *root) } } -int main() -{ +int main() { // Testing AVL Tree node *root = NULL; int i; diff --git a/data_structure/binary_search_tree.cpp b/data_structure/binary_search_tree.cpp index ea9df12d3..c3a74f385 100644 --- a/data_structure/binary_search_tree.cpp +++ b/data_structure/binary_search_tree.cpp @@ -1,15 +1,13 @@ #include using namespace std; -struct node -{ +struct node { int val; node *left; node *right; }; -struct queue -{ +struct queue { node *t[100]; int front; int rear; @@ -21,107 +19,71 @@ void enqueue(node *n) { q.t[q.rear++] = n; } node *dequeue() { return (q.t[q.front++]); } -void Insert(node *n, int x) -{ - if (x < n->val) - { - if (n->left == NULL) - { +void Insert(node *n, int x) { + if (x < n->val) { + if (n->left == NULL) { node *temp = new node; temp->val = x; temp->left = NULL; temp->right = NULL; n->left = temp; - } - else - { + } else { Insert(n->left, x); } - } - else - { - if (n->right == NULL) - { + } else { + if (n->right == NULL) { node *temp = new node; temp->val = x; temp->left = NULL; temp->right = NULL; n->left = temp; - } - else - { + } else { Insert(n->right, x); } } } -int findMaxInLeftST(node *n) -{ - while (n->right != NULL) - { +int findMaxInLeftST(node *n) { + while (n->right != NULL) { n = n->right; } return n->val; } -void Remove(node *p, node *n, int x) -{ - if (n->val == x) - { - if (n->right == NULL && n->left == NULL) - { - if (x < p->val) - { +void Remove(node *p, node *n, int x) { + if (n->val == x) { + if (n->right == NULL && n->left == NULL) { + if (x < p->val) { p->right = NULL; - } - else - { + } else { p->left = NULL; } - } - else if (n->right == NULL) - { - if (x < p->val) - { + } else if (n->right == NULL) { + if (x < p->val) { p->right = n->left; - } - else - { + } else { p->left = n->left; } - } - else if (n->left == NULL) - { - if (x < p->val) - { + } else if (n->left == NULL) { + if (x < p->val) { p->right = n->right; - } - else - { + } else { p->left = n->right; } - } - else - { + } else { int y = findMaxInLeftST(n->left); n->val = y; Remove(n, n->right, y); } - } - else if (x < n->val) - { + } else if (x < n->val) { Remove(n, n->left, x); - } - else - { + } else { Remove(n, n->right, x); } } -void BFT(node *n) -{ - if (n != NULL) - { +void BFT(node *n) { + if (n != NULL) { cout << n->val << " "; enqueue(n->left); enqueue(n->right); @@ -129,38 +91,31 @@ void BFT(node *n) } } -void Pre(node *n) -{ - if (n != NULL) - { +void Pre(node *n) { + if (n != NULL) { cout << n->val << " "; Pre(n->left); Pre(n->right); } } -void In(node *n) -{ - if (n != NULL) - { +void In(node *n) { + if (n != NULL) { In(n->left); cout << n->val << " "; In(n->right); } } -void Post(node *n) -{ - if (n != NULL) - { +void Post(node *n) { + if (n != NULL) { Post(n->left); Post(n->right); cout << n->val << " "; } } -int main() -{ +int main() { q.front = 0; q.rear = 0; int value; @@ -171,8 +126,7 @@ int main() root->val = value; root->left = NULL; root->right = NULL; - do - { + do { cout << "\n1. Insert"; cout << "\n2. Delete"; cout << "\n3. Breadth First"; @@ -183,8 +137,7 @@ int main() cout << "\nEnter Your Choice : "; cin >> ch; int x; - switch (ch) - { + switch (ch) { case 1: cout << "\nEnter the value to be Inserted : "; cin >> x; diff --git a/data_structure/binaryheap.cpp b/data_structure/binaryheap.cpp index b2fc7d99c..a31d87674 100644 --- a/data_structure/binaryheap.cpp +++ b/data_structure/binaryheap.cpp @@ -7,8 +7,7 @@ using namespace std; void swap(int *x, int *y); // A class for Min Heap -class MinHeap -{ +class MinHeap { int *harr; // pointer to array of elements in heap int capacity; // maximum possible size of min heap int heap_size; // Current number of elements in min heap @@ -44,18 +43,15 @@ class MinHeap }; // Constructor: Builds a heap from a given array a[] of given size -MinHeap::MinHeap(int cap) -{ +MinHeap::MinHeap(int cap) { heap_size = 0; capacity = cap; harr = new int[cap]; } // Inserts a new key 'k' -void MinHeap::insertKey(int k) -{ - if (heap_size == capacity) - { +void MinHeap::insertKey(int k) { + if (heap_size == capacity) { cout << "\nOverflow: Could not insertKey\n"; return; } @@ -66,8 +62,7 @@ void MinHeap::insertKey(int k) harr[i] = k; // Fix the min heap property if it is violated - while (i != 0 && harr[parent(i)] > harr[i]) - { + while (i != 0 && harr[parent(i)] > harr[i]) { swap(&harr[i], &harr[parent(i)]); i = parent(i); } @@ -75,23 +70,19 @@ void MinHeap::insertKey(int k) // Decreases value of key at index 'i' to new_val. It is assumed that // new_val is smaller than harr[i]. -void MinHeap::decreaseKey(int i, int new_val) -{ +void MinHeap::decreaseKey(int i, int new_val) { harr[i] = new_val; - while (i != 0 && harr[parent(i)] > harr[i]) - { + while (i != 0 && harr[parent(i)] > harr[i]) { swap(&harr[i], &harr[parent(i)]); i = parent(i); } } // Method to remove minimum element (or root) from min heap -int MinHeap::extractMin() -{ +int MinHeap::extractMin() { if (heap_size <= 0) return INT_MAX; - if (heap_size == 1) - { + if (heap_size == 1) { heap_size--; return harr[0]; } @@ -107,16 +98,14 @@ int MinHeap::extractMin() // This function deletes key at index i. It first reduced value to minus // infinite, then calls extractMin() -void MinHeap::deleteKey(int i) -{ +void MinHeap::deleteKey(int i) { decreaseKey(i, INT_MIN); extractMin(); } // A recursive method to heapify a subtree with the root at given index // This method assumes that the subtrees are already heapified -void MinHeap::MinHeapify(int i) -{ +void MinHeap::MinHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; @@ -124,24 +113,21 @@ void MinHeap::MinHeapify(int i) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; - if (smallest != i) - { + if (smallest != i) { swap(&harr[i], &harr[smallest]); MinHeapify(smallest); } } // A utility function to swap two elements -void swap(int *x, int *y) -{ +void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } // Driver program to test above functions -int main() -{ +int main() { MinHeap h(11); h.insertKey(3); h.insertKey(2); diff --git a/data_structure/circular_queue_using_linked_list.cpp b/data_structure/circular_queue_using_linked_list.cpp index d87124448..b6a471044 100644 --- a/data_structure/circular_queue_using_linked_list.cpp +++ b/data_structure/circular_queue_using_linked_list.cpp @@ -1,24 +1,20 @@ #include using namespace std; -struct node -{ +struct node { int data; struct node *next; }; -class Queue -{ +class Queue { node *front; node *rear; public: - Queue() - { + Queue() { front = NULL; rear = NULL; } - void createNode(int val) - { + void createNode(int val) { node *ptr; node *nn; nn = new node; @@ -28,14 +24,10 @@ class Queue front = nn; rear = nn; } - void enqueue(int val) - { - if (front == NULL || rear == NULL) - { + void enqueue(int val) { + if (front == NULL || rear == NULL) { createNode(val); - } - else - { + } else { node *ptr; node *nn; ptr = front; @@ -46,19 +38,16 @@ class Queue rear = nn; } } - void dequeue() - { + void dequeue() { node *n; n = front; front = front->next; delete (n); } - void traverse() - { + void traverse() { node *ptr; ptr = front; - do - { + do { cout << ptr->data << " "; ptr = ptr->next; } while (ptr != rear->next); @@ -66,8 +55,7 @@ class Queue cout << endl; } }; -int main(void) -{ +int main(void) { Queue q; q.enqueue(10); q.enqueue(20); diff --git a/data_structure/cll/cll.cpp b/data_structure/cll/cll.cpp index e9fcfc40b..42bc9067e 100644 --- a/data_structure/cll/cll.cpp +++ b/data_structure/cll/cll.cpp @@ -5,25 +5,22 @@ using namespace std; /* Constructor */ -cll::cll() -{ +cll::cll() { head = NULL; total = 0; } -cll::~cll() { /* Desstructure, no need to fill */ } +cll::~cll() { /* Desstructure, no need to fill */ +} /* Display a list. and total element */ -void cll::display() -{ +void cll::display() { if (head == NULL) cout << "List is empty !" << endl; - else - { + else { cout << "CLL list: "; node *current = head; - for (int i = 0; i < total; i++) - { + for (int i = 0; i < total; i++) { cout << current->data << " -> "; current = current->next; } @@ -33,22 +30,17 @@ void cll::display() } /* List insert a new value at head in list */ -void cll::insert_front(int new_data) -{ +void cll::insert_front(int new_data) { node *newNode; newNode = new node; newNode->data = new_data; newNode->next = NULL; - if (head == NULL) - { + if (head == NULL) { head = newNode; head->next = head; - } - else - { + } else { node *current = head; - while (current->next != head) - { + while (current->next != head) { current = current->next; } newNode->next = head; @@ -59,22 +51,17 @@ void cll::insert_front(int new_data) } /* List insert a new value at head in list */ -void cll::insert_tail(int new_data) -{ +void cll::insert_tail(int new_data) { node *newNode; newNode = new node; newNode->data = new_data; newNode->next = NULL; - if (head == NULL) - { + if (head == NULL) { head = newNode; head->next = head; - } - else - { + } else { node *current = head; - while (current->next != head) - { + while (current->next != head) { current = current->next; } current->next = newNode; @@ -88,18 +75,13 @@ int cll::get_size() { return total; } /* Return true if the requested item (sent in as an argument) is in the list, otherwise return false */ -bool cll::find_item(int item_to_find) -{ - if (head == NULL) - { +bool cll::find_item(int item_to_find) { + if (head == NULL) { cout << "List is empty !" << endl; return false; - } - else - { + } else { node *current = head; - while (current->next != head) - { + while (current->next != head) { if (current->data == item_to_find) return true; current = current->next; @@ -113,17 +95,12 @@ int cll::operator*() { return head->data; } /* Overload the pre-increment operator. The iterator is advanced to the next node. */ -void cll::operator++() -{ - if (head == NULL) - { +void cll::operator++() { + if (head == NULL) { cout << "List is empty !" << endl; - } - else - { + } else { node *current = head; - while (current->next != head) - { + while (current->next != head) { current = current->next; } current->next = head->next; diff --git a/data_structure/cll/cll.h b/data_structure/cll/cll.h index 89a9fe199..a1a9b4d92 100644 --- a/data_structure/cll/cll.h +++ b/data_structure/cll/cll.h @@ -9,14 +9,12 @@ #ifndef CLL_H #define CLL_H /*The data structure is a linear linked list of integers */ -struct node -{ +struct node { int data; node* next; }; -class cll -{ +class cll { public: cll(); /* Construct without parameter */ ~cll(); diff --git a/data_structure/cll/main_cll.cpp b/data_structure/cll/main_cll.cpp index 3876f0393..0b6bfd3ed 100644 --- a/data_structure/cll/main_cll.cpp +++ b/data_structure/cll/main_cll.cpp @@ -1,8 +1,7 @@ #include "cll.h" using namespace std; -int main() -{ +int main() { /* Test CLL */ cout << "----------- Test construct -----------" << endl; cll list1; diff --git a/data_structure/disjoint_set.cpp b/data_structure/disjoint_set.cpp index 8d27b704f..dd70e4cea 100644 --- a/data_structure/disjoint_set.cpp +++ b/data_structure/disjoint_set.cpp @@ -7,20 +7,16 @@ using std::vector; vector root, rnk; -void CreateSet(int n) -{ +void CreateSet(int n) { root = vector(n + 1); rnk = vector(n + 1, 1); - for (int i = 1; i <= n; ++i) - { + for (int i = 1; i <= n; ++i) { root[i] = i; } } -int Find(int x) -{ - if (root[x] == x) - { +int Find(int x) { + if (root[x] == x) { return x; } return root[x] = Find(root[x]); @@ -28,50 +24,38 @@ int Find(int x) bool InSameUnion(int x, int y) { return Find(x) == Find(y); } -void Union(int x, int y) -{ +void Union(int x, int y) { int a = Find(x), b = Find(y); - if (a != b) - { - if (rnk[a] < rnk[b]) - { + if (a != b) { + if (rnk[a] < rnk[b]) { root[a] = b; - } - else if (rnk[a] > rnk[b]) - { + } else if (rnk[a] > rnk[b]) { root[b] = a; - } - else - { + } else { root[a] = b; ++rnk[b]; } } } -int main() -{ +int main() { // tests CreateSet & Find int n = 100; CreateSet(n); - for (int i = 1; i <= 100; ++i) - { - if (root[i] != i) - { + for (int i = 1; i <= 100; ++i) { + if (root[i] != i) { cout << "Fail" << endl; break; } } // tests InSameUnion & Union cout << "1 and 2 are initially not in the same subset" << endl; - if (InSameUnion(1, 2)) - { + if (InSameUnion(1, 2)) { cout << "Fail" << endl; } Union(1, 2); cout << "1 and 2 are now in the same subset" << endl; - if (!InSameUnion(1, 2)) - { + if (!InSameUnion(1, 2)) { cout << "Fail" << endl; } return 0; diff --git a/data_structure/doubly_linked_list.cpp b/data_structure/doubly_linked_list.cpp index 4907c125d..30cc257d8 100644 --- a/data_structure/doubly_linked_list.cpp +++ b/data_structure/doubly_linked_list.cpp @@ -2,15 +2,13 @@ #include #include -struct node -{ +struct node { int val; node *prev; node *next; } * start; -class double_linked_list -{ +class double_linked_list { public: double_linked_list() { start = NULL; } void insert(int x); @@ -20,13 +18,10 @@ class double_linked_list void reverseShow(); }; -void double_linked_list::insert(int x) -{ +void double_linked_list::insert(int x) { node *t = start; - if (start != NULL) - { - while (t->next != NULL) - { + if (start != NULL) { + while (t->next != NULL) { t = t->next; } node *n = new node; @@ -34,9 +29,7 @@ void double_linked_list::insert(int x) n->prev = t; n->val = x; n->next = NULL; - } - else - { + } else { node *n = new node; n->val = x; n->prev = NULL; @@ -45,91 +38,69 @@ void double_linked_list::insert(int x) } } -void double_linked_list::remove(int x) -{ +void double_linked_list::remove(int x) { node *t = start; - while (t != NULL && t->val != x) - { + while (t != NULL && t->val != x) { t = t->next; } - if (t == NULL) - { + if (t == NULL) { return; } - if (t->prev == NULL) - { - if (t->next == NULL) - { + if (t->prev == NULL) { + if (t->next == NULL) { start = NULL; - } - else - { + } else { start = t->next; start->prev = NULL; } - } - else if (t->next == NULL) - { + } else if (t->next == NULL) { t->prev->next = NULL; - } - else - { + } else { t->prev->next = t->next; t->next->prev = t->prev; } delete t; } -void double_linked_list::search(int x) -{ +void double_linked_list::search(int x) { node *t = start; int found = 0; - while (t != NULL) - { - if (t->val == x) - { + while (t != NULL) { + if (t->val == x) { std::cout << "\nFound"; found = 1; break; } t = t->next; } - if (found == 0) - { + if (found == 0) { std::cout << "\nNot Found"; } } -void double_linked_list::show() -{ +void double_linked_list::show() { node *t = start; - while (t != NULL) - { + while (t != NULL) { std::cout << t->val << "\t"; t = t->next; } } -void double_linked_list::reverseShow() -{ +void double_linked_list::reverseShow() { node *t = start; - while (t != NULL && t->next != NULL) - { + while (t != NULL && t->next != NULL) { t = t->next; } - while (t != NULL) - { + while (t != NULL) { std::cout << t->val << "\t"; t = t->prev; } } -int main() -{ +int main() { int choice, x; double_linked_list ob; - do - { + do { std::cout << "\n1. Insert"; std::cout << "\n2. Delete"; std::cout << "\n3. Search"; @@ -137,8 +108,7 @@ int main() std::cout << "\n5. Reverse print"; std::cout << "\n\nEnter you choice : "; std::cin >> choice; - switch (choice) - { + switch (choice) { case 1: std::cout << "\nEnter the element to be inserted : "; std::cin >> x; diff --git a/data_structure/linked_list.cpp b/data_structure/linked_list.cpp index f639bb16c..8eb6e586d 100644 --- a/data_structure/linked_list.cpp +++ b/data_structure/linked_list.cpp @@ -1,42 +1,32 @@ #include -struct node -{ +struct node { int val; node *next; }; node *start; -void insert(int x) -{ +void insert(int x) { node *t = start; node *n = new node; n->val = x; n->next = NULL; - if (start != NULL) - { - while (t->next != NULL) - { + if (start != NULL) { + while (t->next != NULL) { t = t->next; } t->next = n; - } - else - { + } else { start = n; } } -void remove(int x) -{ - if (start == NULL) - { +void remove(int x) { + if (start == NULL) { std::cout << "\nLinked List is empty\n"; return; - } - else if (start->val == x) - { + } else if (start->val == x) { node *temp = start; start = start->next; delete temp; @@ -45,14 +35,12 @@ void remove(int x) node *temp = start, *parent = start; - while (temp != NULL && temp->val != x) - { + while (temp != NULL && temp->val != x) { parent = temp; temp = temp->next; } - if (temp == NULL) - { + if (temp == NULL) { std::cout << std::endl << x << " not found in list\n"; return; } @@ -61,44 +49,35 @@ void remove(int x) delete temp; } -void search(int x) -{ +void search(int x) { node *t = start; int found = 0; - while (t != NULL) - { - if (t->val == x) - { + while (t != NULL) { + if (t->val == x) { std::cout << "\nFound"; found = 1; break; } t = t->next; } - if (found == 0) - { + if (found == 0) { std::cout << "\nNot Found"; } } -void show() -{ +void show() { node *t = start; - while (t != NULL) - { + while (t != NULL) { std::cout << t->val << "\t"; t = t->next; } } -void reverse() -{ +void reverse() { node *first = start; - if (first != NULL) - { + if (first != NULL) { node *second = first->next; - while (second != NULL) - { + while (second != NULL) { node *tem = second->next; second->next = first; first = second; @@ -106,18 +85,14 @@ void reverse() } start->next = NULL; start = first; - } - else - { + } else { std::cout << "\nEmpty list"; } } -int main() -{ +int main() { int choice, x; - do - { + do { std::cout << "\n1. Insert"; std::cout << "\n2. Delete"; std::cout << "\n3. Search"; @@ -126,8 +101,7 @@ int main() std::cout << "\n0. Exit"; std::cout << "\n\nEnter you choice : "; std::cin >> choice; - switch (choice) - { + switch (choice) { case 1: std::cout << "\nEnter the element to be inserted : "; std::cin >> x; diff --git a/data_structure/linkedlist_implentation_usingarray.cpp b/data_structure/linkedlist_implentation_usingarray.cpp index 168124f00..a078bef16 100644 --- a/data_structure/linkedlist_implentation_usingarray.cpp +++ b/data_structure/linkedlist_implentation_usingarray.cpp @@ -7,18 +7,15 @@ #include using namespace std; -struct Node -{ +struct Node { int data; int next; }; Node AvailArray[100]; // array that will act as nodes of a linked list. int head = -1; int avail = 0; -void initialise_list() -{ - for (int i = 0; i <= 98; i++) - { +void initialise_list() { + for (int i = 0; i <= 98; i++) { AvailArray[i].next = i + 1; } AvailArray[99].next = -1; // indicating the end of the linked list. @@ -50,12 +47,10 @@ void insertAtTheBeginning(int data) // The function will insert the given data head = newNode; } -void insertAtTheEnd(int data) -{ +void insertAtTheEnd(int data) { int newNode = getnode(); int temp = head; - while (AvailArray[temp].next != -1) - { + while (AvailArray[temp].next != -1) { temp = AvailArray[temp].next; } // temp is now pointing to the end node. @@ -64,11 +59,9 @@ void insertAtTheEnd(int data) AvailArray[temp].next = newNode; } -void display() -{ +void display() { int temp = head; - while (temp != -1) - { + while (temp != -1) { cout << AvailArray[temp].data << "->"; temp = AvailArray[temp].next; } @@ -76,20 +69,17 @@ void display() ; } -int main() -{ +int main() { initialise_list(); int x, y, z; - for (;;) - { + for (;;) { cout << "1. Insert At The Beginning" << endl; cout << "2. Insert At The End" << endl; cout << "3. Display" << endl; cout << "4.Exit" << endl; cout << "Enter Your choice" << endl; cin >> z; - switch (z) - { + switch (z) { case 1: cout << "Enter the number you want to enter" << endl; cin >> x; diff --git a/data_structure/list_array.cpp b/data_structure/list_array.cpp index f572b77b4..c796ffef9 100644 --- a/data_structure/list_array.cpp +++ b/data_structure/list_array.cpp @@ -1,16 +1,13 @@ #include using namespace std; -struct list -{ +struct list { int data[50]; int top = 0; bool isSorted = false; - int BinarySearch(int *array, int first, int last, int x) - { - if (last < first) - { + int BinarySearch(int *array, int first, int last, int x) { + if (last < first) { return -1; } int mid = (first + last) / 2; @@ -22,12 +19,9 @@ struct list return (BinarySearch(array, mid + 1, last, x)); } - int LinarSearch(int *array, int x) - { - for (int i = 0; i < top; i++) - { - if (array[i] == x) - { + int LinarSearch(int *array, int x) { + for (int i = 0; i < top; i++) { + if (array[i] == x) { return i; } } @@ -35,41 +29,31 @@ struct list return -1; } - int Search(int x) - { + int Search(int x) { int pos = -1; - if (isSorted) - { + if (isSorted) { pos = BinarySearch(data, 0, top - 1, x); } - else - { + else { pos = LinarSearch(data, x); } - if (pos != -1) - { + if (pos != -1) { cout << "\nElement found at position : " << pos; - } - else - { + } else { cout << "\nElement not found"; } return pos; } - void Sort() - { + void Sort() { int i, j, pos; - for (i = 0; i < top; i++) - { + for (i = 0; i < top; i++) { int min = data[i]; - for (j = i + 1; j < top; j++) - { - if (data[j] < min) - { + for (j = i + 1; j < top; j++) { + if (data[j] < min) { pos = j; min = data[pos]; } @@ -82,40 +66,30 @@ struct list isSorted = true; } - void insert(int x) - { - if (!isSorted) - { - if (top == 49) - { + void insert(int x) { + if (!isSorted) { + if (top == 49) { cout << "\nOverflow"; - } - else - { + } else { data[top] = x; top++; } } - else - { + else { int pos = 0; - for (int i = 0; i < top - 1; i++) - { - if (data[i] <= x && x <= data[i + 1]) - { + for (int i = 0; i < top - 1; i++) { + if (data[i] <= x && x <= data[i + 1]) { pos = i + 1; break; } } - if (pos == 0) - { + if (pos == 0) { pos = top - 1; } - for (int i = top; i > pos; i--) - { + for (int i = top; i > pos; i--) { data[i] = data[i - 1]; } top++; @@ -123,33 +97,27 @@ struct list } } - void Remove(int x) - { + void Remove(int x) { int pos = Search(x); cout << "\n" << data[pos] << " deleted"; - for (int i = pos; i < top; i++) - { + for (int i = pos; i < top; i++) { data[i] = data[i + 1]; } top--; } - void Show() - { - for (int i = 0; i < top; i++) - { + void Show() { + for (int i = 0; i < top; i++) { cout << data[i] << "\t"; } } }; -int main() -{ +int main() { list L; int choice; int x; - do - { + do { cout << "\n1.Insert"; cout << "\n2.Delete"; cout << "\n3.Search"; @@ -157,8 +125,7 @@ int main() cout << "\n5.Print"; cout << "\n\nEnter Your Choice : "; cin >> choice; - switch (choice) - { + switch (choice) { case 1: cout << "\nEnter the element to be inserted : "; cin >> x; diff --git a/data_structure/morrisinorder.cpp b/data_structure/morrisinorder.cpp index 58f267907..f1f9e068c 100644 --- a/data_structure/morrisinorder.cpp +++ b/data_structure/morrisinorder.cpp @@ -7,39 +7,32 @@ using namespace std; -struct Btree -{ +struct Btree { int data; struct Btree *left; // Pointer to left subtree struct Btree *right; // Pointer to right subtree }; -void insert(Btree **root, int d) -{ +void insert(Btree **root, int d) { Btree *nn = new Btree(); // Creating new node nn->data = d; nn->left = NULL; nn->right = NULL; - if (*root == NULL) - { + if (*root == NULL) { *root = nn; return; - } - else - { + } else { queue q; // Adding root node to queue q.push(*root); - while (!q.empty()) - { + while (!q.empty()) { Btree *node = q.front(); // Removing parent node from queue q.pop(); if (node->left) // Adding left child of removed node to queue q.push(node->left); - else - { + else { // Adding new node if no left child is present node->left = nn; return; @@ -47,8 +40,7 @@ void insert(Btree **root, int d) if (node->right) // Adding right child of removed node to queue q.push(node->right); - else - { + else { // Adding new node if no right child is present node->right = nn; return; @@ -57,36 +49,29 @@ void insert(Btree **root, int d) } } -void morrisInorder(Btree *root) -{ +void morrisInorder(Btree *root) { Btree *curr = root; Btree *temp; - while (curr) - { - if (curr->left == NULL) - { + while (curr) { + if (curr->left == NULL) { cout << curr->data << " "; // If left of current node is NULL then curr is shifted to right curr = curr->right; - } - else - { + } else { // Left of current node is stored in temp temp = curr->left; // Moving to extreme right of temp while (temp->right && temp->right != curr) temp = temp->right; // If extreme right is null it is made to point to currrent node // (will be used for backtracking) - if (temp->right == NULL) - { + if (temp->right == NULL) { temp->right = curr; // current node is made to point its left subtree curr = curr->left; } // If extreme right already points to currrent node it it set to // null - else if (temp->right == curr) - { + else if (temp->right == curr) { cout << curr->data << " "; temp->right = NULL; // current node is made to point its right subtree @@ -96,8 +81,7 @@ void morrisInorder(Btree *root) } } -int main() -{ +int main() { // Testing morrisInorder funtion Btree *root = NULL; int i; diff --git a/data_structure/queue/queue.cpp b/data_structure/queue/queue.cpp index e8ff8966c..a7055bb14 100644 --- a/data_structure/queue/queue.cpp +++ b/data_structure/queue/queue.cpp @@ -6,8 +6,7 @@ using namespace std; /* Default constructor*/ template -queue::queue() -{ +queue::queue() { queueFront = NULL; queueRear = NULL; size = 0; @@ -15,18 +14,14 @@ queue::queue() /* Destructor */ template -queue::~queue() -{ -} +queue::~queue() {} /* Display for testing */ template -void queue::display() -{ +void queue::display() { node *current = queueFront; cout << "Front --> "; - while (current != NULL) - { + while (current != NULL) { cout << current->data << " "; current = current->next; } @@ -36,33 +31,27 @@ void queue::display() /* Determine whether the queue is empty */ template -bool queue::isEmptyQueue() -{ +bool queue::isEmptyQueue() { return (queueFront == NULL); } /* Clear queue */ template -void queue::clear() -{ +void queue::clear() { queueFront = NULL; } /* Add new item to the queue */ template -void queue::enQueue(Kind item) -{ +void queue::enQueue(Kind item) { node *newNode; newNode = new node; newNode->data = item; newNode->next = NULL; - if (queueFront == NULL) - { + if (queueFront == NULL) { queueFront = newNode; queueRear = newNode; - } - else - { + } else { queueRear->next = newNode; queueRear = queueRear->next; } @@ -71,26 +60,21 @@ void queue::enQueue(Kind item) /* Return the top element of the queue */ template -Kind queue::front() -{ +Kind queue::front() { assert(queueFront != NULL); return queueFront->data; } /* Remove the element of the queue */ template -void queue::deQueue() -{ +void queue::deQueue() { node *temp; - if (!isEmptyQueue()) - { + if (!isEmptyQueue()) { temp = queueFront; queueFront = queueFront->next; delete temp; size--; - } - else - { + } else { cout << "Queue is empty !" << endl; } } diff --git a/data_structure/queue/queue.h b/data_structure/queue/queue.h index 7e9c44559..d1305fc81 100644 --- a/data_structure/queue/queue.h +++ b/data_structure/queue/queue.h @@ -4,16 +4,14 @@ /* Definition of the node */ template -struct node -{ +struct node { Kind data; node *next; }; /* Definition of the queue class */ template -class queue -{ +class queue { public: void display(); /* Show queue */ queue(); /* Default constructor*/ diff --git a/data_structure/queue/test_queue.cpp b/data_structure/queue/test_queue.cpp index d9308adcb..7f0923f78 100644 --- a/data_structure/queue/test_queue.cpp +++ b/data_structure/queue/test_queue.cpp @@ -5,8 +5,7 @@ using namespace std; -int main() -{ +int main() { queue q; cout << "---------------------- Test construct ----------------------" << endl; diff --git a/data_structure/queue_using_array.cpp b/data_structure/queue_using_array.cpp index c7fbf1ef7..a887c99fc 100644 --- a/data_structure/queue_using_array.cpp +++ b/data_structure/queue_using_array.cpp @@ -10,15 +10,13 @@ #define MAXSIZE 10 -class Queue_Array -{ +class Queue_Array { int front; int rear; int size; public: - Queue_Array() - { + Queue_Array() { front = -1; rear = -1; size = MAXSIZE; @@ -29,59 +27,42 @@ class Queue_Array void display(); }; -void Queue_Array::enqueue(int ele) -{ - if (rear == size - 1) - { +void Queue_Array::enqueue(int ele) { + if (rear == size - 1) { std::cout << "\nStack is full"; - } - else if (front == -1 && rear == -1) - { + } else if (front == -1 && rear == -1) { front = rear = 0; arr[rear] = ele; - } - else if (rear < size) - { + } else if (rear < size) { rear++; arr[rear] = ele; } } -int Queue_Array::dequeue() -{ +int Queue_Array::dequeue() { int d; - if (front == -1) - { + if (front == -1) { std::cout << "\nstack is empty "; return 0; - } - else if (front == rear) - { + } else if (front == rear) { d = arr[front]; front = rear = -1; - } - else - { + } else { d = arr[front++]; } return d; } -void Queue_Array::display() -{ - if (front == -1) - { +void Queue_Array::display() { + if (front == -1) { std::cout << "\nStack is empty"; - } - else - { + } else { for (int i = front; i <= rear; i++) std::cout << arr[i] << " "; } } -int main() -{ +int main() { int op, data; Queue_Array ob; @@ -90,31 +71,21 @@ int main() std::cout << "\n2. dequeue(Deletion)"; std::cout << "\n3. Display"; std::cout << "\n4. Exit"; - while (1) - { + while (1) { std::cout << "\nEnter your choice "; std::cin >> op; - if (op == 1) - { + if (op == 1) { std::cout << "Enter data "; std::cin >> data; ob.enqueue(data); - } - else if (op == 2) - { + } else if (op == 2) { data = ob.dequeue(); std::cout << "\ndequeue element is:\t" << data; - } - else if (op == 3) - { + } else if (op == 3) { ob.display(); - } - else if (op == 4) - { + } else if (op == 4) { exit(0); - } - else - { + } else { std::cout << "\nWrong choice "; } } diff --git a/data_structure/queue_using_array2.cpp b/data_structure/queue_using_array2.cpp index 7e1ada725..13f7d8e17 100644 --- a/data_structure/queue_using_array2.cpp +++ b/data_structure/queue_using_array2.cpp @@ -5,30 +5,22 @@ int queue[10]; int front = 0; int rear = 0; -void Enque(int x) -{ - if (rear == 10) - { +void Enque(int x) { + if (rear == 10) { cout << "\nOverflow"; - } - else - { + } else { queue[rear++] = x; } } -void Deque() -{ - if (front == rear) - { +void Deque() { + if (front == rear) { cout << "\nUnderflow"; } - else - { + else { cout << "\n" << queue[front++] << " deleted"; - for (int i = front; i < rear; i++) - { + for (int i = front; i < rear; i++) { queue[i - front] = queue[i]; } rear = rear - front; @@ -36,36 +28,27 @@ void Deque() } } -void show() -{ - for (int i = front; i < rear; i++) - { +void show() { + for (int i = front; i < rear; i++) { cout << queue[i] << "\t"; } } -int main() -{ +int main() { int ch, x; - do - { + do { cout << "\n1. Enque"; cout << "\n2. Deque"; cout << "\n3. Print"; cout << "\nEnter Your Choice : "; cin >> ch; - if (ch == 1) - { + if (ch == 1) { cout << "\nInsert : "; cin >> x; Enque(x); - } - else if (ch == 2) - { + } else if (ch == 2) { Deque(); - } - else if (ch == 3) - { + } else if (ch == 3) { show(); } } while (ch != 0); diff --git a/data_structure/queue_using_linked_list.cpp b/data_structure/queue_using_linked_list.cpp index 9ddbdaa42..7b44d240c 100644 --- a/data_structure/queue_using_linked_list.cpp +++ b/data_structure/queue_using_linked_list.cpp @@ -1,18 +1,15 @@ #include using namespace std; -struct node -{ +struct node { int val; node *next; }; node *front, *rear; -void Enque(int x) -{ - if (rear == NULL) - { +void Enque(int x) { + if (rear == NULL) { node *n = new node; n->val = x; n->next = NULL; @@ -20,8 +17,7 @@ void Enque(int x) front = n; } - else - { + else { node *n = new node; n->val = x; n->next = NULL; @@ -30,14 +26,10 @@ void Enque(int x) } } -void Deque() -{ - if (rear == NULL && front == NULL) - { +void Deque() { + if (rear == NULL && front == NULL) { cout << "\nUnderflow"; - } - else - { + } else { node *t = front; cout << "\n" << t->val << " deleted"; front = front->next; @@ -47,38 +39,29 @@ void Deque() } } -void show() -{ +void show() { node *t = front; - while (t != NULL) - { + while (t != NULL) { cout << t->val << "\t"; t = t->next; } } -int main() -{ +int main() { int ch, x; - do - { + do { cout << "\n1. Enque"; cout << "\n2. Deque"; cout << "\n3. Print"; cout << "\nEnter Your Choice : "; cin >> ch; - if (ch == 1) - { + if (ch == 1) { cout << "\nInsert : "; cin >> x; Enque(x); - } - else if (ch == 2) - { + } else if (ch == 2) { Deque(); - } - else if (ch == 3) - { + } else if (ch == 3) { show(); } } while (ch != 0); diff --git a/data_structure/queue_using_linkedlist.cpp b/data_structure/queue_using_linkedlist.cpp index 21ff0cfcf..f1bf18123 100644 --- a/data_structure/queue_using_linkedlist.cpp +++ b/data_structure/queue_using_linkedlist.cpp @@ -3,13 +3,11 @@ */ #include -struct linkedlist -{ +struct linkedlist { int data; linkedlist *next; }; -class stack_linkedList -{ +class stack_linkedList { public: linkedlist *front; linkedlist *rear; @@ -19,28 +17,24 @@ class stack_linkedList int dequeue(); void display(); }; -void stack_linkedList::enqueue(int ele) -{ +void stack_linkedList::enqueue(int ele) { linkedlist *temp = new linkedlist(); temp->data = ele; temp->next = NULL; if (front == NULL) front = rear = temp; - else - { + else { rear->next = temp; rear = temp; } } -int stack_linkedList::dequeue() -{ +int stack_linkedList::dequeue() { linkedlist *temp; int ele; if (front == NULL) std::cout << "\nStack is empty"; - else - { + else { temp = front; ele = temp->data; if (front == rear) // if length of queue is 1; @@ -50,25 +44,21 @@ int stack_linkedList::dequeue() } return ele; } -void stack_linkedList::display() -{ +void stack_linkedList::display() { if (front == NULL) std::cout << "\nStack is empty"; - else - { + else { linkedlist *temp; temp = front; - while (temp != NULL) - { + while (temp != NULL) { std::cout << temp->data << " "; temp = temp->next; } } } -int main() -{ +int main() { int op, data; stack_linkedList ob; std::cout << "\n1. enqueue(Insertion) "; @@ -76,17 +66,14 @@ int main() std::cout << "\n3. Display"; std::cout << "\n4. Exit"; - while (1) - { + while (1) { std::cout << "\nEnter your choice "; std::cin >> op; - if (op == 1) - { + if (op == 1) { std::cout << "Enter data "; std::cin >> data; ob.enqueue(data); - } - else if (op == 2) + } else if (op == 2) data = ob.dequeue(); else if (op == 3) ob.display(); diff --git a/data_structure/stack_using_array.cpp b/data_structure/stack_using_array.cpp index dd0709ff2..5dd7ac98e 100644 --- a/data_structure/stack_using_array.cpp +++ b/data_structure/stack_using_array.cpp @@ -4,69 +4,50 @@ using namespace std; int *stack; int top = 0, size; -void push(int x) -{ - if (top == size) - { +void push(int x) { + if (top == size) { cout << "\nOverflow"; - } - else - { + } else { stack[top++] = x; } } -void pop() -{ - if (top == 0) - { +void pop() { + if (top == 0) { cout << "\nUnderflow"; - } - else - { + } else { cout << "\n" << stack[--top] << " deleted"; } } -void show() -{ - for (int i = 0; i < top; i++) - { +void show() { + for (int i = 0; i < top; i++) { cout << stack[i] << "\n"; } } void topmost() { cout << "\nTopmost element: " << stack[top - 1]; } -int main() -{ +int main() { cout << "\nEnter Size of stack : "; cin >> size; stack = new int[size]; int ch, x; - do - { + do { cout << "\n1. Push"; cout << "\n2. Pop"; cout << "\n3. Print"; cout << "\n4. Print topmost element:"; cout << "\nEnter Your Choice : "; cin >> ch; - if (ch == 1) - { + if (ch == 1) { cout << "\nInsert : "; cin >> x; push(x); - } - else if (ch == 2) - { + } else if (ch == 2) { pop(); - } - else if (ch == 3) - { + } else if (ch == 3) { show(); - } - else if (ch == 4) - { + } else if (ch == 4) { topmost(); } } while (ch != 0); diff --git a/data_structure/stack_using_linked_list.cpp b/data_structure/stack_using_linked_list.cpp index 89a15fe39..ae53fe95a 100644 --- a/data_structure/stack_using_linked_list.cpp +++ b/data_structure/stack_using_linked_list.cpp @@ -1,30 +1,24 @@ #include using namespace std; -struct node -{ +struct node { int val; node *next; }; node *top; -void push(int x) -{ +void push(int x) { node *n = new node; n->val = x; n->next = top; top = n; } -void pop() -{ - if (top == NULL) - { +void pop() { + if (top == NULL) { cout << "\nUnderflow"; - } - else - { + } else { node *t = top; cout << "\n" << t->val << " deleted"; top = top->next; @@ -32,38 +26,29 @@ void pop() } } -void show() -{ +void show() { node *t = top; - while (t != NULL) - { + while (t != NULL) { cout << t->val << "\n"; t = t->next; } } -int main() -{ +int main() { int ch, x; - do - { + do { cout << "\n1. Push"; cout << "\n2. Pop"; cout << "\n3. Print"; cout << "\nEnter Your Choice : "; cin >> ch; - if (ch == 1) - { + if (ch == 1) { cout << "\nInsert : "; cin >> x; push(x); - } - else if (ch == 2) - { + } else if (ch == 2) { pop(); - } - else if (ch == 3) - { + } else if (ch == 3) { show(); } } while (ch != 0); diff --git a/data_structure/stk/main.cpp b/data_structure/stk/main.cpp index ceac2ac8a..44b7984e0 100644 --- a/data_structure/stk/main.cpp +++ b/data_structure/stk/main.cpp @@ -19,8 +19,7 @@ using namespace std; -int main(int argc, char* argv[]) -{ +int main(int argc, char* argv[]) { double GPA; double highestGPA; string name; @@ -35,24 +34,19 @@ int main(int argc, char* argv[]) infile >> GPA >> name; highestGPA = GPA; - while (infile) - { - if (GPA > highestGPA) - { + while (infile) { + if (GPA > highestGPA) { stk.clear(); stk.push(name); highestGPA = GPA; - } - else if (GPA == highestGPA) - { + } else if (GPA == highestGPA) { stk.push(name); } infile >> GPA >> name; } cout << "Highest GPA: " << highestGPA << endl; cout << "Students the highest GPA are: " << endl; - while (!stk.isEmptyStack()) - { + while (!stk.isEmptyStack()) { cout << stk.top() << endl; stk.pop(); } diff --git a/data_structure/stk/stack.cpp b/data_structure/stk/stack.cpp index 9f92efbd5..bfa8a353e 100644 --- a/data_structure/stk/stack.cpp +++ b/data_structure/stk/stack.cpp @@ -6,26 +6,21 @@ using namespace std; /* Default constructor*/ template -stack::stack() -{ +stack::stack() { stackTop = NULL; size = 0; } /* Destructor */ template -stack::~stack() -{ -} +stack::~stack() {} /* Display for testing */ template -void stack::display() -{ +void stack::display() { node *current = stackTop; cout << "Top --> "; - while (current != NULL) - { + while (current != NULL) { cout << current->data << " "; current = current->next; } @@ -35,22 +30,19 @@ void stack::display() /* Determine whether the stack is empty */ template -bool stack::isEmptyStack() -{ +bool stack::isEmptyStack() { return (stackTop == NULL); } /* Clear stack */ template -void stack::clear() -{ +void stack::clear() { stackTop = NULL; } /* Add new item to the stack */ template -void stack::push(Type item) -{ +void stack::push(Type item) { node *newNode; newNode = new node; newNode->data = item; @@ -61,42 +53,35 @@ void stack::push(Type item) /* Return the top element of the stack */ template -Type stack::top() -{ +Type stack::top() { assert(stackTop != NULL); return stackTop->data; } /* Remove the top element of the stack */ template -void stack::pop() -{ +void stack::pop() { node *temp; - if (!isEmptyStack()) - { + if (!isEmptyStack()) { temp = stackTop; stackTop = stackTop->next; delete temp; size--; - } - else - { + } else { cout << "Stack is empty !" << endl; } } /* Operator "=" */ template -stack stack::operator=(stack &otherStack) -{ +stack stack::operator=(stack &otherStack) { node *newNode, *current, *last; if (stackTop != NULL) /* If stack is no empty, make it empty */ stackTop = NULL; if (otherStack.stackTop == NULL) stackTop = NULL; - else - { + else { current = otherStack.stackTop; stackTop = new node; stackTop->data = current->data; @@ -104,8 +89,7 @@ stack stack::operator=(stack &otherStack) last = stackTop; current = current->next; /* Copy the remaining stack */ - while (current != NULL) - { + while (current != NULL) { newNode = new node; newNode->data = current->data; newNode->next = NULL; diff --git a/data_structure/stk/stack.h b/data_structure/stk/stack.h index 39b455ac0..da7788b73 100644 --- a/data_structure/stk/stack.h +++ b/data_structure/stk/stack.h @@ -4,16 +4,14 @@ /* Definition of the node */ template -struct node -{ +struct node { Type data; node *next; }; /* Definition of the stack class */ template -class stack -{ +class stack { public: void display(); /* Show stack */ stack(); /* Default constructor*/ diff --git a/data_structure/stk/test_stack.cpp b/data_structure/stk/test_stack.cpp index 8839fdfa3..098027dfd 100644 --- a/data_structure/stk/test_stack.cpp +++ b/data_structure/stk/test_stack.cpp @@ -4,8 +4,7 @@ using namespace std; -int main() -{ +int main() { stack stk; cout << "---------------------- Test construct ----------------------" << endl; diff --git a/data_structure/tree.cpp b/data_structure/tree.cpp index 92d139b72..f46c31ff2 100644 --- a/data_structure/tree.cpp +++ b/data_structure/tree.cpp @@ -2,17 +2,14 @@ #include using namespace std; -struct node -{ +struct node { int val; node *left; node *right; }; -void CreateTree(node *curr, node *n, int x, char pos) -{ - if (n != NULL) - { +void CreateTree(node *curr, node *n, int x, char pos) { + if (n != NULL) { char ch; cout << "\nLeft or Right of " << n->val << " : "; cin >> ch; @@ -20,32 +17,25 @@ void CreateTree(node *curr, node *n, int x, char pos) CreateTree(n, n->left, x, ch); else if (ch == 'r') CreateTree(n, n->right, x, ch); - } - else - { + } else { node *t = new node; t->val = x; t->left = NULL; t->right = NULL; - if (pos == 'l') - { + if (pos == 'l') { curr->left = t; - } - else if (pos == 'r') - { + } else if (pos == 'r') { curr->right = t; } } } -void BFT(node *n) -{ +void BFT(node *n) { list queue; queue.push_back(n); - while (!queue.empty()) - { + while (!queue.empty()) { n = queue.front(); cout << n->val << " "; queue.pop_front(); @@ -57,38 +47,31 @@ void BFT(node *n) } } -void Pre(node *n) -{ - if (n != NULL) - { +void Pre(node *n) { + if (n != NULL) { cout << n->val << " "; Pre(n->left); Pre(n->right); } } -void In(node *n) -{ - if (n != NULL) - { +void In(node *n) { + if (n != NULL) { In(n->left); cout << n->val << " "; In(n->right); } } -void Post(node *n) -{ - if (n != NULL) - { +void Post(node *n) { + if (n != NULL) { Post(n->left); Post(n->right); cout << n->val << " "; } } -int main() -{ +int main() { int value; int ch; node *root = new node; @@ -97,8 +80,7 @@ int main() root->val = value; root->left = NULL; root->right = NULL; - do - { + do { cout << "\n1. Insert"; cout << "\n2. Breadth First"; cout << "\n3. Preorder Depth First"; @@ -107,8 +89,7 @@ int main() cout << "\nEnter Your Choice : "; cin >> ch; - switch (ch) - { + switch (ch) { case 1: int x; char pos; diff --git a/data_structure/trie_tree.cpp b/data_structure/trie_tree.cpp index d34dd2dbc..66b67fbc0 100644 --- a/data_structure/trie_tree.cpp +++ b/data_structure/trie_tree.cpp @@ -5,15 +5,13 @@ #include // structure definition -typedef struct trie -{ +typedef struct trie { struct trie* arr[26]; bool isEndofWord; } trie; // create a new node for trie -trie* createNode() -{ +trie* createNode() { trie* nn = new trie(); for (int i = 0; i < 26; i++) nn->arr[i] = NULL; nn->isEndofWord = false; @@ -21,17 +19,12 @@ trie* createNode() } // insert string into the trie -void insert(trie* root, std::string str) -{ - for (int i = 0; i < str.length(); i++) - { +void insert(trie* root, std::string str) { + for (int i = 0; i < str.length(); i++) { int j = str[i] - 'a'; - if (root->arr[j]) - { + if (root->arr[j]) { root = root->arr[j]; - } - else - { + } else { root->arr[j] = createNode(); root = root->arr[j]; } @@ -40,10 +33,8 @@ void insert(trie* root, std::string str) } // search a string exists inside the trie -bool search(trie* root, std::string str, int index) -{ - if (index == str.length()) - { +bool search(trie* root, std::string str, int index) { + if (index == str.length()) { if (!root->isEndofWord) return false; return true; @@ -59,10 +50,8 @@ removes the string if it is not a prefix of any other string, if it is then just sets the endofword to false, else removes the given string */ -bool deleteString(trie* root, std::string str, int index) -{ - if (index == str.length()) - { +bool deleteString(trie* root, std::string str, int index) { + if (index == str.length()) { if (!root->isEndofWord) return false; root->isEndofWord = false; @@ -73,15 +62,11 @@ bool deleteString(trie* root, std::string str, int index) if (!root->arr[j]) return false; bool var = deleteString(root, str, index + 1); - if (var) - { + if (var) { root->arr[j] = NULL; - if (root->isEndofWord) - { + if (root->isEndofWord) { return false; - } - else - { + } else { int i; for (i = 0; i < 26; i++) if (root->arr[i]) @@ -91,8 +76,7 @@ bool deleteString(trie* root, std::string str, int index) } } -int main() -{ +int main() { trie* root = createNode(); insert(root, "hello"); insert(root, "world"); diff --git a/dynamic_programming/0_1_knapsack.cpp b/dynamic_programming/0_1_knapsack.cpp index 0ce40ca0a..7ea0c04c6 100644 --- a/dynamic_programming/0_1_knapsack.cpp +++ b/dynamic_programming/0_1_knapsack.cpp @@ -28,13 +28,10 @@ using namespace std; // } //} -int Knapsack(int capacity, int n, int weight[], int value[]) -{ +int Knapsack(int capacity, int n, int weight[], int value[]) { int res[20][20]; - for (int i = 0; i < n + 1; ++i) - { - for (int j = 0; j < capacity + 1; ++j) - { + for (int i = 0; i < n + 1; ++i) { + for (int j = 0; j < capacity + 1; ++j) { if (i == 0 || j == 0) res[i][j] = 0; else if (weight[i - 1] <= j) @@ -48,20 +45,17 @@ int Knapsack(int capacity, int n, int weight[], int value[]) // cout<<"\n"; return res[n][capacity]; } -int main() -{ +int main() { int n; cout << "Enter number of items: "; cin >> n; int weight[n], value[n]; cout << "Enter weights: "; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { cin >> weight[i]; } cout << "Enter values: "; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { cin >> value[i]; } int capacity; diff --git a/dynamic_programming/armstrong_number.cpp b/dynamic_programming/armstrong_number.cpp index 218d6365d..270a705f7 100644 --- a/dynamic_programming/armstrong_number.cpp +++ b/dynamic_programming/armstrong_number.cpp @@ -4,14 +4,12 @@ using std::cin; using std::cout; -int main() -{ +int main() { int n, k, d, s = 0; cout << "Enter a number:"; cin >> n; k = n; - while (k != 0) - { + while (k != 0) { d = k % 10; s += d * d * d; k /= 10; diff --git a/dynamic_programming/bellman_ford.cpp b/dynamic_programming/bellman_ford.cpp index 85d3bff06..c96f3fd8e 100644 --- a/dynamic_programming/bellman_ford.cpp +++ b/dynamic_programming/bellman_ford.cpp @@ -4,33 +4,28 @@ using namespace std; // Wrapper class for storing an edge -class Edge -{ +class Edge { public: int src, dst, weight; }; // Wrapper class for storing a graph -class Graph -{ +class Graph { public: int vertexNum, edgeNum; Edge *edges; // Constructs a graph with V vertices and E edges - Graph(int V, int E) - { + Graph(int V, int E) { this->vertexNum = V; this->edgeNum = E; this->edges = (Edge *)malloc(E * sizeof(Edge)); } // Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { + void addEdge(int src, int dst, int weight) { static int edgeInd = 0; - if (edgeInd < this->edgeNum) - { + if (edgeInd < this->edgeNum) { Edge newEdge; newEdge.src = src; newEdge.dst = dst; @@ -41,11 +36,9 @@ class Graph }; // Utility function to print distances -void print(int dist[], int V) -{ +void print(int dist[], int V) { cout << "\nVertex Distance" << endl; - for (int i = 0; i < V; i++) - { + for (int i = 0; i < V; i++) { if (dist[i] != INT_MAX) cout << i << "\t" << dist[i] << endl; else @@ -56,8 +49,7 @@ void print(int dist[], int V) // The main function that finds the shortest path from given source // to all other vertices using Bellman-Ford.It also detects negative // weight cycle -void BellmanFord(Graph graph, int src) -{ +void BellmanFord(Graph graph, int src) { int V = graph.vertexNum; int E = graph.edgeNum; int dist[V]; @@ -70,8 +62,7 @@ void BellmanFord(Graph graph, int src) // Calculate shortest path distance from source to all edges // A path can contain maximum (|V|-1) edges for (int i = 0; i <= V - 1; i++) - for (int j = 0; j < E; j++) - { + for (int j = 0; j < E; j++) { int u = graph.edges[j].src; int v = graph.edges[j].dst; int w = graph.edges[j].weight; @@ -81,14 +72,12 @@ void BellmanFord(Graph graph, int src) } // Iterate inner loop once more to check for negative cycle - for (int j = 0; j < E; j++) - { + for (int j = 0; j < E; j++) { int u = graph.edges[j].src; int v = graph.edges[j].dst; int w = graph.edges[j].weight; - if (dist[u] != INT_MAX && dist[u] + w < dist[v]) - { + if (dist[u] != INT_MAX && dist[u] + w < dist[v]) { cout << "Graph contains negative weight cycle. Hence, shortest " "distance not guaranteed." << endl; @@ -102,8 +91,7 @@ void BellmanFord(Graph graph, int src) } // Driver Function -int main() -{ +int main() { int V, E, gsrc; int src, dst, weight; cout << "Enter number of vertices: "; @@ -111,8 +99,7 @@ int main() cout << "Enter number of edges: "; cin >> E; Graph G(V, E); - for (int i = 0; i < E; i++) - { + for (int i = 0; i < E; i++) { cout << "\nEdge " << i + 1 << "\nEnter source: "; cin >> src; cout << "Enter destination: "; diff --git a/dynamic_programming/catalan_numbers.cpp b/dynamic_programming/catalan_numbers.cpp index 0107b9f20..f5edaa916 100644 --- a/dynamic_programming/catalan_numbers.cpp +++ b/dynamic_programming/catalan_numbers.cpp @@ -11,8 +11,7 @@ using namespace std; int *cat; // global array to hold catalan numbers -unsigned long int catalan_dp(int n) -{ +unsigned long int catalan_dp(int n) { /** Using the tabulation technique in dynamic programming, this function computes the first `n+1` Catalan numbers @@ -29,8 +28,7 @@ unsigned long int catalan_dp(int n) cat[0] = cat[1] = 1; // Compute the remaining numbers from index 2 to index n, using tabulation - for (int i = 2; i <= n; i++) - { + for (int i = 2; i <= n; i++) { cat[i] = 0; for (int j = 0; j < i; j++) cat[i] += cat[j] * cat[i - j - 1]; // applying the definition here @@ -40,8 +38,7 @@ unsigned long int catalan_dp(int n) return cat[n]; } -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { int n; cout << "Enter n: "; cin >> n; @@ -49,8 +46,7 @@ int main(int argc, char *argv[]) cat = new int[n + 1]; cout << "Catalan numbers from 0 to " << n << " are:\n"; - for (int i = 0; i <= n; i++) - { + for (int i = 0; i <= n; i++) { cout << "catalan (" << i << ") = " << catalan_dp(i) << endl; // NOTE: Since `cat` is a global array, calling `catalan_dp` // repeatedly will not recompute the the values already computed diff --git a/dynamic_programming/coin_change.cpp b/dynamic_programming/coin_change.cpp index f43d4fa18..8c8fc3dfb 100644 --- a/dynamic_programming/coin_change.cpp +++ b/dynamic_programming/coin_change.cpp @@ -3,8 +3,7 @@ using namespace std; // Function to find the Minimum number of coins required to get Sum S -int findMinCoins(int arr[], int n, int N) -{ +int findMinCoins(int arr[], int n, int N) { // dp[i] = no of coins required to get a total of i int dp[N + 1]; @@ -12,15 +11,13 @@ int findMinCoins(int arr[], int n, int N) dp[0] = 0; - for (int i = 1; i <= N; i++) - { + for (int i = 1; i <= N; i++) { // initialize minimum number of coins needed to infinity dp[i] = INT_MAX; int res = INT_MAX; // do for each coin - for (int c = 0; c < n; c++) - { + for (int c = 0; c < n; c++) { if (i - arr[c] >= 0) // check if coins doesn't become negative by including it res = dp[i - arr[c]]; @@ -36,8 +33,7 @@ int findMinCoins(int arr[], int n, int N) return dp[N]; } -int main() -{ +int main() { // No of Coins We Have int arr[] = {1, 2, 3, 4}; int n = sizeof(arr) / sizeof(arr[0]); diff --git a/dynamic_programming/cut_rod.cpp b/dynamic_programming/cut_rod.cpp index 3df0a9fbe..136c78dbb 100644 --- a/dynamic_programming/cut_rod.cpp +++ b/dynamic_programming/cut_rod.cpp @@ -5,23 +5,19 @@ the pieces.*/ #include using namespace std; -int cutrod(int p[], int n) -{ +int cutrod(int p[], int n) { int r[n + 1]; r[0] = 0; - for (int j = 0; j < n; j++) - { + for (int j = 0; j < n; j++) { int q = INT_MIN; - for (int i = 0; i <= j; i++) - { + for (int i = 0; i <= j; i++) { q = max(q, p[i] + r[j - i]); } r[j + 1] = q; } return r[n]; } -int main() -{ +int main() { int price[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}; cout << cutrod(price, 30); diff --git a/dynamic_programming/edit_distance.cpp b/dynamic_programming/edit_distance.cpp index da613b238..889b080cb 100644 --- a/dynamic_programming/edit_distance.cpp +++ b/dynamic_programming/edit_distance.cpp @@ -22,8 +22,7 @@ int min(int x, int y, int z) { return min(min(x, y), z); } * str1 to str2. * O(3^m) */ -int editDist(string str1, string str2, int m, int n) -{ +int editDist(string str1, string str2, int m, int n) { if (m == 0) return n; if (n == 0) @@ -45,16 +44,13 @@ int editDist(string str1, string str2, int m, int n) /* A DP based program * O(m x n) */ -int editDistDP(string str1, string str2, int m, int n) -{ +int editDistDP(string str1, string str2, int m, int n) { // Create Table for SubProblems int dp[m + 1][n + 1]; // Fill d[][] in bottom up manner - for (int i = 0; i <= m; i++) - { - for (int j = 0; j <= n; j++) - { + for (int i = 0; i <= m; i++) { + for (int j = 0; j <= n; j++) { // If str1 empty. Then add all of str2 if (i == 0) dp[i][j] = j; @@ -78,8 +74,7 @@ int editDistDP(string str1, string str2, int m, int n) return dp[m][n]; } -int main() -{ +int main() { string str1 = "sunday"; string str2 = "saturday"; diff --git a/dynamic_programming/egg_dropping_puzzle.cpp b/dynamic_programming/egg_dropping_puzzle.cpp index 79de4cc22..7a769ea47 100644 --- a/dynamic_programming/egg_dropping_puzzle.cpp +++ b/dynamic_programming/egg_dropping_puzzle.cpp @@ -6,30 +6,24 @@ #include using namespace std; -int eggDrop(int n, int k) -{ +int eggDrop(int n, int k) { int eggFloor[n + 1][k + 1]; int result; - for (int i = 1; i <= n; i++) - { + for (int i = 1; i <= n; i++) { eggFloor[i][1] = 1; // n eggs..1 Floor eggFloor[i][0] = 0; // n eggs..0 Floor } // Only one egg available - for (int j = 1; j <= k; j++) - { + for (int j = 1; j <= k; j++) { eggFloor[1][j] = j; } - for (int i = 2; i <= n; i++) - { - for (int j = 2; j <= k; j++) - { + for (int i = 2; i <= n; i++) { + for (int j = 2; j <= k; j++) { eggFloor[i][j] = INT_MAX; - for (int x = 1; x <= j; x++) - { + for (int x = 1; x <= j; x++) { // 1+max(eggBreak[one less egg, lower floors], // eggDoesntBreak[same # of eggs, upper floors]); result = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); @@ -42,8 +36,7 @@ int eggDrop(int n, int k) return eggFloor[n][k]; } -int main() -{ +int main() { int n, k; cout << "Enter number of eggs and floors: "; cin >> n >> k; diff --git a/dynamic_programming/fibonacci_bottom_up.cpp b/dynamic_programming/fibonacci_bottom_up.cpp index 3a9669fa9..555f15282 100644 --- a/dynamic_programming/fibonacci_bottom_up.cpp +++ b/dynamic_programming/fibonacci_bottom_up.cpp @@ -1,20 +1,17 @@ #include using namespace std; -int fib(int n) -{ +int fib(int n) { int res[3]; res[0] = 0; res[1] = 1; - for (int i = 2; i <= n; i++) - { + for (int i = 2; i <= n; i++) { res[2] = res[1] + res[0]; res[0] = res[1]; res[1] = res[2]; } return res[1]; } -int main(int argc, char const *argv[]) -{ +int main(int argc, char const *argv[]) { int n; cout << "Enter n: "; cin >> n; diff --git a/dynamic_programming/fibonacci_top_down.cpp b/dynamic_programming/fibonacci_top_down.cpp index 3ac3fdb40..3c0c9a1a3 100644 --- a/dynamic_programming/fibonacci_top_down.cpp +++ b/dynamic_programming/fibonacci_top_down.cpp @@ -1,10 +1,8 @@ #include using namespace std; int arr[1000000]; -int fib(int n) -{ - if (arr[n] == -1) - { +int fib(int n) { + if (arr[n] == -1) { if (n <= 1) arr[n] = n; else @@ -12,13 +10,11 @@ int fib(int n) } return arr[n]; } -int main(int argc, char const *argv[]) -{ +int main(int argc, char const *argv[]) { int n; cout << "Enter n: "; cin >> n; - for (int i = 0; i < n + 1; ++i) - { + for (int i = 0; i < n + 1; ++i) { arr[i] = -1; } cout << "Fibonacci number is " << fib(n) << endl; diff --git a/dynamic_programming/kadane.cpp b/dynamic_programming/kadane.cpp index 31d17ae9e..b5272756b 100644 --- a/dynamic_programming/kadane.cpp +++ b/dynamic_programming/kadane.cpp @@ -1,12 +1,10 @@ #include #include -int maxSubArraySum(int a[], int size) -{ +int maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0; - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; @@ -17,14 +15,12 @@ int maxSubArraySum(int a[], int size) return max_so_far; } -int main() -{ +int main() { int n, i; std::cout << "Enter the number of elements \n"; std::cin >> n; int a[n]; // NOLINT - for (i = 0; i < n; i++) - { + for (i = 0; i < n; i++) { std::cin >> a[i]; } int max_sum = maxSubArraySum(a, n); diff --git a/dynamic_programming/longest_common_string.cpp b/dynamic_programming/longest_common_string.cpp index e33489cb1..81fa8a002 100644 --- a/dynamic_programming/longest_common_string.cpp +++ b/dynamic_programming/longest_common_string.cpp @@ -3,8 +3,7 @@ using namespace std; int max(int a, int b) { return (a > b) ? a : b; } -int main() -{ +int main() { char str1[] = "DEFBCD"; char str2[] = "ABDEFJ"; int i, j, k; @@ -13,10 +12,8 @@ int main() // cout< ma) - { + for (i = 0; i < m; i++) { + for (j = 0; j < n; j++) { + if (a[i][j] > ma) { ma = a[i][j]; indi = i; indj = j; diff --git a/dynamic_programming/longest_common_subsequence.cpp b/dynamic_programming/longest_common_subsequence.cpp index 7973bb05e..662c26ad2 100644 --- a/dynamic_programming/longest_common_subsequence.cpp +++ b/dynamic_programming/longest_common_subsequence.cpp @@ -2,69 +2,50 @@ #include using namespace std; -void Print(int trace[20][20], int m, int n, string a) -{ - if (m == 0 || n == 0) - { +void Print(int trace[20][20], int m, int n, string a) { + if (m == 0 || n == 0) { return; } - if (trace[m][n] == 1) - { + if (trace[m][n] == 1) { Print(trace, m - 1, n - 1, a); cout << a[m - 1]; - } - else if (trace[m][n] == 2) - { + } else if (trace[m][n] == 2) { Print(trace, m - 1, n, a); - } - else if (trace[m][n] == 3) - { + } else if (trace[m][n] == 3) { Print(trace, m, n - 1, a); } } -int lcs(string a, string b) -{ +int lcs(string a, string b) { int m = a.length(), n = b.length(); int res[m + 1][n + 1]; int trace[20][20]; // fills up the arrays with zeros. - for (int i = 0; i < m + 1; i++) - { - for (int j = 0; j < n + 1; j++) - { + for (int i = 0; i < m + 1; i++) { + for (int j = 0; j < n + 1; j++) { res[i][j] = 0; trace[i][j] = 0; } } - for (int i = 0; i < m + 1; ++i) - { - for (int j = 0; j < n + 1; ++j) - { - if (i == 0 || j == 0) - { + for (int i = 0; i < m + 1; ++i) { + for (int j = 0; j < n + 1; ++j) { + if (i == 0 || j == 0) { res[i][j] = 0; trace[i][j] = 0; } - else if (a[i - 1] == b[j - 1]) - { + else if (a[i - 1] == b[j - 1]) { res[i][j] = 1 + res[i - 1][j - 1]; trace[i][j] = 1; // 1 means trace the matrix in upper left // diagonal direction. - } - else - { - if (res[i - 1][j] > res[i][j - 1]) - { + } else { + if (res[i - 1][j] > res[i][j - 1]) { res[i][j] = res[i - 1][j]; trace[i][j] = 2; // 2 means trace the matrix in upwards direction. - } - else - { + } else { res[i][j] = res[i][j - 1]; trace[i][j] = 3; // means trace the matrix in left direction. @@ -76,8 +57,7 @@ int lcs(string a, string b) return res[m][n]; } -int main() -{ +int main() { string a, b; cin >> a >> b; cout << lcs(a, b); diff --git a/dynamic_programming/longest_increasing_subsequence.cpp b/dynamic_programming/longest_increasing_subsequence.cpp index 573db34a5..b6a798aa0 100644 --- a/dynamic_programming/longest_increasing_subsequence.cpp +++ b/dynamic_programming/longest_increasing_subsequence.cpp @@ -1,37 +1,30 @@ // Program to calculate length of longest increasing subsequence in an array #include using namespace std; -int LIS(int a[], int n) -{ +int LIS(int a[], int n) { int lis[n]; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { lis[i] = 1; } - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < i; ++j) - { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < i; ++j) { if (a[i] > a[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; } } int res = 0; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { res = max(res, lis[i]); } return res; } -int main(int argc, char const *argv[]) -{ +int main(int argc, char const *argv[]) { int n; cout << "Enter size of array: "; cin >> n; int a[n]; cout << "Enter array elements: "; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { cin >> a[i]; } cout << LIS(a, n) << endl; diff --git a/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp b/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp index 2471b701f..5bc72345c 100644 --- a/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp +++ b/dynamic_programming/longest_increasing_subsequence_(nlogn).cpp @@ -5,24 +5,19 @@ #include using namespace std; -int LIS(int arr[], int n) -{ +int LIS(int arr[], int n) { set active; // The current built LIS. active.insert(arr[0]); // Loop through every element. - for (int i = 1; i < n; ++i) - { + for (int i = 1; i < n; ++i) { auto get = active.lower_bound(arr[i]); - if (get == active.end()) - { + if (get == active.end()) { active.insert(arr[i]); } // current element is the greatest so LIS increases by 1. - else - { + else { int val = *get; // we find the position where arr[i] will be in the // LIS. If it is in the LIS already we do nothing - if (val > arr[i]) - { + if (val > arr[i]) { // else we remove the bigger element and add a smaller element // (which is arr[i]) and continue; active.erase(get); @@ -32,15 +27,13 @@ int LIS(int arr[], int n) } return active.size(); // size of the LIS. } -int main(int argc, char const* argv[]) -{ +int main(int argc, char const* argv[]) { int n; cout << "Enter size of array: "; cin >> n; int a[n]; cout << "Enter array elements: "; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { cin >> a[i]; } cout << LIS(a, n) << endl; diff --git a/dynamic_programming/matrix_chain_multiplication.cpp b/dynamic_programming/matrix_chain_multiplication.cpp index 378edcc7f..7d6647c52 100644 --- a/dynamic_programming/matrix_chain_multiplication.cpp +++ b/dynamic_programming/matrix_chain_multiplication.cpp @@ -9,8 +9,7 @@ int dp[MAX][MAX]; // Function to find the most efficient way to multiply the given sequence of // matrices -int MatrixChainMultiplication(int dim[], int i, int j) -{ +int MatrixChainMultiplication(int dim[], int i, int j) { // base case: one matrix if (j <= i + 1) return 0; @@ -21,13 +20,11 @@ int MatrixChainMultiplication(int dim[], int i, int j) // if dp[i][j] is not calculated (calculate it!!) - if (dp[i][j] == 0) - { + if (dp[i][j] == 0) { // take the minimum over each possible position at which the // sequence of matrices can be split - for (int k = i + 1; k <= j - 1; k++) - { + for (int k = i + 1; k <= j - 1; k++) { // recur for M[i+1]..M[k] to get a i x k matrix int cost = MatrixChainMultiplication(dim, i, k); @@ -48,8 +45,7 @@ int MatrixChainMultiplication(int dim[], int i, int j) } // main function -int main() -{ +int main() { // Matrix i has Dimensions dim[i-1] & dim[i] for i=1..n // input is 10 x 30 matrix, 30 x 5 matrix, 5 x 60 matrix int dim[] = {10, 30, 5, 60}; diff --git a/dynamic_programming/searching_of_element_in_dynamic_array.cpp b/dynamic_programming/searching_of_element_in_dynamic_array.cpp index 3dea46bf4..7792a5149 100644 --- a/dynamic_programming/searching_of_element_in_dynamic_array.cpp +++ b/dynamic_programming/searching_of_element_in_dynamic_array.cpp @@ -35,8 +35,7 @@ // this is main fuction // *** -int main() -{ +int main() { int64_t r, mr = 0, x, q, i, z; std::cout << "Enter Number of array you want to Store :"; std::cin >> x; @@ -50,8 +49,7 @@ int main() int** ar = new int*[x](); // this for loop is use for entering different variable size array // *** - for (r = 0; r < x; r++) - { + for (r = 0; r < x; r++) { std::cout << "Enter number of element in " << r + 1 << " rows :"; std::cin >> mr; // creating a 1D array @@ -59,8 +57,7 @@ int main() std::cout << "Enter the element of Array "; // this for loop is use for storing values in array // *** - for (i = 0; i < mr; i++) - { + for (i = 0; i < mr; i++) { // entering the value of rows in array in Horizontal std::cin >> ac[i]; } @@ -69,8 +66,7 @@ int main() } // this for loop is use for display result of querry // *** - for (z = 0; z < q; z++) - { + for (z = 0; z < q; z++) { int64_t r1 = 0, q1 = 0; std::cout << "enter the number of row which element you want to find :"; std::cin >> r1; diff --git a/dynamic_programming/tree_height.cpp b/dynamic_programming/tree_height.cpp index 1530dfe7e..480b951c8 100644 --- a/dynamic_programming/tree_height.cpp +++ b/dynamic_programming/tree_height.cpp @@ -29,14 +29,11 @@ std::vector adj[MAX]; std::vector visited; std::vector dp; -void depth_first_search(int u) -{ +void depth_first_search(int u) { visited[u] = true; int child_height = 1; - for (int v : adj[u]) - { - if (!visited[v]) - { + for (int v : adj[u]) { + if (!visited[v]) { depth_first_search(v); // select maximum sub-tree height from all children. @@ -47,8 +44,7 @@ void depth_first_search(int u) dp[u] = child_height; } -int main() -{ +int main() { // number of nodes int number_of_nodes; std::cout << "Enter number of nodes of the tree : " << std::endl; @@ -58,8 +54,7 @@ int main() int u, v; // Tree contains exactly n-1 edges where n denotes the number of nodes. std::cout << "Enter edges of the tree : " << std::endl; - for (int i = 0; i < number_of_nodes - 1; i++) - { + for (int i = 0; i < number_of_nodes - 1; i++) { std::cin >> u >> v; // undirected tree u -> v and v -> u. adj[u].push_back(v); diff --git a/graph/bfs.cpp b/graph/bfs.cpp index f5d372134..3acee8f80 100644 --- a/graph/bfs.cpp +++ b/graph/bfs.cpp @@ -1,7 +1,6 @@ #include using namespace std; -class graph -{ +class graph { int v; list *adj; @@ -11,56 +10,46 @@ class graph void printgraph(); void bfs(int s); }; -graph::graph(int v) -{ +graph::graph(int v) { this->v = v; this->adj = new list[v]; } -void graph::addedge(int src, int dest) -{ +void graph::addedge(int src, int dest) { src--; dest--; adj[src].push_back(dest); // adj[dest].push_back(src); } -void graph::printgraph() -{ - for (int i = 0; i < this->v; i++) - { +void graph::printgraph() { + for (int i = 0; i < this->v; i++) { cout << "Adjacency list of vertex " << i + 1 << " is \n"; list::iterator it; - for (it = adj[i].begin(); it != adj[i].end(); ++it) - { + for (it = adj[i].begin(); it != adj[i].end(); ++it) { cout << *it + 1 << " "; } cout << endl; } } -void graph::bfs(int s) -{ +void graph::bfs(int s) { bool *visited = new bool[this->v + 1]; memset(visited, false, sizeof(bool) * (this->v + 1)); visited[s] = true; list q; q.push_back(s); list::iterator it; - while (!q.empty()) - { + while (!q.empty()) { int u = q.front(); cout << u << " "; q.pop_front(); - for (it = adj[u].begin(); it != adj[u].end(); ++it) - { - if (visited[*it] == false) - { + for (it = adj[u].begin(); it != adj[u].end(); ++it) { + if (visited[*it] == false) { visited[*it] = true; q.push_back(*it); } } } } -int main() -{ +int main() { graph g(4); g.addedge(1, 2); g.addedge(2, 3); diff --git a/graph/bridge_finding_with_tarjan_algorithm.cpp b/graph/bridge_finding_with_tarjan_algorithm.cpp index a283a7c91..eec176af5 100644 --- a/graph/bridge_finding_with_tarjan_algorithm.cpp +++ b/graph/bridge_finding_with_tarjan_algorithm.cpp @@ -10,28 +10,22 @@ using std::cout; using std::min; using std::vector; -class Solution -{ +class Solution { vector> graph; vector in_time, out_time; int timer; vector> bridge; vector visited; - void dfs(int current_node, int parent) - { + void dfs(int current_node, int parent) { visited.at(current_node) = true; in_time[current_node] = out_time[current_node] = timer++; - for (auto& itr : graph[current_node]) - { - if (itr == parent) - { + for (auto& itr : graph[current_node]) { + if (itr == parent) { continue; } - if (!visited[itr]) - { + if (!visited[itr]) { dfs(itr, current_node); - if (out_time[itr] > in_time[current_node]) - { + if (out_time[itr] > in_time[current_node]) { bridge.push_back({itr, current_node}); } } @@ -41,15 +35,13 @@ class Solution public: vector> search_bridges(int n, - const vector>& connections) - { + const vector>& connections) { timer = 0; graph.resize(n); in_time.assign(n, 0); visited.assign(n, false); out_time.assign(n, 0); - for (auto& itr : connections) - { + for (auto& itr : connections) { graph.at(itr[0]).push_back(itr[1]); graph.at(itr[1]).push_back(itr[0]); } @@ -57,8 +49,7 @@ class Solution return bridge; } }; -int main(void) -{ +int main(void) { Solution s1; int number_of_node = 5; vector> node; @@ -81,8 +72,7 @@ int main(void) */ vector> bridges = s1.search_bridges(number_of_node, node); cout << bridges.size() << " bridges found!\n"; - for (auto& itr : bridges) - { + for (auto& itr : bridges) { cout << itr[0] << " --> " << itr[1] << '\n'; } return 0; diff --git a/graph/connected_components.cpp b/graph/connected_components.cpp index f78ef011e..0bfb8bbdb 100644 --- a/graph/connected_components.cpp +++ b/graph/connected_components.cpp @@ -3,8 +3,7 @@ using std::vector; -class graph -{ +class graph { private: vector> adj; int connected_components; @@ -14,48 +13,39 @@ class graph public: explicit graph(int n) : adj(n, vector()) { connected_components = 0; } void addEdge(int, int); - int getConnectedComponents() - { + int getConnectedComponents() { depth_first_search(); return connected_components; } }; -void graph::addEdge(int u, int v) -{ +void graph::addEdge(int u, int v) { adj[u - 1].push_back(v - 1); adj[v - 1].push_back(u - 1); } -void graph::depth_first_search() -{ +void graph::depth_first_search() { int n = adj.size(); vector visited(n, false); - for (int i = 0; i < n; i++) - { - if (!visited[i]) - { + for (int i = 0; i < n; i++) { + if (!visited[i]) { explore(i, visited); connected_components++; } } } -void graph::explore(int u, vector &visited) -{ +void graph::explore(int u, vector &visited) { visited[u] = true; - for (auto v : adj[u]) - { - if (!visited[v]) - { + for (auto v : adj[u]) { + if (!visited[v]) { explore(v, visited); } } } -int main() -{ +int main() { graph g(4); g.addEdge(1, 2); g.addEdge(3, 2); diff --git a/graph/connected_components_with_dsu.cpp b/graph/connected_components_with_dsu.cpp index 07fda5d27..aa03bef8f 100644 --- a/graph/connected_components_with_dsu.cpp +++ b/graph/connected_components_with_dsu.cpp @@ -5,28 +5,23 @@ int N; // denotes number of nodes; std::vector parent; std::vector siz; -void make_set() -{ // function the initialize every node as it's own parent - for (int i = 1; i <= N; i++) - { +void make_set() { // function the initialize every node as it's own parent + for (int i = 1; i <= N; i++) { parent[i] = i; siz[i] = 1; } } // To find the component where following node belongs to -int find_set(int v) -{ +int find_set(int v) { if (v == parent[v]) return v; return parent[v] = find_set(parent[v]); } -void union_sets(int a, int b) -{ // To join 2 components to belong to one +void union_sets(int a, int b) { // To join 2 components to belong to one a = find_set(a); b = find_set(b); - if (a != b) - { + if (a != b) { if (siz[a] < siz[b]) std::swap(a, b); parent[b] = a; @@ -34,8 +29,7 @@ void union_sets(int a, int b) } } -int no_of_connected_components() -{ // To find total no of connected components +int no_of_connected_components() { // To find total no of connected components std::set temp; // temp set to count number of connected components for (int i = 1; i <= N; i++) temp.insert(find_set(i)); return temp.size(); @@ -43,16 +37,14 @@ int no_of_connected_components() // All critical/corner cases have been taken care of. // Input your required values: (not hardcoded) -int main() -{ +int main() { std::cin >> N; parent.resize(N + 1); siz.resize(N + 1); make_set(); int edges; std::cin >> edges; // no of edges in the graph - while (edges--) - { + while (edges--) { int node_a, node_b; std::cin >> node_a >> node_b; union_sets(node_a, node_b); diff --git a/graph/dfs.cpp b/graph/dfs.cpp index 7c7ec7761..2d38c8725 100644 --- a/graph/dfs.cpp +++ b/graph/dfs.cpp @@ -1,28 +1,23 @@ #include using namespace std; int v = 4; -void DFSUtil_(int graph[4][4], bool visited[], int s) -{ +void DFSUtil_(int graph[4][4], bool visited[], int s) { visited[s] = true; cout << s << " "; - for (int i = 0; i < v; i++) - { - if (graph[s][i] == 1 && visited[i] == false) - { + for (int i = 0; i < v; i++) { + if (graph[s][i] == 1 && visited[i] == false) { DFSUtil_(graph, visited, i); } } } -void DFS_(int graph[4][4], int s) -{ +void DFS_(int graph[4][4], int s) { bool visited[v]; memset(visited, 0, sizeof(visited)); DFSUtil_(graph, visited, s); } -int main() -{ +int main() { int graph[4][4] = {{0, 1, 1, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 0, 0, 1}}; cout << "DFS: "; DFS_(graph, 2); diff --git a/graph/dfs_with_stack.cpp b/graph/dfs_with_stack.cpp index cc67c7509..193f3f291 100644 --- a/graph/dfs_with_stack.cpp +++ b/graph/dfs_with_stack.cpp @@ -11,8 +11,7 @@ using namespace std; int checked[999] = {WHITE}; -void dfs(const list lista[], int start) -{ +void dfs(const list lista[], int start) { stack stack; int checked[999] = {WHITE}; @@ -20,33 +19,28 @@ void dfs(const list lista[], int start) stack.push(start); checked[start] = GREY; - while (!stack.empty()) - { + while (!stack.empty()) { int act = stack.top(); stack.pop(); - if (checked[act] == GREY) - { + if (checked[act] == GREY) { cout << act << ' '; - for (auto it = lista[act].begin(); it != lista[act].end(); ++it) - { + for (auto it = lista[act].begin(); it != lista[act].end(); ++it) { stack.push(*it); if (checked[*it] != BLACK) checked[*it] = GREY; } - checked[act] = BLACK; //nodo controllato + checked[act] = BLACK; // nodo controllato } } } -int main() -{ +int main() { int u, w; int n; cin >> n; list lista[INF]; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { cin >> u >> w; lista[u].push_back(w); } diff --git a/graph/dijkstra.cpp b/graph/dijkstra.cpp index f25510935..650f0cd51 100644 --- a/graph/dijkstra.cpp +++ b/graph/dijkstra.cpp @@ -6,8 +6,7 @@ using namespace std; #define INF 10000010 vector> graph[5 * 100001]; int dis[5 * 100001]; -int dij(vector> *v, int s, int *dis) -{ +int dij(vector> *v, int s, int *dis) { priority_queue, vector>, greater>> pq; @@ -15,28 +14,23 @@ int dij(vector> *v, int s, int *dis) pq.push(make_pair(0, s)); dis[s] = 0; int u; - while (!pq.empty()) - { + while (!pq.empty()) { u = (pq.top()).second; pq.pop(); for (vector>::iterator it = v[u].begin(); - it != v[u].end(); it++) - { - if (dis[u] + it->first < dis[it->second]) - { + it != v[u].end(); it++) { + if (dis[u] + it->first < dis[it->second]) { dis[it->second] = dis[u] + it->first; pq.push(make_pair(dis[it->second], it->second)); } } } } -int main() -{ +int main() { int m, n, l, x, y, s; // n--> number of nodes , m --> number of edges cin >> n >> m; - for (int i = 0; i < m; i++) - { + for (int i = 0; i < m; i++) { // input edges. scanf("%d%d%d", &x, &y, &l); graph[x].push_back(make_pair(l, y)); diff --git a/graph/kosaraju.cpp b/graph/kosaraju.cpp index 0efa291bc..00c9d7ca0 100644 --- a/graph/kosaraju.cpp +++ b/graph/kosaraju.cpp @@ -13,10 +13,8 @@ using namespace std; * @param V : vertices * @return void **/ -void print(vector a[], int V) -{ - for (int i = 0; i < V; i++) - { +void print(vector a[], int V) { + for (int i = 0; i < V; i++) { if (!a[i].empty()) cout << "i=" << i << "-->"; for (int j = 0; j < a[i].size(); j++) cout << a[i][j] << " "; @@ -33,11 +31,9 @@ void print(vector a[], int V) * @param adj[] : array of vectors to represent graph * @return void **/ -void push_vertex(int v, stack &st, bool vis[], vector adj[]) -{ +void push_vertex(int v, stack &st, bool vis[], vector adj[]) { vis[v] = true; - for (auto i = adj[v].begin(); i != adj[v].end(); i++) - { + for (auto i = adj[v].begin(); i != adj[v].end(); i++) { if (vis[*i] == false) push_vertex(*i, st, vis, adj); } @@ -51,12 +47,10 @@ void push_vertex(int v, stack &st, bool vis[], vector adj[]) * @param grev[] : graph with reversed edges * @return void **/ -void dfs(int v, bool vis[], vector grev[]) -{ +void dfs(int v, bool vis[], vector grev[]) { vis[v] = true; // cout<0)) i.e. it returns the count of (number of) strongly connected components (SCCs) in the graph. (variable 'count_scc' within function) **/ -int kosaraju(int V, vector adj[]) -{ +int kosaraju(int V, vector adj[]) { bool vis[V] = {}; stack st; - for (int v = 0; v < V; v++) - { + for (int v = 0; v < V; v++) { if (vis[v] == false) push_vertex(v, st, vis, adj); } // making new graph (grev) with reverse edges as in adj[]: vector grev[V]; - for (int i = 0; i < V + 1; i++) - { - for (auto j = adj[i].begin(); j != adj[i].end(); j++) - { + for (int i = 0; i < V + 1; i++) { + for (auto j = adj[i].begin(); j != adj[i].end(); j++) { grev[*j].push_back(i); } } @@ -95,12 +85,10 @@ int kosaraju(int V, vector adj[]) // reinitialise visited to 0 for (int i = 0; i < V; i++) vis[i] = false; int count_scc = 0; - while (!st.empty()) - { + while (!st.empty()) { int t = st.top(); st.pop(); - if (vis[t] == false) - { + if (vis[t] == false) { dfs(t, vis, grev); count_scc++; } @@ -112,12 +100,10 @@ int kosaraju(int V, vector adj[]) // All critical/corner cases have been taken care of. // Input your required values: (not hardcoded) -int main() -{ +int main() { int t; cin >> t; - while (t--) - { + while (t--) { int a, b; // a->number of nodes, b->directed edges. cin >> a >> b; int m, n; diff --git a/graph/kruskal.cpp b/graph/kruskal.cpp index 6bffd5cd9..b7b830668 100644 --- a/graph/kruskal.cpp +++ b/graph/kruskal.cpp @@ -24,47 +24,39 @@ typedef long long ll; cin.tie(NULL); \ cout.tie(NULL); using namespace std; -void in(int &x) -{ +void in(int &x) { register int c = gc(); x = 0; int neg = 0; for (; ((c < 48 || c > 57) && c != '-'); c = gc()) ; - if (c == '-') - { + if (c == '-') { neg = 1; c = gc(); } - for (; c > 47 && c < 58; c = gc()) - { + for (; c > 47 && c < 58; c = gc()) { x = (x << 1) + (x << 3) + c - 48; } if (neg) x = -x; } -void out(int n) -{ +void out(int n) { int N = n, rev, count = 0; rev = N; - if (N == 0) - { + if (N == 0) { pc('0'); return; } - while ((rev % 10) == 0) - { + while ((rev % 10) == 0) { count++; rev /= 10; } rev = 0; - while (N != 0) - { + while (N != 0) { rev = (rev << 3) + (rev << 1) + N % 10; N /= 10; } - while (rev != 0) - { + while (rev != 0) { pc(rev % 10 + '0'); rev /= 10; } @@ -72,53 +64,43 @@ void out(int n) } ll parent[mx], arr[mx], node, edge; vector>> v; -void initial() -{ +void initial() { int i; rep(i, node + edge) parent[i] = i; } -int root(int i) -{ - while (parent[i] != i) - { +int root(int i) { + while (parent[i] != i) { parent[i] = parent[parent[i]]; i = parent[i]; } return i; } -void join(int x, int y) -{ +void join(int x, int y) { int root_x = root(x); // Disjoint set union by rank int root_y = root(y); parent[root_x] = root_y; } -ll kruskal() -{ +ll kruskal() { ll mincost = 0, i, x, y; - rep(i, edge) - { + rep(i, edge) { x = v[i].second.first; y = v[i].second.second; - if (root(x) != root(y)) - { + if (root(x) != root(y)) { mincost += v[i].first; join(x, y); } } return mincost; } -int main() -{ +int main() { fast; - while (1) - { + while (1) { int i, j, from, to, cost, totalcost = 0; cin >> node >> edge; // Enter the nodes and edges if (node == 0 && edge == 0) break; // Enter 0 0 to break out initial(); // Initialise the parent array - rep(i, edge) - { + rep(i, edge) { cin >> from >> to >> cost; v.pb(mp(cost, mp(from, to))); totalcost += cost; diff --git a/graph/lca.cpp b/graph/lca.cpp index 743fb31ed..c05cf7b9b 100644 --- a/graph/lca.cpp +++ b/graph/lca.cpp @@ -7,19 +7,16 @@ using namespace std; // Resource : https://cp-algorithms.com/graph/lca_binary_lifting.html const int N = 1005; const int LG = log2(N) + 1; -struct lca -{ +struct lca { int n; vector adj[N]; // Graph int up[LG][N]; // build this table int level[N]; // get the levels of all of them - lca(int n_) : n(n_) - { + lca(int n_) : n(n_) { memset(up, -1, sizeof(up)); memset(level, 0, sizeof(level)); - for (int i = 0; i < n - 1; ++i) - { + for (int i = 0; i < n - 1; ++i) { int a, b; cin >> a >> b; a--; @@ -31,77 +28,59 @@ struct lca dfs(0, -1); build(); } - void verify() - { - for (int i = 0; i < n; ++i) - { + void verify() { + for (int i = 0; i < n; ++i) { cout << i << " : level: " << level[i] << endl; } cout << endl; - for (int i = 0; i < LG; ++i) - { + for (int i = 0; i < LG; ++i) { cout << "Power:" << i << ": "; - for (int j = 0; j < n; ++j) - { + for (int j = 0; j < n; ++j) { cout << up[i][j] << " "; } cout << endl; } } - void build() - { - for (int i = 1; i < LG; ++i) - { - for (int j = 0; j < n; ++j) - { - if (up[i - 1][j] != -1) - { + void build() { + for (int i = 1; i < LG; ++i) { + for (int j = 0; j < n; ++j) { + if (up[i - 1][j] != -1) { up[i][j] = up[i - 1][up[i - 1][j]]; } } } } - void dfs(int node, int par) - { + void dfs(int node, int par) { up[0][node] = par; - for (auto i : adj[node]) - { - if (i != par) - { + for (auto i : adj[node]) { + if (i != par) { level[i] = level[node] + 1; dfs(i, node); } } } - int query(int u, int v) - { + int query(int u, int v) { u--; v--; - if (level[v] > level[u]) - { + if (level[v] > level[u]) { swap(u, v); } // u is at the bottom. int dist = level[u] - level[v]; // Go up this much distance - for (int i = LG - 1; i >= 0; --i) - { - if (dist & (1 << i)) - { + for (int i = LG - 1; i >= 0; --i) { + if (dist & (1 << i)) { u = up[i][u]; } } - if (u == v) - { + if (u == v) { return u; } assert(level[u] == level[v]); - for (int i = LG - 1; i >= 0; --i) - { - if (up[i][u] != up[i][v]) - { + for (int i = LG - 1; i >= 0; --i) { + if (up[i][u] != up[i][v]) { u = up[i][u]; v = up[i][v]; } @@ -111,8 +90,7 @@ struct lca } }; -int main() -{ +int main() { int n; // number of nodes in the tree. lca l(n); // will take the input in the format given // n-1 edges of the form diff --git a/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp b/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp index f02a48e01..cbd6bc15c 100644 --- a/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp +++ b/graph/max_flow_with_ford_fulkerson_and_edmond_karp_algo.cpp @@ -15,8 +15,7 @@ #include // std::max capacity of node in graph const int MAXN = 505; -class Graph -{ +class Graph { int residual_capacity[MAXN][MAXN]; int capacity[MAXN][MAXN]; // used while checking the flow of edge int total_nodes; @@ -25,26 +24,21 @@ class Graph std::vector > edge_participated; std::bitset visited; int max_flow = 0; - bool bfs(int source, int sink) - { // to find the augmented - path + bool bfs(int source, int sink) { // to find the augmented - path memset(parent, -1, sizeof(parent)); visited.reset(); std::queue q; q.push(source); bool is_path_found = false; - while (q.empty() == false && is_path_found == false) - { + while (q.empty() == false && is_path_found == false) { int current_node = q.front(); visited.set(current_node); q.pop(); - for (int i = 0; i < total_nodes; ++i) - { - if (residual_capacity[current_node][i] > 0 && !visited[i]) - { + for (int i = 0; i < total_nodes; ++i) { + if (residual_capacity[current_node][i] > 0 && !visited[i]) { visited.set(i); parent[i] = current_node; - if (i == sink) - { + if (i == sink) { return true; } q.push(i); @@ -56,32 +50,26 @@ class Graph public: Graph() { memset(residual_capacity, 0, sizeof(residual_capacity)); } - void set_graph(void) - { + void set_graph(void) { std::cin >> total_nodes >> total_edges >> source >> sink; - for (int start, destination, capacity_, i = 0; i < total_edges; ++i) - { + for (int start, destination, capacity_, i = 0; i < total_edges; ++i) { std::cin >> start >> destination >> capacity_; residual_capacity[start][destination] = capacity_; capacity[start][destination] = capacity_; } } - void ford_fulkerson(void) - { - while (bfs(source, sink)) - { + void ford_fulkerson(void) { + while (bfs(source, sink)) { int current_node = sink; int flow = std::numeric_limits::max(); - while (current_node != source) - { + while (current_node != source) { int parent_ = parent[current_node]; flow = std::min(flow, residual_capacity[parent_][current_node]); current_node = parent_; } current_node = sink; max_flow += flow; - while (current_node != source) - { + while (current_node != source) { int parent_ = parent[current_node]; residual_capacity[parent_][current_node] -= flow; residual_capacity[current_node][parent_] += flow; @@ -89,14 +77,11 @@ class Graph } } } - void print_flow_info(void) - { - for (int i = 0; i < total_nodes; ++i) - { - for (int j = 0; j < total_nodes; ++j) - { - if (capacity[i][j] && residual_capacity[i][j] < capacity[i][j]) - { + void print_flow_info(void) { + for (int i = 0; i < total_nodes; ++i) { + for (int j = 0; j < total_nodes; ++j) { + if (capacity[i][j] && + residual_capacity[i][j] < capacity[i][j]) { edge_participated.push_back(std::make_tuple( i, j, capacity[i][j] - residual_capacity[i][j])); } @@ -106,8 +91,7 @@ class Graph << "\nEdge present in flow: " << edge_participated.size() << '\n'; std::cout << "\nSource\tDestination\tCapacity\total_nodes"; - for (auto& edge_data : edge_participated) - { + for (auto& edge_data : edge_participated) { int source, destination, capacity_; std::tie(source, destination, capacity_) = edge_data; std::cout << source << "\t" << destination << "\t\t" << capacity_ @@ -115,8 +99,7 @@ class Graph } } }; -int main(void) -{ +int main(void) { /* Input Graph: (for testing ) 4 5 0 3 diff --git a/graph/prim.cpp b/graph/prim.cpp index 8332bdb36..5cc70bd39 100644 --- a/graph/prim.cpp +++ b/graph/prim.cpp @@ -9,8 +9,7 @@ typedef std::pair PII; bool marked[MAX]; std::vector adj[MAX]; -int prim(int x) -{ +int prim(int x) { // priority queue to maintain edges with respect to weights std::priority_queue, std::greater > Q; int y; @@ -18,8 +17,7 @@ int prim(int x) PII p; Q.push(std::make_pair(0, x)); - while (!Q.empty()) - { + while (!Q.empty()) { // Select the edge with minimum weight p = Q.top(); Q.pop(); @@ -29,8 +27,7 @@ int prim(int x) continue; minimumCost += p.first; marked[x] = true; - for (int i = 0; i < adj[x].size(); ++i) - { + for (int i = 0; i < adj[x].size(); ++i) { y = adj[x][i].second; if (marked[y] == false) Q.push(adj[x][i]); @@ -39,8 +36,7 @@ int prim(int x) return minimumCost; } -int main() -{ +int main() { int nodes, edges, x, y; int weight, minimumCost; @@ -49,8 +45,7 @@ int main() return 0; // Edges with their nodes & weight - for (int i = 0; i < edges; ++i) - { + for (int i = 0; i < edges; ++i) { std::cin >> x >> y >> weight; adj[x].push_back(std::make_pair(weight, y)); adj[y].push_back(std::make_pair(weight, x)); diff --git a/graph/topological_sort.cpp b/graph/topological_sort.cpp index d863c6993..9e6c8917b 100644 --- a/graph/topological_sort.cpp +++ b/graph/topological_sort.cpp @@ -8,44 +8,37 @@ vector> G; vector visited; vector ans; -void dfs(int v) -{ +void dfs(int v) { visited[v] = true; - for (int u : G[v]) - { + for (int u : G[v]) { if (!visited[u]) dfs(u); } ans.push_back(v); } -void topological_sort() -{ +void topological_sort() { visited.assign(n, false); ans.clear(); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { if (!visited[i]) dfs(i); } reverse(ans.begin(), ans.end()); } -int main() -{ +int main() { cout << "Enter the number of vertices and the number of directed edges\n"; cin >> n >> m; int x, y; G.resize(n, vector()); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { cin >> x >> y; x--, y--; // to convert 1-indexed to 0-indexed G[x].push_back(y); } topological_sort(); cout << "Topological Order : \n"; - for (int v : ans) - { + for (int v : ans) { cout << v + 1 << ' '; // converting zero based indexing back to one based. } diff --git a/graph/topological_sort_by_kahns_algo.cpp b/graph/topological_sort_by_kahns_algo.cpp index b56ae5651..57ee01b23 100644 --- a/graph/topological_sort_by_kahns_algo.cpp +++ b/graph/topological_sort_by_kahns_algo.cpp @@ -6,8 +6,7 @@ int *topoSortKahn(int N, std::vector adj[]); -int main() -{ +int main() { int nodes, edges; std::cin >> edges >> nodes; if (edges == 0 || nodes == 0) @@ -20,36 +19,29 @@ int main() // 6 6 // 5 0 5 2 2 3 4 0 4 1 1 3 - for (int i = 0; i < edges; i++) - { + for (int i = 0; i < edges; i++) { std::cin >> u >> v; graph[u].push_back(v); } int *topo = topoSortKahn(nodes, graph); // topologically sorted nodes - for (int i = 0; i < nodes; i++) - { + for (int i = 0; i < nodes; i++) { std::cout << topo[i] << " "; } } -int *topoSortKahn(int V, std::vector adj[]) -{ +int *topoSortKahn(int V, std::vector adj[]) { std::vector vis(V + 1, false); std::vector deg(V + 1, 0); - for (int i = 0; i < V; i++) - { - for (int j = 0; j < adj[i].size(); j++) - { + for (int i = 0; i < V; i++) { + for (int j = 0; j < adj[i].size(); j++) { deg[adj[i][j]]++; } } std::queue q; - for (int i = 0; i < V; i++) - { - if (deg[i] == 0) - { + for (int i = 0; i < V; i++) { + if (deg[i] == 0) { q.push(i); vis[i] = true; } @@ -57,19 +49,15 @@ int *topoSortKahn(int V, std::vector adj[]) int *arr = new int[V + 1]; memset(arr, 0, V + 1); int count = 0; - while (!q.empty()) - { + while (!q.empty()) { int cur = q.front(); q.pop(); arr[count] = cur; count++; - for (int i = 0; i < adj[cur].size(); i++) - { - if (!vis[adj[cur][i]]) - { + for (int i = 0; i < adj[cur].size(); i++) { + if (!vis[adj[cur][i]]) { deg[adj[cur][i]]--; - if (deg[adj[cur][i]] == 0) - { + if (deg[adj[cur][i]] == 0) { q.push(adj[cur][i]); vis[adj[cur][i]] = true; } diff --git a/greedy_algorithms/dijkstra.cpp b/greedy_algorithms/dijkstra.cpp index b87b4ab10..e4450379c 100644 --- a/greedy_algorithms/dijkstra.cpp +++ b/greedy_algorithms/dijkstra.cpp @@ -4,27 +4,22 @@ using namespace std; // Wrapper class for storing a graph -class Graph -{ +class Graph { public: int vertexNum; int **edges; // Constructs a graph with V vertices and E edges - Graph(const int V) - { + Graph(const int V) { // initializes the array edges. this->edges = new int *[V]; - for (int i = 0; i < V; i++) - { + for (int i = 0; i < V; i++) { edges[i] = new int[V]; } // fills the array with zeros. - for (int i = 0; i < V; i++) - { - for (int j = 0; j < V; j++) - { + for (int i = 0; i < V; i++) { + for (int j = 0; j < V; j++) { edges[i][j] = 0; } } @@ -33,19 +28,15 @@ class Graph } // Adds the given edge to the graph - void addEdge(int src, int dst, int weight) - { + void addEdge(int src, int dst, int weight) { this->edges[src][dst] = weight; } }; // Utility function to find minimum distance vertex in mdist -int minDistance(int mdist[], bool vset[], int V) -{ +int minDistance(int mdist[], bool vset[], int V) { int minVal = INT_MAX, minInd = 0; - for (int i = 0; i < V; i++) - { - if (!vset[i] && (mdist[i] < minVal)) - { + for (int i = 0; i < V; i++) { + if (!vset[i] && (mdist[i] < minVal)) { minVal = mdist[i]; minInd = i; } @@ -55,11 +46,9 @@ int minDistance(int mdist[], bool vset[], int V) } // Utility function to print distances -void print(int dist[], int V) -{ +void print(int dist[], int V) { cout << "\nVertex Distance" << endl; - for (int i = 0; i < V; i++) - { + for (int i = 0; i < V; i++) { if (dist[i] < INT_MAX) cout << i << "\t" << dist[i] << endl; else @@ -70,16 +59,14 @@ void print(int dist[], int V) // The main function that finds the shortest path from given source // to all other vertices using Dijkstra's Algorithm.It doesn't work on negative // weights -void Dijkstra(Graph graph, int src) -{ +void Dijkstra(Graph graph, int src) { int V = graph.vertexNum; int mdist[V]; // Stores updated distances to vertex bool vset[V]; // vset[i] is true if the vertex i included // in the shortest path tree // Initialise mdist and vset. Set distance of source as zero - for (int i = 0; i < V; i++) - { + for (int i = 0; i < V; i++) { mdist[i] = INT_MAX; vset[i] = false; } @@ -87,17 +74,14 @@ void Dijkstra(Graph graph, int src) mdist[src] = 0; // iterate to find shortest path - for (int count = 0; count < V - 1; count++) - { + for (int count = 0; count < V - 1; count++) { int u = minDistance(mdist, vset, V); vset[u] = true; - for (int v = 0; v < V; v++) - { + for (int v = 0; v < V; v++) { if (!vset[v] && graph.edges[u][v] && - mdist[u] + graph.edges[u][v] < mdist[v]) - { + mdist[u] + graph.edges[u][v] < mdist[v]) { mdist[v] = mdist[u] + graph.edges[u][v]; } } @@ -107,8 +91,7 @@ void Dijkstra(Graph graph, int src) } // Driver Function -int main() -{ +int main() { int V, E, gsrc; int src, dst, weight; cout << "Enter number of vertices: "; @@ -116,8 +99,7 @@ int main() cout << "Enter number of edges: "; cin >> E; Graph G(V); - for (int i = 0; i < E; i++) - { + for (int i = 0; i < E; i++) { cout << "\nEdge " << i + 1 << "\nEnter source: "; cin >> src; cout << "Enter destination: "; @@ -126,12 +108,9 @@ int main() cin >> weight; // makes sure source and destionation are in the proper bounds. - if (src >= 0 && src < V && dst >= 0 && dst < V) - { + if (src >= 0 && src < V && dst >= 0 && dst < V) { G.addEdge(src, dst, weight); - } - else - { + } else { cout << "source and/or destination out of bounds" << endl; i--; continue; diff --git a/greedy_algorithms/huffman.cpp b/greedy_algorithms/huffman.cpp index bf3d9ff9a..21c8295f3 100644 --- a/greedy_algorithms/huffman.cpp +++ b/greedy_algorithms/huffman.cpp @@ -4,8 +4,7 @@ using namespace std; // A Huffman tree node -struct MinHeapNode -{ +struct MinHeapNode { // One of the input characters char data; @@ -26,8 +25,7 @@ struct MinHeapNode // For comparison of // two heap nodes (needed in min heap) -struct compare -{ +struct compare { bool operator()(MinHeapNode* l, MinHeapNode* r) { @@ -37,8 +35,7 @@ struct compare // Prints huffman codes from // the root of Huffman Tree. -void printCodes(struct MinHeapNode* root, string str) -{ +void printCodes(struct MinHeapNode* root, string str) { if (!root) return; @@ -51,8 +48,7 @@ void printCodes(struct MinHeapNode* root, string str) // The main function that builds a Huffman Tree and // print codes by traversing the built Huffman Tree -void HuffmanCodes(char data[], int freq[], int size) -{ +void HuffmanCodes(char data[], int freq[], int size) { struct MinHeapNode *left, *right, *top; // Create a min heap & inserts all characters of data[] @@ -62,8 +58,7 @@ void HuffmanCodes(char data[], int freq[], int size) minHeap.push(new MinHeapNode(data[i], freq[i])); // Iterate while size of heap doesn't become 1 - while (minHeap.size() != 1) - { + while (minHeap.size() != 1) { // Extract the two minimum // freq items from min heap left = minHeap.top(); @@ -93,8 +88,7 @@ void HuffmanCodes(char data[], int freq[], int size) } // Driver program to test above functions -int main() -{ +int main() { char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'}; int freq[] = {5, 9, 12, 13, 16, 45}; diff --git a/greedy_algorithms/knapsack.cpp b/greedy_algorithms/knapsack.cpp index 81fd879de..74be4fee0 100644 --- a/greedy_algorithms/knapsack.cpp +++ b/greedy_algorithms/knapsack.cpp @@ -1,25 +1,21 @@ #include using namespace std; -struct Item -{ +struct Item { int weight; int profit; }; float profitPerUnit(Item x) { return (float)x.profit / (float)x.weight; } -int partition(Item arr[], int low, int high) -{ +int partition(Item arr[], int low, int high) { Item pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element - for (int j = low; j < high; j++) - { + for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot - if (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) - { + if (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) { i++; // increment index of smaller element Item temp = arr[i]; arr[i] = arr[j]; @@ -32,10 +28,8 @@ int partition(Item arr[], int low, int high) return (i + 1); } -void quickSort(Item arr[], int low, int high) -{ - if (low < high) - { +void quickSort(Item arr[], int low, int high) { + if (low < high) { int p = partition(arr, low, high); quickSort(arr, low, p - 1); @@ -43,8 +37,7 @@ void quickSort(Item arr[], int low, int high) } } -int main() -{ +int main() { cout << "\nEnter the capacity of the knapsack : "; float capacity; cin >> capacity; @@ -52,8 +45,7 @@ int main() int n; cin >> n; Item itemArray[n]; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { cout << "\nEnter the weight and profit of item " << i + 1 << " : "; cin >> itemArray[i].weight; cin >> itemArray[i].profit; @@ -65,17 +57,13 @@ int main() float maxProfit = 0; int i = n; - while (capacity > 0 && --i >= 0) - { - if (capacity >= itemArray[i].weight) - { + while (capacity > 0 && --i >= 0) { + if (capacity >= itemArray[i].weight) { maxProfit += itemArray[i].profit; capacity -= itemArray[i].weight; cout << "\n\t" << itemArray[i].weight << "\t" << itemArray[i].profit; - } - else - { + } else { maxProfit += profitPerUnit(itemArray[i]) * capacity; cout << "\n\t" << capacity << "\t" << profitPerUnit(itemArray[i]) * capacity; diff --git a/greedy_algorithms/kruskals_minimum_spanning_tree.cpp b/greedy_algorithms/kruskals_minimum_spanning_tree.cpp index feeaf0102..9f35e86ac 100644 --- a/greedy_algorithms/kruskals_minimum_spanning_tree.cpp +++ b/greedy_algorithms/kruskals_minimum_spanning_tree.cpp @@ -11,16 +11,12 @@ int graph[V][V] = {{0, 4, 1, 4, INFINITY, INFINITY}, {INFINITY, 3, 1, 5, 0, INFINITY}, {INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}}; -void findMinimumEdge() -{ - for (int i = 0; i < V; i++) - { +void findMinimumEdge() { + for (int i = 0; i < V; i++) { int min = INFINITY; int minIndex = 0; - for (int j = 0; j < V; j++) - { - if (graph[i][j] != 0 && graph[i][j] < min) - { + for (int j = 0; j < V; j++) { + if (graph[i][j] != 0 && graph[i][j] < min) { min = graph[i][j]; minIndex = j; } @@ -29,8 +25,7 @@ void findMinimumEdge() } } -int main() -{ +int main() { findMinimumEdge(); return 0; } diff --git a/greedy_algorithms/prims_minimum_spanning_tree.cpp b/greedy_algorithms/prims_minimum_spanning_tree.cpp index c1d3df669..c804c176d 100644 --- a/greedy_algorithms/prims_minimum_spanning_tree.cpp +++ b/greedy_algorithms/prims_minimum_spanning_tree.cpp @@ -6,8 +6,7 @@ using namespace std; int graph[V][V] = {{0, 5, 1, 2}, {5, 0, 3, 3}, {1, 3, 0, 4}, {2, 3, 4, 0}}; -struct mst -{ +struct mst { bool visited; int key; int near; @@ -15,10 +14,8 @@ struct mst mst MST_Array[V]; -void initilize() -{ - for (int i = 0; i < V; i++) - { +void initilize() { + for (int i = 0; i < V; i++) { MST_Array[i].visited = false; MST_Array[i].key = INFINITY; // considering INFINITY as inifinity MST_Array[i].near = i; @@ -27,17 +24,13 @@ void initilize() MST_Array[0].key = 0; } -void updateNear() -{ - for (int v = 0; v < V; v++) - { +void updateNear() { + for (int v = 0; v < V; v++) { int min = INFINITY; int minIndex = 0; - for (int i = 0; i < V; i++) - { + for (int i = 0; i < V; i++) { if (MST_Array[i].key < min && MST_Array[i].visited == false && - MST_Array[i].key != INFINITY) - { + MST_Array[i].key != INFINITY) { min = MST_Array[i].key; minIndex = i; } @@ -45,12 +38,9 @@ void updateNear() MST_Array[minIndex].visited = true; - for (int i = 0; i < V; i++) - { - if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY) - { - if (graph[minIndex][i] < MST_Array[i].key) - { + for (int i = 0; i < V; i++) { + if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY) { + if (graph[minIndex][i] < MST_Array[i].key) { MST_Array[i].key = graph[minIndex][i]; MST_Array[i].near = minIndex; } @@ -59,17 +49,14 @@ void updateNear() } } -void show() -{ - for (int i = 0; i < V; i++) - { +void show() { + for (int i = 0; i < V; i++) { cout << i << " - " << MST_Array[i].near << "\t" << graph[i][MST_Array[i].near] << "\n"; } } -int main() -{ +int main() { initilize(); updateNear(); show(); diff --git a/hashing/chaining.cpp b/hashing/chaining.cpp index ae46aea59..6afd2d13b 100644 --- a/hashing/chaining.cpp +++ b/hashing/chaining.cpp @@ -2,51 +2,39 @@ #include using namespace std; -struct Node -{ +struct Node { int data; struct Node *next; } * head[100], *curr; -void init() -{ +void init() { for (int i = 0; i < 100; i++) head[i] = NULL; } -void add(int x, int h) -{ +void add(int x, int h) { struct Node *temp = new Node; temp->data = x; temp->next = NULL; - if (!head[h]) - { + if (!head[h]) { head[h] = temp; curr = head[h]; - } - else - { + } else { curr = head[h]; while (curr->next) curr = curr->next; curr->next = temp; } } -void display(int mod) -{ +void display(int mod) { struct Node *temp; int i; - for (i = 0; i < mod; i++) - { - if (!head[i]) - { + for (i = 0; i < mod; i++) { + if (!head[i]) { cout << "Key " << i << " is empty" << endl; - } - else - { + } else { cout << "Key " << i << " has values = "; temp = head[i]; - while (temp->next) - { + while (temp->next) { cout << temp->data << " "; temp = temp->next; } @@ -58,19 +46,16 @@ void display(int mod) int hash(int x, int mod) { return x % mod; } -void find(int x, int h) -{ +void find(int x, int h) { struct Node *temp = head[h]; - if (!head[h]) - { + if (!head[h]) { cout << "Element not found"; return; } while (temp->data != x && temp->next) temp = temp->next; if (temp->next) cout << "Element found"; - else - { + else { if (temp->data == x) cout << "Element found"; else @@ -78,15 +63,13 @@ void find(int x, int h) } } -int main(void) -{ +int main(void) { init(); int c, x, mod, h; cout << "Enter the size of Hash Table. = "; cin >> mod; bool loop = true; - while (loop) - { + while (loop) { cout << endl; cout << "PLEASE CHOOSE -" << endl; cout << "1. Add element." << endl; @@ -95,8 +78,7 @@ int main(void) cout << "4. Display Hash table." << endl; cout << "5. Exit." << endl; cin >> c; - switch (c) - { + switch (c) { case 1: cout << "Enter element to add = "; cin >> x; diff --git a/hashing/double_hash_hash_table.cpp b/hashing/double_hash_hash_table.cpp index 842f383c5..7ee2757de 100644 --- a/hashing/double_hash_hash_table.cpp +++ b/hashing/double_hash_hash_table.cpp @@ -25,55 +25,44 @@ int size; bool rehashing; // Node that holds key -struct Entry -{ +struct Entry { explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key -int hashFxn(int key) -{ +int hashFxn(int key) { std::hash hash; return hash(key); } // Used for second hash function -int otherHashFxn(int key) -{ +int otherHashFxn(int key) { std::hash hash; return 1 + (7 - (hash(key) % 7)); } // Performs double hashing to resolve collisions -int doubleHash(int key, bool searching) -{ +int doubleHash(int key, bool searching) { int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; - do - { + do { int index = static_cast(fabs((hash + (i * otherHashFxn(key))))) % totalSize; entry = table[index]; - if (searching) - { - if (entry.key == notPresent) - { + if (searching) { + if (entry.key == notPresent) { return notPresent; } - if (searchingProber(entry, key)) - { + if (searchingProber(entry, key)) { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; - } - else - { - if (putProber(entry, key)) - { + } else { + if (putProber(entry, key)) { if (!rehashing) cout << "Spot found!" << endl; return index; @@ -87,8 +76,7 @@ int doubleHash(int key, bool searching) << ")" << endl; i++; } - if (i == totalSize * 100) - { + if (i == totalSize * 100) { cout << "DoubleHash probe failed" << endl; return notPresent; } @@ -97,38 +85,28 @@ int doubleHash(int key, bool searching) } // Finds empty spot -bool putProber(Entry entry, int key) -{ - if (entry.key == notPresent || entry.key == tomb) - { +bool putProber(Entry entry, int key) { + if (entry.key == notPresent || entry.key == tomb) { return true; } return false; } // Looks for a matching key -bool searchingProber(Entry entry, int key) -{ +bool searchingProber(Entry entry, int key) { if (entry.key == key) return true; return false; } // Displays the table -void display() -{ - for (int i = 0; i < totalSize; i++) - { - if (table[i].key == notPresent) - { +void display() { + for (int i = 0; i < totalSize; i++) { + if (table[i].key == notPresent) { cout << " Empty "; - } - else if (table[i].key == tomb) - { + } else if (table[i].key == tomb) { cout << " Tomb "; - } - else - { + } else { cout << " "; cout << table[i].key; cout << " "; @@ -138,8 +116,7 @@ void display() } // Rehashes the table into a bigger table -void rehash() -{ +void rehash() { // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; @@ -147,10 +124,8 @@ void rehash() // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; - for (int i = 0; i < oldSize; i++) - { - if (oldTable[i].key != -1 && oldTable[i].key != notPresent) - { + for (int i = 0; i < oldSize; i++) { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { size--; // Size stays the same (add increments size) add(oldTable[i].key); } @@ -161,25 +136,21 @@ void rehash() } // Checks for load factor here -void add(int key) -{ +void add(int key) { Entry* entry = new Entry(); entry->key = key; int index = doubleHash(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size / static_cast(totalSize) >= 0.5) - { + if (++size / static_cast(totalSize) >= 0.5) { rehash(); } } // Removes key. Leaves tombstone upon removal. -void remove(int key) -{ +void remove(int key) { int index = doubleHash(key, true); - if (index == notPresent) - { + if (index == notPresent) { cout << "key not found" << endl; } table[index].key = tomb; @@ -188,8 +159,7 @@ void remove(int key) } // Information about the adding process -void addInfo(int key) -{ +void addInfo(int key) { cout << "Initial table: "; display(); cout << endl; @@ -202,8 +172,7 @@ void addInfo(int key) } // Information about removal process -void removalInfo(int key) -{ +void removalInfo(int key) { cout << "Initial table: "; display(); cout << endl; @@ -216,15 +185,13 @@ void removalInfo(int key) } // I/O -int main(void) -{ +int main(void) { int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; - while (loop) - { + while (loop) { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; @@ -235,8 +202,7 @@ int main(void) cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; - switch (cmd) - { + switch (cmd) { case 1: cout << "Enter key to add = "; cin >> key; @@ -247,13 +213,11 @@ int main(void) cin >> key; removalInfo(key); break; - case 3: - { + case 3: { cout << "Enter key to search = "; cin >> key; Entry entry = table[doubleHash(key, true)]; - if (entry.key == notPresent) - { + if (entry.key == notPresent) { cout << "Key not present"; } break; diff --git a/hashing/linear_probing_hash_table.cpp b/hashing/linear_probing_hash_table.cpp index 0d4b5b0e1..393504c1d 100644 --- a/hashing/linear_probing_hash_table.cpp +++ b/hashing/linear_probing_hash_table.cpp @@ -25,47 +25,37 @@ int size; bool rehashing; // Node that holds key -struct Entry -{ +struct Entry { explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key -int hashFxn(int key) -{ +int hashFxn(int key) { std::hash hash; return hash(key); } // Performs linear probing to resolve collisions -int linearProbe(int key, bool searching) -{ +int linearProbe(int key, bool searching) { int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; - do - { + do { int index = static_cast(fabs((hash + i) % totalSize)); entry = table[index]; - if (searching) - { - if (entry.key == notPresent) - { + if (searching) { + if (entry.key == notPresent) { return notPresent; } - if (searchingProber(entry, key)) - { + if (searchingProber(entry, key)) { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; - } - else - { - if (putProber(entry, key)) - { + } else { + if (putProber(entry, key)) { if (!rehashing) cout << "Spot found!" << endl; return index; @@ -74,8 +64,7 @@ int linearProbe(int key, bool searching) cout << "Spot taken, looking at next" << endl; i++; } - if (i == totalSize) - { + if (i == totalSize) { cout << "Linear probe failed" << endl; return notPresent; } @@ -84,38 +73,28 @@ int linearProbe(int key, bool searching) } // Finds empty spot -bool putProber(Entry entry, int key) -{ - if (entry.key == notPresent || entry.key == tomb) - { +bool putProber(Entry entry, int key) { + if (entry.key == notPresent || entry.key == tomb) { return true; } return false; } // Looks for a matching key -bool searchingProber(Entry entry, int key) -{ +bool searchingProber(Entry entry, int key) { if (entry.key == key) return true; return false; } // Displays the table -void display() -{ - for (int i = 0; i < totalSize; i++) - { - if (table[i].key == notPresent) - { +void display() { + for (int i = 0; i < totalSize; i++) { + if (table[i].key == notPresent) { cout << " Empty "; - } - else if (table[i].key == tomb) - { + } else if (table[i].key == tomb) { cout << " Tomb "; - } - else - { + } else { cout << " "; cout << table[i].key; cout << " "; @@ -125,8 +104,7 @@ void display() } // Rehashes the table into a bigger table -void rehash() -{ +void rehash() { // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; @@ -134,10 +112,8 @@ void rehash() // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; - for (int i = 0; i < oldSize; i++) - { - if (oldTable[i].key != -1 && oldTable[i].key != notPresent) - { + for (int i = 0; i < oldSize; i++) { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { size--; // Size stays the same (add increments size) add(oldTable[i].key); } @@ -148,25 +124,21 @@ void rehash() } // Adds entry using linear probing. Checks for load factor here -void add(int key) -{ +void add(int key) { Entry* entry = new Entry(); entry->key = key; int index = linearProbe(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size / static_cast(totalSize) >= 0.5) - { + if (++size / static_cast(totalSize) >= 0.5) { rehash(); } } // Removes key. Leaves tombstone upon removal. -void remove(int key) -{ +void remove(int key) { int index = linearProbe(key, true); - if (index == notPresent) - { + if (index == notPresent) { cout << "key not found" << endl; } cout << "Removal Successful, leaving tomb" << endl; @@ -175,8 +147,7 @@ void remove(int key) } // Information about the adding process -void addInfo(int key) -{ +void addInfo(int key) { cout << "Initial table: "; display(); cout << endl; @@ -189,8 +160,7 @@ void addInfo(int key) } // Information about removal process -void removalInfo(int key) -{ +void removalInfo(int key) { cout << "Initial table: "; display(); cout << endl; @@ -203,15 +173,13 @@ void removalInfo(int key) } // I/O -int main(void) -{ +int main(void) { int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; - while (loop) - { + while (loop) { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; @@ -222,8 +190,7 @@ int main(void) cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; - switch (cmd) - { + switch (cmd) { case 1: cout << "Enter key to add = "; cin >> key; @@ -234,13 +201,11 @@ int main(void) cin >> key; removalInfo(key); break; - case 3: - { + case 3: { cout << "Enter key to search = "; cin >> key; Entry entry = table[linearProbe(key, true)]; - if (entry.key == notPresent) - { + if (entry.key == notPresent) { cout << "Key not present"; } break; diff --git a/hashing/quadratic_probing_hash_table.cpp b/hashing/quadratic_probing_hash_table.cpp index b549d057d..971c2182d 100644 --- a/hashing/quadratic_probing_hash_table.cpp +++ b/hashing/quadratic_probing_hash_table.cpp @@ -26,54 +26,43 @@ int size; bool rehashing; // Node that holds key -struct Entry -{ +struct Entry { explicit Entry(int key = notPresent) : key(key) {} int key; }; // Hash a key -int hashFxn(int key) -{ +int hashFxn(int key) { std::hash hash; return hash(key); } // Performs quadratic probing to resolve collisions -int quadraticProbe(int key, bool searching) -{ +int quadraticProbe(int key, bool searching) { int hash = static_cast(fabs(hashFxn(key))); int i = 0; Entry entry; - do - { + do { int index = std::round(fabs( (hash + static_cast(std::round(std::pow(i, 2)))) % totalSize)); entry = table[index]; - if (searching) - { - if (entry.key == notPresent) - { + if (searching) { + if (entry.key == notPresent) { return notPresent; } - if (searchingProber(entry, key)) - { + if (searchingProber(entry, key)) { cout << "Found key!" << endl; return index; } cout << "Found tombstone or equal hash, checking next" << endl; i++; - } - else - { - if (putProber(entry, key)) - { + } else { + if (putProber(entry, key)) { if (!rehashing) cout << "Spot found!" << endl; return index; } - if (!rehashing) - { + if (!rehashing) { cout << "Spot taken, looking at next (next index = " << std::round(fabs((hash + static_cast(std::round( std::pow(i + 1, 2)))) % @@ -82,8 +71,7 @@ int quadraticProbe(int key, bool searching) } i++; } - if (i == totalSize * 100) - { + if (i == totalSize * 100) { cout << "Quadratic probe failed (infinite loop)" << endl; return notPresent; } @@ -92,26 +80,22 @@ int quadraticProbe(int key, bool searching) } // Finds empty spot -bool putProber(Entry entry, int key) -{ - if (entry.key == notPresent || entry.key == tomb) - { +bool putProber(Entry entry, int key) { + if (entry.key == notPresent || entry.key == tomb) { return true; } return false; } // Looks for a matching key -bool searchingProber(Entry entry, int key) -{ +bool searchingProber(Entry entry, int key) { if (entry.key == key) return true; return false; } // Helper -Entry find(int key) -{ +Entry find(int key) { int index = quadraticProbe(key, true); if (index == notPresent) return Entry(); @@ -119,20 +103,13 @@ Entry find(int key) } // Displays the table -void display() -{ - for (int i = 0; i < totalSize; i++) - { - if (table[i].key == notPresent) - { +void display() { + for (int i = 0; i < totalSize; i++) { + if (table[i].key == notPresent) { cout << " Empty "; - } - else if (table[i].key == tomb) - { + } else if (table[i].key == tomb) { cout << " Tomb "; - } - else - { + } else { cout << " "; cout << table[i].key; cout << " "; @@ -142,8 +119,7 @@ void display() } // Rehashes the table into a bigger table -void rehash() -{ +void rehash() { // Necessary so wall of add info isn't printed all at once rehashing = true; int oldSize = totalSize; @@ -151,10 +127,8 @@ void rehash() // Really this should use the next prime number greater than totalSize * 2 table = new Entry[totalSize * 2]; totalSize *= 2; - for (int i = 0; i < oldSize; i++) - { - if (oldTable[i].key != -1 && oldTable[i].key != notPresent) - { + for (int i = 0; i < oldSize; i++) { + if (oldTable[i].key != -1 && oldTable[i].key != notPresent) { size--; // Size stays the same (add increments size) add(oldTable[i].key); } @@ -165,25 +139,21 @@ void rehash() } // Checks for load factor here -void add(int key) -{ +void add(int key) { Entry* entry = new Entry(); entry->key = key; int index = quadraticProbe(key, false); table[index] = *entry; // Load factor greater than 0.5 causes resizing - if (++size / static_cast(totalSize) >= 0.5) - { + if (++size / static_cast(totalSize) >= 0.5) { rehash(); } } // Removes key. Leaves tombstone upon removal. -void remove(int key) -{ +void remove(int key) { int index = quadraticProbe(key, true); - if (index == notPresent) - { + if (index == notPresent) { cout << "key not found" << endl; } table[index].key = tomb; @@ -192,8 +162,7 @@ void remove(int key) } // Information about the adding process -void addInfo(int key) -{ +void addInfo(int key) { cout << "Initial table: "; display(); cout << endl; @@ -206,8 +175,7 @@ void addInfo(int key) } // Information about removal process -void removalInfo(int key) -{ +void removalInfo(int key) { cout << "Initial table: "; display(); cout << endl; @@ -220,15 +188,13 @@ void removalInfo(int key) } // I/O -int main(void) -{ +int main(void) { int cmd, hash, key; cout << "Enter the initial size of Hash Table. = "; cin >> totalSize; table = new Entry[totalSize]; bool loop = true; - while (loop) - { + while (loop) { system("pause"); cout << endl; cout << "PLEASE CHOOSE -" << endl; @@ -239,8 +205,7 @@ int main(void) cout << "5. Display Hash table." << endl; cout << "6. Exit." << endl; cin >> cmd; - switch (cmd) - { + switch (cmd) { case 1: cout << "Enter key to add = "; cin >> key; @@ -251,13 +216,11 @@ int main(void) cin >> key; removalInfo(key); break; - case 3: - { + case 3: { cout << "Enter key to search = "; cin >> key; Entry entry = table[quadraticProbe(key, true)]; - if (entry.key == notPresent) - { + if (entry.key == notPresent) { cout << "Key not present"; } break; diff --git a/math/binary_exponent.cpp b/math/binary_exponent.cpp index 7bf3a34a1..05e6f33f7 100644 --- a/math/binary_exponent.cpp +++ b/math/binary_exponent.cpp @@ -25,32 +25,24 @@ /// Recursive function to calculate exponent in \f$O(\log(n))\f$ using binary /// exponent. -int binExpo(int a, int b) -{ - if (b == 0) - { +int binExpo(int a, int b) { + if (b == 0) { return 1; } int res = binExpo(a, b / 2); - if (b % 2) - { + if (b % 2) { return res * res * a; - } - else - { + } else { return res * res; } } /// Iterative function to calculate exponent in \f$O(\log(n))\f$ using binary /// exponent. -int binExpo_alt(int a, int b) -{ +int binExpo_alt(int a, int b) { int res = 1; - while (b > 0) - { - if (b % 2) - { + while (b > 0) { + if (b % 2) { res = res * a; } a = a * a; @@ -60,21 +52,15 @@ int binExpo_alt(int a, int b) } /// Main function -int main() -{ +int main() { int a, b; /// Give two numbers a, b std::cin >> a >> b; - if (a == 0 && b == 0) - { + if (a == 0 && b == 0) { std::cout << "Math error" << std::endl; - } - else if (b < 0) - { + } else if (b < 0) { std::cout << "Exponent must be positive !!" << std::endl; - } - else - { + } else { int resRecurse = binExpo(a, b); /// int resIterate = binExpo_alt(a, b); diff --git a/math/double_factorial.cpp b/math/double_factorial.cpp index 4909ad489..8e5ffcefa 100644 --- a/math/double_factorial.cpp +++ b/math/double_factorial.cpp @@ -13,11 +13,9 @@ /** Compute double factorial using iterative method */ -uint64_t double_factorial_iterative(uint64_t n) -{ +uint64_t double_factorial_iterative(uint64_t n) { uint64_t res = 1; - for (uint64_t i = n;; i -= 2) - { + for (uint64_t i = n;; i -= 2) { if (i == 0 || i == 1) return res; res *= i; @@ -28,16 +26,14 @@ uint64_t double_factorial_iterative(uint64_t n) /** Compute double factorial using resursive method. *
Recursion can be costly for large numbers. */ -uint64_t double_factorial_recursive(uint64_t n) -{ +uint64_t double_factorial_recursive(uint64_t n) { if (n <= 1) return 1; return n * double_factorial_recursive(n - 2); } /// main function -int main() -{ +int main() { uint64_t n; std::cin >> n; assert(n >= 0); diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp index 283516b42..8283ab045 100644 --- a/math/eulers_totient_function.cpp +++ b/math/eulers_totient_function.cpp @@ -29,15 +29,11 @@ /** Function to caculate Euler's totient phi */ -uint64_t phiFunction(uint64_t n) -{ +uint64_t phiFunction(uint64_t n) { uint64_t result = n; - for (uint64_t i = 2; i * i <= n; i++) - { - if (n % i == 0) - { - while (n % i == 0) - { + for (uint64_t i = 2; i * i <= n; i++) { + if (n % i == 0) { + while (n % i == 0) { n /= i; } result -= result / i; @@ -49,15 +45,11 @@ uint64_t phiFunction(uint64_t n) } /// Main function -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { uint64_t n; - if (argc < 2) - { + if (argc < 2) { std::cout << "Enter the number: "; - } - else - { + } else { n = strtoull(argv[1], nullptr, 10); } std::cin >> n; diff --git a/math/extended_euclid_algorithm.cpp b/math/extended_euclid_algorithm.cpp index 8a79e0c78..9fdc9692e 100644 --- a/math/extended_euclid_algorithm.cpp +++ b/math/extended_euclid_algorithm.cpp @@ -21,8 +21,7 @@ * @param[in] quotient unsigned */ template -inline void update_step(T *r, T *r0, const T2 quotient) -{ +inline void update_step(T *r, T *r0, const T2 quotient) { T temp = *r; *r = *r0 - (quotient * temp); *r0 = temp; @@ -39,8 +38,7 @@ inline void update_step(T *r, T *r0, const T2 quotient) * @param[out] y signed */ template -void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) -{ +void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) { if (B > A) std::swap(A, B); // Ensure that A >= B @@ -48,8 +46,7 @@ void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) T2 t = 1, t0 = 0; T1 r = B, r0 = A; - while (r != 0) - { + while (r != 0) { T1 quotient = r0 / r; update_step(&r, &r0, quotient); update_step(&s, &s0, quotient); @@ -70,19 +67,15 @@ void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) * @param[in,out] y signed */ template -void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) -{ +void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) { if (B > A) std::swap(A, B); // Ensure that A >= B - if (B == 0) - { + if (B == 0) { *GCD = A; *x = 1; *y = 0; - } - else - { + } else { extendedEuclid(B, A % B, GCD, x, y); T2 temp = *x; *x = *y; @@ -91,8 +84,7 @@ void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) } /// Main function -int main() -{ +int main() { uint32_t a, b, gcd; int32_t x, y; std::cin >> a >> b; diff --git a/math/factorial.cpp b/math/factorial.cpp index 7f50544e2..353f0b16b 100644 --- a/math/factorial.cpp +++ b/math/factorial.cpp @@ -5,16 +5,14 @@ #include /** function to find factorial of given number */ -unsigned int factorial(unsigned int n) -{ +unsigned int factorial(unsigned int n) { if (n == 0) return 1; return n * factorial(n - 1); } /** Main function */ -int main() -{ +int main() { int num = 5; std::cout << "Factorial of " << num << " is " << factorial(num) << std::endl; diff --git a/math/fast_power.cpp b/math/fast_power.cpp index 8a0525ac1..c5621cd4e 100644 --- a/math/fast_power.cpp +++ b/math/fast_power.cpp @@ -23,8 +23,7 @@ * algorithm implementation for \f$a^b\f$ */ template -double fast_power_recursive(T a, T b) -{ +double fast_power_recursive(T a, T b) { // negative power. a^b = 1 / (a^-b) if (b < 0) return 1.0 / fast_power_recursive(a, -b); @@ -48,15 +47,13 @@ double fast_power_recursive(T a, T b) It still calculates in \f$O(\log N)\f$ */ template -double fast_power_linear(T a, T b) -{ +double fast_power_linear(T a, T b) { // negative power. a^b = 1 / (a^-b) if (b < 0) return 1.0 / fast_power_linear(a, -b); double result = 1; - while (b) - { + while (b) { if (b & 1) result = result * a; a = a * a; @@ -68,14 +65,12 @@ double fast_power_linear(T a, T b) /** * Main function */ -int main() -{ +int main() { std::srand(std::time(nullptr)); std::ios_base::sync_with_stdio(false); std::cout << "Testing..." << std::endl; - for (int i = 0; i < 20; i++) - { + for (int i = 0; i < 20; i++) { int a = std::rand() % 20 - 10; int b = std::rand() % 20 - 10; std::cout << std::endl << "Calculating " << a << "^" << b << std::endl; diff --git a/math/fibonacci.cpp b/math/fibonacci.cpp index 5a219bbf9..e15cfc0cc 100644 --- a/math/fibonacci.cpp +++ b/math/fibonacci.cpp @@ -14,8 +14,7 @@ /** * Recursively compute sequences */ -int fibonacci(unsigned int n) -{ +int fibonacci(unsigned int n) { /* If the input is 0 or 1 just return the same This will set the first 2 values of the sequence */ if (n <= 1) @@ -26,8 +25,7 @@ int fibonacci(unsigned int n) } /// Main function -int main() -{ +int main() { int n; std::cin >> n; assert(n >= 0); diff --git a/math/fibonacci_fast.cpp b/math/fibonacci_fast.cpp index 3b3a3ca38..08cced351 100644 --- a/math/fibonacci_fast.cpp +++ b/math/fibonacci_fast.cpp @@ -26,8 +26,7 @@ const uint64_t MAX = 93; uint64_t f[MAX] = {0}; /** Algorithm */ -uint64_t fib(uint64_t n) -{ +uint64_t fib(uint64_t n) { if (n == 0) return 0; if (n == 1 || n == 2) @@ -44,11 +43,9 @@ uint64_t fib(uint64_t n) } /** Main function */ -int main() -{ +int main() { // Main Function - for (uint64_t i = 1; i < 93; i++) - { + for (uint64_t i = 1; i < 93; i++) { std::cout << i << " th fibonacci number is " << fib(i) << std::endl; } return 0; diff --git a/math/fibonacci_large.cpp b/math/fibonacci_large.cpp index edc513750..d9dbff799 100644 --- a/math/fibonacci_large.cpp +++ b/math/fibonacci_large.cpp @@ -20,13 +20,11 @@ * \f[f(n)=f(n-1)+f(n-2)\f] * and returns the result as a large_number type. */ -large_number fib(uint64_t n) -{ +large_number fib(uint64_t n) { large_number f0(1); large_number f1(1); - do - { + do { large_number f2 = f1; f1 += f0; f0 = f2; @@ -36,15 +34,11 @@ large_number fib(uint64_t n) return f1; } -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { uint64_t N; - if (argc == 2) - { + if (argc == 2) { N = strtoull(argv[1], NULL, 10); - } - else - { + } else { std::cout << "Enter N: "; std::cin >> N; } diff --git a/math/gcd_iterative_euclidean.cpp b/math/gcd_iterative_euclidean.cpp index e832605d7..2c0651ad7 100644 --- a/math/gcd_iterative_euclidean.cpp +++ b/math/gcd_iterative_euclidean.cpp @@ -12,34 +12,27 @@ /** * algorithm */ -int gcd(int num1, int num2) -{ - if (num1 <= 0 | num2 <= 0) - { +int gcd(int num1, int num2) { + if (num1 <= 0 | num2 <= 0) { throw std::domain_error("Euclidean algorithm domain is for ints > 0"); } - if (num1 == num2) - { + if (num1 == num2) { return num1; } int base_num = 0; int previous_remainder = 1; - if (num1 > num2) - { + if (num1 > num2) { base_num = num1; previous_remainder = num2; - } - else - { + } else { base_num = num2; previous_remainder = num1; } - while ((base_num % previous_remainder) != 0) - { + while ((base_num % previous_remainder) != 0) { int old_base = base_num; base_num = previous_remainder; previous_remainder = old_base % previous_remainder; @@ -51,15 +44,11 @@ int gcd(int num1, int num2) /** * Main function */ -int main() -{ +int main() { std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; - try - { + try { std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl; - } - catch (const std::domain_error &e) - { + } catch (const std::domain_error &e) { std::cout << "Error handling was successful" << std::endl; } std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl; diff --git a/math/gcd_of_n_numbers.cpp b/math/gcd_of_n_numbers.cpp index cd81e6025..92968ff12 100644 --- a/math/gcd_of_n_numbers.cpp +++ b/math/gcd_of_n_numbers.cpp @@ -12,12 +12,10 @@ * @param[in] a array of integers to compute GCD for * @param[in] n number of integers in array `a` */ -int gcd(int *a, int n) -{ +int gcd(int *a, int n) { int j = 1; // to access all elements of the array starting from 1 int gcd = a[0]; - while (j < n) - { + while (j < n) { if (a[j] % gcd == 0) // value of gcd is as needed so far j++; // so we check for next element else @@ -27,8 +25,7 @@ int gcd(int *a, int n) } /** Main function */ -int main() -{ +int main() { int n; std::cout << "Enter value of n:" << std::endl; std::cin >> n; diff --git a/math/gcd_recursive_euclidean.cpp b/math/gcd_recursive_euclidean.cpp index d16fb1190..2a3d2183c 100644 --- a/math/gcd_recursive_euclidean.cpp +++ b/math/gcd_recursive_euclidean.cpp @@ -11,15 +11,12 @@ /** * algorithm */ -int gcd(int num1, int num2) -{ - if (num1 <= 0 | num2 <= 0) - { +int gcd(int num1, int num2) { + if (num1 <= 0 | num2 <= 0) { throw std::domain_error("Euclidean algorithm domain is for ints > 0"); } - if (num1 == num2) - { + if (num1 == num2) { return num1; } @@ -42,15 +39,11 @@ int gcd(int num1, int num2) /** * Main function */ -int main() -{ +int main() { std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; - try - { + try { std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl; - } - catch (const std::domain_error &e) - { + } catch (const std::domain_error &e) { std::cout << "Error handling was successful" << std::endl; } std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl; diff --git a/math/large_factorial.cpp b/math/large_factorial.cpp index 0a54f620b..1027f41ab 100644 --- a/math/large_factorial.cpp +++ b/math/large_factorial.cpp @@ -13,8 +13,7 @@ /** Test implementation for 10! Result must be 3628800. * @returns True if test pass else False */ -bool test1() -{ +bool test1() { std::cout << "---- Check 1\t"; unsigned int i, number = 10; large_number result; @@ -24,18 +23,15 @@ bool test1() const char *known_reslt = "3628800"; /* check 1 */ - if (strlen(known_reslt) != result.num_digits()) - { + if (strlen(known_reslt) != result.num_digits()) { std::cerr << "Result lengths dont match! " << strlen(known_reslt) << " != " << result.num_digits() << std::endl; return false; } const size_t N = result.num_digits(); - for (i = 0; i < N; i++) - { - if (known_reslt[i] != result.digit_char(i)) - { + for (i = 0; i < N; i++) { + if (known_reslt[i] != result.digit_char(i)) { std::cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result.digit_char(i) << std::endl; return false; @@ -54,8 +50,7 @@ bool test1() * ``` * @returns True if test pass else False */ -bool test2() -{ +bool test2() { std::cout << "---- Check 2\t"; unsigned int i, number = 100; large_number result; @@ -68,18 +63,15 @@ bool test2() "000000000000000000"; /* check 1 */ - if (strlen(known_reslt) != result.num_digits()) - { + if (strlen(known_reslt) != result.num_digits()) { std::cerr << "Result lengths dont match! " << strlen(known_reslt) << " != " << result.num_digits() << std::endl; return false; } const size_t N = result.num_digits(); - for (i = 0; i < N; i++) - { - if (known_reslt[i] != result.digit_char(i)) - { + for (i = 0; i < N; i++) { + if (known_reslt[i] != result.digit_char(i)) { std::cerr << i << "^th digit mismatch! " << known_reslt[i] << " != " << result.digit_char(i) << std::endl; return false; @@ -93,16 +85,12 @@ bool test2() /** * Main program **/ -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { int number, i; - if (argc == 2) - { + if (argc == 2) { number = atoi(argv[1]); - } - else - { + } else { std::cout << "Enter the value of n(n starts from 0 ): "; std::cin >> number; } diff --git a/math/large_number.h b/math/large_number.h index 88e3ba802..c1a3665e4 100644 --- a/math/large_number.h +++ b/math/large_number.h @@ -20,8 +20,7 @@ * digit to the number, perform multiplication of * large number with long unsigned integers. **/ -class large_number -{ +class large_number { public: /**< initializer with value = 1 */ large_number() { _digits.push_back(1); } @@ -36,11 +35,9 @@ class large_number // } /**< initializer from an integer */ - explicit large_number(int n) - { + explicit large_number(int n) { int carry = n; - do - { + do { add_digit(carry % 10); carry /= 10; } while (carry != 0); @@ -53,10 +50,8 @@ class large_number explicit large_number(std::vector &vec) : _digits(vec) {} /**< initializer from a string */ - explicit large_number(char const *number_str) - { - for (size_t i = strlen(number_str); i > 0; i--) - { + explicit large_number(char const *number_str) { + for (size_t i = strlen(number_str); i > 0; i--) { unsigned char a = number_str[i - 1] - '0'; if (a >= 0 && a <= 9) _digits.push_back(a); @@ -66,55 +61,48 @@ class large_number /** * Function to check implementation **/ - static bool test() - { + static bool test() { std::cout << "------ Checking `large_number` class implementations\t" << std::endl; large_number a(40); // 1. test multiplication a *= 10; - if (a != large_number(400)) - { + if (a != large_number(400)) { std::cerr << "\tFailed 1/6 (" << a << "!=400)" << std::endl; return false; } std::cout << "\tPassed 1/6..."; // 2. test compound addition with integer a += 120; - if (a != large_number(520)) - { + if (a != large_number(520)) { std::cerr << "\tFailed 2/6 (" << a << "!=520)" << std::endl; return false; } std::cout << "\tPassed 2/6..."; // 3. test compound multiplication again a *= 10; - if (a != large_number(5200)) - { + if (a != large_number(5200)) { std::cerr << "\tFailed 3/6 (" << a << "!=5200)" << std::endl; return false; } std::cout << "\tPassed 3/6..."; // 4. test increment (prefix) ++a; - if (a != large_number(5201)) - { + if (a != large_number(5201)) { std::cerr << "\tFailed 4/6 (" << a << "!=5201)" << std::endl; return false; } std::cout << "\tPassed 4/6..."; // 5. test increment (postfix) a++; - if (a != large_number(5202)) - { + if (a != large_number(5202)) { std::cerr << "\tFailed 5/6 (" << a << "!=5202)" << std::endl; return false; } std::cout << "\tPassed 5/6..."; // 6. test addition with another large number a = a + large_number("7000000000000000000000000000000"); - if (a != large_number("7000000000000000000000000005202")) - { + if (a != large_number("7000000000000000000000000005202")) { std::cerr << "\tFailed 6/6 (" << a << "!=7000000000000000000000000005202)" << std::endl; return false; @@ -126,10 +114,8 @@ class large_number /** * add a digit at MSB to the large number **/ - void add_digit(unsigned int value) - { - if (value > 9) - { + void add_digit(unsigned int value) { + if (value > 9) { std::cerr << "digit > 9!!\n"; exit(EXIT_FAILURE); } @@ -149,16 +135,14 @@ class large_number **/ inline unsigned char &operator[](size_t n) { return this->_digits[n]; } - inline const unsigned char &operator[](size_t n) const - { + inline const unsigned char &operator[](size_t n) const { return this->_digits[n]; } /** * operator overload to compare two numbers **/ - friend std::ostream &operator<<(std::ostream &out, const large_number &a) - { + friend std::ostream &operator<<(std::ostream &out, const large_number &a) { for (size_t i = a.num_digits(); i > 0; i--) out << static_cast(a[i - 1]); return out; @@ -167,8 +151,7 @@ class large_number /** * operator overload to compare two numbers **/ - friend bool operator==(large_number const &a, large_number const &b) - { + friend bool operator==(large_number const &a, large_number const &b) { size_t N = a.num_digits(); if (N != b.num_digits()) return false; @@ -181,16 +164,14 @@ class large_number /** * operator overload to compare two numbers **/ - friend bool operator!=(large_number const &a, large_number const &b) - { + friend bool operator!=(large_number const &a, large_number const &b) { return !(a == b); } /** * operator overload to increment (prefix) **/ - large_number &operator++() - { + large_number &operator++() { (*this) += 1; return *this; } @@ -198,8 +179,7 @@ class large_number /** * operator overload to increment (postfix) **/ - large_number &operator++(int) - { + large_number &operator++(int) { static large_number tmp(_digits); ++(*this); return tmp; @@ -208,15 +188,13 @@ class large_number /** * operator overload to add **/ - large_number &operator+=(large_number n) - { + large_number &operator+=(large_number n) { // if adding with another large_number large_number *b = reinterpret_cast(&n); const size_t max_L = std::max(this->num_digits(), b->num_digits()); unsigned int carry = 0; size_t i; - for (i = 0; i < max_L || carry != 0; i++) - { + for (i = 0; i < max_L || carry != 0; i++) { if (i < b->num_digits()) carry += (*b)[i]; if (i < this->num_digits()) @@ -238,8 +216,7 @@ class large_number * operator overload to perform addition **/ template - friend large_number &operator+(const large_number &a, const T &b) - { + friend large_number &operator+(const large_number &a, const T &b) { static large_number c = a; c += b; return c; @@ -248,8 +225,7 @@ class large_number /** * assignment operator **/ - large_number &operator=(const large_number &b) - { + large_number &operator=(const large_number &b) { this->_digits = b._digits; return *this; } @@ -258,8 +234,7 @@ class large_number * operator overload to increment **/ template - large_number &operator*=(const T n) - { + large_number &operator*=(const T n) { static_assert(std::is_integral::value, "Must be integer addition unsigned integer types."); this->multiply(n); @@ -269,8 +244,7 @@ class large_number /** * returns i^th digit as an ASCII character **/ - const char digit_char(size_t i) const - { + const char digit_char(size_t i) const { return _digits[num_digits() - i - 1] + '0'; } @@ -280,8 +254,7 @@ class large_number * store the result in the same large number **/ template - void multiply(const T n) - { + void multiply(const T n) { static_assert(std::is_integral::value, "Can only have integer types."); // assert(!(std::is_signed::value)); //, "Implemented only for @@ -289,24 +262,19 @@ class large_number size_t i; uint64_t carry = 0, temp; - for (i = 0; i < this->num_digits(); i++) - { + for (i = 0; i < this->num_digits(); i++) { temp = (*this)[i] * n; temp += carry; - if (temp < 10) - { + if (temp < 10) { carry = 0; - } - else - { + } else { carry = temp / 10; temp = temp % 10; } (*this)[i] = temp; } - while (carry != 0) - { + while (carry != 0) { this->add_digit(carry % 10); carry /= 10; } diff --git a/math/modular_inverse_fermat_little_theorem.cpp b/math/modular_inverse_fermat_little_theorem.cpp index 6895cafbb..7550e14bf 100644 --- a/math/modular_inverse_fermat_little_theorem.cpp +++ b/math/modular_inverse_fermat_little_theorem.cpp @@ -49,14 +49,11 @@ /** Recursive function to calculate exponent in \f$O(\log n)\f$ using binary * exponent. */ -int64_t binExpo(int64_t a, int64_t b, int64_t m) -{ +int64_t binExpo(int64_t a, int64_t b, int64_t m) { a %= m; int64_t res = 1; - while (b > 0) - { - if (b % 2) - { + while (b > 0) { + if (b % 2) { res = res * a % m; } a = a * a % m; @@ -68,18 +65,12 @@ int64_t binExpo(int64_t a, int64_t b, int64_t m) /** Prime check in \f$O(\sqrt{m})\f$ time. */ -bool isPrime(int64_t m) -{ - if (m <= 1) - { +bool isPrime(int64_t m) { + if (m <= 1) { return false; - } - else - { - for (int64_t i = 2; i * i <= m; i++) - { - if (m % i == 0) - { + } else { + for (int64_t i = 2; i * i <= m; i++) { + if (m % i == 0) { return false; } } @@ -90,21 +81,17 @@ bool isPrime(int64_t m) /** * Main function */ -int main() -{ +int main() { int64_t a, m; // Take input of a and m. std::cout << "Computing ((a^(-1))%(m)) using Fermat's Little Theorem"; std::cout << std::endl << std::endl; std::cout << "Give input 'a' and 'm' space separated : "; std::cin >> a >> m; - if (isPrime(m)) - { + if (isPrime(m)) { std::cout << "The modular inverse of a with mod m is (a^(m-2)) : "; std::cout << binExpo(a, m - 2, m) << std::endl; - } - else - { + } else { std::cout << "m must be a prime number."; std::cout << std::endl; } diff --git a/math/number_of_positive_divisors.cpp b/math/number_of_positive_divisors.cpp index beb459943..f157f7b41 100644 --- a/math/number_of_positive_divisors.cpp +++ b/math/number_of_positive_divisors.cpp @@ -31,31 +31,25 @@ respectively. /** * Algorithm */ -int number_of_positive_divisors(int n) -{ +int number_of_positive_divisors(int n) { std::vector prime_exponent_count; - for (int i = 2; i * i <= n; i++) - { + for (int i = 2; i * i <= n; i++) { int prime_count = 0; - while (n % i == 0) - { + while (n % i == 0) { prime_count += 1; n /= i; } - if (prime_count != 0) - { + if (prime_count != 0) { prime_exponent_count.push_back(prime_count); } } - if (n > 1) - { + if (n > 1) { prime_exponent_count.push_back(1); } int divisors_count = 1; - for (int i = 0; i < prime_exponent_count.size(); i++) - { + for (int i = 0; i < prime_exponent_count.size(); i++) { divisors_count = divisors_count * (prime_exponent_count[i] + 1); } @@ -65,20 +59,15 @@ int number_of_positive_divisors(int n) /** * Main function */ -int main() -{ +int main() { int n; std::cin >> n; - if (n < 0) - { + if (n < 0) { n = -n; } - if (n == 0) - { + if (n == 0) { std::cout << "All non-zero numbers are divisors of 0 !" << std::endl; - } - else - { + } else { std::cout << "Number of positive divisors is : "; std::cout << number_of_positive_divisors(n) << std::endl; } diff --git a/math/power_for_huge_numbers.cpp b/math/power_for_huge_numbers.cpp index 1f969f89d..301767d66 100644 --- a/math/power_for_huge_numbers.cpp +++ b/math/power_for_huge_numbers.cpp @@ -22,15 +22,13 @@ * @param res large number representation using array * @param res_size number of digits in `res` */ -int multiply(int x, int res[], int res_size) -{ +int multiply(int x, int res[], int res_size) { // Initialize carry int carry = 0; // One by one multiply n with // individual digits of res[] - for (int i = 0; i < res_size; i++) - { + for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; // Store last digit of @@ -43,8 +41,7 @@ int multiply(int x, int res[], int res_size) // Put carry in res and // increase result size - while (carry) - { + while (carry) { res[res_size] = carry % 10; carry = carry / 10; res_size++; @@ -56,11 +53,9 @@ int multiply(int x, int res[], int res_size) * @param x base * @param n exponent */ -void power(int x, int n) -{ +void power(int x, int n) { // printing value "1" for power = 0 - if (n == 0) - { + if (n == 0) { std::cout << "1"; return; } @@ -70,8 +65,7 @@ void power(int x, int n) int temp = x; // Initialize result - while (temp != 0) - { + while (temp != 0) { res[res_size++] = temp % 10; temp = temp / 10; } @@ -85,8 +79,7 @@ void power(int x, int n) } /** Main function */ -int main() -{ +int main() { int exponent, base; std::cout << "Enter base "; std::cin >> base; diff --git a/math/prime_factorization.cpp b/math/prime_factorization.cpp index c650497e2..001c2c3c3 100644 --- a/math/prime_factorization.cpp +++ b/math/prime_factorization.cpp @@ -20,43 +20,35 @@ std::vector> factors; /** Calculating prime number upto a given range */ -void SieveOfEratosthenes(int N) -{ +void SieveOfEratosthenes(int N) { // initializes the array isprime memset(isprime, true, sizeof isprime); - for (int i = 2; i <= N; i++) - { - if (isprime[i]) - { + for (int i = 2; i <= N; i++) { + if (isprime[i]) { for (int j = 2 * i; j <= N; j += i) isprime[j] = false; } } - for (int i = 2; i <= N; i++) - { + for (int i = 2; i <= N; i++) { if (isprime[i]) prime_numbers.push_back(i); } } /** Prime factorization of a number */ -void prime_factorization(int num) -{ +void prime_factorization(int num) { int number = num; - for (int i = 0; prime_numbers[i] <= num; i++) - { + for (int i = 0; prime_numbers[i] <= num; i++) { int count = 0; // termination condition - if (number == 1) - { + if (number == 1) { break; } - while (number % prime_numbers[i] == 0) - { + while (number % prime_numbers[i] == 0) { count++; number = number / prime_numbers[i]; } @@ -67,8 +59,7 @@ void prime_factorization(int num) } /** Main program */ -int main() -{ +int main() { int num; std::cout << "\t\tComputes the prime factorization\n\n"; std::cout << "Type in a number: "; @@ -79,8 +70,7 @@ int main() prime_factorization(num); // Prime factors with their powers in the given number in new line - for (auto it : factors) - { + for (auto it : factors) { std::cout << it.first << " " << it.second << std::endl; } diff --git a/math/prime_numbers.cpp b/math/prime_numbers.cpp index b3a52a104..4dd54f136 100644 --- a/math/prime_numbers.cpp +++ b/math/prime_numbers.cpp @@ -9,15 +9,12 @@ /** Generate an increasingly large number of primes * and store in a list */ -std::vector primes(int max) -{ +std::vector primes(int max) { max++; std::vector res; std::vector numbers(max, false); - for (int i = 2; i < max; i++) - { - if (!numbers[i]) - { + for (int i = 2; i < max; i++) { + if (!numbers[i]) { for (int j = i; j < max; j += i) numbers[j] = true; res.push_back(i); } @@ -26,8 +23,7 @@ std::vector primes(int max) } /** main function */ -int main() -{ +int main() { std::cout << "Calculate primes up to:\n>> "; int n; std::cin >> n; diff --git a/math/primes_up_to_billion.cpp b/math/primes_up_to_billion.cpp index 6c02b9089..4fb79a15e 100644 --- a/math/primes_up_to_billion.cpp +++ b/math/primes_up_to_billion.cpp @@ -10,15 +10,12 @@ char prime[100000000]; /** Perform Sieve algorithm */ -void Sieve(int64_t n) -{ +void Sieve(int64_t n) { memset(prime, '1', sizeof(prime)); // intitize '1' to every index prime[0] = '0'; // 0 is not prime prime[1] = '0'; // 1 is not prime - for (int p = 2; p * p <= n; p++) - { - if (prime[p] == '1') - { + for (int p = 2; p * p <= n; p++) { + if (prime[p] == '1') { for (int i = p * p; i <= n; i += p) prime[i] = '0'; // set all multiples of p to false } @@ -26,8 +23,7 @@ void Sieve(int64_t n) } /** Main function */ -int main() -{ +int main() { Sieve(100000000); int64_t n; std::cin >> n; // 10006187 diff --git a/math/sieve_of_eratosthenes.cpp b/math/sieve_of_eratosthenes.cpp index 90ad8bc40..d8fa70531 100644 --- a/math/sieve_of_eratosthenes.cpp +++ b/math/sieve_of_eratosthenes.cpp @@ -22,16 +22,12 @@ bool isprime[MAX]; * This is the function that finds the primes and eliminates * the multiples. */ -void sieve(uint32_t N) -{ +void sieve(uint32_t N) { isprime[0] = false; isprime[1] = false; - for (uint32_t i = 2; i <= N; i++) - { - if (isprime[i]) - { - for (uint32_t j = (i << 1); j <= N; j += i) - { + for (uint32_t i = 2; i <= N; i++) { + if (isprime[i]) { + for (uint32_t j = (i << 1); j <= N; j += i) { isprime[j] = false; } } @@ -41,12 +37,9 @@ void sieve(uint32_t N) /** * This function prints out the primes to STDOUT */ -void print(uint32_t N) -{ - for (uint32_t i = 1; i <= N; i++) - { - if (isprime[i]) - { +void print(uint32_t N) { + for (uint32_t i = 1; i <= N; i++) { + if (isprime[i]) { std::cout << i << ' '; } } @@ -56,17 +49,14 @@ void print(uint32_t N) /** * Initialize the array */ -void init() -{ - for (uint32_t i = 1; i < MAX; i++) - { +void init() { + for (uint32_t i = 1; i < MAX; i++) { isprime[i] = true; } } /** main function */ -int main() -{ +int main() { uint32_t N = 100; init(); sieve(N); diff --git a/math/sqrt_double.cpp b/math/sqrt_double.cpp index ffc83998a..1521b500a 100644 --- a/math/sqrt_double.cpp +++ b/math/sqrt_double.cpp @@ -13,10 +13,8 @@ /** Bisection method implemented for the function \f$x^2-a=0\f$ * whose roots are \f$\pm\sqrt{a}\f$ and only the positive root is returned. */ -double Sqrt(double a) -{ - if (a > 0 && a < 1) - { +double Sqrt(double a) { + if (a > 0 && a < 1) { return 1 / Sqrt(1 / a); } double l = 0, r = a; @@ -26,17 +24,12 @@ double Sqrt(double a) double epsilon = 1e-12; */ double epsilon = 1e-12; - while (l <= r) - { + while (l <= r) { double mid = (l + r) / 2; - if (mid * mid > a) - { + if (mid * mid > a) { r = mid; - } - else - { - if (a - mid * mid < epsilon) - { + } else { + if (a - mid * mid < epsilon) { return mid; } l = mid; @@ -46,8 +39,7 @@ double Sqrt(double a) } /** main function */ -int main() -{ +int main() { double n{}; std::cin >> n; assert(n >= 0); diff --git a/math/string_fibonacci.cpp b/math/string_fibonacci.cpp index 401b04d2d..eb9b6d7e1 100644 --- a/math/string_fibonacci.cpp +++ b/math/string_fibonacci.cpp @@ -21,50 +21,41 @@ * \param [in] b second number in string to add * \returns sum as a std::string */ -std::string add(std::string a, std::string b) -{ +std::string add(std::string a, std::string b) { std::string temp = ""; // carry flag int carry = 0; // fills up with zeros - while (a.length() < b.length()) - { + while (a.length() < b.length()) { a = "0" + a; } // fills up with zeros - while (b.length() < a.length()) - { + while (b.length() < a.length()) { b = "0" + b; } // adds the numbers a and b - for (int i = a.length() - 1; i >= 0; i--) - { + for (int i = a.length() - 1; i >= 0; i--) { char val = static_cast(((a[i] - 48) + (b[i] - 48)) + 48 + carry); - if (val > 57) - { + if (val > 57) { carry = 1; val -= 10; - } - else - { + } else { carry = 0; } temp = val + temp; } // processes the carry flag - if (carry == 1) - { + if (carry == 1) { temp = "1" + temp; } // removes leading zeros. - while (temp[0] == '0' && temp.length() > 1) - { + while (temp[0] == '0' && temp.length() > 1) { temp = temp.substr(1); } @@ -74,13 +65,11 @@ std::string add(std::string a, std::string b) /** Fibonacci iterator * \param [in] n n^th Fibonacci number */ -void fib_Accurate(uint64_t n) -{ +void fib_Accurate(uint64_t n) { std::string tmp = ""; std::string fibMinus1 = "1"; std::string fibMinus2 = "0"; - for (uint64_t i = 0; i < n; i++) - { + for (uint64_t i = 0; i < n; i++) { tmp = add(fibMinus1, fibMinus2); fibMinus2 = fibMinus1; fibMinus1 = tmp; @@ -89,8 +78,7 @@ void fib_Accurate(uint64_t n) } /** main function */ -int main() -{ +int main() { int n; std::cout << "Enter whatever number N you want to find the fibonacci of\n"; std::cin >> n; diff --git a/operations_on_datastructures/array_left_rotation.cpp b/operations_on_datastructures/array_left_rotation.cpp index 444738360..7b8f7f279 100644 --- a/operations_on_datastructures/array_left_rotation.cpp +++ b/operations_on_datastructures/array_left_rotation.cpp @@ -1,7 +1,6 @@ #include using namespace std; -int main() -{ +int main() { int n, k; cout << "Enter size of array=\t"; cin >> n; @@ -9,29 +8,22 @@ int main() cin >> k; int a[n]; cout << "Enter elements of array=\t"; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { cin >> a[i]; } int temp = 0; - for (int i = 0; i < k; i++) - { + for (int i = 0; i < k; i++) { temp = a[0]; - for (int j = 0; j < n; j++) - { - if (j == n - 1) - { + for (int j = 0; j < n; j++) { + if (j == n - 1) { a[n - 1] = temp; - } - else - { + } else { a[j] = a[j + 1]; } } } cout << "Your rotated array is=\t"; - for (int j = 0; j < n; j++) - { + for (int j = 0; j < n; j++) { cout << a[j] << " "; } getchar(); diff --git a/operations_on_datastructures/array_right_rotation.cpp b/operations_on_datastructures/array_right_rotation.cpp index 5077d2d74..8b01a2003 100644 --- a/operations_on_datastructures/array_right_rotation.cpp +++ b/operations_on_datastructures/array_right_rotation.cpp @@ -1,7 +1,6 @@ #include using namespace std; -int main() -{ +int main() { int n, k; cout << "Enter size of array=\t"; cin >> n; @@ -11,24 +10,18 @@ int main() cout << "Enter elements of array=\t"; for (int i = 0; i < n; i++) cin >> a[i]; int temp = 0; - for (int i = 0; i < k; i++) - { + for (int i = 0; i < k; i++) { temp = a[n - 1]; - for (int j = n - 1; j >= 0; j--) - { - if (j == 0) - { + for (int j = n - 1; j >= 0; j--) { + if (j == 0) { a[j] = temp; - } - else - { + } else { a[j] = a[j - 1]; } } } cout << "Your rotated array is=\t"; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { cout << a[i] << " "; } } diff --git a/operations_on_datastructures/circular_linked_list.cpp b/operations_on_datastructures/circular_linked_list.cpp index 2fddd3b7b..1119bb5e7 100644 --- a/operations_on_datastructures/circular_linked_list.cpp +++ b/operations_on_datastructures/circular_linked_list.cpp @@ -1,31 +1,25 @@ #include using namespace std; -struct node -{ +struct node { int val; node *next; }; node *start; -void insert(int x) -{ +void insert(int x) { node *t = start; - if (start != NULL) - { - while (t->next != start) - { + if (start != NULL) { + while (t->next != start) { t = t->next; } node *n = new node; t->next = n; n->val = x; n->next = start; - } - else - { + } else { node *n = new node; n->val = x; start = n; @@ -33,12 +27,10 @@ void insert(int x) } } -void remove(int x) -{ +void remove(int x) { node *t = start; node *p; - while (t->val != x) - { + while (t->val != x) { p = t; t = t->next; } @@ -46,49 +38,40 @@ void remove(int x) delete t; } -void search(int x) -{ +void search(int x) { node *t = start; int found = 0; - while (t->next != start) - { - if (t->val == x) - { + while (t->next != start) { + if (t->val == x) { cout << "\nFound"; found = 1; break; } t = t->next; } - if (found == 0) - { + if (found == 0) { cout << "\nNot Found"; } } -void show() -{ +void show() { node *t = start; - do - { + do { cout << t->val << "\t"; t = t->next; } while (t != start); } -int main() -{ +int main() { int choice, x; - do - { + do { cout << "\n1. Insert"; cout << "\n2. Delete"; cout << "\n3. Search"; cout << "\n4. Print"; cout << "\n\nEnter you choice : "; cin >> choice; - switch (choice) - { + switch (choice) { case 1: cout << "\nEnter the element to be inserted : "; cin >> x; diff --git a/operations_on_datastructures/circular_queue_using_array.cpp b/operations_on_datastructures/circular_queue_using_array.cpp index cf6e39dd5..e0e049611 100644 --- a/operations_on_datastructures/circular_queue_using_array.cpp +++ b/operations_on_datastructures/circular_queue_using_array.cpp @@ -6,65 +6,49 @@ int front = 0; int rear = 0; int count = 0; -void Enque(int x) -{ - if (count == 10) - { +void Enque(int x) { + if (count == 10) { cout << "\nOverflow"; - } - else - { + } else { queue[rear] = x; rear = (rear + 1) % 10; count++; } } -void Deque() -{ - if (front == rear) - { +void Deque() { + if (front == rear) { cout << "\nUnderflow"; } - else - { + else { cout << "\n" << queue[front] << " deleted"; front = (front + 1) % 10; count--; } } -void show() -{ - for (int i = 0; i < count; i++) - { +void show() { + for (int i = 0; i < count; i++) { cout << queue[(i + front) % 10] << "\t"; } } -int main() -{ +int main() { int ch, x; - do - { + do { cout << "\n1. Enque"; cout << "\n2. Deque"; cout << "\n3. Print"; cout << "\nEnter Your Choice : "; cin >> ch; - if (ch == 1) - { + if (ch == 1) { cout << "\nInsert : "; cin >> x; Enque(x); - } - else if (ch == 2) - { + } else if (ch == 2) { Deque(); - } - else if (ch == 3) - { + } else if (ch == 3) { show(); } } while (ch != 0); diff --git a/operations_on_datastructures/get_size_of_linked_list.cpp b/operations_on_datastructures/get_size_of_linked_list.cpp index 0f22967c2..84f8db07f 100644 --- a/operations_on_datastructures/get_size_of_linked_list.cpp +++ b/operations_on_datastructures/get_size_of_linked_list.cpp @@ -1,7 +1,6 @@ #include -class Node -{ +class Node { public: int val; Node *next; @@ -9,23 +8,19 @@ class Node Node(int v, Node *n) : val(v), next(n) {} // Default constructor for Node }; -int getSize(Node *root) -{ - if (root == NULL) - { +int getSize(Node *root) { + if (root == NULL) { return 0; } // Each node will return 1 so the total adds up to be the size return 1 + getSize(root->next); } -int main() -{ +int main() { Node *myList = new Node(0, NULL); // Initializes the LinkedList Node *temp = myList; // Creates a linked lists of total size 10, numbered 1 - 10 - for (int i = 1; i < 10; i++) - { + for (int i = 1; i < 10; i++) { temp->next = new Node(i, NULL); temp = temp->next; } diff --git a/operations_on_datastructures/intersection_of_2_arrays.cpp b/operations_on_datastructures/intersection_of_2_arrays.cpp index df83c9f21..8a3b27edf 100644 --- a/operations_on_datastructures/intersection_of_2_arrays.cpp +++ b/operations_on_datastructures/intersection_of_2_arrays.cpp @@ -1,6 +1,5 @@ #include -int main() -{ +int main() { int i, j, m, n; cout << "Enter size of array 1:"; cin >> m; @@ -13,14 +12,12 @@ int main() for (i = 0; i < n; i++) cin >> b[i]; i = 0; j = 0; - while ((i < m) && (j < n)) - { + while ((i < m) && (j < n)) { if (a[i] < b[j]) i++; else if (a[i] > b[j]) j++; - else - { + else { cout << a[i++] << " "; j++; } diff --git a/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp b/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp index 4fe6d2915..b9540d951 100644 --- a/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp +++ b/operations_on_datastructures/reverse_a_linked_list_using_recusion.cpp @@ -1,30 +1,24 @@ #include using namespace std; -struct node -{ +struct node { int val; node *next; }; node *start; -void insert(int x) -{ +void insert(int x) { node *t = start; - if (start != NULL) - { - while (t->next != NULL) - { + if (start != NULL) { + while (t->next != NULL) { t = t->next; } node *n = new node; t->next = n; n->val = x; n->next = NULL; - } - else - { + } else { node *n = new node; n->val = x; n->next = NULL; @@ -32,35 +26,28 @@ void insert(int x) } } -void reverse(node *p, node *q) -{ - if (q->next == NULL) - { +void reverse(node *p, node *q) { + if (q->next == NULL) { q->next = p; p->next = NULL; start = q; return; - } - else - { + } else { reverse(q, q->next); q->next = p; p->next = NULL; } } -void show() -{ +void show() { node *t = start; - while (t != NULL) - { + while (t != NULL) { cout << t->val << "\t"; t = t->next; } } -int main() -{ +int main() { insert(1); insert(2); insert(3); diff --git a/operations_on_datastructures/selectionsortlinkedlist.cpp b/operations_on_datastructures/selectionsortlinkedlist.cpp index 550928d01..0e8e80def 100644 --- a/operations_on_datastructures/selectionsortlinkedlist.cpp +++ b/operations_on_datastructures/selectionsortlinkedlist.cpp @@ -2,24 +2,20 @@ using namespace std; // node defined -class node -{ +class node { public: int data; node *link; - node(int d) - { + node(int d) { data = d; link = NULL; } }; // printing the linked list -void print(node *head) -{ +void print(node *head) { node *current = head; - while (current != NULL) - { + while (current != NULL) { cout << current->data << " "; current = current->link; } @@ -27,18 +23,15 @@ void print(node *head) } // creating the linked list with 'n' nodes -node *createlist(int n) -{ +node *createlist(int n) { node *head = NULL; node *t = NULL; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { node *temp = NULL; int num; cin >> num; temp = new node(num); - if (head == NULL) - { + if (head == NULL) { head = temp; t = temp; continue; @@ -51,8 +44,7 @@ node *createlist(int n) } // performing selection sort on the linked list in an iterative manner -void my_selection_sort_linked_list(node *&head) -{ +void my_selection_sort_linked_list(node *&head) { node *min = head; // throughout the algorithm 'min' is used to denote the // node with min value out of all the nodes left for // scanning while scanning if we find a node 'X' with @@ -61,7 +53,7 @@ void my_selection_sort_linked_list(node *&head) node *current = min->link; // 'current' refers to the current node we are scanning node *previous = min; //'previous' refers to the node that is previous to - //the current node + // the current node node *temp = NULL; // 'temp' in this algo is used to point to the last node of the // sorted part of the linked list. @@ -102,8 +94,8 @@ void my_selection_sort_linked_list(node *&head) current->link = previous; min = current; current = previous->link; - } - else // if the 'previous' is not pointing to the 'min' node + } else // if the 'previous' is not pointing to the 'min' + // node { // Update the pointers head = current; // update the head pointer with the @@ -113,8 +105,8 @@ void my_selection_sort_linked_list(node *&head) min = current; current = previous->link; } - } - else // if 'temp' is not NULL, i.e., its not the 1st iteration + } else // if 'temp' is not NULL, i.e., its not the 1st + // iteration { temp->link = current; previous->link = current->link; @@ -122,9 +114,8 @@ void my_selection_sort_linked_list(node *&head) min = current; current = previous->link; } - } - else // if the current node is greater than min, just move the - // previous and the current pointer a step further + } else // if the current node is greater than min, just move the + // previous and the current pointer a step further { previous = previous->link; current = current->link; @@ -132,8 +123,8 @@ void my_selection_sort_linked_list(node *&head) } // update the pointers. Set 'temp' to the last node in the sorted part. - // Make 'min' move a step further so that 'min' points to the 1st node of - // the unsorted part start the iteration again + // Make 'min' move a step further so that 'min' points to the 1st node + // of the unsorted part start the iteration again temp = min; min = min->link; previous = min; @@ -163,8 +154,7 @@ void my_selection_sort_linked_list(node *&head) // original list is : 5 3 4 1 -2 -4 // sorted list is : -4 -2 1 3 4 5 -int main() -{ +int main() { node *head = NULL; int n; cout << "enter the no. of nodes : "; // taking input from user about the diff --git a/operations_on_datastructures/union_of_2_arrays.cpp b/operations_on_datastructures/union_of_2_arrays.cpp index 45845f341..cdacf1d2e 100644 --- a/operations_on_datastructures/union_of_2_arrays.cpp +++ b/operations_on_datastructures/union_of_2_arrays.cpp @@ -1,6 +1,5 @@ #include -int main() -{ +int main() { int m, n, i = 0, j = 0; cout << "Enter size of both arrays:"; cin >> m >> n; @@ -12,14 +11,12 @@ int main() for (i = 0; i < n; i++) cin >> b[i]; i = 0; j = 0; - while ((i < m) && (j < n)) - { + while ((i < m) && (j < n)) { if (a[i] < b[j]) cout << a[i++] << " "; else if (a[i] > b[j]) cout << b[j++] << " "; - else - { + else { cout << a[i++]; j++; } diff --git a/others/buzz_number.cpp b/others/buzz_number.cpp index 712b79401..ed9fc5f28 100644 --- a/others/buzz_number.cpp +++ b/others/buzz_number.cpp @@ -6,12 +6,10 @@ #include /** main function */ -int main() -{ +int main() { int n, t; std::cin >> t; - while (t--) - { + while (t--) { std::cin >> n; if ((n % 7 == 0) || (n % 10 == 7)) std::cout << n << " is a buzz number" << std::endl; diff --git a/others/decimal_to_binary.cpp b/others/decimal_to_binary.cpp index 32616944f..11ce064a5 100644 --- a/others/decimal_to_binary.cpp +++ b/others/decimal_to_binary.cpp @@ -8,12 +8,10 @@ * This method converts the bit representation and stores it as a decimal * number. */ -void method1(int number) -{ +void method1(int number) { int remainder, binary = 0, var = 1; - do - { + do { remainder = number % 2; number = number / 2; binary = binary + (remainder * var); @@ -26,13 +24,11 @@ void method1(int number) * This method stores each bit value from LSB to MSB and then prints them back * from MSB to LSB */ -void method2(int number) -{ +void method2(int number) { int num_bits = 0; char bit_string[50]; - do - { + do { bool bit = number & 0x01; // get last bit if (bit) bit_string[num_bits++] = '1'; @@ -47,8 +43,7 @@ void method2(int number) std::cout << std::endl; } -int main() -{ +int main() { int number; std::cout << "Enter a number:"; std::cin >> number; diff --git a/others/decimal_to_hexadecimal.cpp b/others/decimal_to_hexadecimal.cpp index f0a521db6..a3e544f49 100644 --- a/others/decimal_to_hexadecimal.cpp +++ b/others/decimal_to_hexadecimal.cpp @@ -8,8 +8,7 @@ /** * Main program */ -int main(void) -{ +int main(void) { int valueToConvert = 0; // Holds user input int hexArray[8]; // Contains hex values backwards int i = 0; // counter @@ -20,8 +19,7 @@ int main(void) std::cin >> valueToConvert; // Stores value into valueToConvert via user input - while (valueToConvert > 15) - { // Dec to Hex Algorithm + while (valueToConvert > 15) { // Dec to Hex Algorithm hexArray[i++] = valueToConvert % 16; // Gets remainder valueToConvert /= 16; // valueToConvert >>= 4; // This will divide by 2^4=16 and is faster diff --git a/others/decimal_to_roman_numeral.cpp b/others/decimal_to_roman_numeral.cpp index fbcbaa232..ad4aa32c5 100644 --- a/others/decimal_to_roman_numeral.cpp +++ b/others/decimal_to_roman_numeral.cpp @@ -12,8 +12,7 @@ /** This functions fills a string with character c, n times and returns it * @note This can probably be replace by `memcpy` function. */ -std::string fill(char c, int n) -{ +std::string fill(char c, int n) { std::string s = ""; while (n--) s += c; return s; @@ -22,8 +21,7 @@ std::string fill(char c, int n) /** to convert to lowercase Roman Numeral * the function works recursively */ -std::string tolowerRoman(int n) -{ +std::string tolowerRoman(int n) { if (n < 4) return fill('i', n); if (n < 6) @@ -57,8 +55,7 @@ std::string tolowerRoman(int n) /** to convert to uppercase Roman Numeral * the function works recursively */ -std::string toupperRoman(int n) -{ +std::string toupperRoman(int n) { if (n < 4) return fill('I', n); if (n < 6) @@ -90,8 +87,7 @@ std::string toupperRoman(int n) } /** main function */ -int main() -{ +int main() { int n; std::cout << "\t\tRoman numbers converter\n\n"; std::cout << "Type in decimal number between 0 up to 4000 (exclusive): "; diff --git a/others/fast_interger_input.cpp b/others/fast_interger_input.cpp index a71e807dd..87963c9ad 100644 --- a/others/fast_interger_input.cpp +++ b/others/fast_interger_input.cpp @@ -8,8 +8,7 @@ /** Function to read the number from stdin. The function reads input until a non * numeric character is entered. */ -void fastinput(int *number) -{ +void fastinput(int *number) { // variable to indicate sign of input integer bool negative = false; register int c; @@ -17,8 +16,7 @@ void fastinput(int *number) // extract current character from buffer c = std::getchar(); - if (c == '-') - { + if (c == '-') { // number is negative negative = true; @@ -38,8 +36,7 @@ void fastinput(int *number) } /** Main function */ -int main() -{ +int main() { int number; fastinput(&number); std::cout << number << std::endl; diff --git a/others/happy_number.cpp b/others/happy_number.cpp index 494891e3b..b1debaa54 100644 --- a/others/happy_number.cpp +++ b/others/happy_number.cpp @@ -11,13 +11,10 @@ * \returns true if happy else false */ template -bool is_happy(T n) -{ - T s = 0; // stores sum of digits - while (n > 9) - { // while number is > 9, there are more than 1 digit - while (n != 0) - { // get digit +bool is_happy(T n) { + T s = 0; // stores sum of digits + while (n > 9) { // while number is > 9, there are more than 1 digit + while (n != 0) { // get digit T d = n % 10; s += d; n /= 10; @@ -29,8 +26,7 @@ bool is_happy(T n) } /** Main function */ -int main() -{ +int main() { int n; std::cout << "Enter a number:"; std::cin >> n; diff --git a/others/matrix_exponentiation.cpp b/others/matrix_exponentiation.cpp index 78daca8ec..d44d22593 100644 --- a/others/matrix_exponentiation.cpp +++ b/others/matrix_exponentiation.cpp @@ -58,15 +58,11 @@ vector a, b, c; * \result matrix of dimension (m\f$\times\f$q) */ vector> multiply(const vector> &A, - const vector> &B) -{ + const vector> &B) { vector> C(k + 1, vector(k + 1)); - for (ll i = 1; i <= k; i++) - { - for (ll j = 1; j <= k; j++) - { - for (ll z = 1; z <= k; z++) - { + for (ll i = 1; i <= k; i++) { + for (ll j = 1; j <= k; j++) { + for (ll z = 1; z <= k; z++) { C[i][j] = (C[i][j] + (A[i][z] * B[z][j]) % MOD) % MOD; } } @@ -80,16 +76,12 @@ vector> multiply(const vector> &A, * \param [in] p exponent * \return matrix of same dimension as A */ -vector> power(const vector> &A, ll p) -{ +vector> power(const vector> &A, ll p) { if (p == 1) return A; - if (p % 2 == 1) - { + if (p % 2 == 1) { return multiply(A, power(A, p - 1)); - } - else - { + } else { vector> X = power(A, p / 2); return multiply(X, X); } @@ -99,8 +91,7 @@ vector> power(const vector> &A, ll p) * \param[in] n \f$n^\text{th}\f$ Fibonacci number * \return \f$n^\text{th}\f$ Fibonacci number */ -ll ans(ll n) -{ +ll ans(ll n) { if (n == 0) return 0; if (n <= k) @@ -111,12 +102,9 @@ ll ans(ll n) // Transpose matrix vector> T(k + 1, vector(k + 1)); - for (ll i = 1; i <= k; i++) - { - for (ll j = 1; j <= k; j++) - { - if (i < k) - { + for (ll i = 1; i <= k; i++) { + for (ll j = 1; j <= k; j++) { + if (i < k) { if (j == i + 1) T[i][j] = 1; else @@ -131,31 +119,26 @@ ll ans(ll n) // T*F1 ll res = 0; - for (ll i = 1; i <= k; i++) - { + for (ll i = 1; i <= k; i++) { res = (res + (T[1][i] * F1[i]) % MOD) % MOD; } return res; } /** Main function */ -int main() -{ +int main() { cin.tie(0); cout.tie(0); ll t; cin >> t; ll i, j, x; - while (t--) - { + while (t--) { cin >> k; - for (i = 0; i < k; i++) - { + for (i = 0; i < k; i++) { cin >> x; b.pb(x); } - for (i = 0; i < k; i++) - { + for (i = 0; i < k; i++) { cin >> x; c.pb(x); } diff --git a/others/palindrome_of_number.cpp b/others/palindrome_of_number.cpp index d6ed3fc70..66401ff96 100644 --- a/others/palindrome_of_number.cpp +++ b/others/palindrome_of_number.cpp @@ -16,8 +16,7 @@ #endif /** Main function */ -int main() -{ +int main() { int num; std::cout << "Enter number = "; std::cin >> num; diff --git a/others/paranthesis_matching.cpp b/others/paranthesis_matching.cpp index 95a9e1100..2a6358d94 100644 --- a/others/paranthesis_matching.cpp +++ b/others/paranthesis_matching.cpp @@ -33,10 +33,8 @@ char pop() { return stack[top--]; } /** return opening paranthesis corresponding to the close paranthesis * @param[in] ch closed paranthesis character */ -char opening(char ch) -{ - switch (ch) - { +char opening(char ch) { + switch (ch) { case '}': return '{'; case ']': @@ -49,37 +47,27 @@ char opening(char ch) return '\0'; } -int main() -{ +int main() { std::string exp; int valid = 1, i = 0; std::cout << "Enter The Expression : "; std::cin >> exp; - while (valid == 1 && i < exp.length()) - { - if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<') - { + while (valid == 1 && i < exp.length()) { + if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<') { push(exp[i]); - } - else if (top >= 0 && stack[top] == opening(exp[i])) - { + } else if (top >= 0 && stack[top] == opening(exp[i])) { pop(); - } - else - { + } else { valid = 0; } i++; } // makes sure the stack is empty after processsing (above) - if (valid == 1 && top == -1) - { + if (valid == 1 && top == -1) { std::cout << "\nCorrect Expression"; - } - else - { + } else { std::cout << "\nWrong Expression"; } diff --git a/others/pascal_triangle.cpp b/others/pascal_triangle.cpp index 814b9a142..4ea58f3f1 100644 --- a/others/pascal_triangle.cpp +++ b/others/pascal_triangle.cpp @@ -15,12 +15,9 @@ * \param [in] arr 2D-array containing Pascal numbers * \param [in] n depth of Pascal triangle to print */ -void show_pascal(int **arr, int n) -{ - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < n + i; ++j) - { +void show_pascal(int **arr, int n) { + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n + i; ++j) { if (arr[i][j] == 0) std::cout << std::setw(4) << " "; else @@ -36,12 +33,9 @@ void show_pascal(int **arr, int n) * \param [in] n depth of Pascal triangle to print * \result arr pointer returned */ -int **pascal_triangle(int **arr, int n) -{ - for (int i = 0; i < n; ++i) - { - for (int j = n - i - 1; j < n + i; ++j) - { +int **pascal_triangle(int **arr, int n) { + for (int i = 0; i < n; ++i) { + for (int j = n - i - 1; j < n + i; ++j) { if (j == n - i - 1 || j == n + i - 1) arr[i][j] = 1; // The edge of the Pascal triangle goes in 1 else @@ -55,8 +49,7 @@ int **pascal_triangle(int **arr, int n) /** * main function */ -int main() -{ +int main() { int n = 0; std::cout << "Set Pascal's Triangle Height" << std::endl; @@ -64,8 +57,7 @@ int main() // memory allocation (Assign two-dimensional array to store Pascal triangle) int **arr = new int *[n]; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { arr[i] = new int[2 * n - 1]; memset(arr[i], 0, sizeof(int) * (2 * n - 1)); } @@ -74,8 +66,7 @@ int main() show_pascal(arr, n); // deallocation - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { delete[] arr[i]; } delete[] arr; diff --git a/others/primality_test.cpp b/others/primality_test.cpp index 16700ec4a..faec6589c 100644 --- a/others/primality_test.cpp +++ b/others/primality_test.cpp @@ -15,14 +15,12 @@ * \param[in] number number to check * \returns true if prime else false */ -bool IsPrime(int number) -{ +bool IsPrime(int number) { if (((!(number & 1)) && number != 2) || (number < 2) || (number % 3 == 0 && number != 3)) return false; - for (int k = 1; 36 * k * k - 12 * k < number; ++k) - { + for (int k = 1; 36 * k * k - 12 * k < number; ++k) { if ((number % (6 * k + 1) == 0) || (number % (6 * k - 1) == 0)) return false; } @@ -30,8 +28,7 @@ bool IsPrime(int number) } /** main function */ -int main() -{ +int main() { // Main Function std::cout << "Enter the value of n to check if Prime\n"; int n; diff --git a/others/smallest_circle.cpp b/others/smallest_circle.cpp index 5842a33c8..9ee4353eb 100644 --- a/others/smallest_circle.cpp +++ b/others/smallest_circle.cpp @@ -12,8 +12,7 @@ #include /** Define a point */ -struct Point -{ +struct Point { double x, /**< abscissa */ y; /**< ordinate */ @@ -21,8 +20,7 @@ struct Point * \param [in] a absicca (default = 0.0) * \param [in] b ordinate (default = 0.0) */ - explicit Point(double a = 0.f, double b = 0.f) - { + explicit Point(double a = 0.f, double b = 0.f) { x = a; y = b; } @@ -36,8 +34,7 @@ struct Point * \param [in] B point B * \return ditance */ -double LenghtLine(const Point &A, const Point &B) -{ +double LenghtLine(const Point &A, const Point &B) { double dx = B.x - A.x; double dy = B.y - A.y; return std::sqrt((dx * dx) + (dy * dy)); @@ -54,8 +51,7 @@ double LenghtLine(const Point &A, const Point &B) * \param [in] C vertex C * \returns area of triangle */ -double TriangleArea(const Point &A, const Point &B, const Point &C) -{ +double TriangleArea(const Point &A, const Point &B, const Point &C) { double a = LenghtLine(A, B); double b = LenghtLine(B, C); double c = LenghtLine(C, A); @@ -73,10 +69,8 @@ double TriangleArea(const Point &A, const Point &B, const Point &C) * \returns True if P lies on or within the circle * \returns False if P lies outside the circle */ -bool PointInCircle(const std::vector &P, const Point &Center, double R) -{ - for (size_t i = 0; i < P.size(); i++) - { +bool PointInCircle(const std::vector &P, const Point &Center, double R) { + for (size_t i = 0; i < P.size(); i++) { if (LenghtLine(P[i], Center) > R) return false; } @@ -90,8 +84,7 @@ bool PointInCircle(const std::vector &P, const Point &Center, double R) * \param [in] P vector of points * \returns radius of the circle */ -double circle(const std::vector &P) -{ +double circle(const std::vector &P) { double minR = INFINITY; double R; Point C; @@ -103,8 +96,7 @@ double circle(const std::vector &P) // for every subsequent point in the list for (size_t j = i + 1; j < P.size(); j++) // for every subsequent point in the list - for (size_t k = j + 1; k < P.size(); k++) - { + for (size_t k = j + 1; k < P.size(); k++) { // here, we now have picked three points from the given set of // points that we can use // viz., P[i], P[j] and P[k] @@ -129,12 +121,10 @@ double circle(const std::vector &P) R = (LenghtLine(P[i], P[j]) * LenghtLine(P[j], P[k]) * LenghtLine(P[k], P[i])) / (4 * TriangleArea(P[i], P[j], P[k])); - if (!PointInCircle(P, C, R)) - { + if (!PointInCircle(P, C, R)) { continue; } - if (R <= minR) - { + if (R <= minR) { minR = R; minC = C; } @@ -143,18 +133,15 @@ double circle(const std::vector &P) // for each point in the list for (size_t i = 0; i < P.size() - 1; i++) // for every subsequent point in the list - for (size_t j = i + 1; j < P.size(); j++) - { + for (size_t j = i + 1; j < P.size(); j++) { // check for diameterically opposite points C.x = (P[i].x + P[j].x) / 2; C.y = (P[i].y + P[j].y) / 2; R = LenghtLine(C, P[i]); - if (!PointInCircle(P, C, R)) - { + if (!PointInCircle(P, C, R)) { continue; } - if (R <= minR) - { + if (R <= minR) { minR = R; minC = C; } @@ -168,8 +155,7 @@ double circle(const std::vector &P) * \n radius 3.318493136080724 * \n centre at (3.0454545454545454, 1.3181818181818181) */ -void test() -{ +void test() { std::vector Pv; Pv.push_back(Point(0, 0)); Pv.push_back(Point(5, 4)); @@ -184,8 +170,7 @@ void test() * \n radius 1.4142135623730951 * \n centre at (1.0, 1.0) */ -void test2() -{ +void test2() { std::vector Pv; Pv.push_back(Point(0, 0)); Pv.push_back(Point(0, 2)); @@ -200,8 +185,7 @@ void test2() * \n centre at (2.142857142857143, 1.7857142857142856) * @todo This test fails */ -void test3() -{ +void test3() { std::vector Pv; Pv.push_back(Point(0.5, 1)); Pv.push_back(Point(3.5, 3)); @@ -211,8 +195,7 @@ void test3() } /** Main program */ -int main() -{ +int main() { test(); std::cout << std::endl; test2(); diff --git a/others/sparse_matrix.cpp b/others/sparse_matrix.cpp index 5662e065d..a358f0da4 100644 --- a/others/sparse_matrix.cpp +++ b/others/sparse_matrix.cpp @@ -6,8 +6,7 @@ #include /** main function */ -int main() -{ +int main() { int m, n; int counterZeros = 0; @@ -22,20 +21,16 @@ int main() std::cout << "\n"; // reads the matrix from stdin - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { std::cout << "element? "; std::cin >> a[i][j]; } } // counts the zero's - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; j++) - { + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { if (a[i][j] == 0) counterZeros++; // Counting number of zeroes } diff --git a/others/spiral_print.cpp b/others/spiral_print.cpp index da92e6937..02dc3183a 100644 --- a/others/spiral_print.cpp +++ b/others/spiral_print.cpp @@ -9,13 +9,10 @@ * \param [in] r number of rows * \param [in] c number of columns */ -void genArray(int **a, int r, int c) -{ +void genArray(int **a, int r, int c) { int value = 1; - for (int i = 0; i < r; i++) - { - for (int j = 0; j < c; j++) - { + for (int i = 0; i < r; i++) { + for (int j = 0; j < c; j++) { a[i][j] = value; std::cout << a[i][j] << " "; value++; @@ -29,47 +26,39 @@ void genArray(int **a, int r, int c) * \param [in] r number of rows * \param [in] c number of columns */ -void spiralPrint(int **a, int r, int c) -{ +void spiralPrint(int **a, int r, int c) { int startRow = 0, endRow = r - 1; int startCol = 0, endCol = c - 1; int cnt = 0; - while (startRow <= endRow && startCol <= endCol) - { + while (startRow <= endRow && startCol <= endCol) { /// Print start row - for (int i = startCol; i <= endCol; i++, cnt++) - { + for (int i = startCol; i <= endCol; i++, cnt++) { std::cout << a[startRow][i] << " "; } startRow++; /// Print the end col - for (int i = startRow; i <= endRow; i++, cnt++) - { + for (int i = startRow; i <= endRow; i++, cnt++) { std::cout << a[i][endCol] << " "; } endCol--; /// Print the end row - if (cnt == r * c) - { + if (cnt == r * c) { break; } - for (int i = endCol; i >= startCol; i--, cnt++) - { + for (int i = endCol; i >= startCol; i--, cnt++) { std::cout << a[endRow][i] << " "; } endRow--; /// Print the start Col - if (cnt == r * c) - { + if (cnt == r * c) { break; } - for (int i = endRow; i >= startRow; i--, cnt++) - { + for (int i = endRow; i >= startRow; i--, cnt++) { std::cout << a[i][startCol] << " "; } startCol++; @@ -77,8 +66,7 @@ void spiralPrint(int **a, int r, int c) } /** main function */ -int main() -{ +int main() { int r, c; std::cin >> r >> c; int **a = new int *[r]; diff --git a/others/stairs_pattern.cpp b/others/stairs_pattern.cpp index bfd90dd10..a3b8b0a44 100644 --- a/others/stairs_pattern.cpp +++ b/others/stairs_pattern.cpp @@ -14,23 +14,18 @@ where number of pairs line is given by user #include /** main function */ -int main() -{ +int main() { int l, st = 2, x, r, z, n, sp; std::cout << "enter Index "; std::cin >> x; z = x; - for (r = 1; r <= x; r++) - { + for (r = 1; r <= x; r++) { z = z - 1; - for (n = 1; n <= 2; n++) - { - for (sp = 1; sp <= z; sp++) - { + for (n = 1; n <= 2; n++) { + for (sp = 1; sp <= z; sp++) { std::cout << " "; } - for (l = 1; l <= st; l++) - { + for (l = 1; l <= st; l++) { std::cout << "*"; } std::cout << std::endl; diff --git a/others/tower_of_hanoi.cpp b/others/tower_of_hanoi.cpp index 3a832248f..323b2e424 100644 --- a/others/tower_of_hanoi.cpp +++ b/others/tower_of_hanoi.cpp @@ -8,8 +8,7 @@ /** * Define the state of tower */ -struct tower -{ +struct tower { //! Values in the tower int values[10]; //! top tower ID @@ -18,21 +17,17 @@ struct tower /** Display the towers */ void show(const struct tower *const F, const struct tower *const T, - const struct tower *const U) -{ + const struct tower *const U) { std::cout << "\n\n\tF : "; - for (int i = 0; i < F->top; i++) - { + for (int i = 0; i < F->top; i++) { std::cout << F->values[i] << "\t"; } std::cout << "\n\tU : "; - for (int i = 0; i < U->top; i++) - { + for (int i = 0; i < U->top; i++) { std::cout << U->values[i] << "\t"; } std::cout << "\n\tT : "; - for (int i = 0; i < T->top; i++) - { + for (int i = 0; i < T->top; i++) { std::cout << T->values[i] << "\t"; } } @@ -41,8 +36,7 @@ void show(const struct tower *const F, const struct tower *const T, * \param [in,out] From tower to move disk *from* * \param [in,out] To tower to move disk *to* */ -void mov(tower *From, tower *To) -{ +void mov(tower *From, tower *To) { --From->top; To->values[To->top] = From->values[From->top]; ++To->top; @@ -55,15 +49,11 @@ void mov(tower *From, tower *To) * \param [in,out] Using temporary tower for the puzzle * \param [in,out] To tower to move disk to */ -void TH(int n, tower *From, tower *Using, tower *To) -{ - if (n == 1) - { +void TH(int n, tower *From, tower *Using, tower *To) { + if (n == 1) { mov(From, To); show(From, To, Using); - } - else - { + } else { TH(n - 1, From, To, Using); mov(From, To); show(From, To, Using); @@ -72,8 +62,7 @@ void TH(int n, tower *From, tower *Using, tower *To) } /** Main function */ -int main() -{ +int main() { struct tower F, U, T; F.top = 0; @@ -85,8 +74,7 @@ int main() std::cout << "\nEnter number of discs : "; std::cin >> no; - for (int i = no; i > 0; i--) - { + for (int i = no; i > 0; i--) { F.values[F.top++] = i; } diff --git a/others/vector_important_functions.cpp b/others/vector_important_functions.cpp index 765f6a8e5..d23ff9c97 100644 --- a/others/vector_important_functions.cpp +++ b/others/vector_important_functions.cpp @@ -8,8 +8,7 @@ #include /** Main function */ -int main() -{ +int main() { // Initializing vector with array values int arr[] = {10, 20, 5, 23, 42, 15}; int n = sizeof(arr) / sizeof(arr[0]); diff --git a/probability/addition_rule.cpp b/probability/addition_rule.cpp index 0666b29e6..780951489 100644 --- a/probability/addition_rule.cpp +++ b/probability/addition_rule.cpp @@ -11,8 +11,7 @@ * \parama [in] B probability of event B * \returns probability of A and B */ -double addition_rule_independent(double A, double B) -{ +double addition_rule_independent(double A, double B) { return (A + B) - (A * B); } @@ -23,14 +22,12 @@ double addition_rule_independent(double A, double B) * \parama [in] B_given_A probability of event B condition A * \returns probability of A and B */ -double addition_rule_dependent(double A, double B, double B_given_A) -{ +double addition_rule_dependent(double A, double B, double B_given_A) { return (A + B) - (A * B_given_A); } /** Main function */ -int main() -{ +int main() { double A = 0.5; double B = 0.25; double B_given_A = 0.05; diff --git a/probability/bayes_theorem.cpp b/probability/bayes_theorem.cpp index 632611fe5..aaa557a94 100644 --- a/probability/bayes_theorem.cpp +++ b/probability/bayes_theorem.cpp @@ -11,22 +11,19 @@ /** returns P(A|B) */ -double bayes_AgivenB(double BgivenA, double A, double B) -{ +double bayes_AgivenB(double BgivenA, double A, double B) { return (BgivenA * A) / B; } /** returns P(B|A) */ -double bayes_BgivenA(double AgivenB, double A, double B) -{ +double bayes_BgivenA(double AgivenB, double A, double B) { return (AgivenB * B) / A; } /** Main function */ -int main() -{ +int main() { double A = 0.01; double B = 0.1; double BgivenA = 0.9; diff --git a/probability/binomial_dist.cpp b/probability/binomial_dist.cpp index 4d2e90842..1f30c5048 100644 --- a/probability/binomial_dist.cpp +++ b/probability/binomial_dist.cpp @@ -33,8 +33,7 @@ double binomial_variance(double n, double p) { return n * p * (1 - p); } * \param [in] p * \returns \f$\sigma = \sqrt{\sigma^2} = \sqrt{n\cdot p\cdot (1-p)}\f$ */ -double binomial_standard_deviation(double n, double p) -{ +double binomial_standard_deviation(double n, double p) { return std::sqrt(binomial_variance(n, p)); } @@ -45,18 +44,15 @@ double binomial_standard_deviation(double n, double p) * \frac{n!}{r!(n-r)!} = \frac{n\times(n-1)\times(n-2)\times\cdots(n-r)}{r!} * \f$ */ -double nCr(double n, double r) -{ +double nCr(double n, double r) { double numerator = n; double denominator = r; - for (int i = n - 1; i >= ((n - r) + 1); i--) - { + for (int i = n - 1; i >= ((n - r) + 1); i--) { numerator *= i; } - for (int i = 1; i < r; i++) - { + for (int i = 1; i < r; i++) { denominator *= i; } @@ -66,8 +62,7 @@ double nCr(double n, double r) /** calculates the probability of exactly x successes * \returns \f$\displaystyle P(n,p,x) = {n\choose x} p^x (1-p)^{n-x}\f$ */ -double binomial_x_successes(double n, double p, double x) -{ +double binomial_x_successes(double n, double p, double x) { return nCr(n, x) * std::pow(p, x) * std::pow(1 - p, n - x); } @@ -77,19 +72,16 @@ double binomial_x_successes(double n, double p, double x) * =\sum_{i=x_0}^{x_1} {n\choose i} p^i (1-p)^{n-i}\f$ */ double binomial_range_successes(double n, double p, double lower_bound, - double upper_bound) -{ + double upper_bound) { double probability = 0; - for (int i = lower_bound; i <= upper_bound; i++) - { + for (int i = lower_bound; i <= upper_bound; i++) { probability += nCr(n, i) * std::pow(p, i) * std::pow(1 - p, n - i); } return probability; } /** main function */ -int main() -{ +int main() { std::cout << "expected value : " << binomial_expected(100, 0.5) << std::endl; diff --git a/probability/poisson_dist.cpp b/probability/poisson_dist.cpp index 428ee903f..6a2a377c3 100644 --- a/probability/poisson_dist.cpp +++ b/probability/poisson_dist.cpp @@ -14,8 +14,7 @@ * calculate the events per unit time\n * e.g 5 dollars every 2 mins = 5 / 2 = 2.5 */ -double poisson_rate(double events, double timeframe) -{ +double poisson_rate(double events, double timeframe) { return events / timeframe; } @@ -28,16 +27,13 @@ double poisson_expected(double rate, double time) { return rate * time; } /** * Compute factorial of a given number */ -double fact(double x) -{ +double fact(double x) { double x_fact = x; - for (int i = x - 1; i > 0; i--) - { + for (int i = x - 1; i > 0; i--) { x_fact *= i; } - if (x_fact <= 0) - { + if (x_fact <= 0) { x_fact = 1; } return x_fact; @@ -47,8 +43,7 @@ double fact(double x) * Find the probability of x successes in a Poisson dist. * \f[p(\mu,x) = \frac{\mu^x e^{-\mu}}{x!}\f] */ -double poisson_x_successes(double expected, double x) -{ +double poisson_x_successes(double expected, double x) { return (std::pow(expected, x) * std::exp(-expected)) / fact(x); } @@ -56,11 +51,9 @@ double poisson_x_successes(double expected, double x) * probability of a success in range for Poisson dist (inclusive, inclusive) * \f[P = \sum_i p(\mu,i)\f] */ -double poisson_range_successes(double expected, double lower, double upper) -{ +double poisson_range_successes(double expected, double lower, double upper) { double probability = 0; - for (int i = lower; i <= upper; i++) - { + for (int i = lower; i <= upper; i++) { probability += poisson_x_successes(expected, i); } return probability; @@ -69,8 +62,7 @@ double poisson_range_successes(double expected, double lower, double upper) /** * main function */ -int main() -{ +int main() { double rate, expected; rate = poisson_rate(3, 1); std::cout << "Poisson rate : " << rate << std::endl; diff --git a/range_queries/bit.cpp b/range_queries/bit.cpp index 19141b7f5..a1878705b 100644 --- a/range_queries/bit.cpp +++ b/range_queries/bit.cpp @@ -3,46 +3,38 @@ using namespace std; -class Bit -{ +class Bit { int n; vector bit; inline int offset(int x) { return (x & (-x)); } public: - Bit(vector& arr) - { + Bit(vector& arr) { n = arr.size(); bit.assign(n + 1, 0); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { update(i, arr[i]); } } - Bit(int x) - { + Bit(int x) { n = x; bit.assign(n + 1, 0); } - void update(int id, int val) - { + void update(int id, int val) { // Add val at id id++; - while (id <= n) - { + while (id <= n) { bit[id] += val; id += offset(id); } } - int sum(int id) - { + int sum(int id) { // Get prefix sum upto id. id++; int res = 0; - while (id > 0) - { + while (id > 0) { res += bit[id]; id -= offset(id); } @@ -52,8 +44,7 @@ class Bit int sum_range(int l, int r) { return sum(r) - sum(l - 1); } }; -int main() -{ +int main() { int n = 5; vector arr = {1, 2, 3, 4, 5}; Bit x(arr); diff --git a/range_queries/fenwicktree.cpp b/range_queries/fenwicktree.cpp index d78cb0d48..fb7cbaac4 100644 --- a/range_queries/fenwicktree.cpp +++ b/range_queries/fenwicktree.cpp @@ -12,19 +12,15 @@ const int maxn = 1e5 + 7; int tree[maxn] = {0}, range; // segement of [1...range], notice it must be less than `maxn` -void update(int x, int c) -{ - while (x <= range) - { +void update(int x, int c) { + while (x <= range) { tree[x] += c; x += lowbit(x); } } -int query(int x) -{ +int query(int x) { int ans = 0; - while (x) - { + while (x) { ans += tree[x]; x -= lowbit(x); } @@ -32,29 +28,23 @@ int query(int x) } int query_segement(int l, int r) { return query(r) - query(l - 1); } -int main() -{ +int main() { cin >> range; - for (int i = 1; i <= range; i++) - { + for (int i = 1; i <= range; i++) { int num; cin >> num; update(i, num); } int q; cin >> q; - while (q--) - { + while (q--) { int op; cin >> op; - if (op == 0) - { + if (op == 0) { int l, r; cin >> l >> r; cout << query_segement(l, r) << endl; - } - else - { + } else { int x, c; cin >> x >> c; update(x, c); diff --git a/range_queries/mo.cpp b/range_queries/mo.cpp index 4cdcdf30d..d281ef077 100644 --- a/range_queries/mo.cpp +++ b/range_queries/mo.cpp @@ -3,41 +3,35 @@ using namespace std; const int N = 1e6 + 5; int a[N], bucket[N], cnt[N]; int bucket_size; -struct query -{ +struct query { int l, r, i; } q[N]; int ans = 0; -void add(int index) -{ +void add(int index) { cnt[a[index]]++; if (cnt[a[index]] == 1) ans++; } -void remove(int index) -{ +void remove(int index) { cnt[a[index]]--; if (cnt[a[index]] == 0) ans--; } -bool mycmp(query x, query y) -{ +bool mycmp(query x, query y) { if (x.l / bucket_size != y.l / bucket_size) return x.l / bucket_size < y.l / bucket_size; return x.r < y.r; } -int main() -{ +int main() { int n, t, i, j, k = 0; scanf("%d", &n); for (i = 0; i < n; i++) scanf("%d", &a[i]); bucket_size = ceil(sqrt(n)); scanf("%d", &t); - for (i = 0; i < t; i++) - { + for (i = 0; i < t; i++) { scanf("%d %d", &q[i].l, &q[i].r); q[i].l--; q[i].r--; @@ -45,26 +39,21 @@ int main() } sort(q, q + t, mycmp); int left = 0, right = 0; - for (i = 0; i < t; i++) - { + for (i = 0; i < t; i++) { int L = q[i].l, R = q[i].r; - while (left < L) - { + while (left < L) { remove(left); left++; } - while (left > L) - { + while (left > L) { add(left - 1); left--; } - while (right <= R) - { + while (right <= R) { add(right); right++; } - while (right > R + 1) - { + while (right > R + 1) { remove(right - 1); right--; } diff --git a/range_queries/segtree.cpp b/range_queries/segtree.cpp index fb2bbab13..602b3fd95 100644 --- a/range_queries/segtree.cpp +++ b/range_queries/segtree.cpp @@ -3,10 +3,8 @@ #define MAX 4000000 using namespace std; typedef long long ll; -void ConsTree(ll arr[], ll segtree[], ll low, ll high, ll pos) -{ - if (low == high) - { +void ConsTree(ll arr[], ll segtree[], ll low, ll high, ll pos) { + if (low == high) { segtree[pos] = arr[low]; return; } @@ -15,17 +13,14 @@ void ConsTree(ll arr[], ll segtree[], ll low, ll high, ll pos) ConsTree(arr, segtree, mid + 1, high, 2 * pos + 2); segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; } -ll query(ll segtree[], ll lazy[], ll qlow, ll qhigh, ll low, ll high, ll pos) -{ +ll query(ll segtree[], ll lazy[], ll qlow, ll qhigh, ll low, ll high, ll pos) { if (low > high) return 0; if (qlow > high || qhigh < low) return 0; - if (lazy[pos] != 0) - { + if (lazy[pos] != 0) { segtree[pos] += lazy[pos] * (high - low + 1); - if (low != high) - { + if (low != high) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } @@ -38,15 +33,12 @@ ll query(ll segtree[], ll lazy[], ll qlow, ll qhigh, ll low, ll high, ll pos) query(segtree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2); } void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, - ll high, ll pos) -{ + ll high, ll pos) { if (low > high) return; - if (lazy[pos] != 0) - { + if (lazy[pos] != 0) { segtree[pos] += lazy[pos] * (high - low + 1); - if (low != high) - { + if (low != high) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } @@ -54,11 +46,9 @@ void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, } if (start > high || end < low) return; - if (start <= low && end >= high) - { + if (start <= low && end >= high) { segtree[pos] += delta * (high - low + 1); - if (low != high) - { + if (low != high) { lazy[2 * pos + 1] += delta; lazy[2 * pos + 2] += delta; } @@ -69,23 +59,18 @@ void update(ll segtree[], ll lazy[], ll start, ll end, ll delta, ll low, update(segtree, lazy, start, end, delta, mid + 1, high, 2 * pos + 2); segtree[pos] = segtree[2 * pos + 1] + segtree[2 * pos + 2]; } -int main() -{ +int main() { ll n, c; scanf("%lld %lld", &n, &c); ll arr[n] = {0}, p, q, v, choice; ll segtree[MAX], lazy[MAX] = {0}; ConsTree(arr, segtree, 0, n - 1, 0); - while (c--) - { + while (c--) { scanf("%lld", &choice); - if (choice == 0) - { + if (choice == 0) { scanf("%lld %lld %lld", &p, &q, &v); update(segtree, lazy, p - 1, q - 1, v, 0, n - 1, 0); - } - else - { + } else { scanf("%lld %lld", &p, &q); printf("%lld\n", query(segtree, lazy, p - 1, q - 1, 0, n - 1, 0)); } diff --git a/search/binary_search.cpp b/search/binary_search.cpp index ba0ce7644..66da31d7f 100644 --- a/search/binary_search.cpp +++ b/search/binary_search.cpp @@ -12,12 +12,10 @@ * \returns index if T is found * \return -1 if T is not found */ -int binary_search(int a[], int r, int key) -{ +int binary_search(int a[], int r, int key) { int l = 0; - while (l <= r) - { + while (l <= r) { int m = l + (r - l) / 2; if (key == a[m]) return m; @@ -30,8 +28,7 @@ int binary_search(int a[], int r, int key) } /** main function */ -int main(int argc, char const* argv[]) -{ +int main(int argc, char const* argv[]) { int n, key; std::cout << "Enter size of array: "; std::cin >> n; @@ -40,8 +37,7 @@ int main(int argc, char const* argv[]) int* a = new int[n]; // this loop use for store value in Array - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { std::cin >> a[i]; } diff --git a/search/exponential_search.cpp b/search/exponential_search.cpp index 276d03246..f57cbf96b 100644 --- a/search/exponential_search.cpp +++ b/search/exponential_search.cpp @@ -31,12 +31,10 @@ * \returns `nullptr` if value not found */ template -inline Type* binary_s(Type* array, size_t size, Type key) -{ +inline Type* binary_s(Type* array, size_t size, Type key) { int32_t lower_index(0), upper_index(size - 1), middle_index; - while (lower_index <= upper_index) - { + while (lower_index <= upper_index) { middle_index = std::floor((lower_index + upper_index) / 2); if (*(array + middle_index) < key) @@ -58,13 +56,10 @@ inline Type* binary_s(Type* array, size_t size, Type key) * * Auxiliary Space Complexity O(1) */ template -Type* struzik_search(Type* array, size_t size, Type key) -{ +Type* struzik_search(Type* array, size_t size, Type key) { uint32_t block_front(0), block_size = size == 0 ? 0 : 1; - while (block_front != block_size) - { - if (*(array + block_size - 1) < key) - { + while (block_front != block_size) { + if (*(array + block_size - 1) < key) { block_front = block_size; (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size; continue; @@ -76,8 +71,7 @@ Type* struzik_search(Type* array, size_t size, Type key) } /** Main function */ -int main() -{ +int main() { // TEST CASES int* sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203}; assert(struzik_search(sorted_array, 7, 0) == nullptr); diff --git a/search/hash_search.cpp b/search/hash_search.cpp index c417c114b..6e4caffc3 100644 --- a/search/hash_search.cpp +++ b/search/hash_search.cpp @@ -26,8 +26,7 @@ int data[MAX] = {1, 10, 15, 5, 8, 7}; //!< test data /** * a one-way linked list */ -typedef struct list -{ +typedef struct list { int key; //!< key value for node struct list* next; //!< pointer to next link in the chain } node, /**< define node as one item list */ @@ -53,8 +52,7 @@ int h(int key) { return key % HASHMAX; } * \warning dynamic memory allocated to `n` never gets freed. * \todo fix memory leak */ -void create_list(int key) -{ // Construct hash table +void create_list(int key) { // Construct hash table link p, n; int index; n = (link)malloc(sizeof(node)); @@ -62,13 +60,10 @@ void create_list(int key) n->next = NULL; index = h(key); p = hashtab[index].next; - if (p != NULL) - { + if (p != NULL) { n->next = p; hashtab[index].next = n; - } - else - { + } else { hashtab[index].next = n; } } @@ -78,8 +73,7 @@ void create_list(int key) * (int key) function, then one-dimensional linear search. If found @return * element depth and number of searches If not found @return -1 */ -int hash_search(int key, int* counter) -{ // Hash lookup function +int hash_search(int key, int* counter) { // Hash lookup function link pointer; int index; @@ -89,8 +83,7 @@ int hash_search(int key, int* counter) std::cout << "data[" << index << "]:"; - while (pointer != NULL) - { + while (pointer != NULL) { counter[0]++; std::cout << "data[" << pointer->key << "]:"; if (pointer->key == key) @@ -103,27 +96,23 @@ int hash_search(int key, int* counter) } /** main function */ -int main() -{ +int main() { link p; int key, index, i, counter; // Key is the value to be found index = 0; // You can write the input mode here - while (index < MAX) - { // Construct hash table + while (index < MAX) { // Construct hash table create_list(data[index]); index++; } - for (i = 0; i < HASHMAX; i++) - { // Output hash table + for (i = 0; i < HASHMAX; i++) { // Output hash table std::cout << "hashtab [" << i << "]\n"; p = hashtab[i].next; - while (p != NULL) - { + while (p != NULL) { std::cout << "please int key:"; if (p->key > 0) std::cout << "[" << p->key << "]"; @@ -132,8 +121,7 @@ int main() std::cout << std::endl; } - while (key != -1) - { + while (key != -1) { // You can write the input mode here // test key = 10 key = 10; diff --git a/search/interpolation_search.cpp b/search/interpolation_search.cpp index 0b356b119..4339dc366 100644 --- a/search/interpolation_search.cpp +++ b/search/interpolation_search.cpp @@ -12,13 +12,11 @@ * \returns index where the value is found * \returns 0 if not found */ -int interpolation_search(int arr[], int value, int len) -{ +int interpolation_search(int arr[], int value, int len) { int low = 0, high, mid; high = len - 1; - while (arr[low] <= value && arr[high] >= value) - { + while (arr[low] <= value && arr[high] >= value) { mid = (low + ((value - arr[low]) * (high - low)) / (arr[high] - arr[low])); if (arr[mid] > value) @@ -36,8 +34,7 @@ int interpolation_search(int arr[], int value, int len) } /** main function */ -int main() -{ +int main() { int n, value, re; std::cout << "Enter the size of array(less than 100) : "; diff --git a/search/interpolation_search2.cpp b/search/interpolation_search2.cpp index 9400c5f96..93fa6cd83 100644 --- a/search/interpolation_search2.cpp +++ b/search/interpolation_search2.cpp @@ -12,12 +12,10 @@ * \returns index where the value is found * \returns -1 if not found */ -int InterpolationSearch(int A[], int n, int x) -{ +int InterpolationSearch(int A[], int n, int x) { int low = 0; int high = n - 1; - while (low <= high) - { + while (low <= high) { int mid = low + (((high - 1) * (x - A[low])) / (A[high] - A[low])); if (x == A[mid]) return mid; // Found x, return (exit) @@ -31,8 +29,7 @@ int InterpolationSearch(int A[], int n, int x) } /** main function */ -int main() -{ +int main() { int A[] = {2, 4, 5, 7, 13, 14, 15, 23}; int x = 17; diff --git a/search/jump_search.cpp b/search/jump_search.cpp index b854ac6f9..f7b100a4e 100644 --- a/search/jump_search.cpp +++ b/search/jump_search.cpp @@ -9,16 +9,14 @@ /** jump search implementation */ -int jumpSearch(int arr[], int x, int n) -{ +int jumpSearch(int arr[], int x, int n) { // Finding block size to be jumped int step = std::sqrt(n); // Finding the block where element is // present (if it is present) int prev = 0; - while (arr[std::min(step, n) - 1] < x) - { + while (arr[std::min(step, n) - 1] < x) { prev = step; step += std::sqrt(n); if (prev >= n) @@ -27,8 +25,7 @@ int jumpSearch(int arr[], int x, int n) // Doing a linear search for x in block // beginning with prev. - while (arr[prev] < x) - { + while (arr[prev] < x) { prev++; // If we reached next block or end of @@ -44,8 +41,7 @@ int jumpSearch(int arr[], int x, int n) } // Driver program to test function -int main() -{ +int main() { int arr[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}; int x = 55; int n = sizeof(arr) / sizeof(arr[0]); diff --git a/search/linear_search.cpp b/search/linear_search.cpp index b8fd798a7..142506951 100644 --- a/search/linear_search.cpp +++ b/search/linear_search.cpp @@ -13,12 +13,9 @@ * \returns index where the key-value occurs in the array * \returns -1 if key-value not found */ -int LinearSearch(int *array, int size, int key) -{ - for (int i = 0; i < size; ++i) - { - if (array[i] == key) - { +int LinearSearch(int *array, int size, int key) { + for (int i = 0; i < size; ++i) { + if (array[i] == key) { return i; } } @@ -27,8 +24,7 @@ int LinearSearch(int *array, int size, int key) } /** main function */ -int main() -{ +int main() { int size; std::cout << "\nEnter the size of the Array : "; std::cin >> size; @@ -38,8 +34,7 @@ int main() // Input array std::cout << "\nEnter the Array of " << size << " numbers : "; - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { std::cin >> array[i]; } @@ -47,12 +42,9 @@ int main() std::cin >> key; int index = LinearSearch(array, size, key); - if (index != -1) - { + if (index != -1) { std::cout << "\nNumber found at index : " << index; - } - else - { + } else { std::cout << "\nNot found"; } diff --git a/search/median_search.cpp b/search/median_search.cpp index 433ffc1f7..7379cad26 100644 --- a/search/median_search.cpp +++ b/search/median_search.cpp @@ -14,25 +14,18 @@ * @todo add documentation */ template -void comp(X x, std::vector *s1, std::vector *s2, std::vector *s3) -{ - if (s1->size() >= x && s1->size() + s2->size() < x) - { +void comp(X x, std::vector *s1, std::vector *s2, + std::vector *s3) { + if (s1->size() >= x && s1->size() + s2->size() < x) { std::cout << (*s2)[0] << " is the " << x + 1 << "th element from front"; - } - else if (s1->size() > x) - { + } else if (s1->size() > x) { std::sort(s1->begin(), s1->end()); std::cout << (*s1)[x] << " is the " << x + 1 << "th element from front"; - } - else if (s1->size() + s2->size() <= x && s3->size() > x) - { + } else if (s1->size() + s2->size() <= x && s3->size() > x) { std::sort(s3->begin(), s3->end()); std::cout << (*s3)[x - s1->size() - s2->size()] << " is the " << x + 1 << "th element from front"; - } - else - { + } else { std::cout << x + 1 << " is invalid location"; } } @@ -42,8 +35,7 @@ void comp(X x, std::vector *s1, std::vector *s2, std::vector *s3) /** * Main function */ -int main() -{ +int main() { std::vector v{25, 21, 98, 100, 76, 22, 43, 60, 89, 87}; std::vector s1; std::vector s2; @@ -62,20 +54,14 @@ int main() std::cout << "\nmedian=" << median << std::endl; int avg1, avg2, avg3, sum1 = 0, sum2 = 0, sum3 = 0; - for (int i = 0; i < v.size(); i++) - { // iterate through all numbers - if (v.back() == v[median]) - { + for (int i = 0; i < v.size(); i++) { // iterate through all numbers + if (v.back() == v[median]) { avg1 = sum1 + v.back(); s2.push_back(v.back()); - } - else if (v.back() < v[median]) - { + } else if (v.back() < v[median]) { avg2 = sum2 + v.back(); s1.push_back(v.back()); - } - else - { + } else { avg3 = sum3 + v.back(); s3.push_back(v.back()); } diff --git a/search/ternary_search.cpp b/search/ternary_search.cpp index f1e2eccf0..73b89da7a 100644 --- a/search/ternary_search.cpp +++ b/search/ternary_search.cpp @@ -45,14 +45,10 @@ void get_input() {} * \returns index where the target value was found * \returns -1 if target value not found */ -int it_ternary_search(int left, int right, int A[], int target) -{ - while (1) - { - if (left < right) - { - if (right - left < absolutePrecision) - { +int it_ternary_search(int left, int right, int A[], int target) { + while (1) { + if (left < right) { + if (right - left < absolutePrecision) { for (int i = left; i <= right; i++) if (A[i] == target) return i; @@ -75,9 +71,7 @@ int it_ternary_search(int left, int right, int A[], int target) else left = oneThird + 1, right = twoThird - 1; - } - else - { + } else { return -1; } } @@ -93,12 +87,9 @@ int it_ternary_search(int left, int right, int A[], int target) * \returns index where the target value was found * \returns -1 if target value not found */ -int rec_ternary_search(int left, int right, int A[], int target) -{ - if (left < right) - { - if (right - left < absolutePrecision) - { +int rec_ternary_search(int left, int right, int A[], int target) { + if (left < right) { + if (right - left < absolutePrecision) { for (int i = left; i <= right; i++) if (A[i] == target) return i; @@ -120,9 +111,7 @@ int rec_ternary_search(int left, int right, int A[], int target) return rec_ternary_search(twoThird + 1, right, A, target); return rec_ternary_search(oneThird + 1, twoThird - 1, A, target); - } - else - { + } else { return -1; } } @@ -135,16 +124,14 @@ int rec_ternary_search(int left, int right, int A[], int target) * \param[in] A array to search in * \param[in] target value to search for */ -void ternary_search(int N, int A[], int target) -{ +void ternary_search(int N, int A[], int target) { std::cout << it_ternary_search(0, N - 1, A, target) << '\t'; std::cout << rec_ternary_search(0, N - 1, A, target) << '\t'; std::cout << std::endl; } /** Main function */ -int main() -{ +int main() { int N = 21; int A[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 10}; get_input(); diff --git a/search/text_search.cpp b/search/text_search.cpp index a228d23b2..ee66a506a 100644 --- a/search/text_search.cpp +++ b/search/text_search.cpp @@ -12,8 +12,7 @@ /** Main function */ -int main() -{ +int main() { std::string paragraph; std::cout << "Please enter your paragraph: \n"; std::getline(std::cin, paragraph); @@ -21,25 +20,18 @@ int main() std::cout << "\nThe size of your paragraph = " << paragraph.size() << " characters. \n\n"; - if (paragraph.empty()) - { + if (paragraph.empty()) { std::cout << "\nThe paragraph is empty" << std::endl; - } - else - { - while (true) - { + } else { + while (true) { std::string word; std::cout << "Please enter the word you are searching for: "; std::getline(std::cin, word); std::cout << "Hello, your word is " << word << "!\n"; - if (paragraph.find(word) == std::string::npos) - { + if (paragraph.find(word) == std::string::npos) { std::cout << word << " does not exist in the sentence" << std::endl; - } - else - { + } else { std::cout << "The word " << word << " is now found at location " << paragraph.find(word) << std::endl << std::endl; diff --git a/sorting/bead_sort.cpp b/sorting/bead_sort.cpp index 0215fc769..f3276bfcd 100644 --- a/sorting/bead_sort.cpp +++ b/sorting/bead_sort.cpp @@ -5,8 +5,7 @@ #define BEAD(i, j) beads[i * max + j] // function to perform the above algorithm -void beadSort(int *a, int len) -{ +void beadSort(int *a, int len) { // Find the maximum element int max = a[0]; for (int i = 1; i < len; i++) @@ -21,12 +20,10 @@ void beadSort(int *a, int len) for (int i = 0; i < len; i++) for (int j = 0; j < a[i]; j++) BEAD(i, j) = 1; - for (int j = 0; j < max; j++) - { + for (int j = 0; j < max; j++) { // count how many beads are on each post int sum = 0; - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { sum += BEAD(i, j); BEAD(i, j) = 0; } @@ -36,11 +33,9 @@ void beadSort(int *a, int len) } // Put sorted values in array using beads - for (int i = 0; i < len; i++) - { + for (int i = 0; i < len; i++) { int j; - for (j = 0; j < max && BEAD(i, j); j++) - { + for (j = 0; j < max && BEAD(i, j); j++) { } a[i] = j; @@ -49,8 +44,7 @@ void beadSort(int *a, int len) } // driver function to test the algorithm -int main() -{ +int main() { int a[] = {5, 3, 1, 7, 4, 1, 1, 20}; int len = sizeof(a) / sizeof(a[0]); diff --git a/sorting/bitonic_sort.cpp b/sorting/bitonic_sort.cpp index 7f47cbac6..0fbb995ac 100644 --- a/sorting/bitonic_sort.cpp +++ b/sorting/bitonic_sort.cpp @@ -9,8 +9,7 @@ /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/ -void compAndSwap(int a[], int i, int j, int dir) -{ +void compAndSwap(int a[], int i, int j, int dir) { if (dir == (a[i] > a[j])) std::swap(a[i], a[j]); } @@ -19,10 +18,8 @@ void compAndSwap(int a[], int i, int j, int dir) if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ -void bitonicMerge(int a[], int low, int cnt, int dir) -{ - if (cnt > 1) - { +void bitonicMerge(int a[], int low, int cnt, int dir) { + if (cnt > 1) { int k = cnt / 2; for (int i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir); bitonicMerge(a, low, k, dir); @@ -33,10 +30,8 @@ void bitonicMerge(int a[], int low, int cnt, int dir) /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */ -void bitonicSort(int a[], int low, int cnt, int dir) -{ - if (cnt > 1) - { +void bitonicSort(int a[], int low, int cnt, int dir) { + if (cnt > 1) { int k = cnt / 2; // sort in ascending order since dir here is 1 @@ -56,8 +51,7 @@ void bitonicSort(int a[], int low, int cnt, int dir) void sort(int a[], int N, int up) { bitonicSort(a, 0, N, up); } // Driver code -int main() -{ +int main() { int a[] = {3, 7, 4, 8, 6, 2, 1, 5}; int N = sizeof(a) / sizeof(a[0]); diff --git a/sorting/bubble_sort.cpp b/sorting/bubble_sort.cpp index 8d2a33dcd..c43e425fc 100644 --- a/sorting/bubble_sort.cpp +++ b/sorting/bubble_sort.cpp @@ -40,8 +40,7 @@ optimized bubble sort algorithm. It's right down there. #include #include -int main() -{ +int main() { int n; bool swap_check = true; std::cout << "Enter the amount of numbers to sort: "; @@ -51,20 +50,16 @@ int main() int num; // Input - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { std::cin >> num; numbers.push_back(num); } // Bubble Sorting - for (int i = 0; (i < n) && (swap_check); i++) - { + for (int i = 0; (i < n) && (swap_check); i++) { swap_check = false; - for (int j = 0; j < n - 1 - i; j++) - { - if (numbers[j] > numbers[j + 1]) - { + for (int j = 0; j < n - 1 - i; j++) { + if (numbers[j] > numbers[j + 1]) { swap_check = true; std::swap(numbers[j], numbers[j + 1]); // by changing swap location. @@ -77,14 +72,10 @@ int main() // Output std::cout << "\nSorted Array : "; - for (int i = 0; i < numbers.size(); i++) - { - if (i != numbers.size() - 1) - { + for (int i = 0; i < numbers.size(); i++) { + if (i != numbers.size() - 1) { std::cout << numbers[i] << ", "; - } - else - { + } else { std::cout << numbers[i] << std::endl; } } diff --git a/sorting/bucket_sort.cpp b/sorting/bucket_sort.cpp index ee945627c..c43865281 100644 --- a/sorting/bucket_sort.cpp +++ b/sorting/bucket_sort.cpp @@ -4,14 +4,12 @@ #include // Function to sort arr[] of size n using bucket sort -void bucketSort(float arr[], int n) -{ +void bucketSort(float arr[], int n) { // 1) Create n empty buckets std::vector *b = new std::vector[n]; // 2) Put array elements in different buckets - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { int bi = n * arr[i]; // Index in bucket b[bi].push_back(arr[i]); } @@ -27,8 +25,7 @@ void bucketSort(float arr[], int n) } /* Driver program to test above funtion */ -int main() -{ +int main() { float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434}; int n = sizeof(arr) / sizeof(arr[0]); bucketSort(arr, n); diff --git a/sorting/cocktail_selection_sort.cpp b/sorting/cocktail_selection_sort.cpp index ef3d30752..157acafce 100644 --- a/sorting/cocktail_selection_sort.cpp +++ b/sorting/cocktail_selection_sort.cpp @@ -9,35 +9,27 @@ // Iterative Version -void CocktailSelectionSort(std::vector *vec, int low, int high) -{ - while (low <= high) - { +void CocktailSelectionSort(std::vector *vec, int low, int high) { + while (low <= high) { int minimum = (*vec)[low]; int minimumindex = low; int maximum = (*vec)[high]; int maximumindex = high; - for (int i = low; i <= high; i++) - { - if ((*vec)[i] >= maximum) - { + for (int i = low; i <= high; i++) { + if ((*vec)[i] >= maximum) { maximum = (*vec)[i]; maximumindex = i; } - if ((*vec)[i] <= minimum) - { + if ((*vec)[i] <= minimum) { minimum = (*vec)[i]; minimumindex = i; } } - if (low != maximumindex || high != minimumindex) - { + if (low != maximumindex || high != minimumindex) { std::swap((*vec)[low], (*vec)[minimumindex]); std::swap((*vec)[high], (*vec)[maximumindex]); - } - else - { + } else { std::swap((*vec)[low], (*vec)[high]); } @@ -48,8 +40,7 @@ void CocktailSelectionSort(std::vector *vec, int low, int high) // Recursive Version -void CocktailSelectionSort_v2(std::vector *vec, int low, int high) -{ +void CocktailSelectionSort_v2(std::vector *vec, int low, int high) { if (low >= high) return; @@ -58,26 +49,20 @@ void CocktailSelectionSort_v2(std::vector *vec, int low, int high) int maximum = (*vec)[high]; int maximumindex = high; - for (int i = low; i <= high; i++) - { - if ((*vec)[i] >= maximum) - { + for (int i = low; i <= high; i++) { + if ((*vec)[i] >= maximum) { maximum = (*vec)[i]; maximumindex = i; } - if ((*vec)[i] <= minimum) - { + if ((*vec)[i] <= minimum) { minimum = (*vec)[i]; minimumindex = i; } } - if (low != maximumindex || high != minimumindex) - { + if (low != maximumindex || high != minimumindex) { std::swap((*vec)[low], (*vec)[minimumindex]); std::swap((*vec)[high], (*vec)[maximumindex]); - } - else - { + } else { std::swap((*vec)[low], (*vec)[high]); } @@ -86,15 +71,13 @@ void CocktailSelectionSort_v2(std::vector *vec, int low, int high) // main function, select any one of iterative or recursive version -int main() -{ +int main() { int n; std::cout << "Enter number of elements\n"; std::cin >> n; std::vector v(n); std::cout << "Enter all the elements\n"; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { std::cin >> v[i]; } @@ -102,22 +85,16 @@ int main() std::cout << "Enter method: \n\t0: iterative\n\t1: recursive:\t"; std::cin >> method; - if (method == 0) - { + if (method == 0) { CocktailSelectionSort(&v, 0, n - 1); - } - else if (method == 1) - { + } else if (method == 1) { CocktailSelectionSort_v2(&v, 0, n - 1); - } - else - { + } else { std::cerr << "Unknown method" << std::endl; return -1; } std::cout << "Sorted elements are\n"; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { std::cout << v[i] << " "; } diff --git a/sorting/comb_sort.cpp b/sorting/comb_sort.cpp index d554ac757..1b0a4d706 100644 --- a/sorting/comb_sort.cpp +++ b/sorting/comb_sort.cpp @@ -8,15 +8,13 @@ int a[100005]; int n; -int FindNextGap(int x) -{ +int FindNextGap(int x) { x = (x * 10) / 13; return std::max(1, x); } -void CombSort(int a[], int l, int r) -{ +void CombSort(int a[], int l, int r) { // Init gap int gap = n; @@ -24,18 +22,15 @@ void CombSort(int a[], int l, int r) bool swapped = true; // Keep running until gap = 1 or none elements were swapped - while (gap != 1 || swapped) - { + while (gap != 1 || swapped) { // Find next gap gap = FindNextGap(gap); swapped = false; // Compare all elements with current gap - for (int i = l; i <= r - gap; ++i) - { - if (a[i] > a[i + gap]) - { + for (int i = l; i <= r - gap; ++i) { + if (a[i] > a[i + gap]) { std::swap(a[i], a[i + gap]); swapped = true; } @@ -43,8 +38,7 @@ void CombSort(int a[], int l, int r) } } -int main() -{ +int main() { std::cin >> n; for (int i = 1; i <= n; ++i) std::cin >> a[i]; diff --git a/sorting/counting_sort.cpp b/sorting/counting_sort.cpp index 9dadd48cc..1fbfc0fa3 100644 --- a/sorting/counting_sort.cpp +++ b/sorting/counting_sort.cpp @@ -1,8 +1,7 @@ #include using namespace std; -int Max(int Arr[], int N) -{ +int Max(int Arr[], int N) { int max = Arr[0]; for (int i = 1; i < N; i++) if (Arr[i] > max) @@ -10,8 +9,7 @@ int Max(int Arr[], int N) return max; } -int Min(int Arr[], int N) -{ +int Min(int Arr[], int N) { int min = Arr[0]; for (int i = 1; i < N; i++) if (Arr[i] < min) @@ -19,13 +17,11 @@ int Min(int Arr[], int N) return min; } -void Print(int Arr[], int N) -{ +void Print(int Arr[], int N) { for (int i = 0; i < N; i++) cout << Arr[i] << ", "; } -int *Counting_Sort(int Arr[], int N) -{ +int *Counting_Sort(int Arr[], int N) { int max = Max(Arr, N); int min = Min(Arr, N); int *Sorted_Arr = new int[N]; @@ -36,8 +32,7 @@ int *Counting_Sort(int Arr[], int N) for (int i = 1; i < (max - min + 1); i++) Count[i] += Count[i - 1]; - for (int i = N - 1; i >= 0; i--) - { + for (int i = N - 1; i >= 0; i--) { Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i]; Count[Arr[i] - min]--; } @@ -45,8 +40,7 @@ int *Counting_Sort(int Arr[], int N) return Sorted_Arr; } -int main() -{ +int main() { int Arr[] = {47, 65, 20, 66, 25, 53, 64, 69, 72, 22, 74, 25, 53, 15, 42, 36, 4, 69, 86, 19}, N = 20; diff --git a/sorting/counting_sort_string.cpp b/sorting/counting_sort_string.cpp index 77e8cdf89..977f3484d 100644 --- a/sorting/counting_sort_string.cpp +++ b/sorting/counting_sort_string.cpp @@ -3,8 +3,7 @@ using namespace std; -void countSort(string arr) -{ +void countSort(string arr) { string output; int count[256], i; @@ -14,8 +13,7 @@ void countSort(string arr) for (i = 1; i <= 256; ++i) count[i] += count[i - 1]; - for (i = 0; arr[i]; ++i) - { + for (i = 0; arr[i]; ++i) { output[count[arr[i]] - 1] = arr[i]; --count[arr[i]]; } @@ -25,8 +23,7 @@ void countSort(string arr) cout << "Sorted character array is " << arr; } -int main() -{ +int main() { string arr; cin >> arr; diff --git a/sorting/heap_sort.cpp b/sorting/heap_sort.cpp index b9b62a5f6..9948bb821 100644 --- a/sorting/heap_sort.cpp +++ b/sorting/heap_sort.cpp @@ -1,8 +1,7 @@ #include #include -void heapify(int *a, int i, int n) -{ +void heapify(int *a, int i, int n) { int largest = i; const int l = 2 * i + 1; const int r = 2 * i + 2; @@ -13,38 +12,31 @@ void heapify(int *a, int i, int n) if (r < n && a[r] > a[largest]) largest = r; - if (largest != i) - { + if (largest != i) { std::swap(a[i], a[largest]); heapify(a, n, largest); } } -void heapsort(int *a, int n) -{ - for (int i = n - 1; i >= 0; --i) - { +void heapsort(int *a, int n) { + for (int i = n - 1; i >= 0; --i) { std::swap(a[0], a[i]); heapify(a, 0, i); } } -void build_maxheap(int *a, int n) -{ - for (int i = n / 2 - 1; i >= 0; --i) - { +void build_maxheap(int *a, int n) { + for (int i = n / 2 - 1; i >= 0; --i) { heapify(a, i, n); } } -int main() -{ +int main() { int n; std::cout << "Enter number of elements of array\n"; std::cin >> n; int a[20]; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { std::cout << "Enter Element " << i << std::endl; std::cin >> a[i]; } @@ -52,8 +44,7 @@ int main() build_maxheap(a, n); heapsort(a, n); std::cout << "Sorted Output\n"; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { std::cout << a[i] << std::endl; } diff --git a/sorting/insertion_sort.cpp b/sorting/insertion_sort.cpp index b96a44c47..fe920ca59 100644 --- a/sorting/insertion_sort.cpp +++ b/sorting/insertion_sort.cpp @@ -2,8 +2,7 @@ #include -int main() -{ +int main() { int n; std::cout << "\nEnter the length of your array : "; std::cin >> n; @@ -11,18 +10,15 @@ int main() std::cout << "\nEnter any " << n << " Numbers for Unsorted Array : "; // Input - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { std::cin >> Array[i]; } // Sorting - for (int i = 1; i < n; i++) - { + for (int i = 1; i < n; i++) { int temp = Array[i]; int j = i - 1; - while (j >= 0 && temp < Array[j]) - { + while (j >= 0 && temp < Array[j]) { Array[j + 1] = Array[j]; j--; } @@ -31,8 +27,7 @@ int main() // Output std::cout << "\nSorted Array : "; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { std::cout << Array[i] << "\t"; } diff --git a/sorting/library_sort.cpp b/sorting/library_sort.cpp index c0fa857e7..c9cba88d8 100644 --- a/sorting/library_sort.cpp +++ b/sorting/library_sort.cpp @@ -1,8 +1,7 @@ #include #include -void librarySort(int *index, int n) -{ +void librarySort(int *index, int n) { int lib_size, index_pos, *gaps, // gaps *library[2]; // libraries @@ -19,8 +18,7 @@ void librarySort(int *index, int n) target_lib = 0; library[target_lib][0] = index[0]; - while (index_pos < n) - { + while (index_pos < n) { // binary search int insert = std::distance( library[target_lib], @@ -29,23 +27,19 @@ void librarySort(int *index, int n) // if there is no gap to insert a new index ... - if (numbered[insert] == true) - { + if (numbered[insert] == true) { int prov_size = 0, next_target_lib = !target_lib; // update library and clear gaps - for (int i = 0; i <= n; i++) - { - if (numbered[i] == true) - { + for (int i = 0; i <= n; i++) { + if (numbered[i] == true) { library[next_target_lib][prov_size] = gaps[i]; prov_size++; numbered[i] = false; } - if (i <= lib_size) - { + if (i <= lib_size) { library[next_target_lib][prov_size] = library[target_lib][i]; prov_size++; @@ -54,9 +48,7 @@ void librarySort(int *index, int n) target_lib = next_target_lib; lib_size = prov_size - 1; - } - else - { + } else { numbered[insert] = true; gaps[insert] = index[index_pos]; index_pos++; @@ -64,17 +56,14 @@ void librarySort(int *index, int n) } int index_pos_for_output = 0; - for (int i = 0; index_pos_for_output < n; i++) - { - if (numbered[i] == true) - { + for (int i = 0; index_pos_for_output < n; i++) { + if (numbered[i] == true) { // std::cout << gaps[i] << std::endl; index[index_pos_for_output] = gaps[i]; index_pos_for_output++; } - if (i < lib_size) - { + if (i < lib_size) { // std::cout << library[target_lib][i] << std::endl; index[index_pos_for_output] = library[target_lib][i]; index_pos_for_output++; @@ -82,8 +71,7 @@ void librarySort(int *index, int n) } } -int main() -{ +int main() { // ---example-- int index_ex[] = {-6, 5, 9, 1, 9, 1, 0, 1, -8, 4, -12}; int n_ex = sizeof(index_ex) / sizeof(index_ex[0]); diff --git a/sorting/merge_sort.cpp b/sorting/merge_sort.cpp index 1a394ded9..82ab869cd 100644 --- a/sorting/merge_sort.cpp +++ b/sorting/merge_sort.cpp @@ -1,7 +1,6 @@ #include -void merge(int arr[], int l, int m, int r) -{ +void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; @@ -14,30 +13,24 @@ void merge(int arr[], int l, int m, int r) i = 0; j = 0; k = l; - while (i < n1 && j < n2) - { - if (L[i] <= R[j]) - { + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { arr[k] = L[i]; i++; - } - else - { + } else { arr[k] = R[j]; j++; } k++; } - while (i < n1) - { + while (i < n1) { arr[k] = L[i]; i++; k++; } - while (j < n2) - { + while (j < n2) { arr[k] = R[j]; j++; k++; @@ -47,10 +40,8 @@ void merge(int arr[], int l, int m, int r) delete[] R; } -void mergeSort(int arr[], int l, int r) -{ - if (l < r) - { +void mergeSort(int arr[], int l, int r) { + if (l < r) { int m = l + (r - l) / 2; mergeSort(arr, l, m); @@ -60,14 +51,12 @@ void mergeSort(int arr[], int l, int r) } } -void show(int A[], int size) -{ +void show(int A[], int size) { int i; for (i = 0; i < size; i++) std::cout << A[i] << "\n"; } -int main() -{ +int main() { int size; std::cout << "\nEnter the number of elements : "; @@ -77,8 +66,7 @@ int main() std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { std::cout << "\n"; std::cin >> arr[i]; } diff --git a/sorting/non_recursive_merge_sort.cpp b/sorting/non_recursive_merge_sort.cpp index 9086ec0ed..9d4e95f2f 100644 --- a/sorting/non_recursive_merge_sort.cpp +++ b/sorting/non_recursive_merge_sort.cpp @@ -22,20 +22,17 @@ void merge(Iterator, Iterator, const Iterator, char[]); */ template void non_recursive_merge_sort(const Iterator first, const Iterator last, - const size_t n) -{ + const size_t n) { // create a buffer large enough to store all elements // dynamically allocated to comply with cpplint char* buffer = new char[n * sizeof(*first)]; // buffer size can be optimized to largest power of 2 less than n elements // divide the container into equally-sized segments whose length start at 1 // and keeps increasing by factors of 2 - for (size_t length(1); length < n; length <<= 1) - { + for (size_t length(1); length < n; length <<= 1) { // merge adjacent segments whose number is n / (length * 2) Iterator left(first); - for (size_t counter(n / (length << 1)); counter; --counter) - { + for (size_t counter(n / (length << 1)); counter; --counter) { Iterator right(left + length), end(right + length); merge(left, right, end, buffer); left = end; @@ -56,8 +53,7 @@ void non_recursive_merge_sort(const Iterator first, const Iterator last, * @param b points at the buffer */ template -void merge(Iterator l, Iterator r, const Iterator e, char b[]) -{ +void merge(Iterator l, Iterator r, const Iterator e, char b[]) { // create 2 pointers to point at the buffer auto p(reinterpret_cast*>(b)), c(p); // move the left part of the segment @@ -77,8 +73,7 @@ void merge(Iterator l, Iterator r, const Iterator e, char b[]) * @param n the number of elements */ template -void non_recursive_merge_sort(const Iterator first, const size_t n) -{ +void non_recursive_merge_sort(const Iterator first, const size_t n) { non_recursive_merge_sort(first, first + n, n); } /// bottom-up merge sort which sorts elements in a non-decreasing order @@ -87,19 +82,16 @@ void non_recursive_merge_sort(const Iterator first, const size_t n) * @param last points to 1-step past the last element */ template -void non_recursive_merge_sort(const Iterator first, const Iterator last) -{ +void non_recursive_merge_sort(const Iterator first, const Iterator last) { non_recursive_merge_sort(first, last, last - first); } -int main(int argc, char** argv) -{ +int main(int argc, char** argv) { int size; std::cout << "Enter the number of elements : "; std::cin >> size; int* arr = new int[size]; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { std::cout << "arr[" << i << "] = "; std::cin >> arr[i]; } diff --git a/sorting/numeric_string_sort.cpp b/sorting/numeric_string_sort.cpp index 358cc63e3..04a12e71a 100644 --- a/sorting/numeric_string_sort.cpp +++ b/sorting/numeric_string_sort.cpp @@ -13,14 +13,11 @@ #include #include -bool NumericSort(std::string a, std::string b) -{ - while (a[0] == '0') - { +bool NumericSort(std::string a, std::string b) { + while (a[0] == '0') { a.erase(a.begin()); } - while (b[0] == '0') - { + while (b[0] == '0') { b.erase(b.begin()); } int n = a.length(); @@ -30,31 +27,27 @@ bool NumericSort(std::string a, std::string b) return n < m; } -int main() -{ +int main() { int n; std::cout << "Enter number of elements to be sorted Numerically\n"; std::cin >> n; std::vector v(n); std::cout << "Enter the string of Numbers\n"; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { std::cin >> v[i]; } sort(v.begin(), v.end()); std::cout << "Elements sorted normally \n"; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { std::cout << v[i] << " "; } std::cout << "\n"; std::sort(v.begin(), v.end(), NumericSort); std::cout << "Elements sorted Numerically \n"; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { std::cout << v[i] << " "; } diff --git a/sorting/odd_even_sort.cpp b/sorting/odd_even_sort.cpp index 274f3033b..25f2a3712 100644 --- a/sorting/odd_even_sort.cpp +++ b/sorting/odd_even_sort.cpp @@ -4,16 +4,13 @@ using namespace std; -void oddEven(vector &arr, int size) -{ +void oddEven(vector &arr, int size) { bool sorted = false; - while (!sorted) - { + while (!sorted) { sorted = true; for (int i = 1; i < size - 1; i += 2) // Odd { - if (arr[i] > arr[i + 1]) - { + if (arr[i] > arr[i + 1]) { swap(arr[i], arr[i + 1]); sorted = false; } @@ -21,8 +18,7 @@ void oddEven(vector &arr, int size) for (int i = 0; i < size - 1; i += 2) // Even { - if (arr[i] > arr[i + 1]) - { + if (arr[i] > arr[i + 1]) { swap(arr[i], arr[i + 1]); sorted = false; } @@ -30,14 +26,12 @@ void oddEven(vector &arr, int size) } } -void show(vector A, int size) -{ +void show(vector A, int size) { int i; for (i = 0; i < size; i++) cout << A[i] << "\n"; } -int main() -{ +int main() { int size, temp; cout << "\nEnter the number of elements : "; cin >> size; @@ -46,8 +40,7 @@ int main() cout << "\nEnter the unsorted elements : \n"; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { cin >> temp; arr.push_back(temp); } diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index 8bb376b24..1db6b014e 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -33,17 +33,14 @@ * */ -int partition(int arr[], int low, int high) -{ +int partition(int arr[], int low, int high) { int pivot = arr[high]; // taking the last element as pivot int i = (low - 1); // Index of smaller element - for (int j = low; j < high; j++) - { + for (int j = low; j < high; j++) { // If current element is smaller than or // equal to pivot - if (arr[j] <= pivot) - { + if (arr[j] <= pivot) { i++; // increment index of smaller element int temp = arr[i]; arr[i] = arr[j]; @@ -62,10 +59,8 @@ int partition(int arr[], int low, int high) * low --> Starting index, * high --> Ending index */ -void quickSort(int arr[], int low, int high) -{ - if (low < high) - { +void quickSort(int arr[], int low, int high) { + if (low < high) { int p = partition(arr, low, high); quickSort(arr, low, p - 1); quickSort(arr, p + 1, high); @@ -73,15 +68,13 @@ void quickSort(int arr[], int low, int high) } // prints the array after sorting -void show(int arr[], int size) -{ +void show(int arr[], int size) { for (int i = 0; i < size; i++) std::cout << arr[i] << " "; std::cout << "\n"; } /** Driver program to test above functions */ -int main() -{ +int main() { int size; std::cout << "\nEnter the number of elements : "; @@ -91,8 +84,7 @@ int main() std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { std::cout << "\n"; std::cin >> arr[i]; } diff --git a/sorting/radix_sort.cpp b/sorting/radix_sort.cpp index c3b5b1629..a0fbfe99e 100644 --- a/sorting/radix_sort.cpp +++ b/sorting/radix_sort.cpp @@ -3,66 +3,53 @@ #include #include -void radixsort(int a[], int n) -{ +void radixsort(int a[], int n) { int count[10]; int* output = new int[n]; memset(output, 0, n * sizeof(*output)); memset(count, 0, sizeof(count)); int max = 0; - for (int i = 0; i < n; ++i) - { - if (a[i] > max) - { + for (int i = 0; i < n; ++i) { + if (a[i] > max) { max = a[i]; } } int maxdigits = 0; - while (max) - { + while (max) { maxdigits++; max /= 10; } - for (int j = 0; j < maxdigits; j++) - { - for (int i = 0; i < n; i++) - { + for (int j = 0; j < maxdigits; j++) { + for (int i = 0; i < n; i++) { int t = std::pow(10, j); count[(a[i] % (10 * t)) / t]++; } int k = 0; - for (int p = 0; p < 10; p++) - { - for (int i = 0; i < n; i++) - { + for (int p = 0; p < 10; p++) { + for (int i = 0; i < n; i++) { int t = std::pow(10, j); - if ((a[i] % (10 * t)) / t == p) - { + if ((a[i] % (10 * t)) / t == p) { output[k] = a[i]; k++; } } } memset(count, 0, sizeof(count)); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { a[i] = output[i]; } } delete[] output; } -void print(int a[], int n) -{ - for (int i = 0; i < n; ++i) - { +void print(int a[], int n) { + for (int i = 0; i < n; ++i) { std::cout << a[i] << " "; } std::cout << std::endl; } -int main(int argc, char const* argv[]) -{ +int main(int argc, char const* argv[]) { int a[] = {170, 45, 75, 90, 802, 24, 2, 66}; int n = sizeof(a) / sizeof(a[0]); radixsort(a, n); diff --git a/sorting/selection_sort.cpp b/sorting/selection_sort.cpp index 7e8b0678c..3854f52e6 100644 --- a/sorting/selection_sort.cpp +++ b/sorting/selection_sort.cpp @@ -3,25 +3,20 @@ #include using namespace std; -int main() -{ +int main() { int Array[6]; cout << "\nEnter any 6 Numbers for Unsorted Array : "; // Input - for (int i = 0; i < 6; i++) - { + for (int i = 0; i < 6; i++) { cin >> Array[i]; } // Selection Sorting - for (int i = 0; i < 6; i++) - { + for (int i = 0; i < 6; i++) { int min = i; - for (int j = i + 1; j < 6; j++) - { - if (Array[j] < Array[min]) - { + for (int j = i + 1; j < 6; j++) { + if (Array[j] < Array[min]) { min = j; // Finding the smallest number in Array } } @@ -32,8 +27,7 @@ int main() // Output cout << "\nSorted Array : "; - for (int i = 0; i < 6; i++) - { + for (int i = 0; i < 6; i++) { cout << Array[i] << "\t"; } } diff --git a/sorting/shell_sort.cpp b/sorting/shell_sort.cpp index af783eb24..eb701478d 100644 --- a/sorting/shell_sort.cpp +++ b/sorting/shell_sort.cpp @@ -1,31 +1,23 @@ #include -int main() -{ +int main() { int size = 10; int* array = new int[size]; // Input std::cout << "\nHow many numbers do want to enter in unsorted array : "; std::cin >> size; std::cout << "\nEnter the numbers for unsorted array : "; - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { std::cin >> array[i]; } // Sorting - for (int i = size / 2; i > 0; i = i / 2) - { - for (int j = i; j < size; j++) - { - for (int k = j - i; k >= 0; k = k - i) - { - if (array[k] < array[k + i]) - { + for (int i = size / 2; i > 0; i = i / 2) { + for (int j = i; j < size; j++) { + for (int k = j - i; k >= 0; k = k - i) { + if (array[k] < array[k + i]) { break; - } - else - { + } else { int temp = array[k + i]; array[k + i] = array[k]; array[k] = temp; @@ -36,8 +28,7 @@ int main() // Output std::cout << "\nSorted array : "; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { std::cout << array[i] << "\t"; } diff --git a/sorting/shell_sort2.cpp b/sorting/shell_sort2.cpp index dee8cecd7..59f204818 100644 --- a/sorting/shell_sort2.cpp +++ b/sorting/shell_sort2.cpp @@ -7,8 +7,7 @@ #include template -void show_data(T *arr, size_t LEN) -{ +void show_data(T *arr, size_t LEN) { size_t i; for (i = 0; i < LEN; i++) std::cout << arr[i] << ", "; @@ -16,8 +15,7 @@ void show_data(T *arr, size_t LEN) } template -void show_data(T (&arr)[N]) -{ +void show_data(T (&arr)[N]) { show_data(arr, N); } @@ -26,17 +24,14 @@ void show_data(T (&arr)[N]) * Mar **/ template -void shell_sort(T *arr, size_t LEN) -{ +void shell_sort(T *arr, size_t LEN) { const unsigned int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; const unsigned int gap_len = 8; size_t i, j, g; - for (g = 0; g < gap_len; g++) - { + for (g = 0; g < gap_len; g++) { unsigned int gap = gaps[g]; - for (i = gap; i < LEN; i++) - { + for (i = gap; i < LEN; i++) { T tmp = arr[i]; for (j = i; j >= gap && (arr[j - gap] - tmp) > 0; j -= gap) @@ -48,16 +43,14 @@ void shell_sort(T *arr, size_t LEN) } template -void shell_sort(T (&arr)[N]) -{ +void shell_sort(T (&arr)[N]) { shell_sort(arr, N); } /** * function to compare sorting using cstdlib's qsort **/ -int compare(const void *a, const void *b) -{ +int compare(const void *a, const void *b) { int arg1 = *static_cast(a); int arg2 = *static_cast(b); @@ -71,8 +64,7 @@ int compare(const void *a, const void *b) // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present) } -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { int i, NUM_DATA; if (argc == 2) diff --git a/sorting/slow_sort.cpp b/sorting/slow_sort.cpp index e4f175af6..a3e64dba0 100644 --- a/sorting/slow_sort.cpp +++ b/sorting/slow_sort.cpp @@ -10,8 +10,7 @@ #include -void SlowSort(int a[], int i, int j) -{ +void SlowSort(int a[], int i, int j) { if (i >= j) return; int m = i + (j - i) / 2; // midpoint, implemented this way to avoid @@ -19,8 +18,7 @@ void SlowSort(int a[], int i, int j) int temp; SlowSort(a, i, m); SlowSort(a, m + 1, j); - if (a[j] < a[m]) - { + if (a[j] < a[m]) { temp = a[j]; // swapping a[j] & a[m] a[j] = a[m]; a[m] = temp; @@ -30,8 +28,7 @@ void SlowSort(int a[], int i, int j) // Sample Main function -int main() -{ +int main() { int size; std::cout << "\nEnter the number of elements : "; @@ -41,8 +38,7 @@ int main() std::cout << "\nEnter the unsorted elements : "; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { std::cout << "\n"; std::cin >> arr[i]; } @@ -51,8 +47,7 @@ int main() std::cout << "Sorted array\n"; - for (int i = 0; i < size; ++i) - { + for (int i = 0; i < size; ++i) { std::cout << arr[i] << " "; } diff --git a/sorting/swap_sort.cpp b/sorting/swap_sort.cpp index 7d391d8a1..4cdaa57b3 100644 --- a/sorting/swap_sort.cpp +++ b/sorting/swap_sort.cpp @@ -6,14 +6,12 @@ // Function returns the minimum number of swaps // required to sort the array -int minSwaps(int arr[], int n) -{ +int minSwaps(int arr[], int n) { // Create an array of pairs where first // element is array element and second element // is position of first element std::pair *arrPos = new std::pair[n]; - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { arrPos[i].first = arr[i]; arrPos[i].second = i; } @@ -31,8 +29,7 @@ int minSwaps(int arr[], int n) int ans = 0; // Traverse array elements - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos if (vis[i] || arrPos[i].second == i) @@ -42,8 +39,7 @@ int minSwaps(int arr[], int n) // this cycle and add in ans int cycle_size = 0; int j = i; - while (!vis[j]) - { + while (!vis[j]) { vis[j] = 1; // move to next node @@ -52,8 +48,7 @@ int minSwaps(int arr[], int n) } // Update answer by adding current cycle. - if (cycle_size > 0) - { + if (cycle_size > 0) { ans += (cycle_size - 1); } } @@ -65,8 +60,7 @@ int minSwaps(int arr[], int n) } // program to test -int main() -{ +int main() { int arr[] = {6, 7, 8, 1, 2, 3, 9, 12}; int n = (sizeof(arr) / sizeof(int)); std::cout << minSwaps(arr, n); diff --git a/sorting/tim_sort.cpp b/sorting/tim_sort.cpp index 9645a60b1..94f5aa230 100644 --- a/sorting/tim_sort.cpp +++ b/sorting/tim_sort.cpp @@ -6,14 +6,11 @@ const int RUN = 32; // this function sorts array from left index to to right index which is of size // atmost RUN -void insertionSort(int arr[], int left, int right) -{ - for (int i = left + 1; i <= right; i++) - { +void insertionSort(int arr[], int left, int right) { + for (int i = left + 1; i <= right; i++) { int temp = arr[i]; int j = i - 1; - while (arr[j] > temp && j >= left) - { + while (arr[j] > temp && j >= left) { arr[j + 1] = arr[j]; j--; } @@ -22,8 +19,7 @@ void insertionSort(int arr[], int left, int right) } // merge function merges the sorted runs -void merge(int arr[], int l, int m, int r) -{ +void merge(int arr[], int l, int m, int r) { // original array is broken in two parts, left and right array int len1 = m - l + 1, len2 = r - m; int *left = new int[len1], *right = new int[len2]; @@ -35,15 +31,11 @@ void merge(int arr[], int l, int m, int r) int k = l; // after comparing, we merge those two array in larger sub array - while (i < len1 && j < len2) - { - if (left[i] <= right[j]) - { + while (i < len1 && j < len2) { + if (left[i] <= right[j]) { arr[k] = left[i]; i++; - } - else - { + } else { arr[k] = right[j]; j++; } @@ -51,16 +43,14 @@ void merge(int arr[], int l, int m, int r) } // copy remaining elements of left, if any - while (i < len1) - { + while (i < len1) { arr[k] = left[i]; k++; i++; } // copy remaining element of right, if any - while (j < len2) - { + while (j < len2) { arr[k] = right[j]; k++; j++; @@ -70,21 +60,18 @@ void merge(int arr[], int l, int m, int r) } // iterative Timsort function to sort the array[0...n-1] (similar to merge sort) -void timSort(int arr[], int n) -{ +void timSort(int arr[], int n) { // Sort individual subarrays of size RUN for (int i = 0; i < n; i += RUN) insertionSort(arr, i, std::min((i + 31), (n - 1))); // start merging from size RUN (or 32). It will merge to form size 64, then // 128, 256 and so on .... - for (int size = RUN; size < n; size = 2 * size) - { + for (int size = RUN; size < n; size = 2 * size) { // pick starting point of left sub array. We are going to merge // arr[left..left+size-1] and arr[left+size, left+2*size-1] After every // merge, we increase left by 2*size - for (int left = 0; left < n; left += 2 * size) - { + for (int left = 0; left < n; left += 2 * size) { // find ending point of left sub array // mid+1 is starting point of right sub array int mid = left + size - 1; @@ -97,15 +84,13 @@ void timSort(int arr[], int n) } // utility function to print the Array -void printArray(int arr[], int n) -{ +void printArray(int arr[], int n) { for (int i = 0; i < n; i++) printf("%d ", arr[i]); std::cout << std::endl; } // Driver program to test above function -int main() -{ +int main() { int arr[] = {5, 21, 7, 23, 19}; int n = sizeof(arr) / sizeof(arr[0]); printf("Given Array is\n"); diff --git a/strings/brute_force_string_searching.cpp b/strings/brute_force_string_searching.cpp index 5f6116e1b..9a2b5327a 100644 --- a/strings/brute_force_string_searching.cpp +++ b/strings/brute_force_string_searching.cpp @@ -17,18 +17,14 @@ * @return Index where the pattern starts in the text * @return -1 if the pattern was not found. */ -int brute_force(const std::string &text, const std::string &pattern) -{ +int brute_force(const std::string &text, const std::string &pattern) { size_t pat_l = pattern.length(); size_t txt_l = text.length(); int index = -1; - if (pat_l <= txt_l) - { - for (size_t i = 0; i < txt_l - pat_l + 1; i++) - { + if (pat_l <= txt_l) { + for (size_t i = 0; i < txt_l - pat_l + 1; i++) { std::string s = text.substr(i, pat_l); - if (s == pattern) - { + if (s == pattern) { index = i; break; } @@ -44,10 +40,8 @@ const std::vector> test_set = { {"bba", "bb", "0"}, {"bbca", "c", "2"}, {"ab", "b", "1"}}; /** Main function */ -int main() -{ - for (size_t i = 0; i < test_set.size(); i++) - { +int main() { + for (size_t i = 0; i < test_set.size(); i++) { int output = brute_force(test_set[i][0], test_set[i][1]); if (std::to_string(output) == test_set[i][2]) diff --git a/strings/knuth_morris_pratt.cpp b/strings/knuth_morris_pratt.cpp index 29e6ef834..b83cab966 100644 --- a/strings/knuth_morris_pratt.cpp +++ b/strings/knuth_morris_pratt.cpp @@ -26,17 +26,14 @@ * \param[in] pattern text for which to create the partial match table * \returns the partial match table as a vector array */ -std::vector getFailureArray(const std::string &pattern) -{ +std::vector getFailureArray(const std::string &pattern) { int pattern_length = pattern.size(); std::vector failure(pattern_length + 1); failure[0] = -1; int j = -1; - for (int i = 0; i < pattern_length; i++) - { - while (j != -1 && pattern[j] != pattern[i]) - { + for (int i = 0; i < pattern_length; i++) { + while (j != -1 && pattern[j] != pattern[i]) { j = failure[j]; } j++; @@ -52,16 +49,13 @@ std::vector getFailureArray(const std::string &pattern) * \returns `true` if pattern was found * \returns `false` if pattern was not found */ -bool kmp(const std::string &pattern, const std::string &text) -{ +bool kmp(const std::string &pattern, const std::string &text) { int text_length = text.size(), pattern_length = pattern.size(); std::vector failure = getFailureArray(pattern); int k = 0; - for (int j = 0; j < text_length; j++) - { - while (k != -1 && pattern[k] != text[j]) - { + for (int j = 0; j < text_length; j++) { + while (k != -1 && pattern[k] != text[j]) { k = failure[k]; } k++; @@ -72,28 +66,21 @@ bool kmp(const std::string &pattern, const std::string &text) } /** Main function */ -int main() -{ +int main() { std::string text = "alskfjaldsabc1abc1abc12k23adsfabcabc"; std::string pattern = "abc1abc12l"; - if (kmp(pattern, text) == true) - { + if (kmp(pattern, text) == true) { std::cout << "Found" << std::endl; - } - else - { + } else { std::cout << "Not Found" << std::endl; } text = "abcabc"; pattern = "bca"; - if (kmp(pattern, text) == true) - { + if (kmp(pattern, text) == true) { std::cout << "Found" << std::endl; - } - else - { + } else { std::cout << "Not Found" << std::endl; } diff --git a/strings/rabin_karp.cpp b/strings/rabin_karp.cpp index 5baaaf615..018ff5632 100644 --- a/strings/rabin_karp.cpp +++ b/strings/rabin_karp.cpp @@ -21,11 +21,9 @@ * \param[in] n length of substring to hash * \returns hash integer */ -int64_t create_hash(const std::string& s, int n) -{ +int64_t create_hash(const std::string& s, int n) { int64_t result = 0; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { result += (int64_t)(s[i] * (int64_t)pow(PRIME, i)); } return result; @@ -41,8 +39,7 @@ int64_t create_hash(const std::string& s, int n) * \returns new hash integer */ int64_t recalculate_hash(const std::string& s, int old_index, int new_index, - int64_t old_hash, int patLength) -{ + int64_t old_hash, int patLength) { int64_t new_hash = old_hash - s[old_index]; new_hash /= PRIME; new_hash += (int64_t)(s[new_index] * (int64_t)pow(PRIME, patLength - 1)); @@ -60,16 +57,12 @@ int64_t recalculate_hash(const std::string& s, int old_index, int new_index, * @note can this be replaced by std::string::compare? */ bool check_if_equal(const std::string& str1, const std::string& str2, - int start1, int end1, int start2, int end2) -{ - if (end1 - start1 != end2 - start2) - { + int start1, int end1, int start2, int end2) { + if (end1 - start1 != end2 - start2) { return false; } - while (start1 <= end1 && start2 <= end2) - { - if (str1[start1] != str2[start2]) - { + while (start1 <= end1 && start2 <= end2) { + if (str1[start1] != str2[start2]) { return false; } start1++; @@ -86,19 +79,16 @@ bool check_if_equal(const std::string& str1, const std::string& str2, * @return -1 if pattern not found */ -int rabin_karp(const std::string& str, const std::string& pat) -{ +int rabin_karp(const std::string& str, const std::string& pat) { int64_t pat_hash = create_hash(pat, pat.size()); int64_t str_hash = create_hash(str, pat.size()); - for (int i = 0; i <= str.size() - pat.size(); ++i) - { + for (int i = 0; i <= str.size() - pat.size(); ++i) { if (pat_hash == str_hash && - check_if_equal(str, pat, i, i + pat.size() - 1, 0, pat.size() - 1)) - { + check_if_equal(str, pat, i, i + pat.size() - 1, 0, + pat.size() - 1)) { return i; } - if (i < str.size() - pat.size()) - { + if (i < str.size() - pat.size()) { str_hash = recalculate_hash(str, i, i + pat.size(), str_hash, pat.size()); } @@ -107,8 +97,7 @@ int rabin_karp(const std::string& str, const std::string& pat) } /** Main function */ -int main(void) -{ +int main(void) { assert(rabin_karp("helloWorld", "world") == -1); assert(rabin_karp("helloWorld", "World") == 5); assert(rabin_karp("this_is_c++", "c++") == 8); From 3ab76459cd1e792636d7b55787ea30423efa038a Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sat, 30 May 2020 04:02:28 +0000 Subject: [PATCH 57/57] updating DIRECTORY.md --- DIRECTORY.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/DIRECTORY.md b/DIRECTORY.md index 334538685..21f1a0c61 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,3 +1,4 @@ +# List of all files ## Backtracking * [Graph Coloring](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/graph_coloring.cpp) @@ -77,7 +78,7 @@ * [Connected Components](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/connected_components.cpp) * [Connected Components With Dsu](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/connected_components_with_dsu.cpp) * [Dfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dfs.cpp) - * [Dfs With Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/DFS_with_stack.cc) + * [Dfs With Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dfs_with_stack.cpp) * [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/dijkstra.cpp) * [Kosaraju](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kosaraju.cpp) * [Kruskal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kruskal.cpp)