diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
index e63d7f9453e7..272b1b3059bc 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -1,7 +1,5 @@
---
-name: Bug report
-about: Create a report to help us improve
-title: ''
+name: Bug report about: Create a report to help us improve title: ''
labels: ''
assignees: ''
@@ -12,6 +10,7 @@ A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
+
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
index bbcbbe7d6155..5fe926b25cd2 100644
--- a/.github/ISSUE_TEMPLATE/feature_request.md
+++ b/.github/ISSUE_TEMPLATE/feature_request.md
@@ -1,7 +1,5 @@
---
-name: Feature request
-about: Suggest an idea for this project
-title: ''
+name: Feature request about: Suggest an idea for this project title: ''
labels: ''
assignees: ''
diff --git a/.github/stale.yml b/.github/stale.yml
index 36ca56266b26..2f0ef87ab083 100644
--- a/.github/stale.yml
+++ b/.github/stale.yml
@@ -8,7 +8,7 @@ daysUntilStale: 30
daysUntilClose: 7
# Only issues or pull requests with all of these labels are check if stale. Defaults to `[]` (disabled)
-onlyLabels: []
+onlyLabels: [ ]
# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable
exemptLabels:
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 0ef612678c25..93e3ef09109a 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -4,7 +4,7 @@ on:
pull_request:
push:
branches:
- - master
+ - master
jobs:
build:
diff --git a/.github/workflows/checkstyle.yml b/.github/workflows/checkstyle.yml
index 8424300048a0..9d44726eb065 100644
--- a/.github/workflows/checkstyle.yml
+++ b/.github/workflows/checkstyle.yml
@@ -1,6 +1,6 @@
name: Code Formatter
-on: [push, pull_request]
+on: [ push, pull_request ]
jobs:
format:
runs-on: ubuntu-latest
diff --git a/.github/workflows/prettier.yml b/.github/workflows/prettier.yml
index f1ee3157b4ab..352584425337 100644
--- a/.github/workflows/prettier.yml
+++ b/.github/workflows/prettier.yml
@@ -4,23 +4,23 @@ on:
pull_request:
push:
branches:
- - master
- - Development
+ - master
+ - Development
jobs:
prettier:
runs-on: ubuntu-latest
steps:
- - name: Checkout
- uses: actions/checkout@v2
- with:
- ref: ${{ github.head_ref }}
+ - name: Checkout
+ uses: actions/checkout@v2
+ with:
+ ref: ${{ github.head_ref }}
- - name: Prettify code
- uses: creyD/prettier_action@v3.0
- with:
- prettier_options: --write **/*.{java}
- commit_message: 'feat: prettify code'
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ - name: Prettify code
+ uses: creyD/prettier_action@v3.0
+ with:
+ prettier_options: --write **/*.{java}
+ commit_message: 'feat: prettify code'
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml
index 325fa04502af..dc1266a6f5cc 100644
--- a/.github/workflows/update_directory_md.yml
+++ b/.github/workflows/update_directory_md.yml
@@ -1,6 +1,6 @@
# This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push
name: update_directory_md
-on: [push]
+on: [ push ]
jobs:
update_directory_md:
runs-on: ubuntu-latest
@@ -10,51 +10,51 @@ jobs:
- name: update_directory_md
shell: python
run: |
- import os
- from typing import Iterator
+ import os
+ from typing import Iterator
- URL_BASE = "https://github.com/TheAlgorithms/Java/blob/master"
- g_output = []
+ URL_BASE = "https://github.com/TheAlgorithms/Java/blob/master"
+ g_output = []
- def good_filepaths(top_dir: str = ".") -> Iterator[str]:
- 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() == ".java":
- yield os.path.join(dirpath, filename).lstrip("./")
+ def good_filepaths(top_dir: str = ".") -> Iterator[str]:
+ 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() == ".java":
+ yield os.path.join(dirpath, filename).lstrip("./")
- def md_prefix(i):
- return f"{i * ' '}*" if i else "\n##"
+ 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('_', ' ')}")
- return new_path
+ 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('_', ' ')}")
+ 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("_", " "))[0]
- g_output.append(f"{md_prefix(indent)} [{filename}]({url})")
- return "\n".join(g_output)
+ 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("_", " "))[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")
+ with open("DIRECTORY.md", "w") as out_file:
+ out_file.write(build_directory_md(".") + "\n")
- name: Update DIRECTORY.md
run: |
diff --git a/Maths/AbsoluteMax.java b/Maths/AbsoluteMax.java
index fe1376232322..d9d2d34aeb05 100644
--- a/Maths/AbsoluteMax.java
+++ b/Maths/AbsoluteMax.java
@@ -8,27 +8,27 @@
*
absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10
*/
public class AbsoluteMax {
- public static void main(String[] args) {
- int[] testnums = {-2, 0, 16};
- assert absMax(testnums) == 16;
+ public static void main(String[] args) {
+ int[] testnums = {-2, 0, 16};
+ assert absMax(testnums) == 16;
- int[] numbers = {3, -10, -2};
- System.out.println("absMax(" + Arrays.toString(numbers) + ") = " + absMax(numbers));
- }
+ int[] numbers = {3, -10, -2};
+ System.out.println("absMax(" + Arrays.toString(numbers) + ") = " + absMax(numbers));
+ }
- /**
- * get the value, return the absolute max value
- *
- * @param numbers contains elements
- * @return the absolute max value
- */
- public static int absMax(int[] numbers) {
- int absMaxValue = numbers[0];
- for (int i = 1, length = numbers.length; i < length; ++i) {
- if (Math.abs(numbers[i]) > Math.abs(absMaxValue)) {
- absMaxValue = numbers[i];
- }
+ /**
+ * get the value, return the absolute max value
+ *
+ * @param numbers contains elements
+ * @return the absolute max value
+ */
+ public static int absMax(int[] numbers) {
+ int absMaxValue = numbers[0];
+ for (int i = 1, length = numbers.length; i < length; ++i) {
+ if (Math.abs(numbers[i]) > Math.abs(absMaxValue)) {
+ absMaxValue = numbers[i];
+ }
+ }
+ return absMaxValue;
}
- return absMaxValue;
- }
}
diff --git a/Maths/AbsoluteMin.java b/Maths/AbsoluteMin.java
index 8e8c71fdbb29..13dd3939c877 100644
--- a/Maths/AbsoluteMin.java
+++ b/Maths/AbsoluteMin.java
@@ -8,27 +8,27 @@
*
absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2
*/
public class AbsoluteMin {
- public static void main(String[] args) {
- int[] testnums = {4, 0, 16};
- assert absMin(testnums) == 0;
+ public static void main(String[] args) {
+ int[] testnums = {4, 0, 16};
+ assert absMin(testnums) == 0;
- int[] numbers = {3, -10, -2};
- System.out.println("absMin(" + Arrays.toString(numbers) + ") = " + absMin(numbers));
- }
+ int[] numbers = {3, -10, -2};
+ System.out.println("absMin(" + Arrays.toString(numbers) + ") = " + absMin(numbers));
+ }
- /**
- * get the value, returns the absolute min value min
- *
- * @param numbers contains elements
- * @return the absolute min value
- */
- public static int absMin(int[] numbers) {
- int absMinValue = numbers[0];
- for (int i = 1, length = numbers.length; i < length; ++i) {
- if (Math.abs(numbers[i]) < Math.abs(absMinValue)) {
- absMinValue = numbers[i];
- }
+ /**
+ * get the value, returns the absolute min value min
+ *
+ * @param numbers contains elements
+ * @return the absolute min value
+ */
+ public static int absMin(int[] numbers) {
+ int absMinValue = numbers[0];
+ for (int i = 1, length = numbers.length; i < length; ++i) {
+ if (Math.abs(numbers[i]) < Math.abs(absMinValue)) {
+ absMinValue = numbers[i];
+ }
+ }
+ return absMinValue;
}
- return absMinValue;
- }
}
diff --git a/Maths/AbsoluteValue.java b/Maths/AbsoluteValue.java
index d465de67d4ff..2bd8b5378b81 100644
--- a/Maths/AbsoluteValue.java
+++ b/Maths/AbsoluteValue.java
@@ -4,23 +4,23 @@
public class AbsoluteValue {
- public static void main(String[] args) {
- Random random = new Random();
+ public static void main(String[] args) {
+ Random random = new Random();
- /* test 1000 random numbers */
- for (int i = 1; i <= 1000; ++i) {
- int randomNumber = random.nextInt();
- assert absVal(randomNumber) == Math.abs(randomNumber);
+ /* test 1000 random numbers */
+ for (int i = 1; i <= 1000; ++i) {
+ int randomNumber = random.nextInt();
+ assert absVal(randomNumber) == Math.abs(randomNumber);
+ }
}
- }
- /**
- * If value is less than zero, make value positive.
- *
- * @param value a number
- * @return the absolute value of a number
- */
- public static int absVal(int value) {
- return value < 0 ? -value : value;
- }
+ /**
+ * If value is less than zero, make value positive.
+ *
+ * @param value a number
+ * @return the absolute value of a number
+ */
+ public static int absVal(int value) {
+ return value < 0 ? -value : value;
+ }
}
diff --git a/Maths/AliquotSum.java b/Maths/AliquotSum.java
index 09b7c730b159..368317b99ec6 100644
--- a/Maths/AliquotSum.java
+++ b/Maths/AliquotSum.java
@@ -7,26 +7,26 @@
* sum of 15 is 9 i.e. (1 + 3 + 5). Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum
*/
public class AliquotSum {
- public static void main(String[] args) {
- assert aliquotSum(1) == 0;
- assert aliquotSum(6) == 6;
- assert aliquotSum(15) == 9;
- assert aliquotSum(19) == 1;
- }
+ public static void main(String[] args) {
+ assert aliquotSum(1) == 0;
+ assert aliquotSum(6) == 6;
+ assert aliquotSum(15) == 9;
+ assert aliquotSum(19) == 1;
+ }
- /**
- * Finds the aliquot sum of an integer number
- *
- * @param number a positive integer
- * @return aliquot sum of given {@code number}
- */
- public static int aliquotSum(int number) {
- int sum = 0;
- for (int i = 1, limit = number / 2; i <= limit; ++i) {
- if (number % i == 0) {
- sum += i;
- }
+ /**
+ * Finds the aliquot sum of an integer number
+ *
+ * @param number a positive integer
+ * @return aliquot sum of given {@code number}
+ */
+ public static int aliquotSum(int number) {
+ int sum = 0;
+ for (int i = 1, limit = number / 2; i <= limit; ++i) {
+ if (number % i == 0) {
+ sum += i;
+ }
+ }
+ return sum;
}
- return sum;
- }
}
diff --git a/Maths/AmicableNumber.java b/Maths/AmicableNumber.java
index 4080ce6263a0..6fa7b564f839 100644
--- a/Maths/AmicableNumber.java
+++ b/Maths/AmicableNumber.java
@@ -15,73 +15,73 @@
*/
public class AmicableNumber {
- public static void main(String[] args) {
+ public static void main(String[] args) {
- AmicableNumber.findAllInRange(1, 3000);
+ AmicableNumber.findAllInRange(1, 3000);
/* Res -> Int Range of 1 till 3000there are 3Amicable_numbers These are 1: = ( 220,284) 2: = ( 1184,1210)
3: = ( 2620,2924) So it worked */
- }
+ }
- /**
- * @param startValue
- * @param stopValue
- * @return
- */
- static void findAllInRange(int startValue, int stopValue) {
+ /**
+ * @param startValue
+ * @param stopValue
+ * @return
+ */
+ static void findAllInRange(int startValue, int stopValue) {
- /* the 2 for loops are to avoid to double check tuple. For example (200,100) and (100,200) is the same calculation
- * also to avoid is to check the number with it self. a number with itself is always a AmicableNumber
- * */
- StringBuilder res = new StringBuilder();
- int countofRes = 0;
+ /* the 2 for loops are to avoid to double check tuple. For example (200,100) and (100,200) is the same calculation
+ * also to avoid is to check the number with it self. a number with itself is always a AmicableNumber
+ * */
+ StringBuilder res = new StringBuilder();
+ int countofRes = 0;
- for (int i = startValue; i < stopValue; i++) {
- for (int j = i + 1; j <= stopValue; j++) {
- if (isAmicableNumber(i, j)) {
- countofRes++;
- res.append("" + countofRes + ": = ( " + i + "," + j + ")" + "\t");
+ for (int i = startValue; i < stopValue; i++) {
+ for (int j = i + 1; j <= stopValue; j++) {
+ if (isAmicableNumber(i, j)) {
+ countofRes++;
+ res.append("" + countofRes + ": = ( " + i + "," + j + ")" + "\t");
+ }
+ }
}
- }
+ res.insert(
+ 0,
+ "Int Range of "
+ + startValue
+ + " till "
+ + stopValue
+ + " there are "
+ + countofRes
+ + " Amicable_numbers.These are \n ");
+ System.out.println(res.toString());
}
- res.insert(
- 0,
- "Int Range of "
- + startValue
- + " till "
- + stopValue
- + " there are "
- + countofRes
- + " Amicable_numbers.These are \n ");
- System.out.println(res.toString());
- }
- /**
- * Check if {@code numberOne and numberTwo } are AmicableNumbers or not
- *
- * @param numberOne numberTwo
- * @return {@code true} if {@code numberOne numberTwo} isAmicableNumbers otherwise false
- */
- static boolean isAmicableNumber(int numberOne, int numberTwo) {
+ /**
+ * Check if {@code numberOne and numberTwo } are AmicableNumbers or not
+ *
+ * @param numberOne numberTwo
+ * @return {@code true} if {@code numberOne numberTwo} isAmicableNumbers otherwise false
+ */
+ static boolean isAmicableNumber(int numberOne, int numberTwo) {
- return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo
- && numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo)));
- }
+ return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo
+ && numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo)));
+ }
- /**
- * calculated in recursive calls the Sum of all the Dividers beside it self
- *
- * @param number div = the next to test dividely by using the modulo operator
- * @return sum of all the dividers
- */
- static int recursiveCalcOfDividerSum(int number, int div) {
+ /**
+ * calculated in recursive calls the Sum of all the Dividers beside it self
+ *
+ * @param number div = the next to test dividely by using the modulo operator
+ * @return sum of all the dividers
+ */
+ static int recursiveCalcOfDividerSum(int number, int div) {
- if (div == 1) {
- return 0;
- } else if (number % --div == 0) {
- return recursiveCalcOfDividerSum(number, div) + div;
- } else {
- return recursiveCalcOfDividerSum(number, div);
+ if (div == 1) {
+ return 0;
+ } else if (number % --div == 0) {
+ return recursiveCalcOfDividerSum(number, div) + div;
+ } else {
+ return recursiveCalcOfDividerSum(number, div);
+ }
}
- }
}
diff --git a/Maths/Area.java b/Maths/Area.java
index ea1db120b779..56955875f57f 100644
--- a/Maths/Area.java
+++ b/Maths/Area.java
@@ -1,117 +1,119 @@
package Maths;
-/** Find the area of various geometric shapes */
+/**
+ * Find the area of various geometric shapes
+ */
public class Area {
- public static void main(String[] args) {
-
- /* test cube */
- assert Double.compare(surfaceAreaCube(1), 6.0) == 0;
-
- /* test sphere */
- assert Double.compare(surfaceAreaSphere(5), 314.1592653589793) == 0;
- assert Double.compare(surfaceAreaSphere(1), 12.566370614359172) == 0;
-
- /* test rectangle */
- assert Double.compare(surfaceAreaRectangle(10, 20), 200.0) == 0;
-
- /* test square */
- assert Double.compare(surfaceAreaSquare(10), 100.0) == 0;
-
- /* test triangle */
- assert Double.compare(surfaceAreaTriangle(10, 10), 50.0) == 0;
-
- /* test parallelogram */
- assert Double.compare(surfaceAreaParallelogram(10, 20), 200.0) == 0;
-
- /* test trapezium */
- assert Double.compare(surfaceAreaTrapezium(10, 20, 30), 450.0) == 0;
-
- /* test circle */
- assert Double.compare(surfaceAreaCircle(20), 1256.6370614359173) == 0;
- }
-
- /**
- * Calculate the surface area of a cube.
- *
- * @param sideLength side length of cube
- * @return surface area of given cube
- */
- private static double surfaceAreaCube(double sideLength) {
- return 6 * sideLength * sideLength;
- }
-
- /**
- * Calculate the surface area of a sphere.
- *
- * @param radius radius of sphere
- * @return surface area of given sphere
- */
- private static double surfaceAreaSphere(double radius) {
- return 4 * Math.PI * radius * radius;
- }
-
- /**
- * Calculate the area of a rectangle
- *
- * @param length length of rectangle
- * @param width width of rectangle
- * @return area of given rectangle
- */
- private static double surfaceAreaRectangle(double length, double width) {
- return length * width;
- }
-
- /**
- * Calculate the area of a square
- *
- * @param sideLength side length of square
- * @return area of given square
- */
- private static double surfaceAreaSquare(double sideLength) {
- return sideLength * sideLength;
- }
-
- /**
- * Calculate the area of a triangle
- *
- * @param base base of triangle
- * @param height height of triangle
- * @return area of given triangle
- */
- private static double surfaceAreaTriangle(double base, double height) {
- return base * height / 2;
- }
-
- /**
- * Calculate the area of a parallelogram
- *
- * @param base base of parallelogram
- * @param height height of parallelogram
- * @return area of given parallelogram
- */
- private static double surfaceAreaParallelogram(double base, double height) {
- return base * height;
- }
-
- /**
- * Calculate the area of a trapezium
- *
- * @param base1 upper base of trapezium
- * @param base2 bottom base of trapezium
- * @param height height of trapezium
- * @return area of given trapezium
- */
- private static double surfaceAreaTrapezium(double base1, double base2, double height) {
- return (base1 + base2) * height / 2;
- }
-
- /**
- * Calculate the area of a circle
- *
- * @param radius radius of circle
- * @return area of given circle
- */
- private static double surfaceAreaCircle(double radius) {
- return Math.PI * radius * radius;
- }
+ public static void main(String[] args) {
+
+ /* test cube */
+ assert Double.compare(surfaceAreaCube(1), 6.0) == 0;
+
+ /* test sphere */
+ assert Double.compare(surfaceAreaSphere(5), 314.1592653589793) == 0;
+ assert Double.compare(surfaceAreaSphere(1), 12.566370614359172) == 0;
+
+ /* test rectangle */
+ assert Double.compare(surfaceAreaRectangle(10, 20), 200.0) == 0;
+
+ /* test square */
+ assert Double.compare(surfaceAreaSquare(10), 100.0) == 0;
+
+ /* test triangle */
+ assert Double.compare(surfaceAreaTriangle(10, 10), 50.0) == 0;
+
+ /* test parallelogram */
+ assert Double.compare(surfaceAreaParallelogram(10, 20), 200.0) == 0;
+
+ /* test trapezium */
+ assert Double.compare(surfaceAreaTrapezium(10, 20, 30), 450.0) == 0;
+
+ /* test circle */
+ assert Double.compare(surfaceAreaCircle(20), 1256.6370614359173) == 0;
+ }
+
+ /**
+ * Calculate the surface area of a cube.
+ *
+ * @param sideLength side length of cube
+ * @return surface area of given cube
+ */
+ private static double surfaceAreaCube(double sideLength) {
+ return 6 * sideLength * sideLength;
+ }
+
+ /**
+ * Calculate the surface area of a sphere.
+ *
+ * @param radius radius of sphere
+ * @return surface area of given sphere
+ */
+ private static double surfaceAreaSphere(double radius) {
+ return 4 * Math.PI * radius * radius;
+ }
+
+ /**
+ * Calculate the area of a rectangle
+ *
+ * @param length length of rectangle
+ * @param width width of rectangle
+ * @return area of given rectangle
+ */
+ private static double surfaceAreaRectangle(double length, double width) {
+ return length * width;
+ }
+
+ /**
+ * Calculate the area of a square
+ *
+ * @param sideLength side length of square
+ * @return area of given square
+ */
+ private static double surfaceAreaSquare(double sideLength) {
+ return sideLength * sideLength;
+ }
+
+ /**
+ * Calculate the area of a triangle
+ *
+ * @param base base of triangle
+ * @param height height of triangle
+ * @return area of given triangle
+ */
+ private static double surfaceAreaTriangle(double base, double height) {
+ return base * height / 2;
+ }
+
+ /**
+ * Calculate the area of a parallelogram
+ *
+ * @param base base of parallelogram
+ * @param height height of parallelogram
+ * @return area of given parallelogram
+ */
+ private static double surfaceAreaParallelogram(double base, double height) {
+ return base * height;
+ }
+
+ /**
+ * Calculate the area of a trapezium
+ *
+ * @param base1 upper base of trapezium
+ * @param base2 bottom base of trapezium
+ * @param height height of trapezium
+ * @return area of given trapezium
+ */
+ private static double surfaceAreaTrapezium(double base1, double base2, double height) {
+ return (base1 + base2) * height / 2;
+ }
+
+ /**
+ * Calculate the area of a circle
+ *
+ * @param radius radius of circle
+ * @return area of given circle
+ */
+ private static double surfaceAreaCircle(double radius) {
+ return Math.PI * radius * radius;
+ }
}
diff --git a/Maths/Armstrong.java b/Maths/Armstrong.java
index e41e85d062fd..deb99097e0c3 100644
--- a/Maths/Armstrong.java
+++ b/Maths/Armstrong.java
@@ -7,38 +7,38 @@
*/
public class Armstrong {
- public static void main(String[] args) {
- assert (isArmStrong(0));
- assert (isArmStrong(1));
- assert (isArmStrong(153));
- assert (isArmStrong(1634));
- assert (isArmStrong(371));
- assert (!isArmStrong(200));
- }
-
- /**
- * Checks whether a given number is an armstrong number or not.
- *
- * @param number number to check
- * @return {@code true} if given number is armstrong number, {@code false} otherwise
- */
- private static boolean isArmStrong(int number) {
- int sum = 0;
- int temp = number;
- int numberOfDigits = 0;
- while (temp != 0) {
- numberOfDigits++;
- temp /= 10;
+ public static void main(String[] args) {
+ assert (isArmStrong(0));
+ assert (isArmStrong(1));
+ assert (isArmStrong(153));
+ assert (isArmStrong(1634));
+ assert (isArmStrong(371));
+ assert (!isArmStrong(200));
}
- temp = number; /* copy number again */
- while (number > 0) {
- int remainder = number % 10;
- int power = 1;
- for (int i = 1; i <= numberOfDigits; power *= remainder, ++i)
- ;
- sum = sum + power;
- number /= 10;
+
+ /**
+ * Checks whether a given number is an armstrong number or not.
+ *
+ * @param number number to check
+ * @return {@code true} if given number is armstrong number, {@code false} otherwise
+ */
+ private static boolean isArmStrong(int number) {
+ int sum = 0;
+ int temp = number;
+ int numberOfDigits = 0;
+ while (temp != 0) {
+ numberOfDigits++;
+ temp /= 10;
+ }
+ temp = number; /* copy number again */
+ while (number > 0) {
+ int remainder = number % 10;
+ int power = 1;
+ for (int i = 1; i <= numberOfDigits; power *= remainder, ++i)
+ ;
+ sum = sum + power;
+ number /= 10;
+ }
+ return sum == temp;
}
- return sum == temp;
- }
}
diff --git a/Maths/Average.java b/Maths/Average.java
index 5c66569a642e..81edb15e61f0 100644
--- a/Maths/Average.java
+++ b/Maths/Average.java
@@ -1,42 +1,44 @@
package Maths;
-/** Calculate average of a list of numbers */
+/**
+ * Calculate average of a list of numbers
+ */
public class Average {
- private static final double SMALL_VALUE = 0.00001f;
+ private static final double SMALL_VALUE = 0.00001f;
- public static void main(String[] args) {
- assert Math.abs(average(new double[] {3, 6, 9, 12, 15, 18, 21}) - 12) < SMALL_VALUE;
- assert Math.abs(average(new double[] {5, 10, 15, 20, 25, 30, 35}) - 20) < SMALL_VALUE;
- assert Math.abs(average(new double[] {1, 2, 3, 4, 5, 6, 7, 8}) - 4.5) < SMALL_VALUE;
- int[] array = {2, 4, 10};
- assert average(array) == 5;
- }
+ public static void main(String[] args) {
+ assert Math.abs(average(new double[]{3, 6, 9, 12, 15, 18, 21}) - 12) < SMALL_VALUE;
+ assert Math.abs(average(new double[]{5, 10, 15, 20, 25, 30, 35}) - 20) < SMALL_VALUE;
+ assert Math.abs(average(new double[]{1, 2, 3, 4, 5, 6, 7, 8}) - 4.5) < SMALL_VALUE;
+ int[] array = {2, 4, 10};
+ assert average(array) == 5;
+ }
- /**
- * Calculate average of a list of numbers
- *
- * @param numbers array to store numbers
- * @return mean of given numbers
- */
- public static double average(double[] numbers) {
- double sum = 0;
- for (double number : numbers) {
- sum += number;
+ /**
+ * Calculate average of a list of numbers
+ *
+ * @param numbers array to store numbers
+ * @return mean of given numbers
+ */
+ public static double average(double[] numbers) {
+ double sum = 0;
+ for (double number : numbers) {
+ sum += number;
+ }
+ return sum / numbers.length;
}
- return sum / numbers.length;
- }
- /**
- * find average value of int array
- *
- * @param array the array contains element and the sum does not excess long value limit
- * @return average value
- */
- public static int average(int[] array) {
- long sum = 0;
- for (int i = 0; i < array.length; ++i) {
- sum += array[i];
+ /**
+ * find average value of int array
+ *
+ * @param array the array contains element and the sum does not excess long value limit
+ * @return average value
+ */
+ public static int average(int[] array) {
+ long sum = 0;
+ for (int i = 0; i < array.length; ++i) {
+ sum += array[i];
+ }
+ return (int) (sum / array.length);
}
- return (int) (sum / array.length);
- }
}
diff --git a/Maths/BinaryPow.java b/Maths/BinaryPow.java
index b9d5b68fa7d4..8162ab3d4ba6 100644
--- a/Maths/BinaryPow.java
+++ b/Maths/BinaryPow.java
@@ -1,48 +1,48 @@
package Maths;
public class BinaryPow {
- /**
- * Calculate a^p using binary exponentiation
- * [Binary-Exponentiation](https://cp-algorithms.com/algebra/binary-exp.html)
- *
- * @param a the base for exponentiation
- * @param p the exponent - must be greater than 0
- * @return a^p
- */
- public static int binPow(int a, int p) {
- int res = 1;
- while (p > 0) {
- if ((p & 1) == 1) {
- res = res * a;
- }
- a = a * a;
- p >>>= 1;
+ /**
+ * Calculate a^p using binary exponentiation
+ * [Binary-Exponentiation](https://cp-algorithms.com/algebra/binary-exp.html)
+ *
+ * @param a the base for exponentiation
+ * @param p the exponent - must be greater than 0
+ * @return a^p
+ */
+ public static int binPow(int a, int p) {
+ int res = 1;
+ while (p > 0) {
+ if ((p & 1) == 1) {
+ res = res * a;
+ }
+ a = a * a;
+ p >>>= 1;
+ }
+ return res;
}
- return res;
- }
- /**
- * Function for testing binary exponentiation
- *
- * @param a the base
- * @param p the exponent
- */
- public static void test(int a, int p) {
- int res = binPow(a, p);
- assert res == (int) Math.pow(a, p) : "Incorrect Implementation";
- System.out.println(a + "^" + p + ": " + res);
- }
+ /**
+ * Function for testing binary exponentiation
+ *
+ * @param a the base
+ * @param p the exponent
+ */
+ public static void test(int a, int p) {
+ int res = binPow(a, p);
+ assert res == (int) Math.pow(a, p) : "Incorrect Implementation";
+ System.out.println(a + "^" + p + ": " + res);
+ }
- /**
- * Main Function to call tests
- *
- * @param args System Line Arguments
- */
- public static void main(String[] args) {
- // prints 2^15: 32768
- test(2, 15);
+ /**
+ * Main Function to call tests
+ *
+ * @param args System Line Arguments
+ */
+ public static void main(String[] args) {
+ // prints 2^15: 32768
+ test(2, 15);
- // prints 3^9: 19683
- test(3, 9);
- }
+ // prints 3^9: 19683
+ test(3, 9);
+ }
}
diff --git a/Maths/Ceil.java b/Maths/Ceil.java
index fd6d8300a4c9..e9c249533f12 100644
--- a/Maths/Ceil.java
+++ b/Maths/Ceil.java
@@ -3,27 +3,27 @@
import java.util.Random;
public class Ceil {
- public static void main(String[] args) {
- Random random = new Random();
- for (int i = 1; i <= 1000; ++i) {
- double randomNumber = random.nextDouble();
- assert ceil(randomNumber) == Math.ceil(randomNumber);
+ public static void main(String[] args) {
+ Random random = new Random();
+ for (int i = 1; i <= 1000; ++i) {
+ double randomNumber = random.nextDouble();
+ assert ceil(randomNumber) == Math.ceil(randomNumber);
+ }
}
- }
- /**
- * Returns the smallest (closest to negative infinity)
- *
- * @param number the number
- * @return the smallest (closest to negative infinity) of given {@code number}
- */
- public static double ceil(double number) {
- if (number - (int) number == 0) {
- return number;
- } else if (number - (int) number > 0) {
- return (int) (number + 1);
- } else {
- return (int) number;
+ /**
+ * Returns the smallest (closest to negative infinity)
+ *
+ * @param number the number
+ * @return the smallest (closest to negative infinity) of given {@code number}
+ */
+ public static double ceil(double number) {
+ if (number - (int) number == 0) {
+ return number;
+ } else if (number - (int) number > 0) {
+ return (int) (number + 1);
+ } else {
+ return (int) number;
+ }
}
- }
}
diff --git a/Maths/Combinations.java b/Maths/Combinations.java
index 0fb2437c21f3..4ff237bb362f 100644
--- a/Maths/Combinations.java
+++ b/Maths/Combinations.java
@@ -1,35 +1,37 @@
package Maths;
-/** @see Combination */
+/**
+ * @see Combination
+ */
public class Combinations {
- public static void main(String[] args) {
- assert combinations(1, 1) == 1;
- assert combinations(10, 5) == 252;
- assert combinations(6, 3) == 20;
- assert combinations(20, 5) == 15504;
- }
+ public static void main(String[] args) {
+ assert combinations(1, 1) == 1;
+ assert combinations(10, 5) == 252;
+ assert combinations(6, 3) == 20;
+ assert combinations(20, 5) == 15504;
+ }
- /**
- * Calculate of factorial
- *
- * @param n the number
- * @return factorial of given number
- */
- public static long factorial(int n) {
- if (n < 0) {
- throw new IllegalArgumentException("number is negative");
+ /**
+ * Calculate of factorial
+ *
+ * @param n the number
+ * @return factorial of given number
+ */
+ public static long factorial(int n) {
+ if (n < 0) {
+ throw new IllegalArgumentException("number is negative");
+ }
+ return n == 0 || n == 1 ? 1 : n * factorial(n - 1);
}
- return n == 0 || n == 1 ? 1 : n * factorial(n - 1);
- }
- /**
- * Calculate combinations
- *
- * @param n first number
- * @param k second number
- * @return combinations of given {@code n} and {@code k}
- */
- public static long combinations(int n, int k) {
- return factorial(n) / (factorial(k) * factorial(n - k));
- }
+ /**
+ * Calculate combinations
+ *
+ * @param n first number
+ * @param k second number
+ * @return combinations of given {@code n} and {@code k}
+ */
+ public static long combinations(int n, int k) {
+ return factorial(n) / (factorial(k) * factorial(n - k));
+ }
}
diff --git a/Maths/Factorial.java b/Maths/Factorial.java
index 3bd2e74a4864..943c440d95a8 100644
--- a/Maths/Factorial.java
+++ b/Maths/Factorial.java
@@ -2,27 +2,27 @@
public class Factorial {
- /* Driver Code */
- public static void main(String[] args) {
- assert factorial(0) == 1;
- assert factorial(1) == 1;
- assert factorial(5) == 120;
- assert factorial(10) == 3628800;
- }
+ /* Driver Code */
+ public static void main(String[] args) {
+ assert factorial(0) == 1;
+ assert factorial(1) == 1;
+ assert factorial(5) == 120;
+ assert factorial(10) == 3628800;
+ }
- /**
- * Calculate factorial N using iteration
- *
- * @param n the number
- * @return the factorial of {@code n}
- */
- public static long factorial(int n) {
- if (n < 0) {
- throw new IllegalArgumentException("number is negative");
+ /**
+ * Calculate factorial N using iteration
+ *
+ * @param n the number
+ * @return the factorial of {@code n}
+ */
+ public static long factorial(int n) {
+ if (n < 0) {
+ throw new IllegalArgumentException("number is negative");
+ }
+ long factorial = 1;
+ for (int i = 1; i <= n; factorial *= i, ++i)
+ ;
+ return factorial;
}
- long factorial = 1;
- for (int i = 1; i <= n; factorial *= i, ++i)
- ;
- return factorial;
- }
}
diff --git a/Maths/FactorialRecursion.java b/Maths/FactorialRecursion.java
index e580fe9b1ba6..6e12d0babbcd 100644
--- a/Maths/FactorialRecursion.java
+++ b/Maths/FactorialRecursion.java
@@ -2,25 +2,25 @@
public class FactorialRecursion {
- /* Driver Code */
- public static void main(String[] args) {
- assert factorial(0) == 1;
- assert factorial(1) == 1;
- assert factorial(2) == 2;
- assert factorial(3) == 6;
- assert factorial(5) == 120;
- }
+ /* Driver Code */
+ public static void main(String[] args) {
+ assert factorial(0) == 1;
+ assert factorial(1) == 1;
+ assert factorial(2) == 2;
+ assert factorial(3) == 6;
+ assert factorial(5) == 120;
+ }
- /**
- * Recursive FactorialRecursion Method
- *
- * @param n The number to factorial
- * @return The factorial of the number
- */
- public static long factorial(int n) {
- if (n < 0) {
- throw new IllegalArgumentException("number is negative");
+ /**
+ * Recursive FactorialRecursion Method
+ *
+ * @param n The number to factorial
+ * @return The factorial of the number
+ */
+ public static long factorial(int n) {
+ if (n < 0) {
+ throw new IllegalArgumentException("number is negative");
+ }
+ return n == 0 || n == 1 ? 1 : n * factorial(n - 1);
}
- return n == 0 || n == 1 ? 1 : n * factorial(n - 1);
- }
}
diff --git a/Maths/FibonacciNumber.java b/Maths/FibonacciNumber.java
index 1cec0963d30c..1f52666634aa 100644
--- a/Maths/FibonacciNumber.java
+++ b/Maths/FibonacciNumber.java
@@ -1,35 +1,37 @@
package Maths;
-/** Fibonacci: 0 1 1 2 3 5 8 13 21 ... */
+/**
+ * Fibonacci: 0 1 1 2 3 5 8 13 21 ...
+ */
public class FibonacciNumber {
- public static void main(String[] args) {
- assert isFibonacciNumber(1);
- assert isFibonacciNumber(2);
- assert isFibonacciNumber(21);
- assert !isFibonacciNumber(9);
- assert !isFibonacciNumber(10);
- }
+ public static void main(String[] args) {
+ assert isFibonacciNumber(1);
+ assert isFibonacciNumber(2);
+ assert isFibonacciNumber(21);
+ assert !isFibonacciNumber(9);
+ assert !isFibonacciNumber(10);
+ }
- /**
- * Check if a number is perfect square number
- *
- * @param number the number to be checked
- * @return true if {@code number} is perfect square, otherwise false
- */
- public static boolean isPerfectSquare(int number) {
- int sqrt = (int) Math.sqrt(number);
- return sqrt * sqrt == number;
- }
+ /**
+ * Check if a number is perfect square number
+ *
+ * @param number the number to be checked
+ * @return true if {@code number} is perfect square, otherwise false
+ */
+ public static boolean isPerfectSquare(int number) {
+ int sqrt = (int) Math.sqrt(number);
+ return sqrt * sqrt == number;
+ }
- /**
- * Check if a number is fibonacci number This is true if and only if at least one of 5x^2+4 or
- * 5x^2-4 is a perfect square
- *
- * @param number the number
- * @return true if {@code number} is fibonacci number, otherwise false
- * @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification
- */
- public static boolean isFibonacciNumber(int number) {
- return isPerfectSquare(5 * number * number + 4) || isPerfectSquare(5 * number * number - 4);
- }
+ /**
+ * Check if a number is fibonacci number This is true if and only if at least one of 5x^2+4 or
+ * 5x^2-4 is a perfect square
+ *
+ * @param number the number
+ * @return true if {@code number} is fibonacci number, otherwise false
+ * @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification
+ */
+ public static boolean isFibonacciNumber(int number) {
+ return isPerfectSquare(5 * number * number + 4) || isPerfectSquare(5 * number * number - 4);
+ }
}
diff --git a/Maths/FindMax.java b/Maths/FindMax.java
index 961b23380a3a..1a332367de15 100644
--- a/Maths/FindMax.java
+++ b/Maths/FindMax.java
@@ -5,35 +5,37 @@
public class FindMax {
- /** Driver Code */
- public static void main(String[] args) {
- Random random = new Random();
+ /**
+ * Driver Code
+ */
+ public static void main(String[] args) {
+ Random random = new Random();
- /* random size */
- int size = random.nextInt(100) + 1;
- int[] array = new int[size];
+ /* random size */
+ int size = random.nextInt(100) + 1;
+ int[] array = new int[size];
- /* init array with random numbers */
- for (int i = 0; i < size; i++) {
- array[i] = random.nextInt() % 100;
- }
+ /* init array with random numbers */
+ for (int i = 0; i < size; i++) {
+ array[i] = random.nextInt() % 100;
+ }
- assert Arrays.stream(array).max().getAsInt() == findMax(array);
- }
+ assert Arrays.stream(array).max().getAsInt() == findMax(array);
+ }
- /**
- * find max of array
- *
- * @param array the array contains element
- * @return max value of given array
- */
- public static int findMax(int[] array) {
- int max = array[0];
- for (int i = 1; i < array.length; ++i) {
- if (array[i] > max) {
- max = array[i];
- }
+ /**
+ * find max of array
+ *
+ * @param array the array contains element
+ * @return max value of given array
+ */
+ public static int findMax(int[] array) {
+ int max = array[0];
+ for (int i = 1; i < array.length; ++i) {
+ if (array[i] > max) {
+ max = array[i];
+ }
+ }
+ return max;
}
- return max;
- }
}
diff --git a/Maths/FindMaxRecursion.java b/Maths/FindMaxRecursion.java
index 38fe2dae8ac5..55f76544365b 100644
--- a/Maths/FindMaxRecursion.java
+++ b/Maths/FindMaxRecursion.java
@@ -4,51 +4,51 @@
import java.util.Random;
public class FindMaxRecursion {
- public static void main(String[] args) {
- Random rand = new Random();
+ public static void main(String[] args) {
+ Random rand = new Random();
- /* rand size */
- int size = rand.nextInt(100) + 1;
- int[] array = new int[size];
+ /* rand size */
+ int size = rand.nextInt(100) + 1;
+ int[] array = new int[size];
- /* init array with rand numbers */
- for (int i = 0; i < size; i++) {
- array[i] = rand.nextInt() % 100;
- }
+ /* init array with rand numbers */
+ for (int i = 0; i < size; i++) {
+ array[i] = rand.nextInt() % 100;
+ }
- assert max(array, array.length) == Arrays.stream(array).max().getAsInt();
- assert max(array, 0, array.length - 1) == Arrays.stream(array).max().getAsInt();
- }
-
- /**
- * Get max of array using divide and conquer algorithm
- *
- * @param array contains elements
- * @param low the index of the first element
- * @param high the index of the last element
- * @return max of {@code array}
- */
- public static int max(int[] array, int low, int high) {
- if (low == high) {
- return array[low]; // or array[high]
+ assert max(array, array.length) == Arrays.stream(array).max().getAsInt();
+ assert max(array, 0, array.length - 1) == Arrays.stream(array).max().getAsInt();
}
- int mid = (low + high) >>> 1;
-
- int leftMax = max(array, low, mid); // get max in [low, mid]
- int rightMax = max(array, mid + 1, high); // get max in [mid+1, high]
-
- return Math.max(leftMax, rightMax);
- }
+ /**
+ * Get max of array using divide and conquer algorithm
+ *
+ * @param array contains elements
+ * @param low the index of the first element
+ * @param high the index of the last element
+ * @return max of {@code array}
+ */
+ public static int max(int[] array, int low, int high) {
+ if (low == high) {
+ return array[low]; // or array[high]
+ }
+
+ int mid = (low + high) >>> 1;
+
+ int leftMax = max(array, low, mid); // get max in [low, mid]
+ int rightMax = max(array, mid + 1, high); // get max in [mid+1, high]
+
+ return Math.max(leftMax, rightMax);
+ }
- /**
- * Get max of array using recursion algorithm
- *
- * @param array contains elements
- * @param len length of given array
- * @return max value of {@code array}
- */
- public static int max(int[] array, int len) {
- return len == 1 ? array[0] : Math.max(max(array, len - 1), array[len - 1]);
- }
+ /**
+ * Get max of array using recursion algorithm
+ *
+ * @param array contains elements
+ * @param len length of given array
+ * @return max value of {@code array}
+ */
+ public static int max(int[] array, int len) {
+ return len == 1 ? array[0] : Math.max(max(array, len - 1), array[len - 1]);
+ }
}
diff --git a/Maths/FindMin.java b/Maths/FindMin.java
index 198bd1e93a7b..b8996cd106eb 100644
--- a/Maths/FindMin.java
+++ b/Maths/FindMin.java
@@ -5,35 +5,37 @@
public class FindMin {
- /** Driver Code */
- public static void main(String[] args) {
- Random random = new Random();
+ /**
+ * Driver Code
+ */
+ public static void main(String[] args) {
+ Random random = new Random();
- /* random size */
- int size = random.nextInt(100) + 1;
- int[] array = new int[size];
+ /* random size */
+ int size = random.nextInt(100) + 1;
+ int[] array = new int[size];
- /* init array with random numbers */
- for (int i = 0; i < size; i++) {
- array[i] = random.nextInt() % 100;
- }
+ /* init array with random numbers */
+ for (int i = 0; i < size; i++) {
+ array[i] = random.nextInt() % 100;
+ }
- assert Arrays.stream(array).min().getAsInt() == findMin(array);
- }
+ assert Arrays.stream(array).min().getAsInt() == findMin(array);
+ }
- /**
- * Find the minimum number of an array of numbers.
- *
- * @param array the array contains element
- * @return min value
- */
- public static int findMin(int[] array) {
- int min = array[0];
- for (int i = 1; i < array.length; ++i) {
- if (array[i] < min) {
- min = array[i];
- }
+ /**
+ * Find the minimum number of an array of numbers.
+ *
+ * @param array the array contains element
+ * @return min value
+ */
+ public static int findMin(int[] array) {
+ int min = array[0];
+ for (int i = 1; i < array.length; ++i) {
+ if (array[i] < min) {
+ min = array[i];
+ }
+ }
+ return min;
}
- return min;
- }
}
diff --git a/Maths/FindMinRecursion.java b/Maths/FindMinRecursion.java
index 4922e0d109e6..4cb7e8817e55 100644
--- a/Maths/FindMinRecursion.java
+++ b/Maths/FindMinRecursion.java
@@ -5,52 +5,54 @@
public class FindMinRecursion {
- /** Driver Code */
- public static void main(String[] args) {
- Random rand = new Random();
-
- /* rand size */
- int size = rand.nextInt(100) + 1;
- int[] array = new int[size];
-
- /* init array with rand numbers */
- for (int i = 0; i < size; i++) {
- array[i] = rand.nextInt() % 100;
+ /**
+ * Driver Code
+ */
+ public static void main(String[] args) {
+ Random rand = new Random();
+
+ /* rand size */
+ int size = rand.nextInt(100) + 1;
+ int[] array = new int[size];
+
+ /* init array with rand numbers */
+ for (int i = 0; i < size; i++) {
+ array[i] = rand.nextInt() % 100;
+ }
+
+ assert min(array, 0, array.length - 1) == Arrays.stream(array).min().getAsInt();
+ assert min(array, array.length) == Arrays.stream(array).min().getAsInt();
}
- assert min(array, 0, array.length - 1) == Arrays.stream(array).min().getAsInt();
- assert min(array, array.length) == Arrays.stream(array).min().getAsInt();
- }
-
- /**
- * Get min of array using divide and conquer algorithm
- *
- * @param array contains elements
- * @param low the index of the first element
- * @param high the index of the last element
- * @return min of {@code array}
- */
- public static int min(int[] array, int low, int high) {
- if (low == high) {
- return array[low]; // or array[high]
+ /**
+ * Get min of array using divide and conquer algorithm
+ *
+ * @param array contains elements
+ * @param low the index of the first element
+ * @param high the index of the last element
+ * @return min of {@code array}
+ */
+ public static int min(int[] array, int low, int high) {
+ if (low == high) {
+ return array[low]; // or array[high]
+ }
+
+ int mid = (low + high) >>> 1;
+
+ int leftMin = min(array, low, mid); // get min in [low, mid]
+ int rightMin = min(array, mid + 1, high); // get min in [mid+1, high]
+
+ return Math.min(leftMin, rightMin);
}
- int mid = (low + high) >>> 1;
-
- int leftMin = min(array, low, mid); // get min in [low, mid]
- int rightMin = min(array, mid + 1, high); // get min in [mid+1, high]
-
- return Math.min(leftMin, rightMin);
- }
-
- /**
- * Get min of array using recursion algorithm
- *
- * @param array contains elements
- * @param len length of given array
- * @return min value of {@code array}
- */
- public static int min(int[] array, int len) {
- return len == 1 ? array[0] : Math.min(min(array, len - 1), array[len - 1]);
- }
+ /**
+ * Get min of array using recursion algorithm
+ *
+ * @param array contains elements
+ * @param len length of given array
+ * @return min value of {@code array}
+ */
+ public static int min(int[] array, int len) {
+ return len == 1 ? array[0] : Math.min(min(array, len - 1), array[len - 1]);
+ }
}
diff --git a/Maths/Floor.java b/Maths/Floor.java
index dbd41ac87344..9029a4368014 100644
--- a/Maths/Floor.java
+++ b/Maths/Floor.java
@@ -3,27 +3,27 @@
import java.util.Random;
public class Floor {
- public static void main(String[] args) {
- Random random = new Random();
- for (int i = 1; i <= 1000; ++i) {
- double randomNumber = random.nextDouble();
- assert floor(randomNumber) == Math.floor(randomNumber);
+ public static void main(String[] args) {
+ Random random = new Random();
+ for (int i = 1; i <= 1000; ++i) {
+ double randomNumber = random.nextDouble();
+ assert floor(randomNumber) == Math.floor(randomNumber);
+ }
}
- }
- /**
- * Returns the largest (closest to positive infinity)
- *
- * @param number the number
- * @return the largest (closest to positive infinity) of given {@code number}
- */
- public static double floor(double number) {
- if (number - (int) number == 0) {
- return number;
- } else if (number - (int) number > 0) {
- return (int) number;
- } else {
- return (int) number - 1;
+ /**
+ * Returns the largest (closest to positive infinity)
+ *
+ * @param number the number
+ * @return the largest (closest to positive infinity) of given {@code number}
+ */
+ public static double floor(double number) {
+ if (number - (int) number == 0) {
+ return number;
+ } else if (number - (int) number > 0) {
+ return (int) number;
+ } else {
+ return (int) number - 1;
+ }
}
- }
}
diff --git a/Maths/GCD.java b/Maths/GCD.java
index 0f17f6ea5f11..d13c038ca07a 100644
--- a/Maths/GCD.java
+++ b/Maths/GCD.java
@@ -8,50 +8,50 @@
*/
public class GCD {
- /**
- * get greatest common divisor
- *
- * @param num1 the first number
- * @param num2 the second number
- * @return gcd
- */
- public static int gcd(int num1, int num2) {
- if (num1 < 0 || num2 < 0) {
- throw new ArithmeticException();
+ /**
+ * get greatest common divisor
+ *
+ * @param num1 the first number
+ * @param num2 the second number
+ * @return gcd
+ */
+ public static int gcd(int num1, int num2) {
+ if (num1 < 0 || num2 < 0) {
+ throw new ArithmeticException();
+ }
+
+ if (num1 == 0 || num2 == 0) {
+ return Math.abs(num1 - num2);
+ }
+
+ while (num1 % num2 != 0) {
+ int remainder = num1 % num2;
+ num1 = num2;
+ num2 = remainder;
+ }
+ return num2;
}
- if (num1 == 0 || num2 == 0) {
- return Math.abs(num1 - num2);
+ /**
+ * get greatest common divisor in array
+ *
+ * @param number contains number
+ * @return gcd
+ */
+ public static int gcd(int[] number) {
+ int result = number[0];
+ for (int i = 1; i < number.length; i++)
+ // call gcd function (input two value)
+ result = gcd(result, number[i]);
+
+ return result;
}
- while (num1 % num2 != 0) {
- int remainder = num1 % num2;
- num1 = num2;
- num2 = remainder;
+ public static void main(String[] args) {
+ int[] myIntArray = {4, 16, 32};
+
+ // call gcd function (input array)
+ System.out.println(gcd(myIntArray)); // => 4
+ System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8
}
- return num2;
- }
-
- /**
- * get greatest common divisor in array
- *
- * @param number contains number
- * @return gcd
- */
- public static int gcd(int[] number) {
- int result = number[0];
- for (int i = 1; i < number.length; i++)
- // call gcd function (input two value)
- result = gcd(result, number[i]);
-
- return result;
- }
-
- public static void main(String[] args) {
- int[] myIntArray = {4, 16, 32};
-
- // call gcd function (input array)
- System.out.println(gcd(myIntArray)); // => 4
- System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8
- }
}
diff --git a/Maths/GCDRecursion.java b/Maths/GCDRecursion.java
index d0104d3db9e9..e25fcdc71d3d 100644
--- a/Maths/GCDRecursion.java
+++ b/Maths/GCDRecursion.java
@@ -1,34 +1,36 @@
package Maths;
-/** @author https://github.com/shellhub/ */
+/**
+ * @author https://github.com/shellhub/
+ */
public class GCDRecursion {
- public static void main(String[] args) {
- System.out.println(gcd(20, 15)); /* output: 5 */
- System.out.println(gcd(10, 8)); /* output: 2 */
- System.out.println(gcd(gcd(10, 5), gcd(5, 10))); /* output: 5 */
- }
+ public static void main(String[] args) {
+ System.out.println(gcd(20, 15)); /* output: 5 */
+ System.out.println(gcd(10, 8)); /* output: 2 */
+ System.out.println(gcd(gcd(10, 5), gcd(5, 10))); /* output: 5 */
+ }
- /**
- * get greatest common divisor
- *
- * @param a the first number
- * @param b the second number
- * @return gcd
- */
- public static int gcd(int a, int b) {
+ /**
+ * get greatest common divisor
+ *
+ * @param a the first number
+ * @param b the second number
+ * @return gcd
+ */
+ public static int gcd(int a, int b) {
- if (a < 0 || b < 0) {
- throw new ArithmeticException();
- }
+ if (a < 0 || b < 0) {
+ throw new ArithmeticException();
+ }
- if (a == 0 || b == 0) {
- return Math.abs(a - b);
- }
+ if (a == 0 || b == 0) {
+ return Math.abs(a - b);
+ }
- if (a % b == 0) {
- return b;
- } else {
- return gcd(b, a % b);
+ if (a % b == 0) {
+ return b;
+ } else {
+ return gcd(b, a % b);
+ }
}
- }
}
diff --git a/Maths/LucasSeries.java b/Maths/LucasSeries.java
index ade5ab2c52fe..edd470504ac3 100644
--- a/Maths/LucasSeries.java
+++ b/Maths/LucasSeries.java
@@ -1,43 +1,45 @@
package Maths;
-/** https://en.wikipedia.org/wiki/Lucas_number */
+/**
+ * https://en.wikipedia.org/wiki/Lucas_number
+ */
public class LucasSeries {
- public static void main(String[] args) {
- assert lucasSeries(1) == 2 && lucasSeriesIteration(1) == 2;
- assert lucasSeries(2) == 1 && lucasSeriesIteration(2) == 1;
- assert lucasSeries(3) == 3 && lucasSeriesIteration(3) == 3;
- assert lucasSeries(4) == 4 && lucasSeriesIteration(4) == 4;
- assert lucasSeries(5) == 7 && lucasSeriesIteration(5) == 7;
- assert lucasSeries(6) == 11 && lucasSeriesIteration(6) == 11;
- assert lucasSeries(11) == 123 && lucasSeriesIteration(11) == 123;
- }
+ public static void main(String[] args) {
+ assert lucasSeries(1) == 2 && lucasSeriesIteration(1) == 2;
+ assert lucasSeries(2) == 1 && lucasSeriesIteration(2) == 1;
+ assert lucasSeries(3) == 3 && lucasSeriesIteration(3) == 3;
+ assert lucasSeries(4) == 4 && lucasSeriesIteration(4) == 4;
+ assert lucasSeries(5) == 7 && lucasSeriesIteration(5) == 7;
+ assert lucasSeries(6) == 11 && lucasSeriesIteration(6) == 11;
+ assert lucasSeries(11) == 123 && lucasSeriesIteration(11) == 123;
+ }
- /**
- * Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using
- * recursion
- *
- * @param n nth
- * @return nth number of lucas series
- */
- public static int lucasSeries(int n) {
- return n == 1 ? 2 : n == 2 ? 1 : lucasSeries(n - 1) + lucasSeries(n - 2);
- }
+ /**
+ * Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using
+ * recursion
+ *
+ * @param n nth
+ * @return nth number of lucas series
+ */
+ public static int lucasSeries(int n) {
+ return n == 1 ? 2 : n == 2 ? 1 : lucasSeries(n - 1) + lucasSeries(n - 2);
+ }
- /**
- * Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using
- * iteration
- *
- * @param n nth
- * @return nth number of lucas series
- */
- public static int lucasSeriesIteration(int n) {
- int previous = 2;
- int current = 1;
- for (int i = 1; i < n; i++) {
- int next = previous + current;
- previous = current;
- current = next;
+ /**
+ * Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using
+ * iteration
+ *
+ * @param n nth
+ * @return nth number of lucas series
+ */
+ public static int lucasSeriesIteration(int n) {
+ int previous = 2;
+ int current = 1;
+ for (int i = 1; i < n; i++) {
+ int next = previous + current;
+ previous = current;
+ current = next;
+ }
+ return previous;
}
- return previous;
- }
}
diff --git a/Maths/MaxValue.java b/Maths/MaxValue.java
index 504f87bc20a8..d59a00458dc4 100644
--- a/Maths/MaxValue.java
+++ b/Maths/MaxValue.java
@@ -4,29 +4,31 @@
public class MaxValue {
- /** Driver Code */
- public static void main(String[] args) {
- Random rand = new Random();
+ /**
+ * Driver Code
+ */
+ public static void main(String[] args) {
+ Random rand = new Random();
- /* test 100 times using rand numbers */
- for (int i = 1; i <= 100; ++i) {
- /* generate number from -50 to 49 */
- int a = rand.nextInt(100) - 50;
- int b = rand.nextInt(100) - 50;
- assert max(a, b) == Math.max(a, b);
+ /* test 100 times using rand numbers */
+ for (int i = 1; i <= 100; ++i) {
+ /* generate number from -50 to 49 */
+ int a = rand.nextInt(100) - 50;
+ int b = rand.nextInt(100) - 50;
+ assert max(a, b) == Math.max(a, b);
+ }
}
- }
- /**
- * Returns the greater of two {@code int} values. That is, the result is the argument closer to
- * the value of {@link Integer#MAX_VALUE}. If the arguments have the same value, the result is
- * that same value.
- *
- * @param a an argument.
- * @param b another argument.
- * @return the larger of {@code a} and {@code b}.
- */
- public static int max(int a, int b) {
- return a >= b ? a : b;
- }
+ /**
+ * Returns the greater of two {@code int} values. That is, the result is the argument closer to
+ * the value of {@link Integer#MAX_VALUE}. If the arguments have the same value, the result is
+ * that same value.
+ *
+ * @param a an argument.
+ * @param b another argument.
+ * @return the larger of {@code a} and {@code b}.
+ */
+ public static int max(int a, int b) {
+ return a >= b ? a : b;
+ }
}
diff --git a/Maths/Median.java b/Maths/Median.java
index b0b011232a3c..3e597d0e9251 100644
--- a/Maths/Median.java
+++ b/Maths/Median.java
@@ -2,27 +2,29 @@
import java.util.Arrays;
-/** Wikipedia: https://en.wikipedia.org/wiki/Median */
+/**
+ * Wikipedia: https://en.wikipedia.org/wiki/Median
+ */
public class Median {
- public static void main(String[] args) {
- assert median(new int[] {0}) == 0;
- assert median(new int[] {1, 2}) == 1.5;
- assert median(new int[] {4, 1, 3, 2}) == 2.5;
- assert median(new int[] {1, 3, 3, 6, 7, 8, 9}) == 6;
- assert median(new int[] {1, 2, 3, 4, 5, 6, 8, 9}) == 4.5;
- }
+ public static void main(String[] args) {
+ assert median(new int[]{0}) == 0;
+ assert median(new int[]{1, 2}) == 1.5;
+ assert median(new int[]{4, 1, 3, 2}) == 2.5;
+ assert median(new int[]{1, 3, 3, 6, 7, 8, 9}) == 6;
+ assert median(new int[]{1, 2, 3, 4, 5, 6, 8, 9}) == 4.5;
+ }
- /**
- * Calculate average median
- *
- * @param values number series
- * @return median of given {@code values}
- */
- public static double median(int[] values) {
- Arrays.sort(values);
- int length = values.length;
- return length % 2 == 0
- ? (values[length / 2] + values[length / 2 - 1]) / 2.0
- : values[length / 2];
- }
+ /**
+ * Calculate average median
+ *
+ * @param values number series
+ * @return median of given {@code values}
+ */
+ public static double median(int[] values) {
+ Arrays.sort(values);
+ int length = values.length;
+ return length % 2 == 0
+ ? (values[length / 2] + values[length / 2 - 1]) / 2.0
+ : values[length / 2];
+ }
}
diff --git a/Maths/MinValue.java b/Maths/MinValue.java
index 3bb4b5434113..1775f80447ef 100644
--- a/Maths/MinValue.java
+++ b/Maths/MinValue.java
@@ -4,29 +4,31 @@
public class MinValue {
- /** Driver Code */
- public static void main(String[] args) {
- Random rand = new Random();
+ /**
+ * Driver Code
+ */
+ public static void main(String[] args) {
+ Random rand = new Random();
- /* test 100 times using rand numbers */
- for (int i = 1; i <= 100; ++i) {
- /* generate number from -50 to 49 */
- int a = rand.nextInt(100) - 50;
- int b = rand.nextInt(100) - 50;
- assert min(a, b) == Math.min(a, b);
+ /* test 100 times using rand numbers */
+ for (int i = 1; i <= 100; ++i) {
+ /* generate number from -50 to 49 */
+ int a = rand.nextInt(100) - 50;
+ int b = rand.nextInt(100) - 50;
+ assert min(a, b) == Math.min(a, b);
+ }
}
- }
- /**
- * Returns the smaller of two {@code int} values. That is, the result the argument closer to the
- * value of {@link Integer#MIN_VALUE}. If the arguments have the same value, the result is that
- * same value.
- *
- * @param a an argument.
- * @param b another argument.
- * @return the smaller of {@code a} and {@code b}.
- */
- public static int min(int a, int b) {
- return a <= b ? a : b;
- }
+ /**
+ * Returns the smaller of two {@code int} values. That is, the result the argument closer to the
+ * value of {@link Integer#MIN_VALUE}. If the arguments have the same value, the result is that
+ * same value.
+ *
+ * @param a an argument.
+ * @param b another argument.
+ * @return the smaller of {@code a} and {@code b}.
+ */
+ public static int min(int a, int b) {
+ return a <= b ? a : b;
+ }
}
diff --git a/Maths/Mode.java b/Maths/Mode.java
index 5d28c8c8c4bf..b1127561f036 100644
--- a/Maths/Mode.java
+++ b/Maths/Mode.java
@@ -13,47 +13,47 @@
*/
public class Mode {
- public static void main(String[] args) {
-
- /* Test array of integers */
- assert (mode(new int[] {})) == null;
- assert Arrays.equals(mode(new int[] {5}), new int[] {5});
- assert Arrays.equals(mode(new int[] {1, 2, 3, 4, 5}), new int[] {1, 2, 3, 4, 5});
- assert Arrays.equals(mode(new int[] {7, 9, 9, 4, 5, 6, 7, 7, 8}), new int[] {7});
- assert Arrays.equals(mode(new int[] {7, 9, 9, 4, 5, 6, 7, 7, 9}), new int[] {7, 9});
- }
+ public static void main(String[] args) {
+
+ /* Test array of integers */
+ assert (mode(new int[]{})) == null;
+ assert Arrays.equals(mode(new int[]{5}), new int[]{5});
+ assert Arrays.equals(mode(new int[]{1, 2, 3, 4, 5}), new int[]{1, 2, 3, 4, 5});
+ assert Arrays.equals(mode(new int[]{7, 9, 9, 4, 5, 6, 7, 7, 8}), new int[]{7});
+ assert Arrays.equals(mode(new int[]{7, 9, 9, 4, 5, 6, 7, 7, 9}), new int[]{7, 9});
+ }
- /*
- * Find the mode of an array of integers
- *
- * @param numbers array of integers
- * @return mode of the array
- */
- public static int[] mode(int[] numbers) {
+ /*
+ * Find the mode of an array of integers
+ *
+ * @param numbers array of integers
+ * @return mode of the array
+ */
+ public static int[] mode(int[] numbers) {
- if (numbers.length == 0) return null;
+ if (numbers.length == 0) return null;
- HashMap count = new HashMap<>();
+ HashMap count = new HashMap<>();
- for (int num : numbers) {
- if (count.containsKey(num)) {
+ for (int num : numbers) {
+ if (count.containsKey(num)) {
- count.put(num, count.get(num) + 1);
+ count.put(num, count.get(num) + 1);
- } else {
+ } else {
- count.put(num, 1);
- }
- }
+ count.put(num, 1);
+ }
+ }
- int max = Collections.max(count.values());
- ArrayList modes = new ArrayList<>();
+ int max = Collections.max(count.values());
+ ArrayList modes = new ArrayList<>();
- for (int num : count.keySet()) {
- if (count.get(num) == max) {
- modes.add(num);
- }
+ for (int num : count.keySet()) {
+ if (count.get(num) == max) {
+ modes.add(num);
+ }
+ }
+ return modes.stream().mapToInt(n -> n).toArray();
}
- return modes.stream().mapToInt(n -> n).toArray();
- }
}
diff --git a/Maths/NumberOfDigits.java b/Maths/NumberOfDigits.java
index acc9f8c91cb0..3141ab226a3b 100644
--- a/Maths/NumberOfDigits.java
+++ b/Maths/NumberOfDigits.java
@@ -1,59 +1,61 @@
package Maths;
-/** Find the number of digits in a number. */
+/**
+ * Find the number of digits in a number.
+ */
public class NumberOfDigits {
- public static void main(String[] args) {
- int[] numbers = {0, 12, 123, 1234, -12345, 123456, 1234567, 12345678, 123456789};
- for (int i = 0; i < numbers.length; ++i) {
- assert numberOfDigits(numbers[i]) == i + 1;
- assert numberOfDigitsFast(numbers[i]) == i + 1;
- assert numberOfDigitsFaster(numbers[i]) == i + 1;
- assert numberOfDigitsRecursion(numbers[i]) == i + 1;
+ public static void main(String[] args) {
+ int[] numbers = {0, 12, 123, 1234, -12345, 123456, 1234567, 12345678, 123456789};
+ for (int i = 0; i < numbers.length; ++i) {
+ assert numberOfDigits(numbers[i]) == i + 1;
+ assert numberOfDigitsFast(numbers[i]) == i + 1;
+ assert numberOfDigitsFaster(numbers[i]) == i + 1;
+ assert numberOfDigitsRecursion(numbers[i]) == i + 1;
+ }
}
- }
- /**
- * Find the number of digits in a number.
- *
- * @param number number to find
- * @return number of digits of given number
- */
- private static int numberOfDigits(int number) {
- int digits = 0;
- do {
- digits++;
- number /= 10;
- } while (number != 0);
- return digits;
- }
+ /**
+ * Find the number of digits in a number.
+ *
+ * @param number number to find
+ * @return number of digits of given number
+ */
+ private static int numberOfDigits(int number) {
+ int digits = 0;
+ do {
+ digits++;
+ number /= 10;
+ } while (number != 0);
+ return digits;
+ }
- /**
- * Find the number of digits in a number fast version.
- *
- * @param number number to find
- * @return number of digits of given number
- */
- private static int numberOfDigitsFast(int number) {
- return number == 0 ? 1 : (int) Math.floor(Math.log10(Math.abs(number)) + 1);
- }
+ /**
+ * Find the number of digits in a number fast version.
+ *
+ * @param number number to find
+ * @return number of digits of given number
+ */
+ private static int numberOfDigitsFast(int number) {
+ return number == 0 ? 1 : (int) Math.floor(Math.log10(Math.abs(number)) + 1);
+ }
- /**
- * Find the number of digits in a number faster version.
- *
- * @param number number to find
- * @return number of digits of given number
- */
- private static int numberOfDigitsFaster(int number) {
- return number < 0 ? (-number + "").length() : (number + "").length();
- }
+ /**
+ * Find the number of digits in a number faster version.
+ *
+ * @param number number to find
+ * @return number of digits of given number
+ */
+ private static int numberOfDigitsFaster(int number) {
+ return number < 0 ? (-number + "").length() : (number + "").length();
+ }
- /**
- * Find the number of digits in a number using recursion.
- *
- * @param number number to find
- * @return number of digits of given number
- */
- private static int numberOfDigitsRecursion(int number) {
- return number / 10 == 0 ? 1 : 1 + numberOfDigitsRecursion(number / 10);
- }
+ /**
+ * Find the number of digits in a number using recursion.
+ *
+ * @param number number to find
+ * @return number of digits of given number
+ */
+ private static int numberOfDigitsRecursion(int number) {
+ return number / 10 == 0 ? 1 : 1 + numberOfDigitsRecursion(number / 10);
+ }
}
diff --git a/Maths/PalindromeNumber.java b/Maths/PalindromeNumber.java
index 08c4ba01bea7..2916c753e67a 100644
--- a/Maths/PalindromeNumber.java
+++ b/Maths/PalindromeNumber.java
@@ -1,30 +1,30 @@
package Maths;
public class PalindromeNumber {
- public static void main(String[] args) {
+ public static void main(String[] args) {
- assert isPalindrome(12321);
- assert !isPalindrome(1234);
- assert isPalindrome(1);
- }
-
- /**
- * Check if {@code n} is palindrome number or not
- *
- * @param number the number
- * @return {@code true} if {@code n} is palindrome number, otherwise {@code false}
- */
- public static boolean isPalindrome(int number) {
- if (number < 0) {
- throw new IllegalArgumentException(number + "");
+ assert isPalindrome(12321);
+ assert !isPalindrome(1234);
+ assert isPalindrome(1);
}
- int numberCopy = number;
- int reverseNumber = 0;
- while (numberCopy != 0) {
- int remainder = numberCopy % 10;
- reverseNumber = reverseNumber * 10 + remainder;
- numberCopy /= 10;
+
+ /**
+ * Check if {@code n} is palindrome number or not
+ *
+ * @param number the number
+ * @return {@code true} if {@code n} is palindrome number, otherwise {@code false}
+ */
+ public static boolean isPalindrome(int number) {
+ if (number < 0) {
+ throw new IllegalArgumentException(number + "");
+ }
+ int numberCopy = number;
+ int reverseNumber = 0;
+ while (numberCopy != 0) {
+ int remainder = numberCopy % 10;
+ reverseNumber = reverseNumber * 10 + remainder;
+ numberCopy /= 10;
+ }
+ return number == reverseNumber;
}
- return number == reverseNumber;
- }
}
diff --git a/Maths/ParseInteger.java b/Maths/ParseInteger.java
index cf9c9efc88fd..c9c11528c1dc 100644
--- a/Maths/ParseInteger.java
+++ b/Maths/ParseInteger.java
@@ -1,33 +1,33 @@
package Maths;
public class ParseInteger {
- public static void main(String[] args) {
- assert parseInt("123") == Integer.parseInt("123");
- assert parseInt("-123") == Integer.parseInt("-123");
- assert parseInt("0123") == Integer.parseInt("0123");
- assert parseInt("+123") == Integer.parseInt("+123");
- }
-
- /**
- * Parse a string to integer
- *
- * @param s the string
- * @return the integer value represented by the argument in decimal.
- * @throws NumberFormatException if the {@code string} does not contain a parsable integer.
- */
- public static int parseInt(String s) {
- if (s == null || s.length() == 0) {
- throw new NumberFormatException("null");
+ public static void main(String[] args) {
+ assert parseInt("123") == Integer.parseInt("123");
+ assert parseInt("-123") == Integer.parseInt("-123");
+ assert parseInt("0123") == Integer.parseInt("0123");
+ assert parseInt("+123") == Integer.parseInt("+123");
}
- boolean isNegative = s.charAt(0) == '-';
- boolean isPositive = s.charAt(0) == '+';
- int number = 0;
- for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
- if (!Character.isDigit(s.charAt(i))) {
- throw new NumberFormatException("s=" + s);
- }
- number = number * 10 + s.charAt(i) - '0';
+
+ /**
+ * Parse a string to integer
+ *
+ * @param s the string
+ * @return the integer value represented by the argument in decimal.
+ * @throws NumberFormatException if the {@code string} does not contain a parsable integer.
+ */
+ public static int parseInt(String s) {
+ if (s == null || s.length() == 0) {
+ throw new NumberFormatException("null");
+ }
+ boolean isNegative = s.charAt(0) == '-';
+ boolean isPositive = s.charAt(0) == '+';
+ int number = 0;
+ for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
+ if (!Character.isDigit(s.charAt(i))) {
+ throw new NumberFormatException("s=" + s);
+ }
+ number = number * 10 + s.charAt(i) - '0';
+ }
+ return isNegative ? -number : number;
}
- return isNegative ? -number : number;
- }
}
diff --git a/Maths/PerfectCube.java b/Maths/PerfectCube.java
index 2ecb8e805a42..78cbdb777b8c 100644
--- a/Maths/PerfectCube.java
+++ b/Maths/PerfectCube.java
@@ -1,24 +1,26 @@
package Maths;
-/** https://en.wikipedia.org/wiki/Cube_(algebra) */
+/**
+ * https://en.wikipedia.org/wiki/Cube_(algebra)
+ */
public class PerfectCube {
- public static void main(String[] args) {
- assert !isPerfectCube(-1);
- assert isPerfectCube(0);
- assert isPerfectCube(1);
- assert !isPerfectCube(4);
- assert isPerfectCube(8);
- assert isPerfectCube(27);
- }
+ public static void main(String[] args) {
+ assert !isPerfectCube(-1);
+ assert isPerfectCube(0);
+ assert isPerfectCube(1);
+ assert !isPerfectCube(4);
+ assert isPerfectCube(8);
+ assert isPerfectCube(27);
+ }
- /**
- * Check if a number is perfect cube or not
- *
- * @param number number to check
- * @return {@code true} if {@code number} is perfect cube, otherwise {@code false}
- */
- public static boolean isPerfectCube(int number) {
- int a = (int) Math.pow(number, 1.0 / 3);
- return a * a * a == number;
- }
+ /**
+ * Check if a number is perfect cube or not
+ *
+ * @param number number to check
+ * @return {@code true} if {@code number} is perfect cube, otherwise {@code false}
+ */
+ public static boolean isPerfectCube(int number) {
+ int a = (int) Math.pow(number, 1.0 / 3);
+ return a * a * a == number;
+ }
}
diff --git a/Maths/PerfectNumber.java b/Maths/PerfectNumber.java
index de56c4175c02..f4d56101120a 100644
--- a/Maths/PerfectNumber.java
+++ b/Maths/PerfectNumber.java
@@ -8,25 +8,25 @@
* link:https://en.wikipedia.org/wiki/Perfect_number
*/
public class PerfectNumber {
- public static void main(String[] args) {
- assert isPerfectNumber(6); /* 1 + 2 + 3 == 6 */
- assert !isPerfectNumber(8); /* 1 + 2 + 4 != 8 */
- assert isPerfectNumber(28); /* 1 + 2 + 4 + 7 + 14 == 28 */
- }
+ public static void main(String[] args) {
+ assert isPerfectNumber(6); /* 1 + 2 + 3 == 6 */
+ assert !isPerfectNumber(8); /* 1 + 2 + 4 != 8 */
+ assert isPerfectNumber(28); /* 1 + 2 + 4 + 7 + 14 == 28 */
+ }
- /**
- * Check if {@code number} is perfect number or not
- *
- * @param number the number
- * @return {@code true} if {@code number} is perfect number, otherwise false
- */
- public static boolean isPerfectNumber(int number) {
- int sum = 0; /* sum of its positive divisors */
- for (int i = 1; i < number; ++i) {
- if (number % i == 0) {
- sum += i;
- }
+ /**
+ * Check if {@code number} is perfect number or not
+ *
+ * @param number the number
+ * @return {@code true} if {@code number} is perfect number, otherwise false
+ */
+ public static boolean isPerfectNumber(int number) {
+ int sum = 0; /* sum of its positive divisors */
+ for (int i = 1; i < number; ++i) {
+ if (number % i == 0) {
+ sum += i;
+ }
+ }
+ return sum == number;
}
- return sum == number;
- }
}
diff --git a/Maths/PerfectSquare.java b/Maths/PerfectSquare.java
index aef645e2ed2b..c7dca948e1ed 100644
--- a/Maths/PerfectSquare.java
+++ b/Maths/PerfectSquare.java
@@ -1,23 +1,25 @@
package Maths;
-/** https://en.wikipedia.org/wiki/Perfect_square */
+/**
+ * https://en.wikipedia.org/wiki/Perfect_square
+ */
public class PerfectSquare {
- public static void main(String[] args) {
- assert !isPerfectSquare(-1);
- assert !isPerfectSquare(3);
- assert !isPerfectSquare(5);
- assert isPerfectSquare(9);
- assert isPerfectSquare(100);
- }
+ public static void main(String[] args) {
+ assert !isPerfectSquare(-1);
+ assert !isPerfectSquare(3);
+ assert !isPerfectSquare(5);
+ assert isPerfectSquare(9);
+ assert isPerfectSquare(100);
+ }
- /**
- * Check if a number is perfect square number
- *
- * @param number the number to be checked
- * @return true if {@code number} is perfect square, otherwise false
- */
- public static boolean isPerfectSquare(int number) {
- int sqrt = (int) Math.sqrt(number);
- return sqrt * sqrt == number;
- }
+ /**
+ * Check if a number is perfect square number
+ *
+ * @param number the number to be checked
+ * @return true if {@code number} is perfect square, otherwise false
+ */
+ public static boolean isPerfectSquare(int number) {
+ int sqrt = (int) Math.sqrt(number);
+ return sqrt * sqrt == number;
+ }
}
diff --git a/Maths/Pow.java b/Maths/Pow.java
index 6af5446510af..56d1efe77ceb 100644
--- a/Maths/Pow.java
+++ b/Maths/Pow.java
@@ -2,25 +2,25 @@
// POWER (exponentials) Examples (a^b)
public class Pow {
- public static void main(String[] args) {
- assert pow(2, 0) == Math.pow(2, 0); // == 1
- assert pow(0, 2) == Math.pow(0, 2); // == 0
- assert pow(2, 10) == Math.pow(2, 10); // == 1024
- assert pow(10, 2) == Math.pow(10, 2); // == 100
- }
+ public static void main(String[] args) {
+ assert pow(2, 0) == Math.pow(2, 0); // == 1
+ assert pow(0, 2) == Math.pow(0, 2); // == 0
+ assert pow(2, 10) == Math.pow(2, 10); // == 1024
+ assert pow(10, 2) == Math.pow(10, 2); // == 100
+ }
- /**
- * Returns the value of the first argument raised to the power of the second argument
- *
- * @param a the base.
- * @param b the exponent.
- * @return the value {@code a}{@code b}.
- */
- public static long pow(int a, int b) {
- long result = 1;
- for (int i = 1; i <= b; i++) {
- result *= a;
+ /**
+ * Returns the value of the first argument raised to the power of the second argument
+ *
+ * @param a the base.
+ * @param b the exponent.
+ * @return the value {@code a}{@code b}.
+ */
+ public static long pow(int a, int b) {
+ long result = 1;
+ for (int i = 1; i <= b; i++) {
+ result *= a;
+ }
+ return result;
}
- return result;
- }
}
diff --git a/Maths/PowRecursion.java b/Maths/PowRecursion.java
index 598fc724e54a..5a50f0d030c1 100644
--- a/Maths/PowRecursion.java
+++ b/Maths/PowRecursion.java
@@ -1,21 +1,21 @@
package Maths;
public class PowRecursion {
- public static void main(String[] args) {
- assert Double.compare(pow(2, 0), Math.pow(2, 0)) == 0;
- assert Double.compare(pow(0, 2), Math.pow(0, 2)) == 0;
- assert Double.compare(pow(2, 10), Math.pow(2, 10)) == 0;
- assert Double.compare(pow(10, 2), Math.pow(10, 2)) == 0;
- }
+ public static void main(String[] args) {
+ assert Double.compare(pow(2, 0), Math.pow(2, 0)) == 0;
+ assert Double.compare(pow(0, 2), Math.pow(0, 2)) == 0;
+ assert Double.compare(pow(2, 10), Math.pow(2, 10)) == 0;
+ assert Double.compare(pow(10, 2), Math.pow(10, 2)) == 0;
+ }
- /**
- * Returns the value of the first argument raised to the power of the second argument
- *
- * @param a the base.
- * @param b the exponent.
- * @return the value {@code a}{@code b}.
- */
- public static long pow(int a, int b) {
- return b == 0 ? 1 : a * pow(a, b - 1);
- }
+ /**
+ * Returns the value of the first argument raised to the power of the second argument
+ *
+ * @param a the base.
+ * @param b the exponent.
+ * @return the value {@code a}{@code b}.
+ */
+ public static long pow(int a, int b) {
+ return b == 0 ? 1 : a * pow(a, b - 1);
+ }
}
diff --git a/Maths/PowerOfTwoOrNot.java b/Maths/PowerOfTwoOrNot.java
index 329f64d139f2..5b1c7640f375 100644
--- a/Maths/PowerOfTwoOrNot.java
+++ b/Maths/PowerOfTwoOrNot.java
@@ -1,23 +1,25 @@
package Maths;
-/** A utility to check if a given number is power of two or not. For example 8,16 etc. */
+/**
+ * A utility to check if a given number is power of two or not. For example 8,16 etc.
+ */
public class PowerOfTwoOrNot {
- public static void main(String[] args) {
- assert !checkIfPowerOfTwoOrNot(0);
- assert checkIfPowerOfTwoOrNot(1);
- assert checkIfPowerOfTwoOrNot(8);
- assert checkIfPowerOfTwoOrNot(16);
- assert checkIfPowerOfTwoOrNot(1024);
- }
+ public static void main(String[] args) {
+ assert !checkIfPowerOfTwoOrNot(0);
+ assert checkIfPowerOfTwoOrNot(1);
+ assert checkIfPowerOfTwoOrNot(8);
+ assert checkIfPowerOfTwoOrNot(16);
+ assert checkIfPowerOfTwoOrNot(1024);
+ }
- /**
- * Checks whether given number is power of two or not.
- *
- * @param number the number to check
- * @return {@code true} if given number is power of two, otherwise {@code false}
- */
- public static boolean checkIfPowerOfTwoOrNot(int number) {
- return number != 0 && ((number & (number - 1)) == 0);
- }
+ /**
+ * Checks whether given number is power of two or not.
+ *
+ * @param number the number to check
+ * @return {@code true} if given number is power of two, otherwise {@code false}
+ */
+ public static boolean checkIfPowerOfTwoOrNot(int number) {
+ return number != 0 && ((number & (number - 1)) == 0);
+ }
}
diff --git a/Maths/PrimeCheck.java b/Maths/PrimeCheck.java
index 6ea901a8a73e..c972aa8c3e5a 100644
--- a/Maths/PrimeCheck.java
+++ b/Maths/PrimeCheck.java
@@ -3,36 +3,36 @@
import java.util.Scanner;
public class PrimeCheck {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
- System.out.print("Enter a number: ");
- int n = scanner.nextInt();
- if (isPrime(n)) {
- System.out.println(n + " is a prime number");
- } else {
- System.out.println(n + " is not a prime number");
+ System.out.print("Enter a number: ");
+ int n = scanner.nextInt();
+ if (isPrime(n)) {
+ System.out.println(n + " is a prime number");
+ } else {
+ System.out.println(n + " is not a prime number");
+ }
+ scanner.close();
}
- scanner.close();
- }
- /***
- * Checks if a number is prime or not
- * @param n the number
- * @return {@code true} if {@code n} is prime
- */
- public static boolean isPrime(int n) {
- if (n == 2) {
- return true;
+ /***
+ * Checks if a number is prime or not
+ * @param n the number
+ * @return {@code true} if {@code n} is prime
+ */
+ public static boolean isPrime(int n) {
+ if (n == 2) {
+ return true;
+ }
+ if (n < 2 || n % 2 == 0) {
+ return false;
+ }
+ for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) {
+ if (n % i == 0) {
+ return false;
+ }
+ }
+ return true;
}
- if (n < 2 || n % 2 == 0) {
- return false;
- }
- for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) {
- if (n % i == 0) {
- return false;
- }
- }
- return true;
- }
}
diff --git a/Maths/PrimeFactorization.java b/Maths/PrimeFactorization.java
index 79e12a7dc49b..a12a1fd3946a 100644
--- a/Maths/PrimeFactorization.java
+++ b/Maths/PrimeFactorization.java
@@ -3,30 +3,30 @@
import java.util.Scanner;
public class PrimeFactorization {
- public static void main(String[] args) {
- System.out.println("## all prime factors ##");
- Scanner scanner = new Scanner(System.in);
- System.out.print("Enter a number: ");
- int n = scanner.nextInt();
- System.out.print(("printing factors of " + n + " : "));
- pfactors(n);
- scanner.close();
- }
+ public static void main(String[] args) {
+ System.out.println("## all prime factors ##");
+ Scanner scanner = new Scanner(System.in);
+ System.out.print("Enter a number: ");
+ int n = scanner.nextInt();
+ System.out.print(("printing factors of " + n + " : "));
+ pfactors(n);
+ scanner.close();
+ }
- public static void pfactors(int n) {
+ public static void pfactors(int n) {
- while (n % 2 == 0) {
- System.out.print(2 + " ");
- n /= 2;
- }
+ while (n % 2 == 0) {
+ System.out.print(2 + " ");
+ n /= 2;
+ }
- for (int i = 3; i <= Math.sqrt(n); i += 2) {
- while (n % i == 0) {
- System.out.print(i + " ");
- n /= i;
- }
- }
+ for (int i = 3; i <= Math.sqrt(n); i += 2) {
+ while (n % i == 0) {
+ System.out.print(i + " ");
+ n /= i;
+ }
+ }
- if (n > 2) System.out.print(n);
- }
+ if (n > 2) System.out.print(n);
+ }
}
diff --git a/Maths/PythagoreanTriple.java b/Maths/PythagoreanTriple.java
index 5aaf95c7550e..bef364164794 100644
--- a/Maths/PythagoreanTriple.java
+++ b/Maths/PythagoreanTriple.java
@@ -1,30 +1,32 @@
package Maths;
-/** https://en.wikipedia.org/wiki/Pythagorean_triple */
+/**
+ * https://en.wikipedia.org/wiki/Pythagorean_triple
+ */
public class PythagoreanTriple {
- public static void main(String[] args) {
- assert isPythagTriple(3, 4, 5);
- assert isPythagTriple(5, 12, 13);
- assert isPythagTriple(6, 8, 10);
- assert !isPythagTriple(10, 20, 30);
- assert !isPythagTriple(6, 8, 100);
- assert !isPythagTriple(-1, -1, 1);
- }
+ public static void main(String[] args) {
+ assert isPythagTriple(3, 4, 5);
+ assert isPythagTriple(5, 12, 13);
+ assert isPythagTriple(6, 8, 10);
+ assert !isPythagTriple(10, 20, 30);
+ assert !isPythagTriple(6, 8, 100);
+ assert !isPythagTriple(-1, -1, 1);
+ }
- /**
- * Check if a,b,c are a Pythagorean Triple
- *
- * @param a x/y component length of a right triangle
- * @param b y/x component length of a right triangle
- * @param c hypotenuse length of a right triangle
- * @return boolean true if a, b, c satisfy the Pythagorean theorem, otherwise
- * false
- */
- public static boolean isPythagTriple(int a, int b, int c) {
- if (a <= 0 || b <= 0 || c <= 0) {
- return false;
- } else {
- return (a * a) + (b * b) == (c * c);
+ /**
+ * Check if a,b,c are a Pythagorean Triple
+ *
+ * @param a x/y component length of a right triangle
+ * @param b y/x component length of a right triangle
+ * @param c hypotenuse length of a right triangle
+ * @return boolean true if a, b, c satisfy the Pythagorean theorem, otherwise
+ * false
+ */
+ public static boolean isPythagTriple(int a, int b, int c) {
+ if (a <= 0 || b <= 0 || c <= 0) {
+ return false;
+ } else {
+ return (a * a) + (b * b) == (c * c);
+ }
}
- }
}
diff --git a/Maths/SumOfArithmeticSeries.java b/Maths/SumOfArithmeticSeries.java
index 01e7c3a0357c..3be19426251f 100644
--- a/Maths/SumOfArithmeticSeries.java
+++ b/Maths/SumOfArithmeticSeries.java
@@ -9,32 +9,32 @@
*
Wikipedia: https://en.wikipedia.org/wiki/Arithmetic_progression
*/
public class SumOfArithmeticSeries {
- public static void main(String[] args) {
+ public static void main(String[] args) {
- /* 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 */
- assert Double.compare(55.0, sumOfSeries(1, 1, 10)) == 0;
+ /* 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 */
+ assert Double.compare(55.0, sumOfSeries(1, 1, 10)) == 0;
- /* 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 */
- assert Double.compare(100.0, sumOfSeries(1, 2, 10)) == 0;
+ /* 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 */
+ assert Double.compare(100.0, sumOfSeries(1, 2, 10)) == 0;
- /* 1 + 11 + 21 + 31 + 41 + 51 + 61 + 71 + 81 + 91 */
- assert Double.compare(460.0, sumOfSeries(1, 10, 10)) == 0;
+ /* 1 + 11 + 21 + 31 + 41 + 51 + 61 + 71 + 81 + 91 */
+ assert Double.compare(460.0, sumOfSeries(1, 10, 10)) == 0;
- /* 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 0.6 + 0.7 + 0.8 + 0.9 + 1.0 */
- assert Double.compare(5.5, sumOfSeries(0.1, 0.1, 10)) == 0;
+ /* 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 0.6 + 0.7 + 0.8 + 0.9 + 1.0 */
+ assert Double.compare(5.5, sumOfSeries(0.1, 0.1, 10)) == 0;
- assert Double.compare(49600.0, sumOfSeries(1, 10, 100)) == 0;
- }
+ assert Double.compare(49600.0, sumOfSeries(1, 10, 100)) == 0;
+ }
- /**
- * Calculate sum of arithmetic series
- *
- * @param firstTerm the initial term of an arithmetic series
- * @param commonDiff the common difference of an arithmetic series
- * @param numOfTerms the total terms of an arithmetic series
- * @return sum of given arithmetic series
- */
- private static double sumOfSeries(double firstTerm, double commonDiff, int numOfTerms) {
- return numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff);
- }
+ /**
+ * Calculate sum of arithmetic series
+ *
+ * @param firstTerm the initial term of an arithmetic series
+ * @param commonDiff the common difference of an arithmetic series
+ * @param numOfTerms the total terms of an arithmetic series
+ * @return sum of given arithmetic series
+ */
+ private static double sumOfSeries(double firstTerm, double commonDiff, int numOfTerms) {
+ return numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff);
+ }
}
diff --git a/Maths/SumOfDigits.java b/Maths/SumOfDigits.java
index 11b3726a9ddf..ded331ddd940 100644
--- a/Maths/SumOfDigits.java
+++ b/Maths/SumOfDigits.java
@@ -1,56 +1,56 @@
package Maths;
public class SumOfDigits {
- public static void main(String[] args) {
- assert sumOfDigits(-123) == 6 && sumOfDigitsRecursion(-123) == 6 && sumOfDigitsFast(-123) == 6;
+ public static void main(String[] args) {
+ assert sumOfDigits(-123) == 6 && sumOfDigitsRecursion(-123) == 6 && sumOfDigitsFast(-123) == 6;
- assert sumOfDigits(0) == 0 && sumOfDigitsRecursion(0) == 0 && sumOfDigitsFast(0) == 0;
+ assert sumOfDigits(0) == 0 && sumOfDigitsRecursion(0) == 0 && sumOfDigitsFast(0) == 0;
- assert sumOfDigits(12345) == 15
- && sumOfDigitsRecursion(12345) == 15
- && sumOfDigitsFast(12345) == 15;
- }
+ assert sumOfDigits(12345) == 15
+ && sumOfDigitsRecursion(12345) == 15
+ && sumOfDigitsFast(12345) == 15;
+ }
- /**
- * Calculate the sum of digits of a number
- *
- * @param number the number contains digits
- * @return sum of digits of given {@code number}
- */
- public static int sumOfDigits(int number) {
- number = number < 0 ? -number : number; /* calculate abs value */
- int sum = 0;
- while (number != 0) {
- sum += number % 10;
- number /= 10;
+ /**
+ * Calculate the sum of digits of a number
+ *
+ * @param number the number contains digits
+ * @return sum of digits of given {@code number}
+ */
+ public static int sumOfDigits(int number) {
+ number = number < 0 ? -number : number; /* calculate abs value */
+ int sum = 0;
+ while (number != 0) {
+ sum += number % 10;
+ number /= 10;
+ }
+ return sum;
}
- return sum;
- }
- /**
- * Calculate the sum of digits of a number using recursion
- *
- * @param number the number contains digits
- * @return sum of digits of given {@code number}
- */
- public static int sumOfDigitsRecursion(int number) {
- number = number < 0 ? -number : number; /* calculate abs value */
- return number < 10 ? number : number % 10 + sumOfDigitsRecursion(number / 10);
- }
+ /**
+ * Calculate the sum of digits of a number using recursion
+ *
+ * @param number the number contains digits
+ * @return sum of digits of given {@code number}
+ */
+ public static int sumOfDigitsRecursion(int number) {
+ number = number < 0 ? -number : number; /* calculate abs value */
+ return number < 10 ? number : number % 10 + sumOfDigitsRecursion(number / 10);
+ }
- /**
- * Calculate the sum of digits of a number using char array
- *
- * @param number the number contains digits
- * @return sum of digits of given {@code number}
- */
- public static int sumOfDigitsFast(int number) {
- number = number < 0 ? -number : number; /* calculate abs value */
- char[] digits = (number + "").toCharArray();
- int sum = 0;
- for (int i = 0; i < digits.length; ++i) {
- sum += digits[i] - '0';
+ /**
+ * Calculate the sum of digits of a number using char array
+ *
+ * @param number the number contains digits
+ * @return sum of digits of given {@code number}
+ */
+ public static int sumOfDigitsFast(int number) {
+ number = number < 0 ? -number : number; /* calculate abs value */
+ char[] digits = (number + "").toCharArray();
+ int sum = 0;
+ for (int i = 0; i < digits.length; ++i) {
+ sum += digits[i] - '0';
+ }
+ return sum;
}
- return sum;
- }
}
diff --git a/Maths/VampireNumber.java b/Maths/VampireNumber.java
index e09dd0bb0cf8..a3345a19e285 100644
--- a/Maths/VampireNumber.java
+++ b/Maths/VampireNumber.java
@@ -16,63 +16,63 @@
*/
public class VampireNumber {
- public static void main(String[] args) {
+ public static void main(String[] args) {
- test(10, 1000);
- }
+ test(10, 1000);
+ }
- static void test(int startValue, int stopValue) {
- int countofRes = 1;
- StringBuilder res = new StringBuilder();
+ static void test(int startValue, int stopValue) {
+ int countofRes = 1;
+ StringBuilder res = new StringBuilder();
- for (int i = startValue; i <= stopValue; i++) {
- for (int j = i; j <= stopValue; j++) {
- // System.out.println(i+ " "+ j);
- if (isVampireNumber(i, j, true)) {
- countofRes++;
- res.append("" + countofRes + ": = ( " + i + "," + j + " = " + i * j + ")" + "\n");
+ for (int i = startValue; i <= stopValue; i++) {
+ for (int j = i; j <= stopValue; j++) {
+ // System.out.println(i+ " "+ j);
+ if (isVampireNumber(i, j, true)) {
+ countofRes++;
+ res.append("" + countofRes + ": = ( " + i + "," + j + " = " + i * j + ")" + "\n");
+ }
+ }
}
- }
+ System.out.println(res);
}
- System.out.println(res);
- }
- static boolean isVampireNumber(int a, int b, boolean noPseudoVamireNumbers) {
+ static boolean isVampireNumber(int a, int b, boolean noPseudoVamireNumbers) {
- // this is for pseudoVampireNumbers pseudovampire number need not be of length n/2 digits for
- // example
- // 126 = 6 x 21
- if (noPseudoVamireNumbers) {
- if (a * 10 <= b || b * 10 <= a) {
- return false;
- }
- }
+ // this is for pseudoVampireNumbers pseudovampire number need not be of length n/2 digits for
+ // example
+ // 126 = 6 x 21
+ if (noPseudoVamireNumbers) {
+ if (a * 10 <= b || b * 10 <= a) {
+ return false;
+ }
+ }
- String mulDigits = splitIntoDigits(a * b, 0);
- String faktorDigits = splitIntoDigits(a, b);
+ String mulDigits = splitIntoDigits(a * b, 0);
+ String faktorDigits = splitIntoDigits(a, b);
- return mulDigits.equals(faktorDigits);
- }
+ return mulDigits.equals(faktorDigits);
+ }
- // methode to Split the numbers to Digits
- static String splitIntoDigits(int num, int num2) {
+ // methode to Split the numbers to Digits
+ static String splitIntoDigits(int num, int num2) {
- StringBuilder res = new StringBuilder();
+ StringBuilder res = new StringBuilder();
- ArrayList digits = new ArrayList<>();
- while (num > 0) {
- digits.add(num % 10);
- num /= 10;
- }
- while (num2 > 0) {
- digits.add(num2 % 10);
- num2 /= 10;
- }
- Collections.sort(digits);
- for (int i : digits) {
- res.append(i);
- }
+ ArrayList digits = new ArrayList<>();
+ while (num > 0) {
+ digits.add(num % 10);
+ num /= 10;
+ }
+ while (num2 > 0) {
+ digits.add(num2 % 10);
+ num2 /= 10;
+ }
+ Collections.sort(digits);
+ for (int i : digits) {
+ res.append(i);
+ }
- return res.toString();
- }
+ return res.toString();
+ }
}
diff --git a/Misc/MedianOfRunningArray.java b/Misc/MedianOfRunningArray.java
index 21485e62f00a..1b68a88188e6 100644
--- a/Misc/MedianOfRunningArray.java
+++ b/Misc/MedianOfRunningArray.java
@@ -3,44 +3,46 @@
import java.util.Collections;
import java.util.PriorityQueue;
-/** @author shrutisheoran */
+/**
+ * @author shrutisheoran
+ */
public class MedianOfRunningArray {
- private PriorityQueue p1;
- private PriorityQueue p2;
+ private PriorityQueue p1;
+ private PriorityQueue p2;
- // Constructor
- public MedianOfRunningArray() {
- this.p1 = new PriorityQueue<>(Collections.reverseOrder()); // Max Heap
- this.p2 = new PriorityQueue<>(); // Min Heap
- }
+ // Constructor
+ public MedianOfRunningArray() {
+ this.p1 = new PriorityQueue<>(Collections.reverseOrder()); // Max Heap
+ this.p2 = new PriorityQueue<>(); // Min Heap
+ }
- /*
- Inserting lower half of array to max Heap
- and upper half to min heap
- */
- public void insert(Integer e) {
- p2.add(e);
- if (p2.size() - p1.size() > 1) p1.add(p2.remove());
- }
+ /*
+ Inserting lower half of array to max Heap
+ and upper half to min heap
+ */
+ public void insert(Integer e) {
+ p2.add(e);
+ if (p2.size() - p1.size() > 1) p1.add(p2.remove());
+ }
- /*
- Returns median at any given point
- */
- public Integer median() {
- if (p1.size() == p2.size()) return (p1.peek() + p2.peek()) / 2;
- return p1.size() > p2.size() ? p1.peek() : p2.peek();
- }
+ /*
+ Returns median at any given point
+ */
+ public Integer median() {
+ if (p1.size() == p2.size()) return (p1.peek() + p2.peek()) / 2;
+ return p1.size() > p2.size() ? p1.peek() : p2.peek();
+ }
- public static void main(String[] args) {
+ public static void main(String[] args) {
/*
Testing the median function
*/
- MedianOfRunningArray p = new MedianOfRunningArray();
- int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14};
- for (int i = 0; i < 9; i++) {
- p.insert(arr[i]);
- System.out.print(p.median() + " ");
+ MedianOfRunningArray p = new MedianOfRunningArray();
+ int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14};
+ for (int i = 0; i < 9; i++) {
+ p.insert(arr[i]);
+ System.out.print(p.median() + " ");
+ }
}
- }
}
diff --git a/Misc/PalindromePrime.java b/Misc/PalindromePrime.java
index 50b115de81c1..137b2cbb075c 100644
--- a/Misc/PalindromePrime.java
+++ b/Misc/PalindromePrime.java
@@ -4,44 +4,44 @@
public class PalindromePrime {
- public static void main(String[] args) { // Main funtion
- Scanner in = new Scanner(System.in);
- System.out.println("Enter the quantity of First Palindromic Primes you want");
- int n = in.nextInt(); // Input of how many first pallindromic prime we want
- functioning(n); // calling function - functioning
- in.close();
- }
+ public static void main(String[] args) { // Main funtion
+ Scanner in = new Scanner(System.in);
+ System.out.println("Enter the quantity of First Palindromic Primes you want");
+ int n = in.nextInt(); // Input of how many first pallindromic prime we want
+ functioning(n); // calling function - functioning
+ in.close();
+ }
- public static boolean prime(int num) { // checking if number is prime or not
- for (int divisor = 3; divisor <= Math.sqrt(num); divisor += 2) {
- if (num % divisor == 0) {
- return false; // false if not prime
- }
+ public static boolean prime(int num) { // checking if number is prime or not
+ for (int divisor = 3; divisor <= Math.sqrt(num); divisor += 2) {
+ if (num % divisor == 0) {
+ return false; // false if not prime
+ }
+ }
+ return true; // True if prime
}
- return true; // True if prime
- }
- public static int reverse(int n) { // Returns the reverse of the number
- int reverse = 0;
- while (n != 0) {
- reverse *= 10;
- reverse += n % 10;
- n /= 10;
+ public static int reverse(int n) { // Returns the reverse of the number
+ int reverse = 0;
+ while (n != 0) {
+ reverse *= 10;
+ reverse += n % 10;
+ n /= 10;
+ }
+ return reverse;
}
- return reverse;
- }
- public static void functioning(int y) {
- if (y == 0) return;
- System.out.print(2 + "\n"); // print the first Palindromic Prime
- int count = 1;
- int num = 3;
- while (count < y) {
- if (num == reverse(num) && prime(num)) { // number is prime and it's reverse is same
- count++; // counts check when to terminate while loop
- System.out.print(num + "\n"); // print the Palindromic Prime
- }
- num += 2; // inrease iterator value by two
+ public static void functioning(int y) {
+ if (y == 0) return;
+ System.out.print(2 + "\n"); // print the first Palindromic Prime
+ int count = 1;
+ int num = 3;
+ while (count < y) {
+ if (num == reverse(num) && prime(num)) { // number is prime and it's reverse is same
+ count++; // counts check when to terminate while loop
+ System.out.print(num + "\n"); // print the Palindromic Prime
+ }
+ num += 2; // inrease iterator value by two
+ }
}
- }
}
diff --git a/Misc/RangeInSortedArray.java b/Misc/RangeInSortedArray.java
index 5e0563bc21e4..abbe23824215 100644
--- a/Misc/RangeInSortedArray.java
+++ b/Misc/RangeInSortedArray.java
@@ -4,79 +4,79 @@
public class RangeInSortedArray {
- public static void main(String[] args) {
- // Testcases
- assert Arrays.equals(sortedRange(new int[] {1, 2, 3, 3, 3, 4, 5}, 3), new int[] {2, 4});
- assert Arrays.equals(sortedRange(new int[] {1, 2, 3, 3, 3, 4, 5}, 4), new int[] {5, 5});
- assert Arrays.equals(sortedRange(new int[] {0, 1, 2}, 3), new int[] {-1, -1});
- }
+ public static void main(String[] args) {
+ // Testcases
+ assert Arrays.equals(sortedRange(new int[]{1, 2, 3, 3, 3, 4, 5}, 3), new int[]{2, 4});
+ assert Arrays.equals(sortedRange(new int[]{1, 2, 3, 3, 3, 4, 5}, 4), new int[]{5, 5});
+ assert Arrays.equals(sortedRange(new int[]{0, 1, 2}, 3), new int[]{-1, -1});
+ }
- // Get the 1st and last occurrence index of a number 'key' in a non-decreasing array 'nums'
- // Gives [-1, -1] in case element doesn't exist in array
- public static int[] sortedRange(int[] nums, int key) {
- int[] range = new int[] {-1, -1};
- alteredBinSearchIter(nums, key, 0, nums.length - 1, range, true);
- alteredBinSearchIter(nums, key, 0, nums.length - 1, range, false);
- return range;
- }
+ // Get the 1st and last occurrence index of a number 'key' in a non-decreasing array 'nums'
+ // Gives [-1, -1] in case element doesn't exist in array
+ public static int[] sortedRange(int[] nums, int key) {
+ int[] range = new int[]{-1, -1};
+ alteredBinSearchIter(nums, key, 0, nums.length - 1, range, true);
+ alteredBinSearchIter(nums, key, 0, nums.length - 1, range, false);
+ return range;
+ }
- // Recursive altered binary search which searches for leftmost as well as rightmost occurrence of
- // 'key'
- public static void alteredBinSearch(
- int[] nums, int key, int left, int right, int[] range, boolean goLeft) {
- if (left > right) return;
- int mid = (left + right) / 2;
- if (nums[mid] > key) alteredBinSearch(nums, key, left, mid - 1, range, goLeft);
- else if (nums[mid] < key) alteredBinSearch(nums, key, mid + 1, right, range, goLeft);
- else {
- if (goLeft) {
- if (mid == 0 || nums[mid - 1] != key) range[0] = mid;
- else alteredBinSearch(nums, key, left, mid - 1, range, goLeft);
- } else {
- if (mid == nums.length - 1 || nums[mid + 1] != key) range[1] = mid;
- else alteredBinSearch(nums, key, mid + 1, right, range, goLeft);
- }
+ // Recursive altered binary search which searches for leftmost as well as rightmost occurrence of
+ // 'key'
+ public static void alteredBinSearch(
+ int[] nums, int key, int left, int right, int[] range, boolean goLeft) {
+ if (left > right) return;
+ int mid = (left + right) / 2;
+ if (nums[mid] > key) alteredBinSearch(nums, key, left, mid - 1, range, goLeft);
+ else if (nums[mid] < key) alteredBinSearch(nums, key, mid + 1, right, range, goLeft);
+ else {
+ if (goLeft) {
+ if (mid == 0 || nums[mid - 1] != key) range[0] = mid;
+ else alteredBinSearch(nums, key, left, mid - 1, range, goLeft);
+ } else {
+ if (mid == nums.length - 1 || nums[mid + 1] != key) range[1] = mid;
+ else alteredBinSearch(nums, key, mid + 1, right, range, goLeft);
+ }
+ }
}
- }
- // Iterative altered binary search which searches for leftmost as well as rightmost occurrence of
- // 'key'
- public static void alteredBinSearchIter(
- int[] nums, int key, int left, int right, int[] range, boolean goLeft) {
- while (left <= right) {
- int mid = (left + right) / 2;
- if (nums[mid] > key) right = mid - 1;
- else if (nums[mid] < key) left = mid + 1;
- else {
- if (goLeft) {
- if (mid == 0 || nums[mid - 1] != key) {
- range[0] = mid;
- return;
- } else right = mid - 1;
- } else {
- if (mid == nums.length - 1 || nums[mid + 1] != key) {
- range[1] = mid;
- return;
- } else left = mid + 1;
+ // Iterative altered binary search which searches for leftmost as well as rightmost occurrence of
+ // 'key'
+ public static void alteredBinSearchIter(
+ int[] nums, int key, int left, int right, int[] range, boolean goLeft) {
+ while (left <= right) {
+ int mid = (left + right) / 2;
+ if (nums[mid] > key) right = mid - 1;
+ else if (nums[mid] < key) left = mid + 1;
+ else {
+ if (goLeft) {
+ if (mid == 0 || nums[mid - 1] != key) {
+ range[0] = mid;
+ return;
+ } else right = mid - 1;
+ } else {
+ if (mid == nums.length - 1 || nums[mid + 1] != key) {
+ range[1] = mid;
+ return;
+ } else left = mid + 1;
+ }
+ }
}
- }
}
- }
- public static int getCountLessThan(int[] nums, int key) {
- return getLessThan(nums, key, 0, nums.length - 1);
- }
+ public static int getCountLessThan(int[] nums, int key) {
+ return getLessThan(nums, key, 0, nums.length - 1);
+ }
- public static int getLessThan(int[] nums, int key, int left, int right) {
- int count = 0;
- while (left <= right) {
- int mid = (left + right) / 2;
- if (nums[mid] > key) right = mid - 1;
- else if (nums[mid] <= key) {
- count = mid + 1; // Atleast mid+1 elements exist which are <= key
- left = mid + 1;
- }
+ public static int getLessThan(int[] nums, int key, int left, int right) {
+ int count = 0;
+ while (left <= right) {
+ int mid = (left + right) / 2;
+ if (nums[mid] > key) right = mid - 1;
+ else if (nums[mid] <= key) {
+ count = mid + 1; // Atleast mid+1 elements exist which are <= key
+ left = mid + 1;
+ }
+ }
+ return count;
}
- return count;
- }
}
diff --git a/Misc/WordBoggle.java b/Misc/WordBoggle.java
index e7f92642332b..a9fa8bd57f2a 100644
--- a/Misc/WordBoggle.java
+++ b/Misc/WordBoggle.java
@@ -2,129 +2,129 @@
public class WordBoggle {
- /**
- * O(nm * 8^s + ws) time where n=width of boggle board, m=height of boggle board, s=length of
- * longest word in string array, w= length of string array, 8 is due to 8 explorable neighbours
- * O(nm + ws) space.
- */
- public static List boggleBoard(char[][] board, String[] words) {
- Trie trie = new Trie();
- for (String word : words) trie.add(word);
- Set finalWords = new HashSet<>();
- boolean[][] visited = new boolean[board.length][board.length];
- for (int i = 0; i < board.length; i++)
- for (int j = 0; j < board[i].length; j++)
- explore(i, j, board, trie.root, visited, finalWords);
- return new ArrayList<>(finalWords);
- }
-
- public static void main(String[] args) {
- // Testcase
- List ans =
- new ArrayList<>(
- Arrays.asList("a", "boggle", "this", "NOTRE_PEATED", "is", "simple", "board"));
- assert (boggleBoard(
- new char[][] {
- {'t', 'h', 'i', 's', 'i', 's', 'a'},
- {'s', 'i', 'm', 'p', 'l', 'e', 'x'},
- {'b', 'x', 'x', 'x', 'x', 'e', 'b'},
- {'x', 'o', 'g', 'g', 'l', 'x', 'o'},
- {'x', 'x', 'x', 'D', 'T', 'r', 'a'},
- {'R', 'E', 'P', 'E', 'A', 'd', 'x'},
- {'x', 'x', 'x', 'x', 'x', 'x', 'x'},
- {'N', 'O', 'T', 'R', 'E', '_', 'P'},
- {'x', 'x', 'D', 'E', 'T', 'A', 'E'},
- },
- new String[] {
- "this",
- "is",
- "not",
- "a",
- "simple",
- "test",
- "boggle",
- "board",
- "REPEATED",
- "NOTRE_PEATED",
- })
- .equals(ans));
- }
-
- public static void explore(
- int i,
- int j,
- char[][] board,
- TrieNode trieNode,
- boolean[][] visited,
- Set finalWords) {
- if (visited[i][j]) return;
-
- char letter = board[i][j];
- if (!trieNode.children.containsKey(letter)) {
- return;
+ /**
+ * O(nm * 8^s + ws) time where n=width of boggle board, m=height of boggle board, s=length of
+ * longest word in string array, w= length of string array, 8 is due to 8 explorable neighbours
+ * O(nm + ws) space.
+ */
+ public static List boggleBoard(char[][] board, String[] words) {
+ Trie trie = new Trie();
+ for (String word : words) trie.add(word);
+ Set finalWords = new HashSet<>();
+ boolean[][] visited = new boolean[board.length][board.length];
+ for (int i = 0; i < board.length; i++)
+ for (int j = 0; j < board[i].length; j++)
+ explore(i, j, board, trie.root, visited, finalWords);
+ return new ArrayList<>(finalWords);
}
- visited[i][j] = true;
- trieNode = trieNode.children.get(letter);
- if (trieNode.children.containsKey('*')) finalWords.add(trieNode.word);
- List neighbors = getNeighbors(i, j, board);
- for (Integer[] neighbor : neighbors)
- explore(neighbor[0], neighbor[1], board, trieNode, visited, finalWords);
+ public static void main(String[] args) {
+ // Testcase
+ List ans =
+ new ArrayList<>(
+ Arrays.asList("a", "boggle", "this", "NOTRE_PEATED", "is", "simple", "board"));
+ assert (boggleBoard(
+ new char[][]{
+ {'t', 'h', 'i', 's', 'i', 's', 'a'},
+ {'s', 'i', 'm', 'p', 'l', 'e', 'x'},
+ {'b', 'x', 'x', 'x', 'x', 'e', 'b'},
+ {'x', 'o', 'g', 'g', 'l', 'x', 'o'},
+ {'x', 'x', 'x', 'D', 'T', 'r', 'a'},
+ {'R', 'E', 'P', 'E', 'A', 'd', 'x'},
+ {'x', 'x', 'x', 'x', 'x', 'x', 'x'},
+ {'N', 'O', 'T', 'R', 'E', '_', 'P'},
+ {'x', 'x', 'D', 'E', 'T', 'A', 'E'},
+ },
+ new String[]{
+ "this",
+ "is",
+ "not",
+ "a",
+ "simple",
+ "test",
+ "boggle",
+ "board",
+ "REPEATED",
+ "NOTRE_PEATED",
+ })
+ .equals(ans));
+ }
- visited[i][j] = false;
- }
+ public static void explore(
+ int i,
+ int j,
+ char[][] board,
+ TrieNode trieNode,
+ boolean[][] visited,
+ Set finalWords) {
+ if (visited[i][j]) return;
+
+ char letter = board[i][j];
+ if (!trieNode.children.containsKey(letter)) {
+ return;
+ }
+ visited[i][j] = true;
+ trieNode = trieNode.children.get(letter);
+ if (trieNode.children.containsKey('*')) finalWords.add(trieNode.word);
+
+ List neighbors = getNeighbors(i, j, board);
+ for (Integer[] neighbor : neighbors)
+ explore(neighbor[0], neighbor[1], board, trieNode, visited, finalWords);
+
+ visited[i][j] = false;
+ }
- public static List getNeighbors(int i, int j, char[][] board) {
- List neighbors = new ArrayList<>();
- if (i > 0 && j > 0) neighbors.add(new Integer[] {i - 1, j - 1});
+ public static List getNeighbors(int i, int j, char[][] board) {
+ List neighbors = new ArrayList<>();
+ if (i > 0 && j > 0) neighbors.add(new Integer[]{i - 1, j - 1});
- if (i > 0 && j < board[0].length - 1) neighbors.add(new Integer[] {i - 1, j + 1});
+ if (i > 0 && j < board[0].length - 1) neighbors.add(new Integer[]{i - 1, j + 1});
- if (i < board.length - 1 && j < board[0].length - 1)
- neighbors.add(new Integer[] {i + 1, j + 1});
+ if (i < board.length - 1 && j < board[0].length - 1)
+ neighbors.add(new Integer[]{i + 1, j + 1});
- if (i < board.length - 1 && j > 0) neighbors.add(new Integer[] {i + 1, j - 1});
+ if (i < board.length - 1 && j > 0) neighbors.add(new Integer[]{i + 1, j - 1});
- if (i > 0) neighbors.add(new Integer[] {i - 1, j});
+ if (i > 0) neighbors.add(new Integer[]{i - 1, j});
- if (i < board.length - 1) neighbors.add(new Integer[] {i + 1, j});
+ if (i < board.length - 1) neighbors.add(new Integer[]{i + 1, j});
- if (j > 0) neighbors.add(new Integer[] {i, j - 1});
+ if (j > 0) neighbors.add(new Integer[]{i, j - 1});
- if (j < board[0].length - 1) neighbors.add(new Integer[] {i, j + 1});
+ if (j < board[0].length - 1) neighbors.add(new Integer[]{i, j + 1});
- return neighbors;
- }
+ return neighbors;
+ }
}
// Trie used to optimize string search
class TrieNode {
- Map children = new HashMap<>();
- String word = "";
+ Map children = new HashMap<>();
+ String word = "";
}
class Trie {
- TrieNode root;
- char endSymbol;
-
- public Trie() {
- this.root = new TrieNode();
- this.endSymbol = '*';
- }
-
- public void add(String str) {
- TrieNode node = this.root;
- for (int i = 0; i < str.length(); i++) {
- char letter = str.charAt(i);
- if (!node.children.containsKey(letter)) {
- TrieNode newNode = new TrieNode();
- node.children.put(letter, newNode);
- }
- node = node.children.get(letter);
+ TrieNode root;
+ char endSymbol;
+
+ public Trie() {
+ this.root = new TrieNode();
+ this.endSymbol = '*';
+ }
+
+ public void add(String str) {
+ TrieNode node = this.root;
+ for (int i = 0; i < str.length(); i++) {
+ char letter = str.charAt(i);
+ if (!node.children.containsKey(letter)) {
+ TrieNode newNode = new TrieNode();
+ node.children.put(letter, newNode);
+ }
+ node = node.children.get(letter);
+ }
+ node.children.put(this.endSymbol, null);
+ node.word = str;
}
- node.children.put(this.endSymbol, null);
- node.word = str;
- }
}
diff --git a/Others/BestFit.java b/Others/BestFit.java
index 8eec9f615159..9131099b875d 100644
--- a/Others/BestFit.java
+++ b/Others/BestFit.java
@@ -2,95 +2,97 @@
import java.util.ArrayList;
-/** @author Dekas Dimitrios */
+/**
+ * @author Dekas Dimitrios
+ */
public class BestFit {
- private static final int NO_ALLOCATION =
- -255; // if a process has been allocated in position -255,
- // it means that it has not been actually allocated.
+ private static final int NO_ALLOCATION =
+ -255; // if a process has been allocated in position -255,
+ // it means that it has not been actually allocated.
- /**
- * Method to find the maximum valued element of an array filled with positive integers.
- *
- * @param array: an array filled with positive integers.
- * @return the maximum valued element of the array.
- */
- private static int findMaxElement(int[] array) {
- int max = -1;
- for (int value : array) {
- if (value > max) {
- max = value;
- }
+ /**
+ * Method to find the maximum valued element of an array filled with positive integers.
+ *
+ * @param array: an array filled with positive integers.
+ * @return the maximum valued element of the array.
+ */
+ private static int findMaxElement(int[] array) {
+ int max = -1;
+ for (int value : array) {
+ if (value > max) {
+ max = value;
+ }
+ }
+ return max;
}
- return max;
- }
- /**
- * Method to find the index of the memory block that is going to fit the given process based on
- * the best fit algorithm.
- *
- * @param blocks: the array with the available memory blocks.
- * @param process: the size of the process.
- * @return the index of the block that fits, or -255 if no such block exists.
- */
- private static int findBestFit(int[] blockSizes, int processSize) {
- // Initialize minDiff with an unreachable value by a difference between a blockSize and the
- // processSize.
- int minDiff = findMaxElement(blockSizes);
- int index =
- NO_ALLOCATION; // If there is no block that can fit the process, return NO_ALLOCATION as the
- // result.
- for (int i = 0;
- i < blockSizes.length;
- i++) { // Find the most fitting memory block for the given process.
- if (blockSizes[i] - processSize < minDiff && blockSizes[i] - processSize >= 0) {
- minDiff = blockSizes[i] - processSize;
- index = i;
- }
+ /**
+ * Method to find the index of the memory block that is going to fit the given process based on
+ * the best fit algorithm.
+ *
+ * @param blocks: the array with the available memory blocks.
+ * @param process: the size of the process.
+ * @return the index of the block that fits, or -255 if no such block exists.
+ */
+ private static int findBestFit(int[] blockSizes, int processSize) {
+ // Initialize minDiff with an unreachable value by a difference between a blockSize and the
+ // processSize.
+ int minDiff = findMaxElement(blockSizes);
+ int index =
+ NO_ALLOCATION; // If there is no block that can fit the process, return NO_ALLOCATION as the
+ // result.
+ for (int i = 0;
+ i < blockSizes.length;
+ i++) { // Find the most fitting memory block for the given process.
+ if (blockSizes[i] - processSize < minDiff && blockSizes[i] - processSize >= 0) {
+ minDiff = blockSizes[i] - processSize;
+ index = i;
+ }
+ }
+ return index;
}
- return index;
- }
- /**
- * Method to allocate memory to blocks according to the best fit algorithm. It should return an
- * ArrayList of Integers, where the index is the process ID (zero-indexed) and the value is the
- * block number (also zero-indexed).
- *
- * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available.
- * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory
- * blocks for.
- * @return the ArrayList filled with Integers repressenting the memory allocation that took place.
- */
- static ArrayList bestFit(int[] sizeOfBlocks, int[] sizeOfProcesses) {
- // The array list responsible for saving the memory allocations done by the best-fit algorithm
- ArrayList memAlloc = new ArrayList<>();
- // Do this for every process
- for (int processSize : sizeOfProcesses) {
- int chosenBlockIdx =
- findBestFit(
- sizeOfBlocks, processSize); // Find the index of the memory block going to be used
- memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
- if (chosenBlockIdx
- != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
- sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
- }
+ /**
+ * Method to allocate memory to blocks according to the best fit algorithm. It should return an
+ * ArrayList of Integers, where the index is the process ID (zero-indexed) and the value is the
+ * block number (also zero-indexed).
+ *
+ * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available.
+ * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory
+ * blocks for.
+ * @return the ArrayList filled with Integers repressenting the memory allocation that took place.
+ */
+ static ArrayList bestFit(int[] sizeOfBlocks, int[] sizeOfProcesses) {
+ // The array list responsible for saving the memory allocations done by the best-fit algorithm
+ ArrayList memAlloc = new ArrayList<>();
+ // Do this for every process
+ for (int processSize : sizeOfProcesses) {
+ int chosenBlockIdx =
+ findBestFit(
+ sizeOfBlocks, processSize); // Find the index of the memory block going to be used
+ memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
+ if (chosenBlockIdx
+ != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
+ sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
+ }
+ }
+ return memAlloc;
}
- return memAlloc;
- }
- /**
- * Method to print the memory allocated.
- *
- * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the
- * bestFit method.
- */
- public static void printMemoryAllocation(ArrayList memAllocation) {
- System.out.println("Process No.\tBlock No.");
- System.out.println("===========\t=========");
- for (int i = 0; i < memAllocation.size(); i++) {
- System.out.print(" " + i + "\t\t");
- if (memAllocation.get(i) != NO_ALLOCATION) System.out.print(memAllocation.get(i));
- else System.out.print("Not Allocated");
- System.out.println();
+ /**
+ * Method to print the memory allocated.
+ *
+ * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the
+ * bestFit method.
+ */
+ public static void printMemoryAllocation(ArrayList memAllocation) {
+ System.out.println("Process No.\tBlock No.");
+ System.out.println("===========\t=========");
+ for (int i = 0; i < memAllocation.size(); i++) {
+ System.out.print(" " + i + "\t\t");
+ if (memAllocation.get(i) != NO_ALLOCATION) System.out.print(memAllocation.get(i));
+ else System.out.print("Not Allocated");
+ System.out.println();
+ }
}
- }
}
diff --git a/Others/BrianKernighanAlgorithm.java b/Others/BrianKernighanAlgorithm.java
index 8767bee42d44..dc8899903f38 100644
--- a/Others/BrianKernighanAlgorithm.java
+++ b/Others/BrianKernighanAlgorithm.java
@@ -4,37 +4,39 @@
/**
* @author Nishita Aggarwal
- * Brian Kernighan’s Algorithm
- *
algorithm to count the number of set bits in a given number
- *
Subtraction of 1 from a number toggles all the bits (from right to left) till the
- * rightmost set bit(including the rightmost set bit). So if we subtract a number by 1 and do
- * bitwise & with itself i.e. (n & (n-1)), we unset the rightmost set bit.
- *
If we do n & (n-1) in a loop and count the no of times loop executes we get the set bit
- * count.
- *
- *
Time Complexity: O(logn)
+ *
Brian Kernighan’s Algorithm
+ *
algorithm to count the number of set bits in a given number
+ *
Subtraction of 1 from a number toggles all the bits (from right to left) till the
+ * rightmost set bit(including the rightmost set bit). So if we subtract a number by 1 and do
+ * bitwise & with itself i.e. (n & (n-1)), we unset the rightmost set bit.
+ *
If we do n & (n-1) in a loop and count the no of times loop executes we get the set bit
+ * count.
+ *
+ *
Time Complexity: O(logn)
*/
public class BrianKernighanAlgorithm {
- /**
- * @param num: number in which we count the set bits
- * @return int: Number of set bits
- */
- static int countSetBits(int num) {
- int cnt = 0;
- while (num != 0) {
- num = num & (num - 1);
- cnt++;
+ /**
+ * @param num: number in which we count the set bits
+ * @return int: Number of set bits
+ */
+ static int countSetBits(int num) {
+ int cnt = 0;
+ while (num != 0) {
+ num = num & (num - 1);
+ cnt++;
+ }
+ return cnt;
}
- return cnt;
- }
- /** @param args : command line arguments */
- public static void main(String args[]) {
- Scanner sc = new Scanner(System.in);
- int num = sc.nextInt();
- int setBitCount = countSetBits(num);
- System.out.println(setBitCount);
- sc.close();
- }
+ /**
+ * @param args : command line arguments
+ */
+ public static void main(String args[]) {
+ Scanner sc = new Scanner(System.in);
+ int num = sc.nextInt();
+ int setBitCount = countSetBits(num);
+ System.out.println(setBitCount);
+ sc.close();
+ }
}
diff --git a/Others/CRC32.java b/Others/CRC32.java
index 23712eef164a..155d22369f2c 100644
--- a/Others/CRC32.java
+++ b/Others/CRC32.java
@@ -2,26 +2,28 @@
import java.util.BitSet;
-/** Generates a crc32 checksum for a given string or byte array */
+/**
+ * Generates a crc32 checksum for a given string or byte array
+ */
public class CRC32 {
- public static void main(String[] args) {
- System.out.println(Integer.toHexString(crc32("Hello World")));
- }
+ public static void main(String[] args) {
+ System.out.println(Integer.toHexString(crc32("Hello World")));
+ }
- public static int crc32(String str) {
- return crc32(str.getBytes());
- }
+ public static int crc32(String str) {
+ return crc32(str.getBytes());
+ }
- public static int crc32(byte[] data) {
- BitSet bitSet = BitSet.valueOf(data);
- int crc32 = 0xFFFFFFFF; // initial value
- for (int i = 0; i < data.length * 8; i++) {
- if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0))
- crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial
- else crc32 = (crc32 << 1);
+ public static int crc32(byte[] data) {
+ BitSet bitSet = BitSet.valueOf(data);
+ int crc32 = 0xFFFFFFFF; // initial value
+ for (int i = 0; i < data.length * 8; i++) {
+ if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0))
+ crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial
+ else crc32 = (crc32 << 1);
+ }
+ crc32 = Integer.reverse(crc32); // result reflect
+ return crc32 ^ 0xFFFFFFFF; // final xor value
}
- crc32 = Integer.reverse(crc32); // result reflect
- return crc32 ^ 0xFFFFFFFF; // final xor value
- }
}
diff --git a/Others/CRCAlgorithm.java b/Others/CRCAlgorithm.java
index 3729a5ed5a33..efba0d87f39f 100644
--- a/Others/CRCAlgorithm.java
+++ b/Others/CRCAlgorithm.java
@@ -4,190 +4,192 @@
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
-/** @author dimgrichr */
+/**
+ * @author dimgrichr
+ */
public class CRCAlgorithm {
- private int correctMess;
+ private int correctMess;
- private int wrongMess;
+ private int wrongMess;
- private int wrongMessCaught;
+ private int wrongMessCaught;
- private int wrongMessNotCaught;
+ private int wrongMessNotCaught;
- private int messSize;
+ private int messSize;
- private double ber;
+ private double ber;
- private boolean messageChanged;
+ private boolean messageChanged;
- private ArrayList message;
+ private ArrayList message;
- private ArrayList dividedMessage;
+ private ArrayList dividedMessage;
- private ArrayList p;
+ private ArrayList p;
- private Random randomGenerator;
+ private Random randomGenerator;
- /**
- * The algorithm's main constructor. The most significant variables, used in the algorithm, are
- * set in their initial values.
- *
- * @param str The binary number P, in a string form, which is used by the CRC algorithm
- * @param size The size of every transmitted message
- * @param ber The Bit Error Rate
- */
- public CRCAlgorithm(String str, int size, double ber) {
- messageChanged = false;
- message = new ArrayList<>();
- messSize = size;
- dividedMessage = new ArrayList<>();
- p = new ArrayList<>();
- for (int i = 0; i < str.length(); i++) {
- p.add(Character.getNumericValue(str.charAt(i)));
+ /**
+ * The algorithm's main constructor. The most significant variables, used in the algorithm, are
+ * set in their initial values.
+ *
+ * @param str The binary number P, in a string form, which is used by the CRC algorithm
+ * @param size The size of every transmitted message
+ * @param ber The Bit Error Rate
+ */
+ public CRCAlgorithm(String str, int size, double ber) {
+ messageChanged = false;
+ message = new ArrayList<>();
+ messSize = size;
+ dividedMessage = new ArrayList<>();
+ p = new ArrayList<>();
+ for (int i = 0; i < str.length(); i++) {
+ p.add(Character.getNumericValue(str.charAt(i)));
+ }
+ randomGenerator = new Random();
+ correctMess = 0;
+ wrongMess = 0;
+ wrongMessCaught = 0;
+ wrongMessNotCaught = 0;
+ this.ber = ber;
}
- randomGenerator = new Random();
- correctMess = 0;
- wrongMess = 0;
- wrongMessCaught = 0;
- wrongMessNotCaught = 0;
- this.ber = ber;
- }
-
- /**
- * Returns the counter wrongMess
- *
- * @return wrongMess, the number of Wrong Messages
- */
- public int getWrongMess() {
- return wrongMess;
- }
-
- /**
- * Returns the counter wrongMessCaught
- *
- * @return wrongMessCaught, the number of wrong messages, which are caught by the CRC algoriithm
- */
- public int getWrongMessCaught() {
- return wrongMessCaught;
- }
-
- /**
- * Returns the counter wrongMessNotCaught
- *
- * @return wrongMessNotCaught, the number of wrong messages, which are not caught by the CRC
- * algorithm
- */
- public int getWrongMessNotCaught() {
- return wrongMessNotCaught;
- }
-
- /**
- * Returns the counter correctMess
- *
- * @return correctMess, the number of the Correct Messages
- */
- public int getCorrectMess() {
- return correctMess;
- }
-
- /**
- * Resets some of the object's values, used on the main function, so that it can be re-used, in
- * order not to waste too much memory and time, by creating new objects.
- */
- public void refactor() {
- messageChanged = false;
- message = new ArrayList<>();
- dividedMessage = new ArrayList<>();
- }
-
- /**
- * Random messages, consisted of 0's and 1's, are generated, so that they can later be transmitted
- */
- public void generateRandomMess() {
- for (int i = 0; i < messSize; i++) {
- int x = ThreadLocalRandom.current().nextInt(0, 2);
- message.add(x);
+
+ /**
+ * Returns the counter wrongMess
+ *
+ * @return wrongMess, the number of Wrong Messages
+ */
+ public int getWrongMess() {
+ return wrongMess;
}
- }
-
- /**
- * The most significant part of the CRC algorithm. The message is divided by P, so the
- * dividedMessage ArrayList is created. If check == true, the dividedMessaage is
- * examined, in order to see if it contains any 1's. If it does, the message is considered to be
- * wrong by the receiver,so the variable wrongMessCaught changes. If it does not, it is accepted,
- * so one of the variables correctMess, wrongMessNotCaught, changes. If check == false, the
- * diviided Message is added at the end of the ArrayList message.
- *
- * @param check the variable used to determine, if the message is going to be checked from the
- * receiver if true, it is checked otherwise, it is not
- */
- public void divideMessageWithP(boolean check) {
- ArrayList x = new ArrayList<>();
- ArrayList k = (ArrayList) message.clone();
- if (!check) {
- for (int i = 0; i < p.size() - 1; i++) {
- k.add(0);
- }
+
+ /**
+ * Returns the counter wrongMessCaught
+ *
+ * @return wrongMessCaught, the number of wrong messages, which are caught by the CRC algoriithm
+ */
+ public int getWrongMessCaught() {
+ return wrongMessCaught;
}
- while (!k.isEmpty()) {
- while (x.size() < p.size() && !k.isEmpty()) {
- x.add(k.get(0));
- k.remove(0);
- }
- if (x.size() == p.size()) {
- for (int i = 0; i < p.size(); i++) {
- if (x.get(i) == p.get(i)) {
- x.set(i, 0);
- } else {
- x.set(i, 1);
- }
- }
- for (int i = 0; i < x.size() && x.get(i) != 1; i++) {
- x.remove(0);
- }
- }
+
+ /**
+ * Returns the counter wrongMessNotCaught
+ *
+ * @return wrongMessNotCaught, the number of wrong messages, which are not caught by the CRC
+ * algorithm
+ */
+ public int getWrongMessNotCaught() {
+ return wrongMessNotCaught;
+ }
+
+ /**
+ * Returns the counter correctMess
+ *
+ * @return correctMess, the number of the Correct Messages
+ */
+ public int getCorrectMess() {
+ return correctMess;
+ }
+
+ /**
+ * Resets some of the object's values, used on the main function, so that it can be re-used, in
+ * order not to waste too much memory and time, by creating new objects.
+ */
+ public void refactor() {
+ messageChanged = false;
+ message = new ArrayList<>();
+ dividedMessage = new ArrayList<>();
}
- dividedMessage = (ArrayList) x.clone();
- if (!check) {
- for (int z : dividedMessage) {
- message.add(z);
- }
- } else {
- if (dividedMessage.contains(1) && messageChanged) {
- wrongMessCaught++;
- } else if (!dividedMessage.contains(1) && messageChanged) {
- wrongMessNotCaught++;
- } else if (!messageChanged) {
- correctMess++;
- }
+
+ /**
+ * Random messages, consisted of 0's and 1's, are generated, so that they can later be transmitted
+ */
+ public void generateRandomMess() {
+ for (int i = 0; i < messSize; i++) {
+ int x = ThreadLocalRandom.current().nextInt(0, 2);
+ message.add(x);
+ }
}
- }
-
- /**
- * Once the message is transmitted, some of it's elements, is possible to change from 1 to 0, or
- * from 0 to 1, because of the Bit Error Rate (ber). For every element of the message, a random
- * double number is created. If that number is smaller than ber, then the spesific element
- * changes. On the other hand, if it's bigger than ber, it does not. Based on these changes. the
- * boolean variable messageChanged, gets the value: true, or false.
- */
- public void changeMess() {
- for (int y : message) {
- double x = randomGenerator.nextDouble();
- while (x < 0.0000 || x > 1.00000) {
- x = randomGenerator.nextDouble();
- }
- if (x < ber) {
- messageChanged = true;
- if (y == 1) {
- message.set(message.indexOf(y), 0);
+
+ /**
+ * The most significant part of the CRC algorithm. The message is divided by P, so the
+ * dividedMessage ArrayList is created. If check == true, the dividedMessaage is
+ * examined, in order to see if it contains any 1's. If it does, the message is considered to be
+ * wrong by the receiver,so the variable wrongMessCaught changes. If it does not, it is accepted,
+ * so one of the variables correctMess, wrongMessNotCaught, changes. If check == false, the
+ * diviided Message is added at the end of the ArrayList message.
+ *
+ * @param check the variable used to determine, if the message is going to be checked from the
+ * receiver if true, it is checked otherwise, it is not
+ */
+ public void divideMessageWithP(boolean check) {
+ ArrayList x = new ArrayList<>();
+ ArrayList k = (ArrayList) message.clone();
+ if (!check) {
+ for (int i = 0; i < p.size() - 1; i++) {
+ k.add(0);
+ }
+ }
+ while (!k.isEmpty()) {
+ while (x.size() < p.size() && !k.isEmpty()) {
+ x.add(k.get(0));
+ k.remove(0);
+ }
+ if (x.size() == p.size()) {
+ for (int i = 0; i < p.size(); i++) {
+ if (x.get(i) == p.get(i)) {
+ x.set(i, 0);
+ } else {
+ x.set(i, 1);
+ }
+ }
+ for (int i = 0; i < x.size() && x.get(i) != 1; i++) {
+ x.remove(0);
+ }
+ }
+ }
+ dividedMessage = (ArrayList) x.clone();
+ if (!check) {
+ for (int z : dividedMessage) {
+ message.add(z);
+ }
} else {
- message.set(message.indexOf(y), 1);
+ if (dividedMessage.contains(1) && messageChanged) {
+ wrongMessCaught++;
+ } else if (!dividedMessage.contains(1) && messageChanged) {
+ wrongMessNotCaught++;
+ } else if (!messageChanged) {
+ correctMess++;
+ }
}
- }
}
- if (messageChanged) {
- wrongMess++;
+
+ /**
+ * Once the message is transmitted, some of it's elements, is possible to change from 1 to 0, or
+ * from 0 to 1, because of the Bit Error Rate (ber). For every element of the message, a random
+ * double number is created. If that number is smaller than ber, then the spesific element
+ * changes. On the other hand, if it's bigger than ber, it does not. Based on these changes. the
+ * boolean variable messageChanged, gets the value: true, or false.
+ */
+ public void changeMess() {
+ for (int y : message) {
+ double x = randomGenerator.nextDouble();
+ while (x < 0.0000 || x > 1.00000) {
+ x = randomGenerator.nextDouble();
+ }
+ if (x < ber) {
+ messageChanged = true;
+ if (y == 1) {
+ message.set(message.indexOf(y), 0);
+ } else {
+ message.set(message.indexOf(y), 1);
+ }
+ }
+ }
+ if (messageChanged) {
+ wrongMess++;
+ }
}
- }
}
diff --git a/Others/CountChar.java b/Others/CountChar.java
index 9136a4e686d0..8f37217ed5f9 100644
--- a/Others/CountChar.java
+++ b/Others/CountChar.java
@@ -4,21 +4,21 @@
public class CountChar {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- System.out.print("Enter your text: ");
- String str = input.nextLine();
- input.close();
- System.out.println("There are " + CountCharacters(str) + " characters.");
- }
+ public static void main(String[] args) {
+ Scanner input = new Scanner(System.in);
+ System.out.print("Enter your text: ");
+ String str = input.nextLine();
+ input.close();
+ System.out.println("There are " + CountCharacters(str) + " characters.");
+ }
- /**
- * Count non space character in string
- *
- * @param str String to count the characters
- * @return number of character in the specified string
- */
- private static int CountCharacters(String str) {
- return str.replaceAll("\\s", "").length();
- }
+ /**
+ * Count non space character in string
+ *
+ * @param str String to count the characters
+ * @return number of character in the specified string
+ */
+ private static int CountCharacters(String str) {
+ return str.replaceAll("\\s", "").length();
+ }
}
diff --git a/Others/CountWords.java b/Others/CountWords.java
index 746b027ebd59..5f96395def12 100644
--- a/Others/CountWords.java
+++ b/Others/CountWords.java
@@ -10,35 +10,35 @@
*/
public class CountWords {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- System.out.println("Enter your text: ");
- String str = input.nextLine();
+ public static void main(String[] args) {
+ Scanner input = new Scanner(System.in);
+ System.out.println("Enter your text: ");
+ String str = input.nextLine();
- System.out.println("Your text has " + wordCount(str) + " word(s)");
- System.out.println("Your text has " + secondaryWordCount(str) + " word(s)");
- input.close();
- }
+ System.out.println("Your text has " + wordCount(str) + " word(s)");
+ System.out.println("Your text has " + secondaryWordCount(str) + " word(s)");
+ input.close();
+ }
- private static int wordCount(String s) {
- if (s == null || s.isEmpty()) return 0;
- return s.trim().split("[\\s]+").length;
- }
+ private static int wordCount(String s) {
+ if (s == null || s.isEmpty()) return 0;
+ return s.trim().split("[\\s]+").length;
+ }
- /**
- * counts the number of words in a sentence but ignores all potential non-alphanumeric characters
- * that do not represent a word. runs in O(n) where n is the length of s
- *
- * @param s String: sentence with word(s)
- * @return int: number of words
- */
- private static int secondaryWordCount(String s) {
- if (s == null || s.isEmpty()) return 0;
- StringBuilder sb = new StringBuilder();
- for (char c : s.toCharArray()) {
- if (Character.isLetter(c) || Character.isDigit(c)) sb.append(c);
+ /**
+ * counts the number of words in a sentence but ignores all potential non-alphanumeric characters
+ * that do not represent a word. runs in O(n) where n is the length of s
+ *
+ * @param s String: sentence with word(s)
+ * @return int: number of words
+ */
+ private static int secondaryWordCount(String s) {
+ if (s == null || s.isEmpty()) return 0;
+ StringBuilder sb = new StringBuilder();
+ for (char c : s.toCharArray()) {
+ if (Character.isLetter(c) || Character.isDigit(c)) sb.append(c);
+ }
+ s = sb.toString();
+ return s.trim().split("[\\s]+").length;
}
- s = sb.toString();
- return s.trim().split("[\\s]+").length;
- }
}
diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java
index 913f25b3eb2b..fb260f6bcf83 100644
--- a/Others/Dijkstra.java
+++ b/Others/Dijkstra.java
@@ -10,191 +10,208 @@
* Original source of code: https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java Also most of
* the comments are from RosettaCode.
*/
+
import java.util.*;
public class Dijkstra {
- private static final Graph.Edge[] GRAPH = {
- // Distance from node "a" to node "b" is 7.
- // In the current Graph there is no way to move the other way (e,g, from "b" to "a"),
- // a new edge would be needed for that
- new Graph.Edge("a", "b", 7),
- new Graph.Edge("a", "c", 9),
- new Graph.Edge("a", "f", 14),
- new Graph.Edge("b", "c", 10),
- new Graph.Edge("b", "d", 15),
- new Graph.Edge("c", "d", 11),
- new Graph.Edge("c", "f", 2),
- new Graph.Edge("d", "e", 6),
- new Graph.Edge("e", "f", 9),
- };
- private static final String START = "a";
- private static final String END = "e";
-
- /** main function Will run the code with "GRAPH" that was defined above. */
- public static void main(String[] args) {
- Graph g = new Graph(GRAPH);
- g.dijkstra(START);
- g.printPath(END);
- // g.printAllPaths();
- }
+ private static final Graph.Edge[] GRAPH = {
+ // Distance from node "a" to node "b" is 7.
+ // In the current Graph there is no way to move the other way (e,g, from "b" to "a"),
+ // a new edge would be needed for that
+ new Graph.Edge("a", "b", 7),
+ new Graph.Edge("a", "c", 9),
+ new Graph.Edge("a", "f", 14),
+ new Graph.Edge("b", "c", 10),
+ new Graph.Edge("b", "d", 15),
+ new Graph.Edge("c", "d", 11),
+ new Graph.Edge("c", "f", 2),
+ new Graph.Edge("d", "e", 6),
+ new Graph.Edge("e", "f", 9),
+ };
+ private static final String START = "a";
+ private static final String END = "e";
+
+ /**
+ * main function Will run the code with "GRAPH" that was defined above.
+ */
+ public static void main(String[] args) {
+ Graph g = new Graph(GRAPH);
+ g.dijkstra(START);
+ g.printPath(END);
+ // g.printAllPaths();
+ }
}
class Graph {
- // mapping of vertex names to Vertex objects, built from a set of Edges
- private final Map graph;
-
- /** One edge of the graph (only used by Graph constructor) */
- public static class Edge {
- public final String v1, v2;
- public final int dist;
-
- public Edge(String v1, String v2, int dist) {
- this.v1 = v1;
- this.v2 = v2;
- this.dist = dist;
- }
- }
-
- /** One vertex of the graph, complete with mappings to neighbouring vertices */
- public static class Vertex implements Comparable {
- public final String name;
- // MAX_VALUE assumed to be infinity
- public int dist = Integer.MAX_VALUE;
- public Vertex previous = null;
- public final Map neighbours = new HashMap<>();
-
- public Vertex(String name) {
- this.name = name;
+ // mapping of vertex names to Vertex objects, built from a set of Edges
+ private final Map graph;
+
+ /**
+ * One edge of the graph (only used by Graph constructor)
+ */
+ public static class Edge {
+ public final String v1, v2;
+ public final int dist;
+
+ public Edge(String v1, String v2, int dist) {
+ this.v1 = v1;
+ this.v2 = v2;
+ this.dist = dist;
+ }
}
- private void printPath() {
- if (this == this.previous) {
- System.out.printf("%s", this.name);
- } else if (this.previous == null) {
- System.out.printf("%s(unreached)", this.name);
- } else {
- this.previous.printPath();
- System.out.printf(" -> %s(%d)", this.name, this.dist);
- }
- }
+ /**
+ * One vertex of the graph, complete with mappings to neighbouring vertices
+ */
+ public static class Vertex implements Comparable {
+ public final String name;
+ // MAX_VALUE assumed to be infinity
+ public int dist = Integer.MAX_VALUE;
+ public Vertex previous = null;
+ public final Map neighbours = new HashMap<>();
+
+ public Vertex(String name) {
+ this.name = name;
+ }
- public int compareTo(Vertex other) {
- if (dist == other.dist) return name.compareTo(other.name);
+ private void printPath() {
+ if (this == this.previous) {
+ System.out.printf("%s", this.name);
+ } else if (this.previous == null) {
+ System.out.printf("%s(unreached)", this.name);
+ } else {
+ this.previous.printPath();
+ System.out.printf(" -> %s(%d)", this.name, this.dist);
+ }
+ }
- return Integer.compare(dist, other.dist);
- }
+ public int compareTo(Vertex other) {
+ if (dist == other.dist) return name.compareTo(other.name);
- @Override
- public boolean equals(Object object) {
- if (this == object) return true;
- if (object == null || getClass() != object.getClass()) return false;
- if (!super.equals(object)) return false;
+ return Integer.compare(dist, other.dist);
+ }
- Vertex vertex = (Vertex) object;
+ @Override
+ public boolean equals(Object object) {
+ if (this == object) return true;
+ if (object == null || getClass() != object.getClass()) return false;
+ if (!super.equals(object)) return false;
- if (dist != vertex.dist) return false;
- if (name != null ? !name.equals(vertex.name) : vertex.name != null) return false;
- if (previous != null ? !previous.equals(vertex.previous) : vertex.previous != null)
- return false;
- if (neighbours != null ? !neighbours.equals(vertex.neighbours) : vertex.neighbours != null)
- return false;
+ Vertex vertex = (Vertex) object;
- return true;
- }
+ if (dist != vertex.dist) return false;
+ if (name != null ? !name.equals(vertex.name) : vertex.name != null) return false;
+ if (previous != null ? !previous.equals(vertex.previous) : vertex.previous != null)
+ return false;
+ if (neighbours != null ? !neighbours.equals(vertex.neighbours) : vertex.neighbours != null)
+ return false;
- @Override
- public int hashCode() {
- int result = super.hashCode();
- result = 31 * result + (name != null ? name.hashCode() : 0);
- result = 31 * result + dist;
- result = 31 * result + (previous != null ? previous.hashCode() : 0);
- result = 31 * result + (neighbours != null ? neighbours.hashCode() : 0);
- return result;
- }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = super.hashCode();
+ result = 31 * result + (name != null ? name.hashCode() : 0);
+ result = 31 * result + dist;
+ result = 31 * result + (previous != null ? previous.hashCode() : 0);
+ result = 31 * result + (neighbours != null ? neighbours.hashCode() : 0);
+ return result;
+ }
- @Override
- public String toString() {
- return "(" + name + ", " + dist + ")";
+ @Override
+ public String toString() {
+ return "(" + name + ", " + dist + ")";
+ }
}
- }
- /** Builds a graph from a set of edges */
- public Graph(Edge[] edges) {
- graph = new HashMap<>(edges.length);
+ /**
+ * Builds a graph from a set of edges
+ */
+ public Graph(Edge[] edges) {
+ graph = new HashMap<>(edges.length);
- // one pass to find all vertices
- for (Edge e : edges) {
- if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));
- if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));
- }
+ // one pass to find all vertices
+ for (Edge e : edges) {
+ if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));
+ if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));
+ }
- // another pass to set neighbouring vertices
- for (Edge e : edges) {
- graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
- // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected
- // graph
+ // another pass to set neighbouring vertices
+ for (Edge e : edges) {
+ graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
+ // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected
+ // graph
+ }
}
- }
- /** Runs dijkstra using a specified source vertex */
- public void dijkstra(String startName) {
- if (!graph.containsKey(startName)) {
- System.err.printf("Graph doesn't contain start vertex \"%s\"%n", startName);
- return;
- }
- final Vertex source = graph.get(startName);
- NavigableSet q = new TreeSet<>();
-
- // set-up vertices
- for (Vertex v : graph.values()) {
- v.previous = v == source ? source : null;
- v.dist = v == source ? 0 : Integer.MAX_VALUE;
- q.add(v);
+ /**
+ * Runs dijkstra using a specified source vertex
+ */
+ public void dijkstra(String startName) {
+ if (!graph.containsKey(startName)) {
+ System.err.printf("Graph doesn't contain start vertex \"%s\"%n", startName);
+ return;
+ }
+ final Vertex source = graph.get(startName);
+ NavigableSet q = new TreeSet<>();
+
+ // set-up vertices
+ for (Vertex v : graph.values()) {
+ v.previous = v == source ? source : null;
+ v.dist = v == source ? 0 : Integer.MAX_VALUE;
+ q.add(v);
+ }
+
+ dijkstra(q);
}
- dijkstra(q);
- }
-
- /** Implementation of dijkstra's algorithm using a binary heap. */
- private void dijkstra(final NavigableSet q) {
- Vertex u, v;
- while (!q.isEmpty()) {
- // vertex with shortest distance (first iteration will return source)
- u = q.pollFirst();
- if (u.dist == Integer.MAX_VALUE)
- break; // we can ignore u (and any other remaining vertices) since they are unreachable
-
- // look at distances to each neighbour
- for (Map.Entry a : u.neighbours.entrySet()) {
- v = a.getKey(); // the neighbour in this iteration
-
- final int alternateDist = u.dist + a.getValue();
- if (alternateDist < v.dist) { // shorter path to neighbour found
- q.remove(v);
- v.dist = alternateDist;
- v.previous = u;
- q.add(v);
+ /**
+ * Implementation of dijkstra's algorithm using a binary heap.
+ */
+ private void dijkstra(final NavigableSet q) {
+ Vertex u, v;
+ while (!q.isEmpty()) {
+ // vertex with shortest distance (first iteration will return source)
+ u = q.pollFirst();
+ if (u.dist == Integer.MAX_VALUE)
+ break; // we can ignore u (and any other remaining vertices) since they are unreachable
+
+ // look at distances to each neighbour
+ for (Map.Entry a : u.neighbours.entrySet()) {
+ v = a.getKey(); // the neighbour in this iteration
+
+ final int alternateDist = u.dist + a.getValue();
+ if (alternateDist < v.dist) { // shorter path to neighbour found
+ q.remove(v);
+ v.dist = alternateDist;
+ v.previous = u;
+ q.add(v);
+ }
+ }
}
- }
}
- }
- /** Prints a path from the source to the specified vertex */
- public void printPath(String endName) {
- if (!graph.containsKey(endName)) {
- System.err.printf("Graph doesn't contain end vertex \"%s\"%n", endName);
- return;
- }
+ /**
+ * Prints a path from the source to the specified vertex
+ */
+ public void printPath(String endName) {
+ if (!graph.containsKey(endName)) {
+ System.err.printf("Graph doesn't contain end vertex \"%s\"%n", endName);
+ return;
+ }
- graph.get(endName).printPath();
- System.out.println();
- }
+ graph.get(endName).printPath();
+ System.out.println();
+ }
- /** Prints the path from the source to every vertex (output order is not guaranteed) */
- public void printAllPaths() {
- for (Vertex v : graph.values()) {
- v.printPath();
- System.out.println();
+ /**
+ * Prints the path from the source to every vertex (output order is not guaranteed)
+ */
+ public void printAllPaths() {
+ for (Vertex v : graph.values()) {
+ v.printPath();
+ System.out.println();
+ }
}
- }
}
diff --git a/Others/EulersFunction.java b/Others/EulersFunction.java
index 1e7efeafbd0b..9069e7cecf85 100644
--- a/Others/EulersFunction.java
+++ b/Others/EulersFunction.java
@@ -6,23 +6,23 @@
* See https://en.wikipedia.org/wiki/Euler%27s_totient_function
*/
public class EulersFunction {
- // This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time
- // complexity;
- public static int getEuler(int n) {
- int result = n;
- for (int i = 2; i * i <= n; i++) {
- if (n % i == 0) {
- while (n % i == 0) n /= i;
- result -= result / i;
- }
+ // This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time
+ // complexity;
+ public static int getEuler(int n) {
+ int result = n;
+ for (int 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;
+ return result;
}
- if (n > 1) result -= result / n;
- return result;
- }
- public static void main(String[] args) {
- for (int i = 1; i < 100; i++) {
- System.out.println(getEuler(i));
+ public static void main(String[] args) {
+ for (int i = 1; i < 100; i++) {
+ System.out.println(getEuler(i));
+ }
}
- }
}
diff --git a/Others/FibToN.java b/Others/FibToN.java
index 479e895729c4..536b52d9aa6b 100644
--- a/Others/FibToN.java
+++ b/Others/FibToN.java
@@ -11,21 +11,21 @@
*
Source for the explanation: https://en.wikipedia.org/wiki/Fibonacci_number
*/
public class FibToN {
- public static void main(String[] args) {
- // take input
- Scanner scn = new Scanner(System.in);
- int N = scn.nextInt();
- // print all Fibonacci numbers that are smaller than your given input N
- int first = 0, second = 1;
- scn.close();
- while (first <= N) {
- // print first fibo 0 then add second fibo into it while updating second as well
+ public static void main(String[] args) {
+ // take input
+ Scanner scn = new Scanner(System.in);
+ int N = scn.nextInt();
+ // print all Fibonacci numbers that are smaller than your given input N
+ int first = 0, second = 1;
+ scn.close();
+ while (first <= N) {
+ // print first fibo 0 then add second fibo into it while updating second as well
- System.out.println(first);
+ System.out.println(first);
- int next = first + second;
- first = second;
- second = next;
+ int next = first + second;
+ first = second;
+ second = next;
+ }
}
- }
}
diff --git a/Others/FirstFit.java b/Others/FirstFit.java
index 06cea111c54d..8f45e6d39da1 100644
--- a/Others/FirstFit.java
+++ b/Others/FirstFit.java
@@ -2,71 +2,73 @@
import java.util.ArrayList;
-/** @author Dekas Dimitrios */
+/**
+ * @author Dekas Dimitrios
+ */
public class FirstFit {
- private static final int NO_ALLOCATION =
- -255; // if a process has been allocated in position -255,
- // it means that it has not been actually allocated.
+ private static final int NO_ALLOCATION =
+ -255; // if a process has been allocated in position -255,
+ // it means that it has not been actually allocated.
- /**
- * Method to find the index of the memory block that is going to fit the given process based on
- * the first fit algorithm.
- *
- * @param blocks: the array with the available memory blocks.
- * @param process: the size of the process.
- * @return the index of the block that fits, or -255 if no such block exists.
- */
- private static int findFirstFit(int[] blockSizes, int processSize) {
- for (int i = 0; i < blockSizes.length; i++) {
- if (blockSizes[i] >= processSize) {
- return i;
- }
+ /**
+ * Method to find the index of the memory block that is going to fit the given process based on
+ * the first fit algorithm.
+ *
+ * @param blocks: the array with the available memory blocks.
+ * @param process: the size of the process.
+ * @return the index of the block that fits, or -255 if no such block exists.
+ */
+ private static int findFirstFit(int[] blockSizes, int processSize) {
+ for (int i = 0; i < blockSizes.length; i++) {
+ if (blockSizes[i] >= processSize) {
+ return i;
+ }
+ }
+ // If there is not a block that can fit the process, return -255 as the result
+ return NO_ALLOCATION;
}
- // If there is not a block that can fit the process, return -255 as the result
- return NO_ALLOCATION;
- }
- /**
- * Method to allocate memory to blocks according to the first fit algorithm. It should return an
- * ArrayList of Integers, where the index is the process ID (zero-indexed) and the value is the
- * block number (also zero-indexed).
- *
- * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available.
- * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory
- * blocks for.
- * @return the ArrayList filled with Integers repressenting the memory allocation that took place.
- */
- static ArrayList firstFit(int[] sizeOfBlocks, int[] sizeOfProcesses) {
- // The array list responsible for saving the memory allocations done by the first-fit algorithm
- ArrayList memAlloc = new ArrayList<>();
- // Do this for every process
- for (int processSize : sizeOfProcesses) {
- int chosenBlockIdx =
- findFirstFit(
- sizeOfBlocks, processSize); // Find the index of the memory block going to be used
- memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
- if (chosenBlockIdx
- != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
- sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
- }
+ /**
+ * Method to allocate memory to blocks according to the first fit algorithm. It should return an
+ * ArrayList of Integers, where the index is the process ID (zero-indexed) and the value is the
+ * block number (also zero-indexed).
+ *
+ * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available.
+ * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory
+ * blocks for.
+ * @return the ArrayList filled with Integers repressenting the memory allocation that took place.
+ */
+ static ArrayList firstFit(int[] sizeOfBlocks, int[] sizeOfProcesses) {
+ // The array list responsible for saving the memory allocations done by the first-fit algorithm
+ ArrayList memAlloc = new ArrayList<>();
+ // Do this for every process
+ for (int processSize : sizeOfProcesses) {
+ int chosenBlockIdx =
+ findFirstFit(
+ sizeOfBlocks, processSize); // Find the index of the memory block going to be used
+ memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
+ if (chosenBlockIdx
+ != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
+ sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
+ }
+ }
+ return memAlloc;
}
- return memAlloc;
- }
- /**
- * Method to print the memory allocated.
- *
- * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the
- * firstFit method.
- */
- public static void printMemoryAllocation(ArrayList memAllocation) {
- System.out.println("Process No.\tBlock No.");
- System.out.println("===========\t=========");
- for (int i = 0; i < memAllocation.size(); i++) {
- System.out.print(" " + i + "\t\t");
- if (memAllocation.get(i) != NO_ALLOCATION) System.out.print(memAllocation.get(i));
- else System.out.print("Not Allocated");
- System.out.println();
+ /**
+ * Method to print the memory allocated.
+ *
+ * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the
+ * firstFit method.
+ */
+ public static void printMemoryAllocation(ArrayList memAllocation) {
+ System.out.println("Process No.\tBlock No.");
+ System.out.println("===========\t=========");
+ for (int i = 0; i < memAllocation.size(); i++) {
+ System.out.print(" " + i + "\t\t");
+ if (memAllocation.get(i) != NO_ALLOCATION) System.out.print(memAllocation.get(i));
+ else System.out.print("Not Allocated");
+ System.out.println();
+ }
}
- }
}
diff --git a/Others/FloydTriangle.java b/Others/FloydTriangle.java
index 73b988f72398..3edf6db7b60c 100644
--- a/Others/FloydTriangle.java
+++ b/Others/FloydTriangle.java
@@ -3,16 +3,16 @@
import java.util.Scanner;
class FloydTriangle {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter the number of rows which you want in your Floyd Triangle: ");
- int r = sc.nextInt(), n = 0;
- sc.close();
- for (int i = 0; i < r; i++) {
- for (int j = 0; j <= i; j++) {
- System.out.print(++n + " ");
- }
- System.out.println();
+ public static void main(String[] args) {
+ Scanner sc = new Scanner(System.in);
+ System.out.println("Enter the number of rows which you want in your Floyd Triangle: ");
+ int r = sc.nextInt(), n = 0;
+ sc.close();
+ for (int i = 0; i < r; i++) {
+ for (int j = 0; j <= i; j++) {
+ System.out.print(++n + " ");
+ }
+ System.out.println();
+ }
}
- }
}
diff --git a/Others/GuassLegendre.java b/Others/GuassLegendre.java
index 4b30bdc3fa03..20322235da7f 100644
--- a/Others/GuassLegendre.java
+++ b/Others/GuassLegendre.java
@@ -7,34 +7,34 @@
*/
public class GuassLegendre {
- public static void main(String[] args) {
- for (int i = 1; i <= 3; ++i) System.out.println(pi(i));
- }
+ public static void main(String[] args) {
+ for (int i = 1; i <= 3; ++i) System.out.println(pi(i));
+ }
- static double pi(int l) {
- /*
- * l: No of loops to run
- */
+ static double pi(int l) {
+ /*
+ * l: No of loops to run
+ */
- double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1;
- for (int i = 0; i < l; ++i) {
- double temp[] = update(a, b, t, p);
- a = temp[0];
- b = temp[1];
- t = temp[2];
- p = temp[3];
- }
+ double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1;
+ for (int i = 0; i < l; ++i) {
+ double temp[] = update(a, b, t, p);
+ a = temp[0];
+ b = temp[1];
+ t = temp[2];
+ p = temp[3];
+ }
- return Math.pow(a + b, 2) / (4 * t);
- }
+ return Math.pow(a + b, 2) / (4 * t);
+ }
- static double[] update(double a, double b, double t, double p) {
- double values[] = new double[4];
- values[0] = (a + b) / 2;
- values[1] = Math.sqrt(a * b);
- values[2] = t - p * Math.pow(a - values[0], 2);
- values[3] = 2 * p;
+ static double[] update(double a, double b, double t, double p) {
+ double values[] = new double[4];
+ values[0] = (a + b) / 2;
+ values[1] = Math.sqrt(a * b);
+ values[2] = t - p * Math.pow(a - values[0], 2);
+ values[3] = 2 * p;
- return values;
- }
+ return values;
+ }
}
diff --git a/Others/InsertDeleteInArray.java b/Others/InsertDeleteInArray.java
index 20d81462136f..807fe41b72b6 100644
--- a/Others/InsertDeleteInArray.java
+++ b/Others/InsertDeleteInArray.java
@@ -4,45 +4,45 @@
public class InsertDeleteInArray {
- public static void main(String[] args) {
- Scanner s = new Scanner(System.in); // Input statement
- System.out.println("Enter the size of the array");
- int size = s.nextInt();
- int a[] = new int[size];
- int i;
+ public static void main(String[] args) {
+ Scanner s = new Scanner(System.in); // Input statement
+ System.out.println("Enter the size of the array");
+ int size = s.nextInt();
+ int a[] = new int[size];
+ int i;
- // To enter the initial elements
- for (i = 0; i < size; i++) {
- System.out.println("Enter the element");
- a[i] = s.nextInt();
- }
+ // To enter the initial elements
+ for (i = 0; i < size; i++) {
+ System.out.println("Enter the element");
+ a[i] = s.nextInt();
+ }
- // To insert a new element(we are creating a new array)
- System.out.println("Enter the index at which the element should be inserted");
- int insert_pos = s.nextInt();
- System.out.println("Enter the element to be inserted");
- int ins = s.nextInt();
- int size2 = size + 1;
- int b[] = new int[size2];
- for (i = 0; i < size2; i++) {
- if (i <= insert_pos) {
- b[i] = a[i];
- } else {
- b[i] = a[i - 1];
- }
- }
- b[insert_pos] = ins;
- for (i = 0; i < size2; i++) {
- System.out.println(b[i]);
- }
+ // To insert a new element(we are creating a new array)
+ System.out.println("Enter the index at which the element should be inserted");
+ int insert_pos = s.nextInt();
+ System.out.println("Enter the element to be inserted");
+ int ins = s.nextInt();
+ int size2 = size + 1;
+ int b[] = new int[size2];
+ for (i = 0; i < size2; i++) {
+ if (i <= insert_pos) {
+ b[i] = a[i];
+ } else {
+ b[i] = a[i - 1];
+ }
+ }
+ b[insert_pos] = ins;
+ for (i = 0; i < size2; i++) {
+ System.out.println(b[i]);
+ }
- // To delete an element given the index
- System.out.println("Enter the index at which element is to be deleted");
- int del_pos = s.nextInt();
- for (i = del_pos; i < size2 - 1; i++) {
- b[i] = b[i + 1];
+ // To delete an element given the index
+ System.out.println("Enter the index at which element is to be deleted");
+ int del_pos = s.nextInt();
+ for (i = del_pos; i < size2 - 1; i++) {
+ b[i] = b[i + 1];
+ }
+ for (i = 0; i < size2 - 1; i++) System.out.println(b[i]);
+ s.close();
}
- for (i = 0; i < size2 - 1; i++) System.out.println(b[i]);
- s.close();
- }
}
diff --git a/Others/KMP.java b/Others/KMP.java
index c221edf3f353..950f56a1a24a 100644
--- a/Others/KMP.java
+++ b/Others/KMP.java
@@ -1,53 +1,55 @@
package Others;
-/** Implementation of Knuth–Morris–Pratt algorithm Usage: see the main function for an example */
+/**
+ * Implementation of Knuth–Morris–Pratt algorithm Usage: see the main function for an example
+ */
public class KMP {
- // a working example
- public static void main(String[] args) {
- final String haystack = "AAAAABAAABA"; // This is the full string
- final String needle = "AAAA"; // This is the substring that we want to find
- KMPmatcher(haystack, needle);
- }
+ // a working example
+ public static void main(String[] args) {
+ final String haystack = "AAAAABAAABA"; // This is the full string
+ final String needle = "AAAA"; // This is the substring that we want to find
+ KMPmatcher(haystack, needle);
+ }
- // find the starting index in string haystack[] that matches the search word P[]
- public static void KMPmatcher(final String haystack, final String needle) {
- final int m = haystack.length();
- final int n = needle.length();
- final int[] pi = computePrefixFunction(needle);
- int q = 0;
- for (int i = 0; i < m; i++) {
- while (q > 0 && haystack.charAt(i) != needle.charAt(q)) {
- q = pi[q - 1];
- }
+ // find the starting index in string haystack[] that matches the search word P[]
+ public static void KMPmatcher(final String haystack, final String needle) {
+ final int m = haystack.length();
+ final int n = needle.length();
+ final int[] pi = computePrefixFunction(needle);
+ int q = 0;
+ for (int i = 0; i < m; i++) {
+ while (q > 0 && haystack.charAt(i) != needle.charAt(q)) {
+ q = pi[q - 1];
+ }
- if (haystack.charAt(i) == needle.charAt(q)) {
- q++;
- }
+ if (haystack.charAt(i) == needle.charAt(q)) {
+ q++;
+ }
- if (q == n) {
- System.out.println("Pattern starts: " + (i + 1 - n));
- q = pi[q - 1];
- }
+ if (q == n) {
+ System.out.println("Pattern starts: " + (i + 1 - n));
+ q = pi[q - 1];
+ }
+ }
}
- }
- // return the prefix function
- private static int[] computePrefixFunction(final String P) {
- final int n = P.length();
- final int[] pi = new int[n];
- pi[0] = 0;
- int q = 0;
- for (int i = 1; i < n; i++) {
- while (q > 0 && P.charAt(q) != P.charAt(i)) {
- q = pi[q - 1];
- }
+ // return the prefix function
+ private static int[] computePrefixFunction(final String P) {
+ final int n = P.length();
+ final int[] pi = new int[n];
+ pi[0] = 0;
+ int q = 0;
+ for (int i = 1; i < n; i++) {
+ while (q > 0 && P.charAt(q) != P.charAt(i)) {
+ q = pi[q - 1];
+ }
- if (P.charAt(q) == P.charAt(i)) {
- q++;
- }
+ if (P.charAt(q) == P.charAt(i)) {
+ q++;
+ }
- pi[i] = q;
+ pi[i] = q;
+ }
+ return pi;
}
- return pi;
- }
}
diff --git a/Others/Krishnamurthy.java b/Others/Krishnamurthy.java
index d7a48522537f..5896f7dc03c9 100644
--- a/Others/Krishnamurthy.java
+++ b/Others/Krishnamurthy.java
@@ -3,25 +3,25 @@
import java.util.Scanner;
class Krishnamurthy {
- static int fact(int n) {
- int i, p = 1;
- for (i = n; i >= 1; i--) p = p * i;
- return p;
- }
+ static int fact(int n) {
+ int i, p = 1;
+ for (i = n; i >= 1; i--) p = p * i;
+ return p;
+ }
- public static void main(String args[]) {
- Scanner sc = new Scanner(System.in);
- int a, b, s = 0;
- System.out.print("Enter the number : ");
- a = sc.nextInt();
- int n = a;
- while (a > 0) {
- b = a % 10;
- s = s + fact(b);
- a = a / 10;
+ public static void main(String args[]) {
+ Scanner sc = new Scanner(System.in);
+ int a, b, s = 0;
+ System.out.print("Enter the number : ");
+ a = sc.nextInt();
+ int n = a;
+ while (a > 0) {
+ b = a % 10;
+ s = s + fact(b);
+ a = a / 10;
+ }
+ if (s == n) System.out.print(n + " is a krishnamurthy number");
+ else System.out.print(n + " is not a krishnamurthy number");
+ sc.close();
}
- if (s == n) System.out.print(n + " is a krishnamurthy number");
- else System.out.print(n + " is not a krishnamurthy number");
- sc.close();
- }
}
diff --git a/Others/LinearCongruentialGenerator.java b/Others/LinearCongruentialGenerator.java
index d735d6a663e0..ac3695759516 100644
--- a/Others/LinearCongruentialGenerator.java
+++ b/Others/LinearCongruentialGenerator.java
@@ -8,55 +8,55 @@
*/
public class LinearCongruentialGenerator {
- private double a, c, m, previousValue;
+ private double a, c, m, previousValue;
- /***
- * These parameters are saved and used when nextNumber() is called.
- * The current timestamp in milliseconds is used as the seed.
- *
- * @param multiplier
- * @param increment
- * @param modulo The maximum number that can be generated (exclusive). A common value is 2^32.
- */
- public LinearCongruentialGenerator(double multiplier, double increment, double modulo) {
- this(System.currentTimeMillis(), multiplier, increment, modulo);
- }
+ /***
+ * These parameters are saved and used when nextNumber() is called.
+ * The current timestamp in milliseconds is used as the seed.
+ *
+ * @param multiplier
+ * @param increment
+ * @param modulo The maximum number that can be generated (exclusive). A common value is 2^32.
+ */
+ public LinearCongruentialGenerator(double multiplier, double increment, double modulo) {
+ this(System.currentTimeMillis(), multiplier, increment, modulo);
+ }
- /***
- * These parameters are saved and used when nextNumber() is called.
- *
- * @param seed
- * @param multiplier
- * @param increment
- * @param modulo The maximum number that can be generated (exclusive). A common value is 2^32.
- */
- public LinearCongruentialGenerator(
- double seed, double multiplier, double increment, double modulo) {
- this.previousValue = seed;
- this.a = multiplier;
- this.c = increment;
- this.m = modulo;
- }
+ /***
+ * These parameters are saved and used when nextNumber() is called.
+ *
+ * @param seed
+ * @param multiplier
+ * @param increment
+ * @param modulo The maximum number that can be generated (exclusive). A common value is 2^32.
+ */
+ public LinearCongruentialGenerator(
+ double seed, double multiplier, double increment, double modulo) {
+ this.previousValue = seed;
+ this.a = multiplier;
+ this.c = increment;
+ this.m = modulo;
+ }
- /**
- * The smallest number that can be generated is zero. The largest number that can be generated is
- * modulo-1. modulo is set in the constructor.
- *
- * @return a pseudorandom number.
- */
- public double nextNumber() {
- previousValue = (a * previousValue + c) % m;
- return previousValue;
- }
+ /**
+ * The smallest number that can be generated is zero. The largest number that can be generated is
+ * modulo-1. modulo is set in the constructor.
+ *
+ * @return a pseudorandom number.
+ */
+ public double nextNumber() {
+ previousValue = (a * previousValue + c) % m;
+ return previousValue;
+ }
- public static void main(String[] args) {
- // Show the LCG in action.
- // Decisive proof that the LCG works could be made by adding each number
- // generated to a Set while checking for duplicates.
- LinearCongruentialGenerator lcg =
- new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0));
- for (int i = 0; i < 512; i++) {
- System.out.println(lcg.nextNumber());
+ public static void main(String[] args) {
+ // Show the LCG in action.
+ // Decisive proof that the LCG works could be made by adding each number
+ // generated to a Set while checking for duplicates.
+ LinearCongruentialGenerator lcg =
+ new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0));
+ for (int i = 0; i < 512; i++) {
+ System.out.println(lcg.nextNumber());
+ }
}
- }
}
diff --git a/Others/LowestBasePalindrome.java b/Others/LowestBasePalindrome.java
index b6d169887524..d955ab1d6d38 100644
--- a/Others/LowestBasePalindrome.java
+++ b/Others/LowestBasePalindrome.java
@@ -14,129 +14,129 @@
*/
public class LowestBasePalindrome {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int n = 0;
- while (true) {
- try {
- System.out.print("Enter number: ");
- n = in.nextInt();
- break;
- } catch (InputMismatchException e) {
- System.out.println("Invalid input!");
- in.next();
- }
+ public static void main(String[] args) {
+ Scanner in = new Scanner(System.in);
+ int n = 0;
+ while (true) {
+ try {
+ System.out.print("Enter number: ");
+ n = in.nextInt();
+ break;
+ } catch (InputMismatchException e) {
+ System.out.println("Invalid input!");
+ in.next();
+ }
+ }
+ System.out.println(n + " is a palindrome in base " + lowestBasePalindrome(n));
+ System.out.println(base2base(Integer.toString(n), 10, lowestBasePalindrome(n)));
+ in.close();
}
- System.out.println(n + " is a palindrome in base " + lowestBasePalindrome(n));
- System.out.println(base2base(Integer.toString(n), 10, lowestBasePalindrome(n)));
- in.close();
- }
- /**
- * Given a number in base 10, returns the lowest base in which the number is represented by a
- * palindrome (read the same left-to-right and right-to-left).
- *
- * @param num A number in base 10.
- * @return The lowest base in which num is a palindrome.
- */
- public static int lowestBasePalindrome(int num) {
- int base, num2 = num;
- int digit;
- char digitC;
- boolean foundBase = false;
- String newNum = "";
- String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+ /**
+ * Given a number in base 10, returns the lowest base in which the number is represented by a
+ * palindrome (read the same left-to-right and right-to-left).
+ *
+ * @param num A number in base 10.
+ * @return The lowest base in which num is a palindrome.
+ */
+ public static int lowestBasePalindrome(int num) {
+ int base, num2 = num;
+ int digit;
+ char digitC;
+ boolean foundBase = false;
+ String newNum = "";
+ String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- while (!foundBase) {
- // Try from bases 2 to num-1
- for (base = 2; base < num2; base++) {
- newNum = "";
- while (num > 0) {
- // Obtain the first digit of n in the current base,
- // which is equivalent to the integer remainder of (n/base).
- // The next digit is obtained by dividing n by the base and
- // continuing the process of getting the remainder. This is done
- // until n is <=0 and the number in the new base is obtained.
- digit = (num % base);
- num /= base;
- // If the digit isn't in the set of [0-9][A-Z] (beyond base 36), its character
- // form is just its value in ASCII.
+ while (!foundBase) {
+ // Try from bases 2 to num-1
+ for (base = 2; base < num2; base++) {
+ newNum = "";
+ while (num > 0) {
+ // Obtain the first digit of n in the current base,
+ // which is equivalent to the integer remainder of (n/base).
+ // The next digit is obtained by dividing n by the base and
+ // continuing the process of getting the remainder. This is done
+ // until n is <=0 and the number in the new base is obtained.
+ digit = (num % base);
+ num /= base;
+ // If the digit isn't in the set of [0-9][A-Z] (beyond base 36), its character
+ // form is just its value in ASCII.
- // NOTE: This may cause problems, as the capital letters are ASCII values
- // 65-90. It may cause false positives when one digit is, for instance 10 and assigned
- // 'A' from the character array and the other is 65 and also assigned 'A'.
+ // NOTE: This may cause problems, as the capital letters are ASCII values
+ // 65-90. It may cause false positives when one digit is, for instance 10 and assigned
+ // 'A' from the character array and the other is 65 and also assigned 'A'.
- // Regardless, the character is added to the representation of n
- // in the current base.
- if (digit >= digits.length()) {
- digitC = (char) (digit);
- newNum += digitC;
- continue;
- }
- newNum += digits.charAt(digit);
- }
- // Num is assigned back its original value for the next iteration.
- num = num2;
- // Auxiliary method reverses the number.
- String reverse = reverse(newNum);
- // If the number is read the same as its reverse, then it is a palindrome.
- // The current base is returned.
- if (reverse.equals(newNum)) {
- foundBase = true;
- return base;
+ // Regardless, the character is added to the representation of n
+ // in the current base.
+ if (digit >= digits.length()) {
+ digitC = (char) (digit);
+ newNum += digitC;
+ continue;
+ }
+ newNum += digits.charAt(digit);
+ }
+ // Num is assigned back its original value for the next iteration.
+ num = num2;
+ // Auxiliary method reverses the number.
+ String reverse = reverse(newNum);
+ // If the number is read the same as its reverse, then it is a palindrome.
+ // The current base is returned.
+ if (reverse.equals(newNum)) {
+ foundBase = true;
+ return base;
+ }
+ }
}
- }
+ // If all else fails, n is always a palindrome in base n-1. ("11")
+ return num - 1;
}
- // If all else fails, n is always a palindrome in base n-1. ("11")
- return num - 1;
- }
- private static String reverse(String str) {
- String reverse = "";
- for (int i = str.length() - 1; i >= 0; i--) {
- reverse += str.charAt(i);
+ private static String reverse(String str) {
+ String reverse = "";
+ for (int i = str.length() - 1; i >= 0; i--) {
+ reverse += str.charAt(i);
+ }
+ return reverse;
}
- return reverse;
- }
- private static String base2base(String n, int b1, int b2) {
- // Declare variables: decimal value of n,
- // character of base b1, character of base b2,
- // and the string that will be returned.
- int decimalValue = 0, charB2;
- char charB1;
- String output = "";
- // Go through every character of n
- for (int i = 0; i < n.length(); i++) {
- // store the character in charB1
- charB1 = n.charAt(i);
- // if it is a non-number, convert it to a decimal value >9 and store it in charB2
- if (charB1 >= 'A' && charB1 <= 'Z') charB2 = 10 + (charB1 - 'A');
- // Else, store the integer value in charB2
- else charB2 = charB1 - '0';
- // Convert the digit to decimal and add it to the
- // decimalValue of n
- decimalValue = decimalValue * b1 + charB2;
- }
+ private static String base2base(String n, int b1, int b2) {
+ // Declare variables: decimal value of n,
+ // character of base b1, character of base b2,
+ // and the string that will be returned.
+ int decimalValue = 0, charB2;
+ char charB1;
+ String output = "";
+ // Go through every character of n
+ for (int i = 0; i < n.length(); i++) {
+ // store the character in charB1
+ charB1 = n.charAt(i);
+ // if it is a non-number, convert it to a decimal value >9 and store it in charB2
+ if (charB1 >= 'A' && charB1 <= 'Z') charB2 = 10 + (charB1 - 'A');
+ // Else, store the integer value in charB2
+ else charB2 = charB1 - '0';
+ // Convert the digit to decimal and add it to the
+ // decimalValue of n
+ decimalValue = decimalValue * b1 + charB2;
+ }
- // Converting the decimal value to base b2:
- // A number is converted from decimal to another base
- // by continuously dividing by the base and recording
- // the remainder until the quotient is zero. The number in the
- // new base is the remainders, with the last remainder
- // being the left-most digit.
+ // Converting the decimal value to base b2:
+ // A number is converted from decimal to another base
+ // by continuously dividing by the base and recording
+ // the remainder until the quotient is zero. The number in the
+ // new base is the remainders, with the last remainder
+ // being the left-most digit.
- // While the quotient is NOT zero:
- while (decimalValue != 0) {
- // If the remainder is a digit < 10, simply add it to
- // the left side of the new number.
- if (decimalValue % b2 < 10) output = Integer.toString(decimalValue % b2) + output;
- // If the remainder is >= 10, add a character with the
- // corresponding value to the new number. (A = 10, B = 11, C = 12, ...)
- else output = (char) ((decimalValue % b2) + 55) + output;
- // Divide by the new base again
- decimalValue /= b2;
+ // While the quotient is NOT zero:
+ while (decimalValue != 0) {
+ // If the remainder is a digit < 10, simply add it to
+ // the left side of the new number.
+ if (decimalValue % b2 < 10) output = Integer.toString(decimalValue % b2) + output;
+ // If the remainder is >= 10, add a character with the
+ // corresponding value to the new number. (A = 10, B = 11, C = 12, ...)
+ else output = (char) ((decimalValue % b2) + 55) + output;
+ // Divide by the new base again
+ decimalValue /= b2;
+ }
+ return output;
}
- return output;
- }
}
diff --git a/Others/PasswordGen.java b/Others/PasswordGen.java
index 018cffe6bacd..7e6151df70a1 100644
--- a/Others/PasswordGen.java
+++ b/Others/PasswordGen.java
@@ -12,33 +12,33 @@
* @date 2017.10.25
*/
class PasswordGen {
- public static void main(String args[]) {
- String password = generatePassword(8, 16);
- System.out.print("Password: " + password);
- }
+ public static void main(String args[]) {
+ String password = generatePassword(8, 16);
+ System.out.print("Password: " + password);
+ }
- static String generatePassword(int min_length, int max_length) {
- Random random = new Random();
+ static String generatePassword(int min_length, int max_length) {
+ Random random = new Random();
- String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- String lower = "abcdefghijklmnopqrstuvwxyz";
- String numbers = "0123456789";
- String specialChars = "!@#$%^&*(){}?";
+ String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+ String lower = "abcdefghijklmnopqrstuvwxyz";
+ String numbers = "0123456789";
+ String specialChars = "!@#$%^&*(){}?";
- String allChars = upper + lower + numbers + specialChars;
+ String allChars = upper + lower + numbers + specialChars;
- List letters = new ArrayList();
- for (char c : allChars.toCharArray()) letters.add(c);
+ List letters = new ArrayList();
+ for (char c : allChars.toCharArray()) letters.add(c);
- // Inbuilt method to randomly shuffle a elements of a list
- Collections.shuffle(letters);
- StringBuilder password = new StringBuilder();
+ // Inbuilt method to randomly shuffle a elements of a list
+ Collections.shuffle(letters);
+ StringBuilder password = new StringBuilder();
- // Note that size of the password is also random
- for (int i = random.nextInt(max_length - min_length) + min_length; i > 0; --i) {
- password.append(letters.get(random.nextInt(letters.size())));
- }
+ // Note that size of the password is also random
+ for (int i = random.nextInt(max_length - min_length) + min_length; i > 0; --i) {
+ password.append(letters.get(random.nextInt(letters.size())));
+ }
- return password.toString();
- }
+ return password.toString();
+ }
}
diff --git a/Others/PerlinNoise.java b/Others/PerlinNoise.java
index 4c1ad993a134..a1e03b9555d1 100644
--- a/Others/PerlinNoise.java
+++ b/Others/PerlinNoise.java
@@ -8,161 +8,161 @@
* href="http://devmag.org.za/2009/04/25/perlin-noise/">Perlin-Noise
*/
public class PerlinNoise {
- /**
- * @param width width of noise array
- * @param height height of noise array
- * @param octaveCount numbers of layers used for blending noise
- * @param persistence value of impact each layer get while blending
- * @param seed used for randomizer
- * @return float array containing calculated "Perlin-Noise" values
- */
- static float[][] generatePerlinNoise(
- int width, int height, int octaveCount, float persistence, long seed) {
- final float[][] base = new float[width][height];
- final float[][] perlinNoise = new float[width][height];
- final float[][][] noiseLayers = new float[octaveCount][][];
-
- Random random = new Random(seed);
- // fill base array with random values as base for noise
- for (int x = 0; x < width; x++) {
- for (int y = 0; y < height; y++) {
- base[x][y] = random.nextFloat();
- }
- }
-
- // calculate octaves with different roughness
- for (int octave = 0; octave < octaveCount; octave++) {
- noiseLayers[octave] = generatePerlinNoiseLayer(base, width, height, octave);
- }
+ /**
+ * @param width width of noise array
+ * @param height height of noise array
+ * @param octaveCount numbers of layers used for blending noise
+ * @param persistence value of impact each layer get while blending
+ * @param seed used for randomizer
+ * @return float array containing calculated "Perlin-Noise" values
+ */
+ static float[][] generatePerlinNoise(
+ int width, int height, int octaveCount, float persistence, long seed) {
+ final float[][] base = new float[width][height];
+ final float[][] perlinNoise = new float[width][height];
+ final float[][][] noiseLayers = new float[octaveCount][][];
+
+ Random random = new Random(seed);
+ // fill base array with random values as base for noise
+ for (int x = 0; x < width; x++) {
+ for (int y = 0; y < height; y++) {
+ base[x][y] = random.nextFloat();
+ }
+ }
- float amplitude = 1f;
- float totalAmplitude = 0f;
+ // calculate octaves with different roughness
+ for (int octave = 0; octave < octaveCount; octave++) {
+ noiseLayers[octave] = generatePerlinNoiseLayer(base, width, height, octave);
+ }
- // calculate perlin noise by blending each layer together with specific persistence
- for (int octave = octaveCount - 1; octave >= 0; octave--) {
- amplitude *= persistence;
- totalAmplitude += amplitude;
+ float amplitude = 1f;
+ float totalAmplitude = 0f;
+
+ // calculate perlin noise by blending each layer together with specific persistence
+ for (int octave = octaveCount - 1; octave >= 0; octave--) {
+ amplitude *= persistence;
+ totalAmplitude += amplitude;
+
+ for (int x = 0; x < width; x++) {
+ for (int y = 0; y < height; y++) {
+ // adding each value of the noise layer to the noise
+ // by increasing amplitude the rougher noises will have more impact
+ perlinNoise[x][y] += noiseLayers[octave][x][y] * amplitude;
+ }
+ }
+ }
- for (int x = 0; x < width; x++) {
- for (int y = 0; y < height; y++) {
- // adding each value of the noise layer to the noise
- // by increasing amplitude the rougher noises will have more impact
- perlinNoise[x][y] += noiseLayers[octave][x][y] * amplitude;
+ // normalize values so that they stay between 0..1
+ for (int x = 0; x < width; x++) {
+ for (int y = 0; y < height; y++) {
+ perlinNoise[x][y] /= totalAmplitude;
+ }
}
- }
+
+ return perlinNoise;
}
- // normalize values so that they stay between 0..1
- for (int x = 0; x < width; x++) {
- for (int y = 0; y < height; y++) {
- perlinNoise[x][y] /= totalAmplitude;
- }
+ /**
+ * @param base base random float array
+ * @param width width of noise array
+ * @param height height of noise array
+ * @param octave current layer
+ * @return float array containing calculated "Perlin-Noise-Layer" values
+ */
+ static float[][] generatePerlinNoiseLayer(float[][] base, int width, int height, int octave) {
+ float[][] perlinNoiseLayer = new float[width][height];
+
+ // calculate period (wavelength) for different shapes
+ int period = 1 << octave; // 2^k
+ float frequency = 1f / period; // 1/2^k
+
+ for (int x = 0; x < width; x++) {
+ // calculates the horizontal sampling indices
+ int x0 = (x / period) * period;
+ int x1 = (x0 + period) % width;
+ float horizintalBlend = (x - x0) * frequency;
+
+ for (int y = 0; y < height; y++) {
+ // calculates the vertical sampling indices
+ int y0 = (y / period) * period;
+ int y1 = (y0 + period) % height;
+ float verticalBlend = (y - y0) * frequency;
+
+ // blend top corners
+ float top = interpolate(base[x0][y0], base[x1][y0], horizintalBlend);
+
+ // blend bottom corners
+ float bottom = interpolate(base[x0][y1], base[x1][y1], horizintalBlend);
+
+ // blend top and bottom interpolation to get the final blend value for this cell
+ perlinNoiseLayer[x][y] = interpolate(top, bottom, verticalBlend);
+ }
+ }
+
+ return perlinNoiseLayer;
}
- return perlinNoise;
- }
-
- /**
- * @param base base random float array
- * @param width width of noise array
- * @param height height of noise array
- * @param octave current layer
- * @return float array containing calculated "Perlin-Noise-Layer" values
- */
- static float[][] generatePerlinNoiseLayer(float[][] base, int width, int height, int octave) {
- float[][] perlinNoiseLayer = new float[width][height];
-
- // calculate period (wavelength) for different shapes
- int period = 1 << octave; // 2^k
- float frequency = 1f / period; // 1/2^k
-
- for (int x = 0; x < width; x++) {
- // calculates the horizontal sampling indices
- int x0 = (x / period) * period;
- int x1 = (x0 + period) % width;
- float horizintalBlend = (x - x0) * frequency;
-
- for (int y = 0; y < height; y++) {
- // calculates the vertical sampling indices
- int y0 = (y / period) * period;
- int y1 = (y0 + period) % height;
- float verticalBlend = (y - y0) * frequency;
-
- // blend top corners
- float top = interpolate(base[x0][y0], base[x1][y0], horizintalBlend);
-
- // blend bottom corners
- float bottom = interpolate(base[x0][y1], base[x1][y1], horizintalBlend);
-
- // blend top and bottom interpolation to get the final blend value for this cell
- perlinNoiseLayer[x][y] = interpolate(top, bottom, verticalBlend);
- }
+ /**
+ * @param a value of point a
+ * @param b value of point b
+ * @param alpha determine which value has more impact (closer to 0 -> a, closer to 1 -> b)
+ * @return interpolated value
+ */
+ static float interpolate(float a, float b, float alpha) {
+ return a * (1 - alpha) + alpha * b;
}
- return perlinNoiseLayer;
- }
-
- /**
- * @param a value of point a
- * @param b value of point b
- * @param alpha determine which value has more impact (closer to 0 -> a, closer to 1 -> b)
- * @return interpolated value
- */
- static float interpolate(float a, float b, float alpha) {
- return a * (1 - alpha) + alpha * b;
- }
-
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
-
- final int width;
- final int height;
- final int octaveCount;
- final float persistence;
- final long seed;
- final String charset;
- final float[][] perlinNoise;
-
- System.out.println("Width (int): ");
- width = in.nextInt();
-
- System.out.println("Height (int): ");
- height = in.nextInt();
-
- System.out.println("Octave count (int): ");
- octaveCount = in.nextInt();
-
- System.out.println("Persistence (float): ");
- persistence = in.nextFloat();
-
- System.out.println("Seed (long): ");
- seed = in.nextLong();
-
- System.out.println("Charset (String): ");
- charset = in.next();
-
- perlinNoise = generatePerlinNoise(width, height, octaveCount, persistence, seed);
- final char[] chars = charset.toCharArray();
- final int length = chars.length;
- final float step = 1f / length;
- // output based on charset
- for (int x = 0; x < width; x++) {
- for (int y = 0; y < height; y++) {
- float value = step;
- float noiseValue = perlinNoise[x][y];
-
- for (char c : chars) {
- if (noiseValue <= value) {
- System.out.print(c);
- break;
- }
-
- value += step;
- }
- }
+ public static void main(String[] args) {
+ Scanner in = new Scanner(System.in);
+
+ final int width;
+ final int height;
+ final int octaveCount;
+ final float persistence;
+ final long seed;
+ final String charset;
+ final float[][] perlinNoise;
- System.out.println();
+ System.out.println("Width (int): ");
+ width = in.nextInt();
+
+ System.out.println("Height (int): ");
+ height = in.nextInt();
+
+ System.out.println("Octave count (int): ");
+ octaveCount = in.nextInt();
+
+ System.out.println("Persistence (float): ");
+ persistence = in.nextFloat();
+
+ System.out.println("Seed (long): ");
+ seed = in.nextLong();
+
+ System.out.println("Charset (String): ");
+ charset = in.next();
+
+ perlinNoise = generatePerlinNoise(width, height, octaveCount, persistence, seed);
+ final char[] chars = charset.toCharArray();
+ final int length = chars.length;
+ final float step = 1f / length;
+ // output based on charset
+ for (int x = 0; x < width; x++) {
+ for (int y = 0; y < height; y++) {
+ float value = step;
+ float noiseValue = perlinNoise[x][y];
+
+ for (char c : chars) {
+ if (noiseValue <= value) {
+ System.out.print(c);
+ break;
+ }
+
+ value += step;
+ }
+ }
+
+ System.out.println();
+ }
+ in.close();
}
- in.close();
- }
}
diff --git a/Others/QueueUsingTwoStacks.java b/Others/QueueUsingTwoStacks.java
index 104f6b922088..ee301d3fabc1 100644
--- a/Others/QueueUsingTwoStacks.java
+++ b/Others/QueueUsingTwoStacks.java
@@ -14,74 +14,76 @@
*/
class QueueWithStack {
- // Stack to keep track of elements inserted into the queue
- private Stack inStack;
- // Stack to keep track of elements to be removed next in queue
- private Stack outStack;
-
- /** Constructor */
- public QueueWithStack() {
- this.inStack = new Stack();
- this.outStack = new Stack();
- }
-
- /**
- * Inserts an element at the rear of the queue
- *
- * @param x element to be added
- */
- public void insert(Object x) {
- // Insert element into inStack
- this.inStack.push(x);
- }
-
- /**
- * Remove an element from the front of the queue
- *
- * @return the new front of the queue
- */
- public Object remove() {
- if (this.outStack.isEmpty()) {
- // Move all elements from inStack to outStack (preserving the order)
- while (!this.inStack.isEmpty()) {
- this.outStack.push(this.inStack.pop());
- }
+ // Stack to keep track of elements inserted into the queue
+ private Stack inStack;
+ // Stack to keep track of elements to be removed next in queue
+ private Stack outStack;
+
+ /**
+ * Constructor
+ */
+ public QueueWithStack() {
+ this.inStack = new Stack();
+ this.outStack = new Stack();
}
- return this.outStack.pop();
- }
-
- /**
- * Peek at the element from the front of the queue
- *
- * @return the front element of the queue
- */
- public Object peekFront() {
- if (this.outStack.isEmpty()) {
- // Move all elements from inStack to outStack (preserving the order)
- while (!this.inStack.isEmpty()) {
- this.outStack.push(this.inStack.pop());
- }
+
+ /**
+ * Inserts an element at the rear of the queue
+ *
+ * @param x element to be added
+ */
+ public void insert(Object x) {
+ // Insert element into inStack
+ this.inStack.push(x);
+ }
+
+ /**
+ * Remove an element from the front of the queue
+ *
+ * @return the new front of the queue
+ */
+ public Object remove() {
+ if (this.outStack.isEmpty()) {
+ // Move all elements from inStack to outStack (preserving the order)
+ while (!this.inStack.isEmpty()) {
+ this.outStack.push(this.inStack.pop());
+ }
+ }
+ return this.outStack.pop();
+ }
+
+ /**
+ * Peek at the element from the front of the queue
+ *
+ * @return the front element of the queue
+ */
+ public Object peekFront() {
+ if (this.outStack.isEmpty()) {
+ // Move all elements from inStack to outStack (preserving the order)
+ while (!this.inStack.isEmpty()) {
+ this.outStack.push(this.inStack.pop());
+ }
+ }
+ return this.outStack.peek();
+ }
+
+ /**
+ * Peek at the element from the back of the queue
+ *
+ * @return the back element of the queue
+ */
+ public Object peekBack() {
+ return this.inStack.peek();
+ }
+
+ /**
+ * Returns true if the queue is empty
+ *
+ * @return true if the queue is empty
+ */
+ public boolean isEmpty() {
+ return (this.inStack.isEmpty() && this.outStack.isEmpty());
}
- return this.outStack.peek();
- }
-
- /**
- * Peek at the element from the back of the queue
- *
- * @return the back element of the queue
- */
- public Object peekBack() {
- return this.inStack.peek();
- }
-
- /**
- * Returns true if the queue is empty
- *
- * @return true if the queue is empty
- */
- public boolean isEmpty() {
- return (this.inStack.isEmpty() && this.outStack.isEmpty());
- }
}
/**
@@ -91,60 +93,60 @@ public boolean isEmpty() {
*/
public class QueueUsingTwoStacks {
- /**
- * Main method
- *
- * @param args Command line arguments
- */
- public static void main(String args[]) {
- QueueWithStack myQueue = new QueueWithStack();
- myQueue.insert(1);
- System.out.println(myQueue.peekBack()); // Will print 1
- // instack: [(top) 1]
- // outStack: []
- myQueue.insert(2);
- System.out.println(myQueue.peekBack()); // Will print 2
- // instack: [(top) 2, 1]
- // outStack: []
- myQueue.insert(3);
- System.out.println(myQueue.peekBack()); // Will print 3
- // instack: [(top) 3, 2, 1]
- // outStack: []
- myQueue.insert(4);
- System.out.println(myQueue.peekBack()); // Will print 4
- // instack: [(top) 4, 3, 2, 1]
- // outStack: []
-
- System.out.println(myQueue.isEmpty()); // Will print false
-
- System.out.println(myQueue.remove()); // Will print 1
- System.out.println(myQueue.peekBack()); // Will print NULL
- // instack: []
- // outStack: [(top) 2, 3, 4]
-
- myQueue.insert(5);
- System.out.println(myQueue.peekFront()); // Will print 2
- // instack: [(top) 5]
- // outStack: [(top) 2, 3, 4]
-
- myQueue.remove();
- System.out.println(myQueue.peekFront()); // Will print 3
- // instack: [(top) 5]
- // outStack: [(top) 3, 4]
- myQueue.remove();
- System.out.println(myQueue.peekFront()); // Will print 4
- // instack: [(top) 5]
- // outStack: [(top) 4]
- myQueue.remove();
- // instack: [(top) 5]
- // outStack: []
- System.out.println(myQueue.peekFront()); // Will print 5
- // instack: []
- // outStack: [(top) 5]
- myQueue.remove();
- // instack: []
- // outStack: []
-
- System.out.println(myQueue.isEmpty()); // Will print true
- }
+ /**
+ * Main method
+ *
+ * @param args Command line arguments
+ */
+ public static void main(String args[]) {
+ QueueWithStack myQueue = new QueueWithStack();
+ myQueue.insert(1);
+ System.out.println(myQueue.peekBack()); // Will print 1
+ // instack: [(top) 1]
+ // outStack: []
+ myQueue.insert(2);
+ System.out.println(myQueue.peekBack()); // Will print 2
+ // instack: [(top) 2, 1]
+ // outStack: []
+ myQueue.insert(3);
+ System.out.println(myQueue.peekBack()); // Will print 3
+ // instack: [(top) 3, 2, 1]
+ // outStack: []
+ myQueue.insert(4);
+ System.out.println(myQueue.peekBack()); // Will print 4
+ // instack: [(top) 4, 3, 2, 1]
+ // outStack: []
+
+ System.out.println(myQueue.isEmpty()); // Will print false
+
+ System.out.println(myQueue.remove()); // Will print 1
+ System.out.println(myQueue.peekBack()); // Will print NULL
+ // instack: []
+ // outStack: [(top) 2, 3, 4]
+
+ myQueue.insert(5);
+ System.out.println(myQueue.peekFront()); // Will print 2
+ // instack: [(top) 5]
+ // outStack: [(top) 2, 3, 4]
+
+ myQueue.remove();
+ System.out.println(myQueue.peekFront()); // Will print 3
+ // instack: [(top) 5]
+ // outStack: [(top) 3, 4]
+ myQueue.remove();
+ System.out.println(myQueue.peekFront()); // Will print 4
+ // instack: [(top) 5]
+ // outStack: [(top) 4]
+ myQueue.remove();
+ // instack: [(top) 5]
+ // outStack: []
+ System.out.println(myQueue.peekFront()); // Will print 5
+ // instack: []
+ // outStack: [(top) 5]
+ myQueue.remove();
+ // instack: []
+ // outStack: []
+
+ System.out.println(myQueue.isEmpty()); // Will print true
+ }
}
diff --git a/Others/RabinKarp.java b/Others/RabinKarp.java
index 7dafa00c7874..226e6fb03c88 100644
--- a/Others/RabinKarp.java
+++ b/Others/RabinKarp.java
@@ -1,79 +1,82 @@
-/** @author Prateek Kumar Oraon (https://github.com/prateekKrOraon) */
+/**
+ * @author Prateek Kumar Oraon (https://github.com/prateekKrOraon)
+ */
+
import java.util.Scanner;
// An implementation of Rabin-Karp string matching algorithm
// Program will simply end if there is no match
public class RabinKarp {
- public static Scanner scanner = null;
- public static final int d = 256;
-
- public static void main(String[] args) {
-
- scanner = new Scanner(System.in);
- System.out.println("Enter String");
- String text = scanner.nextLine();
- System.out.println("Enter pattern");
- String pattern = scanner.nextLine();
-
- int q = 101;
- searchPat(text, pattern, q);
- }
-
- private static void searchPat(String text, String pattern, int q) {
+ public static Scanner scanner = null;
+ public static final int d = 256;
- int m = pattern.length();
- int n = text.length();
- int t = 0;
- int p = 0;
- int h = 1;
- int j = 0;
- int i = 0;
+ public static void main(String[] args) {
- h = (int) Math.pow(d, m - 1) % q;
+ scanner = new Scanner(System.in);
+ System.out.println("Enter String");
+ String text = scanner.nextLine();
+ System.out.println("Enter pattern");
+ String pattern = scanner.nextLine();
- for (i = 0; i < m; i++) {
- // hash value is calculated for each character and then added with the hash value of the next
- // character for pattern
- // as well as the text for length equal to the length of pattern
- p = (d * p + pattern.charAt(i)) % q;
- t = (d * t + text.charAt(i)) % q;
+ int q = 101;
+ searchPat(text, pattern, q);
}
- for (i = 0; i <= n - m; i++) {
+ private static void searchPat(String text, String pattern, int q) {
- // if the calculated hash value of the pattern and text matches then
- // all the characters of the pattern is matched with the text of length equal to length of the
- // pattern
- // if all matches then pattern exist in string
- // if not then the hash value of the first character of the text is subtracted and hash value
- // of the next character after the end
- // of the evaluated characters is added
- if (p == t) {
+ int m = pattern.length();
+ int n = text.length();
+ int t = 0;
+ int p = 0;
+ int h = 1;
+ int j = 0;
+ int i = 0;
- // if hash value matches then the individual characters are matched
- for (j = 0; j < m; j++) {
+ h = (int) Math.pow(d, m - 1) % q;
- // if not matched then break out of the loop
- if (text.charAt(i + j) != pattern.charAt(j)) break;
+ for (i = 0; i < m; i++) {
+ // hash value is calculated for each character and then added with the hash value of the next
+ // character for pattern
+ // as well as the text for length equal to the length of pattern
+ p = (d * p + pattern.charAt(i)) % q;
+ t = (d * t + text.charAt(i)) % q;
}
- // if all characters are matched then pattern exist in the string
- if (j == m) {
- System.out.println("Pattern found at index " + i);
+ for (i = 0; i <= n - m; i++) {
+
+ // if the calculated hash value of the pattern and text matches then
+ // all the characters of the pattern is matched with the text of length equal to length of the
+ // pattern
+ // if all matches then pattern exist in string
+ // if not then the hash value of the first character of the text is subtracted and hash value
+ // of the next character after the end
+ // of the evaluated characters is added
+ if (p == t) {
+
+ // if hash value matches then the individual characters are matched
+ for (j = 0; j < m; j++) {
+
+ // if not matched then break out of the loop
+ if (text.charAt(i + j) != pattern.charAt(j)) break;
+ }
+
+ // if all characters are matched then pattern exist in the string
+ if (j == m) {
+ System.out.println("Pattern found at index " + i);
+ }
+ }
+
+ // if i movements = new ArrayList();
- public StringBuilder stringBuilder = new StringBuilder();
-
- public ArrayList Stack1 = new ArrayList();
- public ArrayList Stack2 = new ArrayList();
- public ArrayList Stack3 = new ArrayList();
-
- public void updateStacks() {
- if (game_counter != movements.size()) {
- String temp = movements.get(game_counter);
- System.out.println(temp);
- if (temp.charAt(1) == 'A') {
- if (temp.charAt(2) == 'B') {
- int x = Stack1.get(Stack1.size() - 1);
- Stack1.remove(Stack1.size() - 1);
- Stack2.add(x);
+ public static int ONE_SECOND = 1000;
+
+ int number_of_disks = 0;
+ int game_counter = 0;
+ int i = 0;
+
+ /* GUI COMPONENTS */
+ public JButton move_button = new JButton();
+ public JButton exit_button = new JButton();
+ public JButton replay_button = new JButton();
+ public JButton auto_button = new JButton();
+
+ /* BACKEND COMPONENTS */
+ public ArrayList movements = new ArrayList();
+ public StringBuilder stringBuilder = new StringBuilder();
+
+ public ArrayList Stack1 = new ArrayList();
+ public ArrayList Stack2 = new ArrayList();
+ public ArrayList Stack3 = new ArrayList();
+
+ public void updateStacks() {
+ if (game_counter != movements.size()) {
+ String temp = movements.get(game_counter);
+ System.out.println(temp);
+ if (temp.charAt(1) == 'A') {
+ if (temp.charAt(2) == 'B') {
+ int x = Stack1.get(Stack1.size() - 1);
+ Stack1.remove(Stack1.size() - 1);
+ Stack2.add(x);
+ }
+ }
+ if (temp.charAt(1) == 'C') {
+ if (temp.charAt(2) == 'B') {
+ int x = Stack3.get(Stack3.size() - 1);
+ Stack3.remove(Stack3.size() - 1);
+ Stack2.add(x);
+ }
+ }
+
+ if (temp.charAt(1) == 'B') {
+ if (temp.charAt(2) == 'C') {
+ int x = Stack2.get(Stack2.size() - 1);
+ Stack2.remove(Stack2.size() - 1);
+ Stack3.add(x);
+ } else if (temp.charAt(2) == 'A') {
+ int x = Stack2.get(Stack2.size() - 1);
+ Stack2.remove(Stack2.size() - 1);
+ Stack1.add(x);
+ }
+ }
+ revalidate();
+ repaint();
+ game_counter++;
+ }
+ }
+
+ public void paint(Graphics canvas) {
+ super.paint(canvas);
+
+ // Drawing pedestels
+ for (int i = 0; i < 3; i++) {
+ canvas.drawRect(30 + i * 230, 670, 200, 20);
+ canvas.setColor(new Color(76, 174, 227)); // Blue Accent
+ canvas.fillRect(30 + i * 230, 670, 200, 20);
+
+ canvas.fillRect(130 + i * 230 - 2, 670 - 170, 4, 170);
+ canvas.setColor(new Color(150, 0, 0)); // Arseny
+ canvas.fillRect(130 + i * 230 - 2, 670 - 170, 4, 170);
}
- }
- if (temp.charAt(1) == 'C') {
- if (temp.charAt(2) == 'B') {
- int x = Stack3.get(Stack3.size() - 1);
- Stack3.remove(Stack3.size() - 1);
- Stack2.add(x);
+
+ // Disks in stack1
+ for (int i = 1; i <= Stack1.size(); i++) {
+ canvas.drawRect(130 - Stack1.get(i - 1) * 10, 670 - i * 12, Stack1.get(i - 1) * 20, 10);
+ canvas.setColor(new Color(64, 26, 0)); // Brown Wolfers
+ canvas.fillRect(130 - Stack1.get(i - 1) * 10, 670 - i * 12, Stack1.get(i - 1) * 20, 10);
}
- }
-
- if (temp.charAt(1) == 'B') {
- if (temp.charAt(2) == 'C') {
- int x = Stack2.get(Stack2.size() - 1);
- Stack2.remove(Stack2.size() - 1);
- Stack3.add(x);
- } else if (temp.charAt(2) == 'A') {
- int x = Stack2.get(Stack2.size() - 1);
- Stack2.remove(Stack2.size() - 1);
- Stack1.add(x);
+
+ // Disks in stack2
+ for (int i = 1; i <= Stack2.size(); i++) {
+ canvas.drawRect(360 - Stack2.get(i - 1) * 10, 670 - i * 12, Stack2.get(i - 1) * 20, 10);
+ canvas.setColor(new Color(64, 26, 0)); // Brown Wolfers
+ canvas.fillRect(360 - Stack2.get(i - 1) * 10, 670 - i * 12, Stack2.get(i - 1) * 20, 10);
+ }
+
+ // Disks in stack3
+ for (int i = 1; i <= Stack3.size(); i++) {
+ canvas.drawRect(590 - Stack3.get(i - 1) * 10, 670 - i * 12, Stack3.get(i - 1) * 20, 10);
+ canvas.setColor(new Color(64, 26, 0)); // Brown Wolfers
+ canvas.fillRect(590 - Stack3.get(i - 1) * 10, 670 - i * 12, Stack3.get(i - 1) * 20, 10);
}
- }
- revalidate();
- repaint();
- game_counter++;
}
- }
- public void paint(Graphics canvas) {
- super.paint(canvas);
+ // Function to initialize the widget properties and the frame.
+ public void initialize() {
- // Drawing pedestels
- for (int i = 0; i < 3; i++) {
- canvas.drawRect(30 + i * 230, 670, 200, 20);
- canvas.setColor(new Color(76, 174, 227)); // Blue Accent
- canvas.fillRect(30 + i * 230, 670, 200, 20);
+ move_button.setIcon(new ImageIcon("../Resources/rsz_move.png"));
+ move_button.setBounds(130, 0, 50, 50);
- canvas.fillRect(130 + i * 230 - 2, 670 - 170, 4, 170);
- canvas.setColor(new Color(150, 0, 0)); // Arseny
- canvas.fillRect(130 + i * 230 - 2, 670 - 170, 4, 170);
- }
+ auto_button.setIcon(new ImageIcon("../Resources/rsz_loop.png"));
+ auto_button.setBounds(260, 0, 50, 50);
- // Disks in stack1
- for (int i = 1; i <= Stack1.size(); i++) {
- canvas.drawRect(130 - Stack1.get(i - 1) * 10, 670 - i * 12, Stack1.get(i - 1) * 20, 10);
- canvas.setColor(new Color(64, 26, 0)); // Brown Wolfers
- canvas.fillRect(130 - Stack1.get(i - 1) * 10, 670 - i * 12, Stack1.get(i - 1) * 20, 10);
- }
+ replay_button.setIcon(new ImageIcon("../Resources/rsz_replay.jpg"));
+ replay_button.setBounds(390, 0, 50, 50);
+
+ exit_button.setIcon(new ImageIcon("../Resources/rsz_exit.png"));
+ exit_button.setBounds(520, 0, 50, 50);
+
+ add(move_button);
+ add(exit_button);
+ add(replay_button);
+ add(auto_button);
- // Disks in stack2
- for (int i = 1; i <= Stack2.size(); i++) {
- canvas.drawRect(360 - Stack2.get(i - 1) * 10, 670 - i * 12, Stack2.get(i - 1) * 20, 10);
- canvas.setColor(new Color(64, 26, 0)); // Brown Wolfers
- canvas.fillRect(360 - Stack2.get(i - 1) * 10, 670 - i * 12, Stack2.get(i - 1) * 20, 10);
+ setLayout(null);
+ setSize(720, 720);
+ setVisible(true);
+ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
- // Disks in stack3
- for (int i = 1; i <= Stack3.size(); i++) {
- canvas.drawRect(590 - Stack3.get(i - 1) * 10, 670 - i * 12, Stack3.get(i - 1) * 20, 10);
- canvas.setColor(new Color(64, 26, 0)); // Brown Wolfers
- canvas.fillRect(590 - Stack3.get(i - 1) * 10, 670 - i * 12, Stack3.get(i - 1) * 20, 10);
+ // Main cnstructor.
+ Hanoi() {
+ super("restricted tower of hanoi");
+ initialize();
+
+ // MOVE BUTTON ACTION LISTENER
+ move_button.addActionListener(
+ new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ updateStacks();
+ }
+ });
+
+ // EXIT BUTTON ACTION LISTENER
+ exit_button.addActionListener(
+ new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ System.exit(0);
+ }
+ });
+
+ // REPLAY BUTTON ACTION LISTENER
+ replay_button.addActionListener(
+ new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ startGame();
+ repaint();
+ }
+ });
+
+ // AUTOMATIC PLAY BUTTON ACTION LISTENER
+ auto_button.addActionListener(
+ new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ timer.start();
+ if (game_counter == movements.size()) {
+ timer.stop();
+ }
+ }
+ });
}
- }
-
- // Function to initialize the widget properties and the frame.
- public void initialize() {
-
- move_button.setIcon(new ImageIcon("../Resources/rsz_move.png"));
- move_button.setBounds(130, 0, 50, 50);
-
- auto_button.setIcon(new ImageIcon("../Resources/rsz_loop.png"));
- auto_button.setBounds(260, 0, 50, 50);
-
- replay_button.setIcon(new ImageIcon("../Resources/rsz_replay.jpg"));
- replay_button.setBounds(390, 0, 50, 50);
-
- exit_button.setIcon(new ImageIcon("../Resources/rsz_exit.png"));
- exit_button.setBounds(520, 0, 50, 50);
-
- add(move_button);
- add(exit_button);
- add(replay_button);
- add(auto_button);
-
- setLayout(null);
- setSize(720, 720);
- setVisible(true);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- }
- // Main cnstructor.
- Hanoi() {
- super("restricted tower of hanoi");
- initialize();
-
- // MOVE BUTTON ACTION LISTENER
- move_button.addActionListener(
- new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- updateStacks();
- }
- });
-
- // EXIT BUTTON ACTION LISTENER
- exit_button.addActionListener(
- new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- System.exit(0);
- }
- });
-
- // REPLAY BUTTON ACTION LISTENER
- replay_button.addActionListener(
- new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- startGame();
- repaint();
- }
- });
-
- // AUTOMATIC PLAY BUTTON ACTION LISTENER
- auto_button.addActionListener(
- new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- timer.start();
- if (game_counter == movements.size()) {
- timer.stop();
- }
- }
- });
- }
-
- Timer timer =
- new Timer(
- ONE_SECOND,
- new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- updateStacks();
- }
- });
- public void startGame() {
+ Timer timer =
+ new Timer(
+ ONE_SECOND,
+ new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ updateStacks();
+ }
+ });
- System.out.println("New Game Started");
- timer.stop();
+ public void startGame() {
- Stack1 = new ArrayList();
- Stack2 = new ArrayList();
- Stack3 = new ArrayList();
+ System.out.println("New Game Started");
+ timer.stop();
- movements = new ArrayList();
- game_counter = 0;
+ Stack1 = new ArrayList();
+ Stack2 = new ArrayList();
+ Stack3 = new ArrayList();
- for (int i = 0; i < number_of_disks; i++) {
- Stack1.add(number_of_disks - i);
- }
+ movements = new ArrayList();
+ game_counter = 0;
+
+ for (int i = 0; i < number_of_disks; i++) {
+ Stack1.add(number_of_disks - i);
+ }
- towerOfHanoi(number_of_disks, 'A', 'C', 'B');
- }
+ towerOfHanoi(number_of_disks, 'A', 'C', 'B');
+ }
- public static void main(String args[]) {
- Hanoi tower = new Hanoi();
- int number = Integer.parseInt(args[0]);
- tower.number_of_disks = number;
- tower.startGame();
+ public static void main(String args[]) {
+ Hanoi tower = new Hanoi();
+ int number = Integer.parseInt(args[0]);
+ tower.number_of_disks = number;
+ tower.startGame();
/*for(int i=0;i stack = new Stack<>();
-
- // Main function
- public static void main(String[] args) {
- // To Create a Dummy Stack containing integers from 0-9
- for (int i = 0; i < 10; i++) {
- stack.push(i);
+ // Stack
+ private static Stack stack = new Stack<>();
+
+ // Main function
+ public static void main(String[] args) {
+ // To Create a Dummy Stack containing integers from 0-9
+ for (int i = 0; i < 10; i++) {
+ stack.push(i);
+ }
+ System.out.println("STACK");
+
+ // To print that dummy Stack
+ for (int k = 9; k >= 0; k--) {
+ System.out.println(k);
+ }
+
+ // Reverse Function called
+ reverseUsingRecursion(stack);
+
+ System.out.println("REVERSED STACK : ");
+ // To print reversed stack
+ while (!stack.isEmpty()) {
+ System.out.println(stack.pop());
+ }
}
- System.out.println("STACK");
- // To print that dummy Stack
- for (int k = 9; k >= 0; k--) {
- System.out.println(k);
+ // Function Used to reverse Stack Using Recursion
+ private static void reverseUsingRecursion(Stack stack) {
+ if (stack.isEmpty()) // If stack is empty then return
+ {
+ return;
+ }
+ /* All items are stored in call stack until we reach the end*/
+
+ int temptop = stack.peek();
+ stack.pop();
+ reverseUsingRecursion(stack); // Recursion call
+ insertAtEnd(temptop); // Insert items held in call stack one by one into stack
}
- // Reverse Function called
- reverseUsingRecursion(stack);
+ // Function used to insert element at the end of stack
+ private static void insertAtEnd(int temptop) {
+ if (stack.isEmpty()) {
+ stack.push(temptop); // If stack is empty push the element
+ } else {
+ int temp = stack.peek(); /* All the items are stored in call stack until we reach end*/
+ stack.pop();
- System.out.println("REVERSED STACK : ");
- // To print reversed stack
- while (!stack.isEmpty()) {
- System.out.println(stack.pop());
- }
- }
-
- // Function Used to reverse Stack Using Recursion
- private static void reverseUsingRecursion(Stack stack) {
- if (stack.isEmpty()) // If stack is empty then return
- {
- return;
- }
- /* All items are stored in call stack until we reach the end*/
-
- int temptop = stack.peek();
- stack.pop();
- reverseUsingRecursion(stack); // Recursion call
- insertAtEnd(temptop); // Insert items held in call stack one by one into stack
- }
-
- // Function used to insert element at the end of stack
- private static void insertAtEnd(int temptop) {
- if (stack.isEmpty()) {
- stack.push(temptop); // If stack is empty push the element
- } else {
- int temp = stack.peek(); /* All the items are stored in call stack until we reach end*/
- stack.pop();
-
- insertAtEnd(temptop); // Recursive call
+ insertAtEnd(temptop); // Recursive call
- stack.push(temp);
+ stack.push(temp);
+ }
}
- }
}
diff --git a/Others/RootPrecision.java b/Others/RootPrecision.java
index 4f9f86965c2b..22a196c8004c 100644
--- a/Others/RootPrecision.java
+++ b/Others/RootPrecision.java
@@ -4,33 +4,33 @@
public class RootPrecision {
- public static void main(String[] args) {
- // take input
- Scanner scn = new Scanner(System.in);
+ public static void main(String[] args) {
+ // take input
+ Scanner scn = new Scanner(System.in);
- // N is the input number
- int N = scn.nextInt();
+ // N is the input number
+ int N = scn.nextInt();
- // P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870.
- int P = scn.nextInt();
- System.out.println(squareRoot(N, P));
+ // P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870.
+ int P = scn.nextInt();
+ System.out.println(squareRoot(N, P));
- scn.close();
- }
+ scn.close();
+ }
- public static double squareRoot(int N, int P) {
- // rv means return value
- double rv;
+ public static double squareRoot(int N, int P) {
+ // rv means return value
+ double rv;
- double root = Math.pow(N, 0.5);
+ double root = Math.pow(N, 0.5);
- // calculate precision to power of 10 and then multiply it with root value.
- int precision = (int) Math.pow(10, P);
- root = root * precision;
+ // calculate precision to power of 10 and then multiply it with root value.
+ int precision = (int) Math.pow(10, P);
+ root = root * precision;
/*typecast it into integer then divide by precision and again typecast into double
so as to have decimal points upto P precision */
- rv = (int) root;
- return rv / precision;
- }
+ rv = (int) root;
+ return rv / precision;
+ }
}
diff --git a/Others/SJF.java b/Others/SJF.java
index 9eb9e1844daf..1cced0a756a1 100644
--- a/Others/SJF.java
+++ b/Others/SJF.java
@@ -1,7 +1,5 @@
package Others;
/**
- *
- *
* Shortest job first.
*
* Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting
@@ -13,6 +11,7 @@
* @author shivg7706
* @since 2018/10/27
*/
+
import java.util.*;
import java.util.ArrayList;
import java.util.Comparator;
@@ -20,165 +19,165 @@
class Process {
- public int pid;
- public int arrivalTime;
- public int burstTime;
- public int priority;
- public int turnAroundTime;
- public int waitTime;
- public int remainingTime;
+ public int pid;
+ public int arrivalTime;
+ public int burstTime;
+ public int priority;
+ public int turnAroundTime;
+ public int waitTime;
+ public int remainingTime;
}
class Schedule {
- private int noOfProcess;
- private int timer = 0;
- private ArrayList processes;
- private ArrayList remainingProcess;
- private ArrayList gantChart;
- private float burstAll;
- private Map> arrivals;
-
- Schedule() {
- Scanner in = new Scanner(System.in);
-
- processes = new ArrayList();
- remainingProcess = new ArrayList();
-
- gantChart = new ArrayList<>();
- arrivals = new HashMap<>();
-
- System.out.print("Enter the no. of processes: ");
- noOfProcess = in.nextInt();
- System.out.println("Enter the arrival, burst and priority of processes");
- for (int i = 0; i < noOfProcess; i++) {
- Process p = new Process();
- p.pid = i;
- p.arrivalTime = in.nextInt();
- p.burstTime = in.nextInt();
- p.priority = in.nextInt();
- p.turnAroundTime = 0;
- p.waitTime = 0;
- p.remainingTime = p.burstTime;
-
- if (arrivals.get(p.arrivalTime) == null) {
- arrivals.put(p.arrivalTime, new ArrayList());
- }
- arrivals.get(p.arrivalTime).add(p);
- processes.add(p);
- burstAll += p.burstTime;
- }
- in.close();
- }
-
- void startScheduling() {
-
- processes.sort(
- new Comparator() {
- @Override
- public int compare(Process a, Process b) {
- return a.arrivalTime - b.arrivalTime;
- }
- });
-
- while (!(arrivals.size() == 0 && remainingProcess.size() == 0)) {
- removeFinishedProcess();
- if (arrivals.get(timer) != null) {
- remainingProcess.addAll(arrivals.get(timer));
- arrivals.remove(timer);
- }
-
- remainingProcess.sort(
- new Comparator() {
- private int alpha = 6;
- private int beta = 1;
-
- @Override
- public int compare(Process a, Process b) {
- int aRem = a.remainingTime;
- int bRem = b.remainingTime;
- int aprior = a.priority;
- int bprior = b.priority;
- return (alpha * aRem + beta * aprior) - (alpha * bRem + beta * bprior);
+ private int noOfProcess;
+ private int timer = 0;
+ private ArrayList processes;
+ private ArrayList remainingProcess;
+ private ArrayList gantChart;
+ private float burstAll;
+ private Map> arrivals;
+
+ Schedule() {
+ Scanner in = new Scanner(System.in);
+
+ processes = new ArrayList();
+ remainingProcess = new ArrayList();
+
+ gantChart = new ArrayList<>();
+ arrivals = new HashMap<>();
+
+ System.out.print("Enter the no. of processes: ");
+ noOfProcess = in.nextInt();
+ System.out.println("Enter the arrival, burst and priority of processes");
+ for (int i = 0; i < noOfProcess; i++) {
+ Process p = new Process();
+ p.pid = i;
+ p.arrivalTime = in.nextInt();
+ p.burstTime = in.nextInt();
+ p.priority = in.nextInt();
+ p.turnAroundTime = 0;
+ p.waitTime = 0;
+ p.remainingTime = p.burstTime;
+
+ if (arrivals.get(p.arrivalTime) == null) {
+ arrivals.put(p.arrivalTime, new ArrayList());
}
- });
-
- int k = timeElapsed(timer);
- ageing(k);
- timer++;
+ arrivals.get(p.arrivalTime).add(p);
+ processes.add(p);
+ burstAll += p.burstTime;
+ }
+ in.close();
}
- System.out.println("Total time required: " + (timer - 1));
- }
+ void startScheduling() {
+
+ processes.sort(
+ new Comparator() {
+ @Override
+ public int compare(Process a, Process b) {
+ return a.arrivalTime - b.arrivalTime;
+ }
+ });
+
+ while (!(arrivals.size() == 0 && remainingProcess.size() == 0)) {
+ removeFinishedProcess();
+ if (arrivals.get(timer) != null) {
+ remainingProcess.addAll(arrivals.get(timer));
+ arrivals.remove(timer);
+ }
- void removeFinishedProcess() {
- ArrayList completed = new ArrayList();
- for (int i = 0; i < remainingProcess.size(); i++) {
- if (remainingProcess.get(i).remainingTime == 0) {
- completed.add(i);
- }
+ remainingProcess.sort(
+ new Comparator() {
+ private int alpha = 6;
+ private int beta = 1;
+
+ @Override
+ public int compare(Process a, Process b) {
+ int aRem = a.remainingTime;
+ int bRem = b.remainingTime;
+ int aprior = a.priority;
+ int bprior = b.priority;
+ return (alpha * aRem + beta * aprior) - (alpha * bRem + beta * bprior);
+ }
+ });
+
+ int k = timeElapsed(timer);
+ ageing(k);
+ timer++;
+ }
+
+ System.out.println("Total time required: " + (timer - 1));
}
- for (int i = 0; i < completed.size(); i++) {
- int pid = remainingProcess.get(completed.get(i)).pid;
- processes.get(pid).waitTime = remainingProcess.get(completed.get(i)).waitTime;
- remainingProcess.remove(remainingProcess.get(completed.get(i)));
- }
- }
+ void removeFinishedProcess() {
+ ArrayList completed = new ArrayList();
+ for (int i = 0; i < remainingProcess.size(); i++) {
+ if (remainingProcess.get(i).remainingTime == 0) {
+ completed.add(i);
+ }
+ }
- public int timeElapsed(int i) {
- if (!remainingProcess.isEmpty()) {
- gantChart.add(i, remainingProcess.get(0).pid);
- remainingProcess.get(0).remainingTime--;
- return 1;
+ for (int i = 0; i < completed.size(); i++) {
+ int pid = remainingProcess.get(completed.get(i)).pid;
+ processes.get(pid).waitTime = remainingProcess.get(completed.get(i)).waitTime;
+ remainingProcess.remove(remainingProcess.get(completed.get(i)));
+ }
}
- return 0;
- }
-
- public void ageing(int k) {
- for (int i = k; i < remainingProcess.size(); i++) {
- remainingProcess.get(i).waitTime++;
- if (remainingProcess.get(i).waitTime % 7 == 0) {
- remainingProcess.get(i).priority--;
- }
- }
- }
- public void solve() {
- System.out.println("Gant chart ");
- for (int i = 0; i < gantChart.size(); i++) {
- System.out.print(gantChart.get(i) + " ");
+ public int timeElapsed(int i) {
+ if (!remainingProcess.isEmpty()) {
+ gantChart.add(i, remainingProcess.get(0).pid);
+ remainingProcess.get(0).remainingTime--;
+ return 1;
+ }
+ return 0;
}
- System.out.println();
-
- float waitTimeTot = 0;
- float tatTime = 0;
-
- for (int i = 0; i < noOfProcess; i++) {
- processes.get(i).turnAroundTime = processes.get(i).waitTime + processes.get(i).burstTime;
-
- waitTimeTot += processes.get(i).waitTime;
- tatTime += processes.get(i).turnAroundTime;
- System.out.println(
- "Process no.: "
- + i
- + " Wait time: "
- + processes.get(i).waitTime
- + " Turn Around Time: "
- + processes.get(i).turnAroundTime);
+ public void ageing(int k) {
+ for (int i = k; i < remainingProcess.size(); i++) {
+ remainingProcess.get(i).waitTime++;
+ if (remainingProcess.get(i).waitTime % 7 == 0) {
+ remainingProcess.get(i).priority--;
+ }
+ }
}
- System.out.println("Average Waiting Time: " + waitTimeTot / noOfProcess);
- System.out.println("Average TAT Time: " + tatTime / noOfProcess);
- System.out.println("Throughput: " + (float) noOfProcess / (timer - 1));
- }
+ public void solve() {
+ System.out.println("Gant chart ");
+ for (int i = 0; i < gantChart.size(); i++) {
+ System.out.print(gantChart.get(i) + " ");
+ }
+ System.out.println();
+
+ float waitTimeTot = 0;
+ float tatTime = 0;
+
+ for (int i = 0; i < noOfProcess; i++) {
+ processes.get(i).turnAroundTime = processes.get(i).waitTime + processes.get(i).burstTime;
+
+ waitTimeTot += processes.get(i).waitTime;
+ tatTime += processes.get(i).turnAroundTime;
+
+ System.out.println(
+ "Process no.: "
+ + i
+ + " Wait time: "
+ + processes.get(i).waitTime
+ + " Turn Around Time: "
+ + processes.get(i).turnAroundTime);
+ }
+
+ System.out.println("Average Waiting Time: " + waitTimeTot / noOfProcess);
+ System.out.println("Average TAT Time: " + tatTime / noOfProcess);
+ System.out.println("Throughput: " + (float) noOfProcess / (timer - 1));
+ }
}
public class SJF {
- public static void main(String[] args) {
- Schedule s = new Schedule();
- s.startScheduling();
- s.solve();
- }
+ public static void main(String[] args) {
+ Schedule s = new Schedule();
+ s.startScheduling();
+ s.solve();
+ }
}
diff --git a/Others/SieveOfEratosthenes.java b/Others/SieveOfEratosthenes.java
index f3759d2fdb56..343305357463 100644
--- a/Others/SieveOfEratosthenes.java
+++ b/Others/SieveOfEratosthenes.java
@@ -1,44 +1,46 @@
package Others;
-/** @author Varun Upadhyay (https://github.com/varunu28) */
+/**
+ * @author Varun Upadhyay (https://github.com/varunu28)
+ */
public class SieveOfEratosthenes {
- /**
- * This method implements the Sieve of Eratosthenes Algorithm
- *
- * @param n The number till which we have to check for prime Prints all the prime numbers till n
- */
- public static void findPrimesTillN(int n) {
- int[] arr = new int[n + 1];
+ /**
+ * This method implements the Sieve of Eratosthenes Algorithm
+ *
+ * @param n The number till which we have to check for prime Prints all the prime numbers till n
+ */
+ public static void findPrimesTillN(int n) {
+ int[] arr = new int[n + 1];
- for (int i = 0; i <= n; i++) {
- arr[i] = 1;
- }
+ for (int i = 0; i <= n; i++) {
+ arr[i] = 1;
+ }
- arr[0] = arr[1] = 0;
+ arr[0] = arr[1] = 0;
- for (int i = 2; i <= Math.sqrt(n); i++) {
- if (arr[i] == 1) {
- for (int j = 2; i * j <= n; j++) {
- arr[i * j] = 0;
+ for (int i = 2; i <= Math.sqrt(n); i++) {
+ if (arr[i] == 1) {
+ for (int j = 2; i * j <= n; j++) {
+ arr[i * j] = 0;
+ }
+ }
}
- }
- }
- for (int i = 0; i < n + 1; i++) {
- if (arr[i] == 1) {
- System.out.print(i + " ");
- }
- }
+ for (int i = 0; i < n + 1; i++) {
+ if (arr[i] == 1) {
+ System.out.print(i + " ");
+ }
+ }
- System.out.println();
- }
+ System.out.println();
+ }
- // Driver Program
- public static void main(String[] args) {
- int n = 100;
+ // Driver Program
+ public static void main(String[] args) {
+ int n = 100;
- // Prints 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
- findPrimesTillN(n);
- }
+ // Prints 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
+ findPrimesTillN(n);
+ }
}
diff --git a/Others/SkylineProblem.java b/Others/SkylineProblem.java
index 5be6501c9cc2..ae3d69180970 100644
--- a/Others/SkylineProblem.java
+++ b/Others/SkylineProblem.java
@@ -5,128 +5,128 @@
import java.util.Scanner;
public class SkylineProblem {
- Building[] building;
- int count;
+ Building[] building;
+ int count;
- public void run() {
- Scanner sc = new Scanner(System.in);
+ public void run() {
+ Scanner sc = new Scanner(System.in);
- int num = sc.nextInt();
- this.building = new Building[num];
+ int num = sc.nextInt();
+ this.building = new Building[num];
- for (int i = 0; i < num; i++) {
- String input = sc.next();
- String[] data = input.split(",");
- this.add(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2]));
- }
- this.print(this.findSkyline(0, num - 1));
-
- sc.close();
- }
-
- public void add(int left, int height, int right) {
- building[count++] = new Building(left, height, right);
- }
+ for (int i = 0; i < num; i++) {
+ String input = sc.next();
+ String[] data = input.split(",");
+ this.add(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2]));
+ }
+ this.print(this.findSkyline(0, num - 1));
- public void print(ArrayList skyline) {
- Iterator it = skyline.iterator();
+ sc.close();
+ }
- while (it.hasNext()) {
- Skyline temp = it.next();
- System.out.print(temp.coordinates + "," + temp.height);
- if (it.hasNext()) {
- System.out.print(",");
- }
+ public void add(int left, int height, int right) {
+ building[count++] = new Building(left, height, right);
}
- }
- public ArrayList findSkyline(int start, int end) {
- if (start == end) {
- ArrayList list = new ArrayList<>();
- list.add(new Skyline(building[start].left, building[start].height));
- list.add(new Skyline(building[end].right, 0));
+ public void print(ArrayList skyline) {
+ Iterator it = skyline.iterator();
- return list;
+ while (it.hasNext()) {
+ Skyline temp = it.next();
+ System.out.print(temp.coordinates + "," + temp.height);
+ if (it.hasNext()) {
+ System.out.print(",");
+ }
+ }
}
- int mid = (start + end) / 2;
+ public ArrayList findSkyline(int start, int end) {
+ if (start == end) {
+ ArrayList list = new ArrayList<>();
+ list.add(new Skyline(building[start].left, building[start].height));
+ list.add(new Skyline(building[end].right, 0));
- ArrayList sky1 = this.findSkyline(start, mid);
- ArrayList sky2 = this.findSkyline(mid + 1, end);
+ return list;
+ }
- return this.mergeSkyline(sky1, sky2);
- }
+ int mid = (start + end) / 2;
- public ArrayList mergeSkyline(ArrayList sky1, ArrayList sky2) {
- int currentH1 = 0, currentH2 = 0;
- ArrayList skyline = new ArrayList<>();
- int maxH = 0;
+ ArrayList sky1 = this.findSkyline(start, mid);
+ ArrayList sky2 = this.findSkyline(mid + 1, end);
- while (!sky1.isEmpty() && !sky2.isEmpty()) {
- if (sky1.get(0).coordinates < sky2.get(0).coordinates) {
- int currentX = sky1.get(0).coordinates;
- currentH1 = sky1.get(0).height;
+ return this.mergeSkyline(sky1, sky2);
+ }
- if (currentH1 < currentH2) {
- sky1.remove(0);
- if (maxH != currentH2) skyline.add(new Skyline(currentX, currentH2));
- } else {
- maxH = currentH1;
- sky1.remove(0);
- skyline.add(new Skyline(currentX, currentH1));
+ public ArrayList mergeSkyline(ArrayList sky1, ArrayList sky2) {
+ int currentH1 = 0, currentH2 = 0;
+ ArrayList skyline = new ArrayList<>();
+ int maxH = 0;
+
+ while (!sky1.isEmpty() && !sky2.isEmpty()) {
+ if (sky1.get(0).coordinates < sky2.get(0).coordinates) {
+ int currentX = sky1.get(0).coordinates;
+ currentH1 = sky1.get(0).height;
+
+ if (currentH1 < currentH2) {
+ sky1.remove(0);
+ if (maxH != currentH2) skyline.add(new Skyline(currentX, currentH2));
+ } else {
+ maxH = currentH1;
+ sky1.remove(0);
+ skyline.add(new Skyline(currentX, currentH1));
+ }
+ } else {
+ int currentX = sky2.get(0).coordinates;
+ currentH2 = sky2.get(0).height;
+
+ if (currentH2 < currentH1) {
+ sky2.remove(0);
+ if (maxH != currentH1) skyline.add(new Skyline(currentX, currentH1));
+ } else {
+ maxH = currentH2;
+ sky2.remove(0);
+ skyline.add(new Skyline(currentX, currentH2));
+ }
+ }
}
- } else {
- int currentX = sky2.get(0).coordinates;
- currentH2 = sky2.get(0).height;
-
- if (currentH2 < currentH1) {
- sky2.remove(0);
- if (maxH != currentH1) skyline.add(new Skyline(currentX, currentH1));
- } else {
- maxH = currentH2;
- sky2.remove(0);
- skyline.add(new Skyline(currentX, currentH2));
+
+ while (!sky1.isEmpty()) {
+ skyline.add(sky1.get(0));
+ sky1.remove(0);
}
- }
- }
- while (!sky1.isEmpty()) {
- skyline.add(sky1.get(0));
- sky1.remove(0);
- }
+ while (!sky2.isEmpty()) {
+ skyline.add(sky2.get(0));
+ sky2.remove(0);
+ }
- while (!sky2.isEmpty()) {
- skyline.add(sky2.get(0));
- sky2.remove(0);
+ return skyline;
}
- return skyline;
- }
+ public class Skyline {
+ public int coordinates;
+ public int height;
- public class Skyline {
- public int coordinates;
- public int height;
-
- public Skyline(int coordinates, int height) {
- this.coordinates = coordinates;
- this.height = height;
+ public Skyline(int coordinates, int height) {
+ this.coordinates = coordinates;
+ this.height = height;
+ }
}
- }
- public class Building {
- public int left;
- public int height;
- public int right;
+ public class Building {
+ public int left;
+ public int height;
+ public int right;
- public Building(int left, int height, int right) {
- this.left = left;
- this.height = height;
- this.right = right;
+ public Building(int left, int height, int right) {
+ this.left = left;
+ this.height = height;
+ this.right = right;
+ }
}
- }
- public static void main(String[] args) {
- SkylineProblem skylineProblem = new SkylineProblem();
- skylineProblem.run();
- }
+ public static void main(String[] args) {
+ SkylineProblem skylineProblem = new SkylineProblem();
+ skylineProblem.run();
+ }
}
diff --git a/Others/StackPostfixNotation.java b/Others/StackPostfixNotation.java
index 63b4d3c76a3a..30ec757ae851 100644
--- a/Others/StackPostfixNotation.java
+++ b/Others/StackPostfixNotation.java
@@ -3,40 +3,40 @@
import java.util.*;
public class StackPostfixNotation {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String post = scanner.nextLine(); // Takes input with spaces in between eg. "1 21 +"
- System.out.println(postfixEvaluate(post));
- scanner.close();
- }
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ String post = scanner.nextLine(); // Takes input with spaces in between eg. "1 21 +"
+ System.out.println(postfixEvaluate(post));
+ scanner.close();
+ }
- // Evaluates the given postfix expression string and returns the result.
- public static int postfixEvaluate(String exp) {
- Stack s = new Stack();
- Scanner tokens = new Scanner(exp);
+ // Evaluates the given postfix expression string and returns the result.
+ public static int postfixEvaluate(String exp) {
+ Stack s = new Stack();
+ Scanner tokens = new Scanner(exp);
- while (tokens.hasNext()) {
- if (tokens.hasNextInt()) {
- s.push(tokens.nextInt()); // If int then push to stack
- } else { // else pop top two values and perform the operation
- int num2 = s.pop();
- int num1 = s.pop();
- String op = tokens.next();
+ while (tokens.hasNext()) {
+ if (tokens.hasNextInt()) {
+ s.push(tokens.nextInt()); // If int then push to stack
+ } else { // else pop top two values and perform the operation
+ int num2 = s.pop();
+ int num1 = s.pop();
+ String op = tokens.next();
- if (op.equals("+")) {
- s.push(num1 + num2);
- } else if (op.equals("-")) {
- s.push(num1 - num2);
- } else if (op.equals("*")) {
- s.push(num1 * num2);
- } else {
- s.push(num1 / num2);
- }
+ if (op.equals("+")) {
+ s.push(num1 + num2);
+ } else if (op.equals("-")) {
+ s.push(num1 - num2);
+ } else if (op.equals("*")) {
+ s.push(num1 * num2);
+ } else {
+ s.push(num1 / num2);
+ }
- // "+", "-", "*", "/"
- }
+ // "+", "-", "*", "/"
+ }
+ }
+ tokens.close();
+ return s.pop();
}
- tokens.close();
- return s.pop();
- }
}
diff --git a/Others/StringMatchFiniteAutomata.java b/Others/StringMatchFiniteAutomata.java
index a6d3fbab4d62..293f1706f009 100644
--- a/Others/StringMatchFiniteAutomata.java
+++ b/Others/StringMatchFiniteAutomata.java
@@ -1,81 +1,84 @@
-/** @author Prateek Kumar Oraon (https://github.com/prateekKrOraon) */
+/**
+ * @author Prateek Kumar Oraon (https://github.com/prateekKrOraon)
+ */
+
import java.util.Scanner;
// An implementaion of string matching using finite automata
public class StringMatchFiniteAutomata {
- public static final int CHARS = 256;
- public static int[][] FA;
- public static Scanner scanner = null;
+ public static final int CHARS = 256;
+ public static int[][] FA;
+ public static Scanner scanner = null;
- public static void main(String[] args) {
+ public static void main(String[] args) {
- scanner = new Scanner(System.in);
- System.out.println("Enter String");
- String text = scanner.nextLine();
- System.out.println("Enter pattern");
- String pat = scanner.nextLine();
+ scanner = new Scanner(System.in);
+ System.out.println("Enter String");
+ String text = scanner.nextLine();
+ System.out.println("Enter pattern");
+ String pat = scanner.nextLine();
- searchPat(text, pat);
+ searchPat(text, pat);
- scanner.close();
- }
+ scanner.close();
+ }
- public static void searchPat(String text, String pat) {
+ public static void searchPat(String text, String pat) {
- int m = pat.length();
- int n = text.length();
+ int m = pat.length();
+ int n = text.length();
- FA = new int[m + 1][CHARS];
+ FA = new int[m + 1][CHARS];
- computeFA(pat, m, FA);
+ computeFA(pat, m, FA);
- int state = 0;
- for (int i = 0; i < n; i++) {
- state = FA[state][text.charAt(i)];
+ int state = 0;
+ for (int i = 0; i < n; i++) {
+ state = FA[state][text.charAt(i)];
- if (state == m) {
- System.out.println("Pattern found at index " + (i - m + 1));
- }
+ if (state == m) {
+ System.out.println("Pattern found at index " + (i - m + 1));
+ }
+ }
}
- }
- // Computes finite automata for the partern
- public static void computeFA(String pat, int m, int[][] FA) {
+ // Computes finite automata for the partern
+ public static void computeFA(String pat, int m, int[][] FA) {
- for (int state = 0; state <= m; ++state) {
- for (int x = 0; x < CHARS; ++x) {
- FA[state][x] = getNextState(pat, m, state, x);
- }
+ for (int state = 0; state <= m; ++state) {
+ for (int x = 0; x < CHARS; ++x) {
+ FA[state][x] = getNextState(pat, m, state, x);
+ }
+ }
}
- }
- public static int getNextState(String pat, int m, int state, int x) {
+ public static int getNextState(String pat, int m, int state, int x) {
- // if current state is less than length of pattern
- // and input character of pattern matches the character in the alphabet
- // then automata goes to next state
- if (state < m && x == pat.charAt(state)) {
- return state + 1;
- }
+ // if current state is less than length of pattern
+ // and input character of pattern matches the character in the alphabet
+ // then automata goes to next state
+ if (state < m && x == pat.charAt(state)) {
+ return state + 1;
+ }
- for (int ns = state; ns > 0; ns--) {
+ for (int ns = state; ns > 0; ns--) {
- if (pat.charAt(ns - 1) == x) {
+ if (pat.charAt(ns - 1) == x) {
- for (int i = 0; i < ns - 1; i++) {
+ for (int i = 0; i < ns - 1; i++) {
- if (pat.charAt(i) != pat.charAt(state - ns + i + 1)) {
- break;
- }
+ if (pat.charAt(i) != pat.charAt(state - ns + i + 1)) {
+ break;
+ }
- if (i == ns - 1) {
- return ns;
- }
+ if (i == ns - 1) {
+ return ns;
+ }
+ }
+ }
}
- }
- }
- return 0;
- }
+ return 0;
+ }
}
diff --git a/Others/ThreeSum.java b/Others/ThreeSum.java
index 9524bb6f54e4..7778e2463d90 100644
--- a/Others/ThreeSum.java
+++ b/Others/ThreeSum.java
@@ -10,38 +10,38 @@
*
* @author Ujjawal Joshi
* @date 2020.05.18
- * Test Cases: Input: 6 //Length of array 12 3 4 1 6 9 target=24 Output:3 9 12 Explanation:
- * There is a triplet (12, 3 and 9) present in the array whose sum is 24.
+ *
Test Cases: Input: 6 //Length of array 12 3 4 1 6 9 target=24 Output:3 9 12 Explanation:
+ * There is a triplet (12, 3 and 9) present in the array whose sum is 24.
*/
class ThreeSum {
- public static void main(String args[]) {
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt(); // Length of an array
+ public static void main(String args[]) {
+ Scanner sc = new Scanner(System.in);
+ int n = sc.nextInt(); // Length of an array
- int a[] = new int[n];
+ int a[] = new int[n];
- for (int i = 0; i < n; i++) {
- a[i] = sc.nextInt();
- }
- System.out.println("Target");
- int n_find = sc.nextInt();
+ for (int i = 0; i < n; i++) {
+ a[i] = sc.nextInt();
+ }
+ System.out.println("Target");
+ int n_find = sc.nextInt();
- Arrays.sort(a); // Sort the array if array is not sorted
+ Arrays.sort(a); // Sort the array if array is not sorted
- for (int i = 0; i < n; i++) {
+ for (int i = 0; i < n; i++) {
- int l = i + 1, r = n - 1;
+ int l = i + 1, r = n - 1;
- while (l < r) {
- if (a[i] + a[l] + a[r] == n_find) {
- System.out.println(a[i] + " " + a[l] + " " + a[r]);
- break;
- } // if you want all the triplets write l++;r--; insted of break;
- else if (a[i] + a[l] + a[r] < n_find) l++;
- else r--;
- }
- }
+ while (l < r) {
+ if (a[i] + a[l] + a[r] == n_find) {
+ System.out.println(a[i] + " " + a[l] + " " + a[r]);
+ break;
+ } // if you want all the triplets write l++;r--; insted of break;
+ else if (a[i] + a[l] + a[r] < n_find) l++;
+ else r--;
+ }
+ }
- sc.close();
- }
+ sc.close();
+ }
}
diff --git a/Others/TopKWords.java b/Others/TopKWords.java
index 98a683e5dbfb..0e45cd8358c1 100644
--- a/Others/TopKWords.java
+++ b/Others/TopKWords.java
@@ -7,80 +7,80 @@
in the file – shown in order (ignore case and periods) */
public class TopKWords {
- static class CountWords {
- private String fileName;
+ static class CountWords {
+ private String fileName;
- public CountWords(String fileName) {
- this.fileName = fileName;
- }
+ public CountWords(String fileName) {
+ this.fileName = fileName;
+ }
- public Map getDictionary() {
- Map dictionary = new HashMap<>();
- FileInputStream fis = null;
+ public Map getDictionary() {
+ Map dictionary = new HashMap<>();
+ FileInputStream fis = null;
- try {
+ try {
- fis = new FileInputStream(fileName); // open the file
- int in = 0;
- String s = ""; // init a empty word
- in = fis.read(); // read one character
+ fis = new FileInputStream(fileName); // open the file
+ int in = 0;
+ String s = ""; // init a empty word
+ in = fis.read(); // read one character
- while (-1 != in) {
- if (Character.isLetter((char) in)) {
- s += (char) in; // if get a letter, append to s
- } else {
- // this branch means an entire word has just been read
- if (s.length() > 0) {
- // see whether word exists or not
- if (dictionary.containsKey(s)) {
- // if exist, count++
- dictionary.put(s, dictionary.get(s) + 1);
- } else {
- // if not exist, initiate count of this word with 1
- dictionary.put(s, 1);
- }
+ while (-1 != in) {
+ if (Character.isLetter((char) in)) {
+ s += (char) in; // if get a letter, append to s
+ } else {
+ // this branch means an entire word has just been read
+ if (s.length() > 0) {
+ // see whether word exists or not
+ if (dictionary.containsKey(s)) {
+ // if exist, count++
+ dictionary.put(s, dictionary.get(s) + 1);
+ } else {
+ // if not exist, initiate count of this word with 1
+ dictionary.put(s, 1);
+ }
+ }
+ s = ""; // reInit a empty word
+ }
+ in = fis.read();
+ }
+ return dictionary;
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ // you always have to close the I/O streams
+ if (fis != null) fis.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
}
- s = ""; // reInit a empty word
- }
- in = fis.read();
- }
- return dictionary;
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- // you always have to close the I/O streams
- if (fis != null) fis.close();
- } catch (IOException e) {
- e.printStackTrace();
+ return null;
}
- }
- return null;
}
- }
- public static void main(String[] args) {
- // you can replace the filePath with yours
- CountWords cw = new CountWords("/Users/lisanaaa/Desktop/words.txt");
- Map dictionary =
- cw.getDictionary(); // get the words dictionary: {word: frequency}
+ public static void main(String[] args) {
+ // you can replace the filePath with yours
+ CountWords cw = new CountWords("/Users/lisanaaa/Desktop/words.txt");
+ Map dictionary =
+ cw.getDictionary(); // get the words dictionary: {word: frequency}
- // we change the map to list for convenient sort
- List> list = new ArrayList<>(dictionary.entrySet());
+ // we change the map to list for convenient sort
+ List> list = new ArrayList<>(dictionary.entrySet());
- // sort by lambda valueComparator
- list.sort(Comparator.comparing(m -> m.getValue()));
+ // sort by lambda valueComparator
+ list.sort(Comparator.comparing(m -> m.getValue()));
- Scanner input = new Scanner(System.in);
- int k = input.nextInt();
- while (k > list.size()) {
- System.out.println("Retype a number, your number is too large");
- input = new Scanner(System.in);
- k = input.nextInt();
- }
- for (int i = 0; i < k; i++) {
- System.out.println(list.get(list.size() - i - 1));
+ Scanner input = new Scanner(System.in);
+ int k = input.nextInt();
+ while (k > list.size()) {
+ System.out.println("Retype a number, your number is too large");
+ input = new Scanner(System.in);
+ k = input.nextInt();
+ }
+ for (int i = 0; i < k; i++) {
+ System.out.println(list.get(list.size() - i - 1));
+ }
+ input.close();
}
- input.close();
- }
}
diff --git a/Others/TowerOfHanoi.java b/Others/TowerOfHanoi.java
index c339739cc79e..5b335894963c 100644
--- a/Others/TowerOfHanoi.java
+++ b/Others/TowerOfHanoi.java
@@ -3,24 +3,24 @@
import java.util.Scanner;
class TowerOfHanoi {
- public static void shift(int n, String startPole, String intermediatePole, String endPole) {
- // if n becomes zero the program returns thus ending the loop.
- if (n != 0) {
- // Shift function is called in recursion for swapping the n-1 disc from the startPole to the
- // intermediatePole
- shift(n - 1, startPole, endPole, intermediatePole);
- System.out.format("Move %d from %s to %s\n", n, startPole, endPole); // Result Printing
- // Shift function is called in recursion for swapping the n-1 disc from the intermediatePole
- // to the endPole
- shift(n - 1, intermediatePole, startPole, endPole);
+ public static void shift(int n, String startPole, String intermediatePole, String endPole) {
+ // if n becomes zero the program returns thus ending the loop.
+ if (n != 0) {
+ // Shift function is called in recursion for swapping the n-1 disc from the startPole to the
+ // intermediatePole
+ shift(n - 1, startPole, endPole, intermediatePole);
+ System.out.format("Move %d from %s to %s\n", n, startPole, endPole); // Result Printing
+ // Shift function is called in recursion for swapping the n-1 disc from the intermediatePole
+ // to the endPole
+ shift(n - 1, intermediatePole, startPole, endPole);
+ }
}
- }
- public static void main(String[] args) {
- System.out.print("Enter number of discs on Pole 1: ");
- Scanner scanner = new Scanner(System.in);
- int numberOfDiscs = scanner.nextInt(); // input of number of discs on pole 1
- shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); // Shift function called
- scanner.close();
- }
+ public static void main(String[] args) {
+ System.out.print("Enter number of discs on Pole 1: ");
+ Scanner scanner = new Scanner(System.in);
+ int numberOfDiscs = scanner.nextInt(); // input of number of discs on pole 1
+ shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); // Shift function called
+ scanner.close();
+ }
}
diff --git a/Others/TwoPointers.java b/Others/TwoPointers.java
index ee38192d630c..56e655feebcf 100644
--- a/Others/TwoPointers.java
+++ b/Others/TwoPointers.java
@@ -9,42 +9,42 @@
*/
class TwoPointers {
- public static void main(String[] args) {
- int[] arr = {10, 20, 35, 50, 75, 80};
- int key = 70;
- assert isPairedSum(arr, key); /* 20 + 60 == 70 */
+ public static void main(String[] args) {
+ int[] arr = {10, 20, 35, 50, 75, 80};
+ int key = 70;
+ assert isPairedSum(arr, key); /* 20 + 60 == 70 */
- arr = new int[] {1, 2, 3, 4, 5, 6, 7};
- key = 13;
- assert isPairedSum(arr, key); /* 6 + 7 == 13 */
+ arr = new int[]{1, 2, 3, 4, 5, 6, 7};
+ key = 13;
+ assert isPairedSum(arr, key); /* 6 + 7 == 13 */
- key = 14;
- assert !isPairedSum(arr, key);
- }
+ key = 14;
+ assert !isPairedSum(arr, key);
+ }
- /**
- * Given a sorted array arr (sorted in ascending order). Find if there exists any pair of elements
- * such that their sum is equal to key.
- *
- * @param arr the array contains elements
- * @param key the number to search
- * @return {@code true} if there exists a pair of elements, {@code false} otherwise.
- */
- private static boolean isPairedSum(int[] arr, int key) {
- /* array sorting is necessary for this algorithm to function correctly */
- Arrays.sort(arr);
- int i = 0; /* index of first element */
- int j = arr.length - 1; /* index of last element */
+ /**
+ * Given a sorted array arr (sorted in ascending order). Find if there exists any pair of elements
+ * such that their sum is equal to key.
+ *
+ * @param arr the array contains elements
+ * @param key the number to search
+ * @return {@code true} if there exists a pair of elements, {@code false} otherwise.
+ */
+ private static boolean isPairedSum(int[] arr, int key) {
+ /* array sorting is necessary for this algorithm to function correctly */
+ Arrays.sort(arr);
+ int i = 0; /* index of first element */
+ int j = arr.length - 1; /* index of last element */
- while (i < j) {
- if (arr[i] + arr[j] == key) {
- return true;
- } else if (arr[i] + arr[j] < key) {
- i++;
- } else {
- j--;
- }
+ while (i < j) {
+ if (arr[i] + arr[j] == key) {
+ return true;
+ } else if (arr[i] + arr[j] < key) {
+ i++;
+ } else {
+ j--;
+ }
+ }
+ return false;
}
- return false;
- }
}
diff --git a/Others/WorstFit.java b/Others/WorstFit.java
index 23753b28fef2..ef34109fdcab 100644
--- a/Others/WorstFit.java
+++ b/Others/WorstFit.java
@@ -2,79 +2,81 @@
import java.util.ArrayList;
-/** @author Dekas Dimitrios */
+/**
+ * @author Dekas Dimitrios
+ */
public class WorstFit {
- private static final int NO_ALLOCATION =
- -255; // if a process has been allocated in position -255,
- // it means that it has not been actually allocated.
+ private static final int NO_ALLOCATION =
+ -255; // if a process has been allocated in position -255,
+ // it means that it has not been actually allocated.
- /**
- * Method to find the index of the memory block that is going to fit the given process based on
- * the worst fit algorithm.
- *
- * @param blocks: the array with the available memory blocks.
- * @param process: the size of the process.
- * @return the index of the block that fits, or -255 if no such block exists.
- */
- private static int findWorstFit(int[] blockSizes, int processSize) {
- int max = -1;
- int index = -1;
- for (int i = 0;
- i < blockSizes.length;
- i++) { // Find the index of the biggest memory block available.
- if (blockSizes[i] > max) {
- max = blockSizes[i];
- index = i;
- }
+ /**
+ * Method to find the index of the memory block that is going to fit the given process based on
+ * the worst fit algorithm.
+ *
+ * @param blocks: the array with the available memory blocks.
+ * @param process: the size of the process.
+ * @return the index of the block that fits, or -255 if no such block exists.
+ */
+ private static int findWorstFit(int[] blockSizes, int processSize) {
+ int max = -1;
+ int index = -1;
+ for (int i = 0;
+ i < blockSizes.length;
+ i++) { // Find the index of the biggest memory block available.
+ if (blockSizes[i] > max) {
+ max = blockSizes[i];
+ index = i;
+ }
+ }
+ // If the biggest memory block cannot fit the process, return -255 as the result
+ if (processSize > blockSizes[index]) {
+ return NO_ALLOCATION;
+ }
+ return index;
}
- // If the biggest memory block cannot fit the process, return -255 as the result
- if (processSize > blockSizes[index]) {
- return NO_ALLOCATION;
- }
- return index;
- }
- /**
- * Method to allocate memory to blocks according to the worst fit algorithm. It should return an
- * ArrayList of Integers, where the index is the process ID (zero-indexed) and the value is the
- * block number (also zero-indexed).
- *
- * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available.
- * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory
- * blocks for.
- * @return the ArrayList filled with Integers repressenting the memory allocation that took place.
- */
- static ArrayList worstFit(int[] sizeOfBlocks, int[] sizeOfProcesses) {
- // The array list responsible for saving the memory allocations done by the worst-fit algorithm
- ArrayList memAlloc = new ArrayList<>();
- // Do this for every process
- for (int processSize : sizeOfProcesses) {
- int chosenBlockIdx =
- findWorstFit(
- sizeOfBlocks, processSize); // Find the index of the memory block going to be used
- memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
- if (chosenBlockIdx
- != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
- sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
- }
+ /**
+ * Method to allocate memory to blocks according to the worst fit algorithm. It should return an
+ * ArrayList of Integers, where the index is the process ID (zero-indexed) and the value is the
+ * block number (also zero-indexed).
+ *
+ * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available.
+ * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory
+ * blocks for.
+ * @return the ArrayList filled with Integers repressenting the memory allocation that took place.
+ */
+ static ArrayList worstFit(int[] sizeOfBlocks, int[] sizeOfProcesses) {
+ // The array list responsible for saving the memory allocations done by the worst-fit algorithm
+ ArrayList memAlloc = new ArrayList<>();
+ // Do this for every process
+ for (int processSize : sizeOfProcesses) {
+ int chosenBlockIdx =
+ findWorstFit(
+ sizeOfBlocks, processSize); // Find the index of the memory block going to be used
+ memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
+ if (chosenBlockIdx
+ != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
+ sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
+ }
+ }
+ return memAlloc;
}
- return memAlloc;
- }
- /**
- * Method to print the memory allocated.
- *
- * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the
- * worstFit method.
- */
- public static void printMemoryAllocation(ArrayList memAllocation) {
- System.out.println("Process No.\tBlock No.");
- System.out.println("===========\t=========");
- for (int i = 0; i < memAllocation.size(); i++) {
- System.out.print(" " + i + "\t\t");
- if (memAllocation.get(i) != NO_ALLOCATION) System.out.print(memAllocation.get(i));
- else System.out.print("Not Allocated");
- System.out.println();
+ /**
+ * Method to print the memory allocated.
+ *
+ * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the
+ * worstFit method.
+ */
+ public static void printMemoryAllocation(ArrayList memAllocation) {
+ System.out.println("Process No.\tBlock No.");
+ System.out.println("===========\t=========");
+ for (int i = 0; i < memAllocation.size(); i++) {
+ System.out.print(" " + i + "\t\t");
+ if (memAllocation.get(i) != NO_ALLOCATION) System.out.print(memAllocation.get(i));
+ else System.out.print("Not Allocated");
+ System.out.println();
+ }
}
- }
}
diff --git a/Sorts/BitonicSort.java b/Sorts/BitonicSort.java
index 4888cc070c6f..ea756e0d0e07 100644
--- a/Sorts/BitonicSort.java
+++ b/Sorts/BitonicSort.java
@@ -3,72 +3,72 @@
/* Java program for Bitonic Sort. Note that this program
works only when size of input is a power of 2. */
public class BitonicSort {
- /* 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 ((a[i] > a[j] && dir == 1) || (a[i] < a[j] && dir == 0)) {
- // Swapping elements
- int temp = a[i];
- a[i] = a[j];
- a[j] = temp;
+ /* 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 ((a[i] > a[j] && dir == 1) || (a[i] < a[j] && dir == 0)) {
+ // Swapping elements
+ int temp = a[i];
+ a[i] = a[j];
+ a[j] = temp;
+ }
}
- }
- /* 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) {
- int k = cnt / 2;
- for (int i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir);
- bitonicMerge(a, low, k, dir);
- bitonicMerge(a, low + k, k, dir);
+ /* 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) {
+ int k = cnt / 2;
+ for (int i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir);
+ bitonicMerge(a, low, k, dir);
+ bitonicMerge(a, low + k, k, dir);
+ }
}
- }
- /* This funcion 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) {
- int k = cnt / 2;
+ /* This funcion 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) {
+ int k = cnt / 2;
- // sort in ascending order since dir here is 1
- bitonicSort(a, low, k, 1);
+ // sort in ascending order since dir here is 1
+ bitonicSort(a, low, k, 1);
- // sort in descending order since dir here is 0
- bitonicSort(a, low + k, k, 0);
+ // sort in descending order since dir here is 0
+ bitonicSort(a, low + k, k, 0);
- // Will merge wole sequence in ascending order
- // since dir=1.
- bitonicMerge(a, low, cnt, dir);
+ // Will merge wole sequence in ascending order
+ // since dir=1.
+ bitonicMerge(a, low, cnt, dir);
+ }
}
- }
- /*Caller of bitonicSort for sorting the entire array
- of length N in ASCENDING order */
- void sort(int a[], int N, int up) {
- bitonicSort(a, 0, N, up);
- }
+ /*Caller of bitonicSort for sorting the entire array
+ of length N in ASCENDING order */
+ void sort(int a[], int N, int up) {
+ bitonicSort(a, 0, N, up);
+ }
- /* A utility function to print array of size n */
- static void printArray(int arr[]) {
- int n = arr.length;
- for (int i = 0; i < n; ++i) System.out.print(arr[i] + " ");
- System.out.println();
- }
+ /* A utility function to print array of size n */
+ static void printArray(int arr[]) {
+ int n = arr.length;
+ for (int i = 0; i < n; ++i) System.out.print(arr[i] + " ");
+ System.out.println();
+ }
- public static void main(String args[]) {
- int a[] = {3, 7, 4, 8, 6, 2, 1, 5};
- int up = 1;
- BitonicSort ob = new BitonicSort();
- ob.sort(a, a.length, up);
- System.out.println("\nSorted array");
- printArray(a);
- }
+ public static void main(String args[]) {
+ int a[] = {3, 7, 4, 8, 6, 2, 1, 5};
+ int up = 1;
+ BitonicSort ob = new BitonicSort();
+ ob.sort(a, a.length, up);
+ System.out.println("\nSorted array");
+ printArray(a);
+ }
}
diff --git a/Sorts/BogoSort.java b/Sorts/BogoSort.java
index fc746480f235..6146f87a5d5c 100644
--- a/Sorts/BogoSort.java
+++ b/Sorts/BogoSort.java
@@ -8,45 +8,45 @@
*/
public class BogoSort implements SortAlgorithm {
- private static final Random random = new Random();
+ private static final Random random = new Random();
- private static > boolean isSorted(T[] array) {
- for (int i = 0; i < array.length - 1; i++) {
- if (SortUtils.less(array[i + 1], array[i])) return false;
+ private static > boolean isSorted(T[] array) {
+ for (int i = 0; i < array.length - 1; i++) {
+ if (SortUtils.less(array[i + 1], array[i])) return false;
+ }
+ return true;
}
- return true;
- }
- // Randomly shuffles the array
- private static void nextPermutation(T[] array) {
- int length = array.length;
+ // Randomly shuffles the array
+ private static void nextPermutation(T[] array) {
+ int length = array.length;
- for (int i = 0; i < array.length; i++) {
- int randomIndex = i + random.nextInt(length - i);
- SortUtils.swap(array, randomIndex, i);
+ for (int i = 0; i < array.length; i++) {
+ int randomIndex = i + random.nextInt(length - i);
+ SortUtils.swap(array, randomIndex, i);
+ }
}
- }
- public > T[] sort(T[] array) {
- while (!isSorted(array)) {
- nextPermutation(array);
+ public > T[] sort(T[] array) {
+ while (!isSorted(array)) {
+ nextPermutation(array);
+ }
+ return array;
}
- return array;
- }
- // Driver Program
- public static void main(String[] args) {
- // Integer Input
- Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
+ // Driver Program
+ public static void main(String[] args) {
+ // Integer Input
+ Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
- BogoSort bogoSort = new BogoSort();
+ BogoSort bogoSort = new BogoSort();
- // print a sorted array
- SortUtils.print(bogoSort.sort(integers));
+ // print a sorted array
+ SortUtils.print(bogoSort.sort(integers));
- // String Input
- String[] strings = {"c", "a", "e", "b", "d"};
+ // String Input
+ String[] strings = {"c", "a", "e", "b", "d"};
- SortUtils.print(bogoSort.sort(strings));
- }
+ SortUtils.print(bogoSort.sort(strings));
+ }
}
diff --git a/Sorts/BubbleSort.java b/Sorts/BubbleSort.java
index 9ca94954d641..0a90fd6e64ff 100644
--- a/Sorts/BubbleSort.java
+++ b/Sorts/BubbleSort.java
@@ -9,47 +9,49 @@
*/
class BubbleSort implements SortAlgorithm {
- /**
- * Implements generic bubble sort algorithm.
- *
- * @param array the array to be sorted.
- * @param the type of elements in the array.
- * @return the sorted array.
- */
- @Override
- public > T[] sort(T[] array) {
- for (int i = 0, size = array.length; i < size - 1; ++i) {
- boolean swapped = false;
- for (int j = 0; j < size - 1 - i; ++j) {
- if (greater(array[j], array[j + 1])) {
- swap(array, j, j + 1);
- swapped = true;
+ /**
+ * Implements generic bubble sort algorithm.
+ *
+ * @param array the array to be sorted.
+ * @param the type of elements in the array.
+ * @return the sorted array.
+ */
+ @Override
+ public > T[] sort(T[] array) {
+ for (int i = 0, size = array.length; i < size - 1; ++i) {
+ boolean swapped = false;
+ for (int j = 0; j < size - 1 - i; ++j) {
+ if (greater(array[j], array[j + 1])) {
+ swap(array, j, j + 1);
+ swapped = true;
+ }
+ }
+ if (!swapped) {
+ break;
+ }
}
- }
- if (!swapped) {
- break;
- }
+ return array;
}
- return array;
- }
- /** Driver Code */
- public static void main(String[] args) {
+ /**
+ * Driver Code
+ */
+ public static void main(String[] args) {
- Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
- BubbleSort bubbleSort = new BubbleSort();
- bubbleSort.sort(integers);
+ Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
+ BubbleSort bubbleSort = new BubbleSort();
+ bubbleSort.sort(integers);
- for (int i = 0; i < integers.length - 1; ++i) {
- assert integers[i] <= integers[i + 1];
- }
- print(integers); /* output: [1, 4, 6, 9, 12, 23, 54, 78, 231] */
+ for (int i = 0; i < integers.length - 1; ++i) {
+ assert integers[i] <= integers[i + 1];
+ }
+ print(integers); /* output: [1, 4, 6, 9, 12, 23, 54, 78, 231] */
- String[] strings = {"c", "a", "e", "b", "d"};
- bubbleSort.sort(strings);
- for (int i = 0; i < strings.length - 1; i++) {
- assert strings[i].compareTo(strings[i + 1]) <= 0;
+ String[] strings = {"c", "a", "e", "b", "d"};
+ bubbleSort.sort(strings);
+ for (int i = 0; i < strings.length - 1; i++) {
+ assert strings[i].compareTo(strings[i + 1]) <= 0;
+ }
+ print(bubbleSort.sort(strings)); /* output: [a, b, c, d, e] */
}
- print(bubbleSort.sort(strings)); /* output: [a, b, c, d, e] */
- }
}
diff --git a/Sorts/BubbleSortRecursion.java b/Sorts/BubbleSortRecursion.java
index ce51b1bfe29c..6af7778f199a 100644
--- a/Sorts/BubbleSortRecursion.java
+++ b/Sorts/BubbleSortRecursion.java
@@ -2,52 +2,54 @@
import java.util.Random;
-/** BubbleSort algorithm implements using recursion */
+/**
+ * BubbleSort algorithm implements using recursion
+ */
public class BubbleSortRecursion implements SortAlgorithm {
- public static void main(String[] args) {
- Integer[] array = new Integer[10];
+ public static void main(String[] args) {
+ Integer[] array = new Integer[10];
- Random random = new Random();
- /* generate 10 random numbers from -50 to 49 */
- for (int i = 0; i < array.length; ++i) {
- array[i] = random.nextInt(100) - 50;
- }
+ Random random = new Random();
+ /* generate 10 random numbers from -50 to 49 */
+ for (int i = 0; i < array.length; ++i) {
+ array[i] = random.nextInt(100) - 50;
+ }
- BubbleSortRecursion bubbleSortRecursion = new BubbleSortRecursion();
- bubbleSortRecursion.sort(array);
+ BubbleSortRecursion bubbleSortRecursion = new BubbleSortRecursion();
+ bubbleSortRecursion.sort(array);
- /* check array is sorted or not */
- for (int i = 0; i < array.length - 1; ++i) {
- assert (array[i].compareTo(array[i + 1]) <= 0);
+ /* check array is sorted or not */
+ for (int i = 0; i < array.length - 1; ++i) {
+ assert (array[i].compareTo(array[i + 1]) <= 0);
+ }
}
- }
-
- /**
- * @param unsorted - an array should be sorted
- * @return sorted array
- */
- @Override
- public > T[] sort(T[] unsorted) {
- bubbleSort(unsorted, unsorted.length);
- return unsorted;
- }
- /**
- * BubbleSort algorithm implements using recursion
- *
- * @param unsorted array contains elements
- * @param len length of given array
- */
- private static > void bubbleSort(T[] unsorted, int len) {
- boolean swapped = false; /* flag to check if array is sorted or not */
- for (int i = 0; i < len - 1; ++i) {
- if (SortUtils.greater(unsorted[i], unsorted[i + 1])) {
- SortUtils.swap(unsorted, i, i + 1);
- swapped = true;
- }
+ /**
+ * @param unsorted - an array should be sorted
+ * @return sorted array
+ */
+ @Override
+ public > T[] sort(T[] unsorted) {
+ bubbleSort(unsorted, unsorted.length);
+ return unsorted;
}
- if (swapped) {
- bubbleSort(unsorted, len - 1);
+
+ /**
+ * BubbleSort algorithm implements using recursion
+ *
+ * @param unsorted array contains elements
+ * @param len length of given array
+ */
+ private static > void bubbleSort(T[] unsorted, int len) {
+ boolean swapped = false; /* flag to check if array is sorted or not */
+ for (int i = 0; i < len - 1; ++i) {
+ if (SortUtils.greater(unsorted[i], unsorted[i + 1])) {
+ SortUtils.swap(unsorted, i, i + 1);
+ swapped = true;
+ }
+ }
+ if (swapped) {
+ bubbleSort(unsorted, len - 1);
+ }
}
- }
}
diff --git a/Sorts/BucketSort.java b/Sorts/BucketSort.java
index 66795f7f3c89..55f2fd34aa08 100644
--- a/Sorts/BucketSort.java
+++ b/Sorts/BucketSort.java
@@ -5,108 +5,110 @@
import java.util.List;
import java.util.Random;
-/** Wikipedia: https://en.wikipedia.org/wiki/Bucket_sort */
+/**
+ * Wikipedia: https://en.wikipedia.org/wiki/Bucket_sort
+ */
public class BucketSort {
- public static void main(String[] args) {
- int[] arr = new int[10];
+ public static void main(String[] args) {
+ int[] arr = new int[10];
- /* generate 10 random numbers from -50 to 49 */
- Random random = new Random();
- for (int i = 0; i < arr.length; ++i) {
- arr[i] = random.nextInt(100) - 50;
- }
+ /* generate 10 random numbers from -50 to 49 */
+ Random random = new Random();
+ for (int i = 0; i < arr.length; ++i) {
+ arr[i] = random.nextInt(100) - 50;
+ }
- bucketSort(arr);
+ bucketSort(arr);
- /* check array is sorted or not */
- for (int i = 0, limit = arr.length - 1; i < limit; ++i) {
- assert arr[i] <= arr[i + 1];
+ /* check array is sorted or not */
+ for (int i = 0, limit = arr.length - 1; i < limit; ++i) {
+ assert arr[i] <= arr[i + 1];
+ }
}
- }
-
- /**
- * BucketSort algorithms implements
- *
- * @param arr the array contains elements
- */
- private static void bucketSort(int[] arr) {
- /* get max value of arr */
- int max = max(arr);
-
- /* get min value of arr */
- int min = min(arr);
-
- /* number of buckets */
- int numberOfBuckets = max - min + 1;
- List> buckets = new ArrayList<>(numberOfBuckets);
-
- /* init buckets */
- for (int i = 0; i < numberOfBuckets; ++i) {
- buckets.add(new ArrayList<>());
+ /**
+ * BucketSort algorithms implements
+ *
+ * @param arr the array contains elements
+ */
+ private static void bucketSort(int[] arr) {
+ /* get max value of arr */
+ int max = max(arr);
+
+ /* get min value of arr */
+ int min = min(arr);
+
+ /* number of buckets */
+ int numberOfBuckets = max - min + 1;
+
+ List> buckets = new ArrayList<>(numberOfBuckets);
+
+ /* init buckets */
+ for (int i = 0; i < numberOfBuckets; ++i) {
+ buckets.add(new ArrayList<>());
+ }
+
+ /* store elements to buckets */
+ for (int value : arr) {
+ int hash = hash(value, min, numberOfBuckets);
+ buckets.get(hash).add(value);
+ }
+
+ /* sort individual bucket */
+ for (List bucket : buckets) {
+ Collections.sort(bucket);
+ }
+
+ /* concatenate buckets to origin array */
+ int index = 0;
+ for (List bucket : buckets) {
+ for (int value : bucket) {
+ arr[index++] = value;
+ }
+ }
}
- /* store elements to buckets */
- for (int value : arr) {
- int hash = hash(value, min, numberOfBuckets);
- buckets.get(hash).add(value);
+ /**
+ * Get index of bucket which of our elements gets placed into it.
+ *
+ * @param elem the element of array to be sorted
+ * @param min min value of array
+ * @param numberOfBucket the number of bucket
+ * @return index of bucket
+ */
+ private static int hash(int elem, int min, int numberOfBucket) {
+ return (elem - min) / numberOfBucket;
}
- /* sort individual bucket */
- for (List bucket : buckets) {
- Collections.sort(bucket);
+ /**
+ * Calculate max value of array
+ *
+ * @param arr the array contains elements
+ * @return max value of given array
+ */
+ public static int max(int[] arr) {
+ int max = arr[0];
+ for (int value : arr) {
+ if (value > max) {
+ max = value;
+ }
+ }
+ return max;
}
- /* concatenate buckets to origin array */
- int index = 0;
- for (List bucket : buckets) {
- for (int value : bucket) {
- arr[index++] = value;
- }
- }
- }
-
- /**
- * Get index of bucket which of our elements gets placed into it.
- *
- * @param elem the element of array to be sorted
- * @param min min value of array
- * @param numberOfBucket the number of bucket
- * @return index of bucket
- */
- private static int hash(int elem, int min, int numberOfBucket) {
- return (elem - min) / numberOfBucket;
- }
-
- /**
- * Calculate max value of array
- *
- * @param arr the array contains elements
- * @return max value of given array
- */
- public static int max(int[] arr) {
- int max = arr[0];
- for (int value : arr) {
- if (value > max) {
- max = value;
- }
- }
- return max;
- }
-
- /**
- * Calculate min value of array
- *
- * @param arr the array contains elements
- * @return min value of given array
- */
- public static int min(int[] arr) {
- int min = arr[0];
- for (int value : arr) {
- if (value < min) {
- min = value;
- }
+ /**
+ * Calculate min value of array
+ *
+ * @param arr the array contains elements
+ * @return min value of given array
+ */
+ public static int min(int[] arr) {
+ int min = arr[0];
+ for (int value : arr) {
+ if (value < min) {
+ min = value;
+ }
+ }
+ return min;
}
- return min;
- }
}
diff --git a/Sorts/CocktailShakerSort.java b/Sorts/CocktailShakerSort.java
index 12f1e4f38e6b..4aa505b2a3dc 100644
--- a/Sorts/CocktailShakerSort.java
+++ b/Sorts/CocktailShakerSort.java
@@ -6,52 +6,52 @@
*/
class CocktailShakerSort implements SortAlgorithm {
- /**
- * This method implements the Generic Cocktail Shaker Sort
- *
- * @param array The array to be sorted Sorts the array in increasing order
- */
- @Override
- public > T[] sort(T[] array) {
+ /**
+ * This method implements the Generic Cocktail Shaker Sort
+ *
+ * @param array The array to be sorted Sorts the array in increasing order
+ */
+ @Override
+ public > T[] sort(T[] array) {
- int length = array.length;
- int left = 0;
- int right = length - 1;
- int swappedLeft, swappedRight;
- while (left < right) {
- // front
- swappedRight = 0;
- for (int i = left; i < right; i++) {
- if (SortUtils.less(array[i + 1], array[i])) {
- SortUtils.swap(array, i, i + 1);
- swappedRight = i;
+ int length = array.length;
+ int left = 0;
+ int right = length - 1;
+ int swappedLeft, swappedRight;
+ while (left < right) {
+ // front
+ swappedRight = 0;
+ for (int i = left; i < right; i++) {
+ if (SortUtils.less(array[i + 1], array[i])) {
+ SortUtils.swap(array, i, i + 1);
+ swappedRight = i;
+ }
+ }
+ // back
+ right = swappedRight;
+ swappedLeft = length - 1;
+ for (int j = right; j > left; j--) {
+ if (SortUtils.less(array[j], array[j - 1])) {
+ SortUtils.swap(array, j - 1, j);
+ swappedLeft = j;
+ }
+ }
+ left = swappedLeft;
}
- }
- // back
- right = swappedRight;
- swappedLeft = length - 1;
- for (int j = right; j > left; j--) {
- if (SortUtils.less(array[j], array[j - 1])) {
- SortUtils.swap(array, j - 1, j);
- swappedLeft = j;
- }
- }
- left = swappedLeft;
+ return array;
}
- return array;
- }
- // Driver Program
- public static void main(String[] args) {
- // Integer Input
- Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
- CocktailShakerSort shakerSort = new CocktailShakerSort();
+ // Driver Program
+ public static void main(String[] args) {
+ // Integer Input
+ Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
+ CocktailShakerSort shakerSort = new CocktailShakerSort();
- // Output => 1 4 6 9 12 23 54 78 231
- SortUtils.print(shakerSort.sort(integers));
+ // Output => 1 4 6 9 12 23 54 78 231
+ SortUtils.print(shakerSort.sort(integers));
- // String Input
- String[] strings = {"c", "a", "e", "b", "d"};
- SortUtils.print(shakerSort.sort(strings));
- }
+ // String Input
+ String[] strings = {"c", "a", "e", "b", "d"};
+ SortUtils.print(shakerSort.sort(strings));
+ }
}
diff --git a/Sorts/CombSort.java b/Sorts/CombSort.java
index 44afb3c288aa..c98ce8b9ffe6 100644
--- a/Sorts/CombSort.java
+++ b/Sorts/CombSort.java
@@ -17,55 +17,55 @@
*/
class CombSort implements SortAlgorithm {
- // To find gap between elements
- private int nextGap(int gap) {
- // Shrink gap by Shrink factor
- gap = (gap * 10) / 13;
- return (gap < 1) ? 1 : gap;
- }
+ // To find gap between elements
+ private int nextGap(int gap) {
+ // Shrink gap by Shrink factor
+ gap = (gap * 10) / 13;
+ return (gap < 1) ? 1 : gap;
+ }
- /**
- * Function to sort arr[] using Comb
- *
- * @param arr - an array should be sorted
- * @return sorted array
- */
- @Override
- public > T[] sort(T[] arr) {
- int size = arr.length;
+ /**
+ * Function to sort arr[] using Comb
+ *
+ * @param arr - an array should be sorted
+ * @return sorted array
+ */
+ @Override
+ public > T[] sort(T[] arr) {
+ int size = arr.length;
- // initialize gap
- int gap = size;
+ // initialize gap
+ int gap = size;
- // Initialize swapped as true to make sure that loop runs
- boolean swapped = true;
+ // Initialize swapped as true to make sure that loop runs
+ boolean swapped = true;
- // Keep running while gap is more than 1 and last iteration caused a swap
- while (gap != 1 || swapped) {
- // Find next gap
- gap = nextGap(gap);
+ // Keep running while gap is more than 1 and last iteration caused a swap
+ while (gap != 1 || swapped) {
+ // Find next gap
+ gap = nextGap(gap);
- // Initialize swapped as false so that we can check if swap happened or not
- swapped = false;
+ // Initialize swapped as false so that we can check if swap happened or not
+ swapped = false;
- // Compare all elements with current gap
- for (int i = 0; i < size - gap; i++) {
- if (less(arr[i + gap], arr[i])) {
- // Swap arr[i] and arr[i+gap]
- swapped = swap(arr, i, i + gap);
+ // Compare all elements with current gap
+ for (int i = 0; i < size - gap; i++) {
+ if (less(arr[i + gap], arr[i])) {
+ // Swap arr[i] and arr[i+gap]
+ swapped = swap(arr, i, i + gap);
+ }
+ }
}
- }
+ return arr;
}
- return arr;
- }
- // Driver method
- public static void main(String[] args) {
- CombSort ob = new CombSort();
- Integer[] arr = {8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0};
- ob.sort(arr);
+ // Driver method
+ public static void main(String[] args) {
+ CombSort ob = new CombSort();
+ Integer[] arr = {8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0};
+ ob.sort(arr);
- System.out.println("sorted array");
- print(arr);
- }
+ System.out.println("sorted array");
+ print(arr);
+ }
}
diff --git a/Sorts/CountingSort.java b/Sorts/CountingSort.java
index 37a6c4e3a7a5..40e984c09e3f 100644
--- a/Sorts/CountingSort.java
+++ b/Sorts/CountingSort.java
@@ -14,83 +14,83 @@
*/
class CountingSort implements SortAlgorithm {
- @Override
- public > T[] sort(T[] unsorted) {
- return sort(Arrays.asList(unsorted)).toArray(unsorted);
- }
-
- /**
- * This method implements the Generic Counting Sort
- *
- * @param list The list to be sorted
- * Sorts the list in increasing order The method uses list elements as keys in the
- * frequency map
- */
- @Override
- public > List sort(List list) {
-
- Map frequency = new TreeMap<>();
- // The final output array
- List sortedArray = new ArrayList<>(list.size());
-
- // Counting the frequency of @param array elements
- list.forEach(v -> frequency.put(v, frequency.getOrDefault(v, 0) + 1));
-
- // Filling the sortedArray
- for (Map.Entry element : frequency.entrySet()) {
- for (int j = 0; j < element.getValue(); j++) {
- sortedArray.add(element.getKey());
- }
+ @Override
+ public > T[] sort(T[] unsorted) {
+ return sort(Arrays.asList(unsorted)).toArray(unsorted);
}
- return sortedArray;
- }
-
- /**
- * Stream Counting Sort The same as method {@link CountingSort#sort(List)} } but this method uses
- * stream API
- *
- * @param list The list to be sorted
- */
- private static > List streamSort(List list) {
- return list.stream()
- .collect(toMap(k -> k, v -> 1, (v1, v2) -> v1 + v2, TreeMap::new))
- .entrySet()
- .stream()
- .flatMap(entry -> IntStream.rangeClosed(1, entry.getValue()).mapToObj(t -> entry.getKey()))
- .collect(toList());
- }
-
- // Driver Program
- public static void main(String[] args) {
- // Integer Input
- List unsortedInts =
- Stream.of(4, 23, 6, 78, 1, 54, 23, 1, 9, 231, 9, 12).collect(toList());
- CountingSort countingSort = new CountingSort();
-
- System.out.println("Before Sorting:");
- print(unsortedInts);
-
- // Output => 1 1 4 6 9 9 12 23 23 54 78 231
- System.out.println("After Sorting:");
- print(countingSort.sort(unsortedInts));
- System.out.println("After Sorting By Streams:");
- print(streamSort(unsortedInts));
-
- System.out.println("\n------------------------------\n");
-
- // String Input
- List unsortedStrings =
- Stream.of("c", "a", "e", "b", "d", "a", "f", "g", "c").collect(toList());
-
- System.out.println("Before Sorting:");
- print(unsortedStrings);
-
- // Output => a a b c c d e f g
- System.out.println("After Sorting:");
- print(countingSort.sort(unsortedStrings));
-
- System.out.println("After Sorting By Streams:");
- print(streamSort(unsortedStrings));
- }
+ /**
+ * This method implements the Generic Counting Sort
+ *
+ * @param list The list to be sorted
+ * Sorts the list in increasing order The method uses list elements as keys in the
+ * frequency map
+ */
+ @Override
+ public > List sort(List list) {
+
+ Map frequency = new TreeMap<>();
+ // The final output array
+ List sortedArray = new ArrayList<>(list.size());
+
+ // Counting the frequency of @param array elements
+ list.forEach(v -> frequency.put(v, frequency.getOrDefault(v, 0) + 1));
+
+ // Filling the sortedArray
+ for (Map.Entry element : frequency.entrySet()) {
+ for (int j = 0; j < element.getValue(); j++) {
+ sortedArray.add(element.getKey());
+ }
+ }
+
+ return sortedArray;
+ }
+
+ /**
+ * Stream Counting Sort The same as method {@link CountingSort#sort(List)} } but this method uses
+ * stream API
+ *
+ * @param list The list to be sorted
+ */
+ private static > List streamSort(List list) {
+ return list.stream()
+ .collect(toMap(k -> k, v -> 1, (v1, v2) -> v1 + v2, TreeMap::new))
+ .entrySet()
+ .stream()
+ .flatMap(entry -> IntStream.rangeClosed(1, entry.getValue()).mapToObj(t -> entry.getKey()))
+ .collect(toList());
+ }
+
+ // Driver Program
+ public static void main(String[] args) {
+ // Integer Input
+ List unsortedInts =
+ Stream.of(4, 23, 6, 78, 1, 54, 23, 1, 9, 231, 9, 12).collect(toList());
+ CountingSort countingSort = new CountingSort();
+
+ System.out.println("Before Sorting:");
+ print(unsortedInts);
+
+ // Output => 1 1 4 6 9 9 12 23 23 54 78 231
+ System.out.println("After Sorting:");
+ print(countingSort.sort(unsortedInts));
+ System.out.println("After Sorting By Streams:");
+ print(streamSort(unsortedInts));
+
+ System.out.println("\n------------------------------\n");
+
+ // String Input
+ List unsortedStrings =
+ Stream.of("c", "a", "e", "b", "d", "a", "f", "g", "c").collect(toList());
+
+ System.out.println("Before Sorting:");
+ print(unsortedStrings);
+
+ // Output => a a b c c d e f g
+ System.out.println("After Sorting:");
+ print(countingSort.sort(unsortedStrings));
+
+ System.out.println("After Sorting By Streams:");
+ print(streamSort(unsortedStrings));
+ }
}
diff --git a/Sorts/CycleSort.java b/Sorts/CycleSort.java
index 20543665ea14..e0dc3e8d6936 100644
--- a/Sorts/CycleSort.java
+++ b/Sorts/CycleSort.java
@@ -3,69 +3,71 @@
import static Sorts.SortUtils.less;
import static Sorts.SortUtils.print;
-/** @author Podshivalov Nikita (https://github.com/nikitap492) */
+/**
+ * @author Podshivalov Nikita (https://github.com/nikitap492)
+ */
class CycleSort implements SortAlgorithm {
- @Override
- public > T[] sort(T[] arr) {
- int n = arr.length;
+ @Override
+ public > T[] sort(T[] arr) {
+ int n = arr.length;
- // traverse array elements
- for (int j = 0; j <= n - 2; j++) {
- // initialize item as starting point
- T item = arr[j];
+ // traverse array elements
+ for (int j = 0; j <= n - 2; j++) {
+ // initialize item as starting point
+ T item = arr[j];
- // Find position where we put the item.
- int pos = j;
- for (int i = j + 1; i < n; i++) if (less(arr[i], item)) pos++;
+ // Find position where we put the item.
+ int pos = j;
+ for (int i = j + 1; i < n; i++) if (less(arr[i], item)) pos++;
- // If item is already in correct position
- if (pos == j) continue;
+ // If item is already in correct position
+ if (pos == j) continue;
- // ignore all duplicate elements
- while (item.compareTo(arr[pos]) == 0) pos += 1;
+ // ignore all duplicate elements
+ while (item.compareTo(arr[pos]) == 0) pos += 1;
- // put the item to it's right position
- if (pos != j) {
- item = replace(arr, pos, item);
- }
+ // put the item to it's right position
+ if (pos != j) {
+ item = replace(arr, pos, item);
+ }
- // Rotate rest of the cycle
- while (pos != j) {
- pos = j;
+ // Rotate rest of the cycle
+ while (pos != j) {
+ pos = j;
- // Find position where we put the element
- for (int i = j + 1; i < n; i++)
- if (less(arr[i], item)) {
- pos += 1;
- }
+ // Find position where we put the element
+ for (int i = j + 1; i < n; i++)
+ if (less(arr[i], item)) {
+ pos += 1;
+ }
- // ignore all duplicate elements
- while (item.compareTo(arr[pos]) == 0) pos += 1;
+ // ignore all duplicate elements
+ while (item.compareTo(arr[pos]) == 0) pos += 1;
- // put the item to it's right position
- if (item != arr[pos]) {
- item = replace(arr, pos, item);
+ // put the item to it's right position
+ if (item != arr[pos]) {
+ item = replace(arr, pos, item);
+ }
+ }
}
- }
- }
- return arr;
- }
+ return arr;
+ }
- private > T replace(T[] arr, int pos, T item) {
- T temp = item;
- item = arr[pos];
- arr[pos] = temp;
- return item;
- }
+ private > T replace(T[] arr, int pos, T item) {
+ T temp = item;
+ item = arr[pos];
+ arr[pos] = temp;
+ return item;
+ }
- public static void main(String[] args) {
- Integer arr[] = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12};
- CycleSort cycleSort = new CycleSort();
- cycleSort.sort(arr);
+ public static void main(String[] args) {
+ Integer arr[] = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12};
+ CycleSort cycleSort = new CycleSort();
+ cycleSort.sort(arr);
- System.out.println("After sort : ");
- print(arr);
- }
+ System.out.println("After sort : ");
+ print(arr);
+ }
}
diff --git a/Sorts/GnomeSort.java b/Sorts/GnomeSort.java
index 3bf7213b38eb..24d35290dea0 100644
--- a/Sorts/GnomeSort.java
+++ b/Sorts/GnomeSort.java
@@ -10,33 +10,33 @@
*/
public class GnomeSort implements SortAlgorithm {
- @Override
- public > T[] sort(T[] arr) {
- int i = 1;
- int j = 2;
- while (i < arr.length) {
- if (less(arr[i - 1], arr[i])) i = j++;
- else {
- swap(arr, i - 1, i);
- if (--i == 0) {
- i = j++;
+ @Override
+ public > T[] sort(T[] arr) {
+ int i = 1;
+ int j = 2;
+ while (i < arr.length) {
+ if (less(arr[i - 1], arr[i])) i = j++;
+ else {
+ swap(arr, i - 1, i);
+ if (--i == 0) {
+ i = j++;
+ }
+ }
}
- }
- }
- return null;
- }
+ return null;
+ }
- public static void main(String[] args) {
- Integer[] integers = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12};
- String[] strings = {"c", "a", "e", "b", "d", "dd", "da", "zz", "AA", "aa", "aB", "Hb", "Z"};
- GnomeSort gnomeSort = new GnomeSort();
+ public static void main(String[] args) {
+ Integer[] integers = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12};
+ String[] strings = {"c", "a", "e", "b", "d", "dd", "da", "zz", "AA", "aa", "aB", "Hb", "Z"};
+ GnomeSort gnomeSort = new GnomeSort();
- gnomeSort.sort(integers);
- gnomeSort.sort(strings);
+ gnomeSort.sort(integers);
+ gnomeSort.sort(strings);
- System.out.println("After sort : ");
- print(integers);
- print(strings);
- }
+ System.out.println("After sort : ");
+ print(integers);
+ print(strings);
+ }
}
diff --git a/Sorts/HeapSort.java b/Sorts/HeapSort.java
index 29f14bab658e..3afe94bf558c 100644
--- a/Sorts/HeapSort.java
+++ b/Sorts/HeapSort.java
@@ -13,109 +13,111 @@
*/
public class HeapSort implements SortAlgorithm {
- private static class Heap> {
- /** Array to store heap */
- private T[] heap;
+ private static class Heap> {
+ /**
+ * Array to store heap
+ */
+ private T[] heap;
- /**
- * Constructor
- *
- * @param heap array of unordered integers
- */
- public Heap(T[] heap) {
- this.heap = heap;
- }
+ /**
+ * Constructor
+ *
+ * @param heap array of unordered integers
+ */
+ public Heap(T[] heap) {
+ this.heap = heap;
+ }
- /**
- * Heapifies subtree from top as root to last as last child
- *
- * @param rootIndex index of root
- * @param lastChild index of last child
- */
- private void heapSubtree(int rootIndex, int lastChild) {
- int leftIndex = rootIndex * 2 + 1;
- int rightIndex = rootIndex * 2 + 2;
- T root = heap[rootIndex];
- if (rightIndex <= lastChild) { // if has right and left children
- T left = heap[leftIndex];
- T right = heap[rightIndex];
- if (less(left, right) && less(left, root)) {
- swap(heap, leftIndex, rootIndex);
- heapSubtree(leftIndex, lastChild);
- } else if (less(right, root)) {
- swap(heap, rightIndex, rootIndex);
- heapSubtree(rightIndex, lastChild);
+ /**
+ * Heapifies subtree from top as root to last as last child
+ *
+ * @param rootIndex index of root
+ * @param lastChild index of last child
+ */
+ private void heapSubtree(int rootIndex, int lastChild) {
+ int leftIndex = rootIndex * 2 + 1;
+ int rightIndex = rootIndex * 2 + 2;
+ T root = heap[rootIndex];
+ if (rightIndex <= lastChild) { // if has right and left children
+ T left = heap[leftIndex];
+ T right = heap[rightIndex];
+ if (less(left, right) && less(left, root)) {
+ swap(heap, leftIndex, rootIndex);
+ heapSubtree(leftIndex, lastChild);
+ } else if (less(right, root)) {
+ swap(heap, rightIndex, rootIndex);
+ heapSubtree(rightIndex, lastChild);
+ }
+ } else if (leftIndex <= lastChild) { // if no right child, but has left child
+ T left = heap[leftIndex];
+ if (less(left, root)) {
+ swap(heap, leftIndex, rootIndex);
+ heapSubtree(leftIndex, lastChild);
+ }
+ }
}
- } else if (leftIndex <= lastChild) { // if no right child, but has left child
- T left = heap[leftIndex];
- if (less(left, root)) {
- swap(heap, leftIndex, rootIndex);
- heapSubtree(leftIndex, lastChild);
+
+ /**
+ * Makes heap with root as root
+ *
+ * @param root index of root of heap
+ */
+ private void makeMinHeap(int root) {
+ int leftIndex = root * 2 + 1;
+ int rightIndex = root * 2 + 2;
+ boolean hasLeftChild = leftIndex < heap.length;
+ boolean hasRightChild = rightIndex < heap.length;
+ if (hasRightChild) { // if has left and right
+ makeMinHeap(leftIndex);
+ makeMinHeap(rightIndex);
+ heapSubtree(root, heap.length - 1);
+ } else if (hasLeftChild) {
+ heapSubtree(root, heap.length - 1);
+ }
}
- }
- }
- /**
- * Makes heap with root as root
- *
- * @param root index of root of heap
- */
- private void makeMinHeap(int root) {
- int leftIndex = root * 2 + 1;
- int rightIndex = root * 2 + 2;
- boolean hasLeftChild = leftIndex < heap.length;
- boolean hasRightChild = rightIndex < heap.length;
- if (hasRightChild) { // if has left and right
- makeMinHeap(leftIndex);
- makeMinHeap(rightIndex);
- heapSubtree(root, heap.length - 1);
- } else if (hasLeftChild) {
- heapSubtree(root, heap.length - 1);
- }
+ /**
+ * Gets the root of heap
+ *
+ * @return root of heap
+ */
+ private T getRoot(int size) {
+ swap(heap, 0, size);
+ heapSubtree(0, size - 1);
+ return heap[size]; // return old root
+ }
}
- /**
- * Gets the root of heap
- *
- * @return root of heap
- */
- private T getRoot(int size) {
- swap(heap, 0, size);
- heapSubtree(0, size - 1);
- return heap[size]; // return old root
+ @Override
+ public > T[] sort(T[] unsorted) {
+ return sort(Arrays.asList(unsorted)).toArray(unsorted);
}
- }
- @Override
- public > T[] sort(T[] unsorted) {
- return sort(Arrays.asList(unsorted)).toArray(unsorted);
- }
+ @Override
+ public > List sort(List unsorted) {
+ int size = unsorted.size();
- @Override
- public > List sort(List unsorted) {
- int size = unsorted.size();
+ @SuppressWarnings("unchecked")
+ Heap heap = new Heap<>(unsorted.toArray((T[]) new Comparable[unsorted.size()]));
- @SuppressWarnings("unchecked")
- Heap heap = new Heap<>(unsorted.toArray((T[]) new Comparable[unsorted.size()]));
+ heap.makeMinHeap(0); // make min heap using index 0 as root.
+ List sorted = new ArrayList<>(size);
+ while (size > 0) {
+ T min = heap.getRoot(--size);
+ sorted.add(min);
+ }
- heap.makeMinHeap(0); // make min heap using index 0 as root.
- List sorted = new ArrayList<>(size);
- while (size > 0) {
- T min = heap.getRoot(--size);
- sorted.add(min);
+ return sorted;
}
- return sorted;
- }
-
- /**
- * Main method
- *
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- Integer[] heap = {4, 23, 6, 78, 1, 54, 231, 9, 12};
- HeapSort heapSort = new HeapSort();
- print(heapSort.sort(heap));
- }
+ /**
+ * Main method
+ *
+ * @param args the command line arguments
+ */
+ public static void main(String[] args) {
+ Integer[] heap = {4, 23, 6, 78, 1, 54, 231, 9, 12};
+ HeapSort heapSort = new HeapSort();
+ print(heapSort.sort(heap));
+ }
}
diff --git a/Sorts/InsertionSort.java b/Sorts/InsertionSort.java
index d2dd1c93e409..e263193d8538 100644
--- a/Sorts/InsertionSort.java
+++ b/Sorts/InsertionSort.java
@@ -9,47 +9,47 @@
*/
class InsertionSort implements SortAlgorithm {
- /**
- * This method implements the Generic Insertion Sort Sorts the array in increasing order
- *
- * @param array The array to be sorted
- */
- @Override
- public > T[] sort(T[] array) {
- for (int j = 1; j < array.length; j++) {
-
- // Picking up the key(Card)
- T key = array[j];
- int i = j - 1;
-
- while (i >= 0 && less(key, array[i])) {
- array[i + 1] = array[i];
- i--;
- }
- // Placing the key (Card) at its correct position in the sorted subarray
- array[i + 1] = key;
+ /**
+ * This method implements the Generic Insertion Sort Sorts the array in increasing order
+ *
+ * @param array The array to be sorted
+ */
+ @Override
+ public > T[] sort(T[] array) {
+ for (int j = 1; j < array.length; j++) {
+
+ // Picking up the key(Card)
+ T key = array[j];
+ int i = j - 1;
+
+ while (i >= 0 && less(key, array[i])) {
+ array[i + 1] = array[i];
+ i--;
+ }
+ // Placing the key (Card) at its correct position in the sorted subarray
+ array[i + 1] = key;
+ }
+ return array;
}
- return array;
- }
- // Driver Program
- public static void main(String[] args) {
- // Integer Input
- Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
+ // Driver Program
+ public static void main(String[] args) {
+ // Integer Input
+ Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
- InsertionSort sort = new InsertionSort();
+ InsertionSort sort = new InsertionSort();
- sort.sort(integers);
+ sort.sort(integers);
- // Output => 1 4 6 9 12 23 54 78 231
- print(integers);
+ // Output => 1 4 6 9 12 23 54 78 231
+ print(integers);
- // String Input
- String[] strings = {"c", "a", "e", "b", "d"};
+ // String Input
+ String[] strings = {"c", "a", "e", "b", "d"};
- sort.sort(strings);
+ sort.sort(strings);
- // Output => a b c d e
- print(strings);
- }
+ // Output => a b c d e
+ print(strings);
+ }
}
diff --git a/Sorts/MergeSort.java b/Sorts/MergeSort.java
index dfd350afb283..fe06f75d44f3 100644
--- a/Sorts/MergeSort.java
+++ b/Sorts/MergeSort.java
@@ -11,82 +11,82 @@
*/
class MergeSort implements SortAlgorithm {
- /**
- * This method implements the Generic Merge Sort
- *
- * @param unsorted the array which should be sorted
- * @param Comparable class
- * @return sorted array
- */
- @Override
- public > T[] sort(T[] unsorted) {
- doSort(unsorted, 0, unsorted.length - 1);
- return unsorted;
- }
+ /**
+ * This method implements the Generic Merge Sort
+ *
+ * @param unsorted the array which should be sorted
+ * @param Comparable class
+ * @return sorted array
+ */
+ @Override
+ public > T[] sort(T[] unsorted) {
+ doSort(unsorted, 0, unsorted.length - 1);
+ return unsorted;
+ }
- /**
- * @param arr The array to be sorted
- * @param left The first index of the array
- * @param right The last index of the array Recursively sorts the array in increasing order
- */
- private static > void doSort(T[] arr, int left, int right) {
- if (left < right) {
- int mid = left + (right - left) / 2;
- doSort(arr, left, mid);
- doSort(arr, mid + 1, right);
- merge(arr, left, mid, right);
+ /**
+ * @param arr The array to be sorted
+ * @param left The first index of the array
+ * @param right The last index of the array Recursively sorts the array in increasing order
+ */
+ private static > void doSort(T[] arr, int left, int right) {
+ if (left < right) {
+ int mid = left + (right - left) / 2;
+ doSort(arr, left, mid);
+ doSort(arr, mid + 1, right);
+ merge(arr, left, mid, right);
+ }
}
- }
- /**
- * This method implements the merge step of the merge sort
- *
- * @param arr The array to be sorted
- * @param left The first index of the array
- * @param mid The middle index of the array
- * @param right The last index of the array merges two parts of an array in increasing order
- */
- private static > void merge(T[] arr, int left, int mid, int right) {
- int length = right - left + 1;
- T[] temp = (T[]) new Comparable[length];
- int i = left;
- int j = mid + 1;
- int k = 0;
+ /**
+ * This method implements the merge step of the merge sort
+ *
+ * @param arr The array to be sorted
+ * @param left The first index of the array
+ * @param mid The middle index of the array
+ * @param right The last index of the array merges two parts of an array in increasing order
+ */
+ private static > void merge(T[] arr, int left, int mid, int right) {
+ int length = right - left + 1;
+ T[] temp = (T[]) new Comparable[length];
+ int i = left;
+ int j = mid + 1;
+ int k = 0;
- while (i <= mid && j <= right) {
- if (arr[i].compareTo(arr[j]) <= 0) {
- temp[k++] = arr[i++];
- } else {
- temp[k++] = arr[j++];
- }
- }
+ while (i <= mid && j <= right) {
+ if (arr[i].compareTo(arr[j]) <= 0) {
+ temp[k++] = arr[i++];
+ } else {
+ temp[k++] = arr[j++];
+ }
+ }
- while (i <= mid) {
- temp[k++] = arr[i++];
- }
+ while (i <= mid) {
+ temp[k++] = arr[i++];
+ }
- while (j <= right) {
- temp[k++] = arr[j++];
- }
+ while (j <= right) {
+ temp[k++] = arr[j++];
+ }
- System.arraycopy(temp, 0, arr, left, length);
- }
+ System.arraycopy(temp, 0, arr, left, length);
+ }
- // Driver program
- public static void main(String[] args) {
+ // Driver program
+ public static void main(String[] args) {
- // Integer Input
- Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12};
- MergeSort mergeSort = new MergeSort();
- mergeSort.sort(arr);
+ // Integer Input
+ Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12};
+ MergeSort mergeSort = new MergeSort();
+ mergeSort.sort(arr);
- // Output => 1 4 6 9 12 23 54 78 231
- print(arr);
+ // Output => 1 4 6 9 12 23 54 78 231
+ print(arr);
- // String Inpu
- String[] stringArray = {"c", "a", "e", "b", "d"};
- mergeSort.sort(stringArray);
- // Output => a b c d e
- print(stringArray);
- }
+ // String Inpu
+ String[] stringArray = {"c", "a", "e", "b", "d"};
+ mergeSort.sort(stringArray);
+ // Output => a b c d e
+ print(stringArray);
+ }
}
diff --git a/Sorts/PancakeSort.java b/Sorts/PancakeSort.java
index f679b37226ad..c21180e9fbb3 100644
--- a/Sorts/PancakeSort.java
+++ b/Sorts/PancakeSort.java
@@ -10,32 +10,32 @@
*/
public class PancakeSort implements SortAlgorithm {
- @Override
- public > T[] sort(T[] array) {
- int size = array.length;
+ @Override
+ public > T[] sort(T[] array) {
+ int size = array.length;
- for (int i = 0; i < size; i++) {
- T max = array[0];
- int index = 0;
- for (int j = 0; j < size - i; j++) {
- if (less(max, array[j])) {
- max = array[j];
- index = j;
+ for (int i = 0; i < size; i++) {
+ T max = array[0];
+ int index = 0;
+ for (int j = 0; j < size - i; j++) {
+ if (less(max, array[j])) {
+ max = array[j];
+ index = j;
+ }
+ }
+ flip(array, index, array.length - 1 - i);
}
- }
- flip(array, index, array.length - 1 - i);
+ return array;
}
- return array;
- }
- public static void main(String[] args) {
+ public static void main(String[] args) {
- Integer[] arr = {
- 10, 9, 8, 7, 6, 15, 14, 7, 4, 3, 8, 6, 3, 1, 2, -2, -5, -8, -3, -1, 13, 12, 11, 5, 4, 3, 2, 1
- };
- PancakeSort pancakeSort = new PancakeSort();
- System.out.println("After sorting:");
- pancakeSort.sort(arr);
- print(arr);
- }
+ Integer[] arr = {
+ 10, 9, 8, 7, 6, 15, 14, 7, 4, 3, 8, 6, 3, 1, 2, -2, -5, -8, -3, -1, 13, 12, 11, 5, 4, 3, 2, 1
+ };
+ PancakeSort pancakeSort = new PancakeSort();
+ System.out.println("After sorting:");
+ pancakeSort.sort(arr);
+ print(arr);
+ }
}
diff --git a/Sorts/QuickSort.java b/Sorts/QuickSort.java
index b88b1dec5ce4..2d86029b6087 100644
--- a/Sorts/QuickSort.java
+++ b/Sorts/QuickSort.java
@@ -9,89 +9,89 @@
*/
class QuickSort implements SortAlgorithm {
- /**
- * This method implements the Generic Quick Sort
- *
- * @param array The array to be sorted Sorts the array in increasing order
- */
- @Override
- public > T[] sort(T[] array) {
- doSort(array, 0, array.length - 1);
- return array;
- }
+ /**
+ * This method implements the Generic Quick Sort
+ *
+ * @param array The array to be sorted Sorts the array in increasing order
+ */
+ @Override
+ public > T[] sort(T[] array) {
+ doSort(array, 0, array.length - 1);
+ return array;
+ }
- /**
- * The sorting process
- *
- * @param left The first index of an array
- * @param right The last index of an array
- * @param array The array to be sorted
- */
- private static > void doSort(T[] array, int left, int right) {
- if (left < right) {
- int pivot = randomPartition(array, left, right);
- doSort(array, left, pivot - 1);
- doSort(array, pivot, right);
+ /**
+ * The sorting process
+ *
+ * @param left The first index of an array
+ * @param right The last index of an array
+ * @param array The array to be sorted
+ */
+ private static > void doSort(T[] array, int left, int right) {
+ if (left < right) {
+ int pivot = randomPartition(array, left, right);
+ doSort(array, left, pivot - 1);
+ doSort(array, pivot, right);
+ }
}
- }
- /**
- * Ramdomize the array to avoid the basically ordered sequences
- *
- * @param array The array to be sorted
- * @param left The first index of an array
- * @param right The last index of an array
- * @return the partition index of the array
- */
- private static