style: format code (#4212)

close #4204
This commit is contained in:
acbin
2023-06-09 18:52:05 +08:00
committed by GitHub
parent ad03086f54
commit 00282efd8b
521 changed files with 5233 additions and 7309 deletions

View File

@ -11,16 +11,16 @@ Test Case:
here target is 10
int n=10;
startAlgo();
System.out.println(bpR(0,n));
System.out.println(endAlgo()+"ms");
int[] strg=new int [n+1];
startAlgo();
System.out.println(bpRS(0,n,strg));
System.out.println(endAlgo()+"ms");
startAlgo();
System.out.println(bpIS(0,n,strg));
System.out.println(endAlgo()+"ms");
startAlgo();
System.out.println(bpR(0,n));
System.out.println(endAlgo()+"ms");
int[] strg=new int [n+1];
startAlgo();
System.out.println(bpRS(0,n,strg));
System.out.println(endAlgo()+"ms");
startAlgo();
System.out.println(bpIS(0,n,strg));
System.out.println(endAlgo()+"ms");

View File

@ -13,11 +13,7 @@ public class BoundaryFill {
* @param x_co_ordinate The x co-ordinate of which color is to be obtained
* @param y_co_ordinate The y co-ordinate of which color is to be obtained
*/
public static int getPixel(
int[][] image,
int x_co_ordinate,
int y_co_ordinate
) {
public static int getPixel(int[][] image, int x_co_ordinate, int y_co_ordinate) {
return image[x_co_ordinate][y_co_ordinate];
}
@ -29,11 +25,7 @@ public class BoundaryFill {
* @param y_co_ordinate The y co-ordinate at which color is to be filled
*/
public static void putPixel(
int[][] image,
int x_co_ordinate,
int y_co_ordinate,
int new_color
) {
int[][] image, int x_co_ordinate, int y_co_ordinate, int new_color) {
image[x_co_ordinate][y_co_ordinate] = new_color;
}
@ -47,75 +39,19 @@ public class BoundaryFill {
* @param boundary_color The old color which is to be replaced in the image
*/
public static void boundaryFill(
int[][] image,
int x_co_ordinate,
int y_co_ordinate,
int new_color,
int boundary_color
) {
if (
x_co_ordinate >= 0 &&
y_co_ordinate >= 0 &&
getPixel(image, x_co_ordinate, y_co_ordinate) != new_color &&
getPixel(image, x_co_ordinate, y_co_ordinate) != boundary_color
) {
int[][] image, int x_co_ordinate, int y_co_ordinate, int new_color, int boundary_color) {
if (x_co_ordinate >= 0 && y_co_ordinate >= 0
&& getPixel(image, x_co_ordinate, y_co_ordinate) != new_color
&& getPixel(image, x_co_ordinate, y_co_ordinate) != boundary_color) {
putPixel(image, x_co_ordinate, y_co_ordinate, new_color);
boundaryFill(
image,
x_co_ordinate + 1,
y_co_ordinate,
new_color,
boundary_color
);
boundaryFill(
image,
x_co_ordinate - 1,
y_co_ordinate,
new_color,
boundary_color
);
boundaryFill(
image,
x_co_ordinate,
y_co_ordinate + 1,
new_color,
boundary_color
);
boundaryFill(
image,
x_co_ordinate,
y_co_ordinate - 1,
new_color,
boundary_color
);
boundaryFill(
image,
x_co_ordinate + 1,
y_co_ordinate - 1,
new_color,
boundary_color
);
boundaryFill(
image,
x_co_ordinate - 1,
y_co_ordinate + 1,
new_color,
boundary_color
);
boundaryFill(
image,
x_co_ordinate + 1,
y_co_ordinate + 1,
new_color,
boundary_color
);
boundaryFill(
image,
x_co_ordinate - 1,
y_co_ordinate - 1,
new_color,
boundary_color
);
boundaryFill(image, x_co_ordinate + 1, y_co_ordinate, new_color, boundary_color);
boundaryFill(image, x_co_ordinate - 1, y_co_ordinate, new_color, boundary_color);
boundaryFill(image, x_co_ordinate, y_co_ordinate + 1, new_color, boundary_color);
boundaryFill(image, x_co_ordinate, y_co_ordinate - 1, new_color, boundary_color);
boundaryFill(image, x_co_ordinate + 1, y_co_ordinate - 1, new_color, boundary_color);
boundaryFill(image, x_co_ordinate - 1, y_co_ordinate + 1, new_color, boundary_color);
boundaryFill(image, x_co_ordinate + 1, y_co_ordinate + 1, new_color, boundary_color);
boundaryFill(image, x_co_ordinate - 1, y_co_ordinate - 1, new_color, boundary_color);
}
}
@ -136,30 +72,30 @@ public class BoundaryFill {
// Driver Program
public static void main(String[] args) {
//Input 2D image matrix
// Input 2D image matrix
int[][] image = {
{ 0, 0, 0, 0, 0, 0, 0 },
{ 0, 3, 3, 3, 3, 0, 0 },
{ 0, 3, 0, 0, 3, 0, 0 },
{ 0, 3, 0, 0, 3, 3, 3 },
{ 0, 3, 3, 3, 0, 0, 3 },
{ 0, 0, 0, 3, 0, 0, 3 },
{ 0, 0, 0, 3, 3, 3, 3 },
{0, 0, 0, 0, 0, 0, 0},
{0, 3, 3, 3, 3, 0, 0},
{0, 3, 0, 0, 3, 0, 0},
{0, 3, 0, 0, 3, 3, 3},
{0, 3, 3, 3, 0, 0, 3},
{0, 0, 0, 3, 0, 0, 3},
{0, 0, 0, 3, 3, 3, 3},
};
boundaryFill(image, 2, 2, 5, 3);
/* Output ==>
* 0 0 0 0 0 0 0
0 3 3 3 3 0 0
0 3 5 5 3 0 0
0 3 5 5 3 3 3
0 3 3 3 5 5 3
0 0 0 3 5 5 3
* 0 0 0 0 0 0 0
0 3 3 3 3 0 0
0 3 5 5 3 0 0
0 3 5 5 3 3 3
0 3 3 3 5 5 3
0 0 0 3 5 5 3
0 0 0 3 3 3 3
* */
* */
//print 2D image matrix
// print 2D image matrix
printImageArray(image);
}
}

View File

@ -22,16 +22,15 @@ public class BruteForceKnapsack {
// (1) nth item included
// (2) not included
else {
return Math.max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1)
);
return Math.max(
val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1));
}
}
// Driver code
public static void main(String[] args) {
int[] val = new int[] { 60, 100, 120 };
int[] wt = new int[] { 10, 20, 30 };
int[] val = new int[] {60, 100, 120};
int[] wt = new int[] {10, 20, 30};
int W = 50;
int n = val.length;
System.out.println(knapSack(W, wt, val, n));

View File

@ -47,9 +47,7 @@ public class CatalanNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(
"Enter the number n to find nth Catalan number (n <= 50)"
);
System.out.println("Enter the number n to find nth Catalan number (n <= 50)");
int n = sc.nextInt();
System.out.println(n + "th Catalan number is " + findNthCatalan(n));

View File

@ -9,7 +9,7 @@ public class ClimbingStairs {
public static int numberOfWays(int n) {
if(n == 1 || n == 0){
if (n == 1 || n == 0) {
return n;
}
int prev = 1;
@ -17,14 +17,13 @@ public class ClimbingStairs {
int next;
for(int i = 2; i <= n; i++){
next = curr+prev;
for (int i = 2; i <= n; i++) {
next = curr + prev;
prev = curr;
curr = next;
}
return curr;
}
}

View File

@ -8,20 +8,12 @@ public class CoinChange {
// Driver Program
public static void main(String[] args) {
int amount = 12;
int[] coins = { 2, 4, 5 };
int[] coins = {2, 4, 5};
System.out.println(
"Number of combinations of getting change for " +
amount +
" is: " +
change(coins, amount)
);
System.out.println(
"Minimum number of coins required for amount :" +
amount +
" is: " +
minimumCoins(coins, amount)
);
System.out.println("Number of combinations of getting change for " + amount
+ " is: " + change(coins, amount));
System.out.println("Minimum number of coins required for amount :" + amount
+ " is: " + minimumCoins(coins, amount));
}
/**
@ -67,10 +59,7 @@ public class CoinChange {
for (int coin : coins) {
if (coin <= i) {
int sub_res = minimumCoins[i - coin];
if (
sub_res != Integer.MAX_VALUE &&
sub_res + 1 < minimumCoins[i]
) {
if (sub_res != Integer.MAX_VALUE && sub_res + 1 < minimumCoins[i]) {
minimumCoins[i] = sub_res + 1;
}
}

View File

@ -1,8 +1,10 @@
/** Author : Siddhant Swarup Mallick
/**
* Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/
/**
* In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal to number of times n appears in the sequence.
* In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal
* to number of times n appears in the sequence.
*/
/**

View File

@ -15,11 +15,12 @@ Following is implementation of Dynamic Programming approach. */
// dice where every dice has 'm' faces
class DP {
/* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m faces. */
/* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m
* faces. */
public static long findWays(int m, int n, int x) {
/* Create a table to store the results of subproblems.
One extra row and column are used for simplicity
(Number of dice is directly used as row index and sum is directly used as column index).
/* Create a table to store the results of subproblems.
One extra row and column are used for simplicity
(Number of dice is directly used as row index and sum is directly used as column index).
The entries in 0th row and 0th column are never used. */
long[][] table = new long[n + 1][x + 1];
@ -28,7 +29,7 @@ class DP {
table[1][j] = 1;
}
/* Fill rest of the entries in table using recursive relation
/* Fill rest of the entries in table using recursive relation
i: number of dice, j: sum */
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= x; j++) {

View File

@ -27,8 +27,8 @@ public class DyanamicProgrammingKnapsack {
// Driver code
public static void main(String[] args) {
int[] val = new int[] { 60, 100, 120 };
int[] wt = new int[] { 10, 20, 30 };
int[] val = new int[] {60, 100, 120};
int[] wt = new int[] {10, 20, 30};
int W = 50;
int n = val.length;
System.out.println(knapSack(W, wt, val, n));

View File

@ -77,13 +77,7 @@ public class EditDistance {
// ans stores the final Edit Distance between the two strings
int ans = minDistance(s1, s2);
System.out.println(
"The minimum Edit Distance between \"" +
s1 +
"\" and \"" +
s2 +
"\" is " +
ans
);
"The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans);
input.close();
}
@ -108,8 +102,7 @@ public class EditDistance {
return storage[m][n];
}
if (s1.charAt(0) == s2.charAt(0)) {
storage[m][n] =
editDistance(s1.substring(1), s2.substring(1), storage);
storage[m][n] = editDistance(s1.substring(1), s2.substring(1), storage);
} else {
int op1 = editDistance(s1, s2.substring(1), storage);
int op2 = editDistance(s1.substring(1), s2, storage);

View File

@ -25,9 +25,7 @@ public class EggDropping {
for (int j = 2; j <= m; j++) {
eggFloor[i][j] = Integer.MAX_VALUE;
for (x = 1; x <= j; x++) {
result =
1 +
Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]);
result = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]);
// choose min of all values for particular x
if (result < eggFloor[i][j]) {

View File

@ -91,21 +91,22 @@ public class Fibonacci {
res = next;
}
return res;
}
}
/**
* We have only defined the nth Fibonacci number in terms of the two before it. Now, we will look at Binet's formula to calculate the nth Fibonacci number in constant time.
* The Fibonacci terms maintain a ratio called golden ratio denoted by Φ, the Greek character pronounced phi'.
* First, let's look at how the golden ratio is calculated: Φ = ( 1 + √5 )/2 = 1.6180339887...
* Now, let's look at Binet's formula: Sn = Φⁿ–( Φ⁻ⁿ)/√5
* We first calculate the squareRootof5 and phi and store them in variables. Later, we apply Binet's formula to get the required term.
* Time Complexity will be O(1)
*/
* We have only defined the nth Fibonacci number in terms of the two before it. Now, we will
* look at Binet's formula to calculate the nth Fibonacci number in constant time. The Fibonacci
* terms maintain a ratio called golden ratio denoted by Φ, the Greek character pronounced
* phi'. First, let's look at how the golden ratio is calculated: Φ = ( 1 + √5 )/2
* = 1.6180339887... Now, let's look at Binet's formula: Sn = Φⁿ–( Φ⁻ⁿ)/√5 We first calculate
* the squareRootof5 and phi and store them in variables. Later, we apply Binet's formula to get
* the required term. Time Complexity will be O(1)
*/
public static int fibBinet(int n) {
double squareRootOf5 = Math.sqrt(5);
double phi = (1 + squareRootOf5)/2;
int nthTerm = (int) ((Math.pow(phi, n) - Math.pow(-phi, -n))/squareRootOf5);
double phi = (1 + squareRootOf5) / 2;
int nthTerm = (int) ((Math.pow(phi, n) - Math.pow(-phi, -n)) / squareRootOf5);
return nthTerm;
}
}

View File

@ -26,9 +26,7 @@ public class FordFulkerson {
capacity[3][4] = 15;
capacity[4][5] = 17;
System.out.println(
"Max capacity in networkFlow : " + networkFlow(0, 5)
);
System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5));
}
private static int networkFlow(int source, int sink) {
@ -46,10 +44,7 @@ public class FordFulkerson {
int here = q.peek();
q.poll();
for (int there = 0; there < V; ++there) {
if (
capacity[here][there] - flow[here][there] > 0 &&
parent.get(there) == -1
) {
if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) {
q.add(there);
parent.set(there, here);
}
@ -63,11 +58,7 @@ public class FordFulkerson {
String printer = "path : ";
StringBuilder sb = new StringBuilder();
for (int p = sink; p != source; p = parent.get(p)) {
amount =
Math.min(
capacity[parent.get(p)][p] - flow[parent.get(p)][p],
amount
);
amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount);
sb.append(p + "-");
}
sb.append(source);

View File

@ -1,4 +1,5 @@
/** Author : Siddhant Swarup Mallick
/**
* Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/

View File

@ -5,8 +5,7 @@ package com.thealgorithms.dynamicprogramming;
*/
public class Knapsack {
private static int knapSack(int W, int[] wt, int[] val, int n)
throws IllegalArgumentException {
private static int knapSack(int W, int[] wt, int[] val, int n) throws IllegalArgumentException {
if (wt == null || val == null) {
throw new IllegalArgumentException();
}
@ -19,11 +18,7 @@ public class Knapsack {
if (i == 0 || w == 0) {
rv[i][w] = 0;
} else if (wt[i - 1] <= w) {
rv[i][w] =
Math.max(
val[i - 1] + rv[i - 1][w - wt[i - 1]],
rv[i - 1][w]
);
rv[i][w] = Math.max(val[i - 1] + rv[i - 1][w - wt[i - 1]], rv[i - 1][w]);
} else {
rv[i][w] = rv[i - 1][w];
}
@ -35,8 +30,8 @@ public class Knapsack {
// Driver program to test above function
public static void main(String[] args) {
int[] val = new int[] { 50, 100, 130 };
int[] wt = new int[] { 10, 20, 40 };
int[] val = new int[] {50, 100, 130};
int[] wt = new int[] {10, 20, 40};
int W = 50;
System.out.println(knapSack(W, wt, val, val.length));
}

View File

@ -25,9 +25,8 @@ public class KnapsackMemoization {
}
// Returns the value of maximum profit using recursive approach
int solveKnapsackRecursive(int capacity, int[] weights,
int[] profits, int numOfItems,
int[][] dpTable) {
int solveKnapsackRecursive(
int capacity, int[] weights, int[] profits, int numOfItems, int[][] dpTable) {
// Base condition
if (numOfItems == 0 || capacity == 0) {
return 0;
@ -39,11 +38,15 @@ public class KnapsackMemoization {
if (weights[numOfItems - 1] > capacity) {
// Store the value of function call stack in table
dpTable[numOfItems][capacity] = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable);
dpTable[numOfItems][capacity]
= solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable);
return dpTable[numOfItems][capacity];
} else {
// Return value of table after storing
return dpTable[numOfItems][capacity] = Math.max((profits[numOfItems - 1] + solveKnapsackRecursive(capacity - weights[numOfItems - 1], weights, profits, numOfItems - 1, dpTable)),
return dpTable[numOfItems][capacity]
= Math.max((profits[numOfItems - 1]
+ solveKnapsackRecursive(capacity - weights[numOfItems - 1], weights,
profits, numOfItems - 1, dpTable)),
solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable));
}
}

View File

@ -32,12 +32,9 @@ public class LevenshteinDistance {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
distanceMat[i][j] = distanceMat[i - 1][j - 1];
} else {
distanceMat[i][j] =
1 + minimum(
distanceMat[i - 1][j],
distanceMat[i - 1][j - 1],
distanceMat[i][j - 1]
);
distanceMat[i][j] = 1
+ minimum(distanceMat[i - 1][j], distanceMat[i - 1][j - 1],
distanceMat[i][j - 1]);
}
}
}
@ -48,9 +45,7 @@ public class LevenshteinDistance {
String str1 = ""; // enter your string here
String str2 = ""; // enter your string here
System.out.print(
"Levenshtein distance between " + str1 + " and " + str2 + " is: "
);
System.out.print("Levenshtein distance between " + str1 + " and " + str2 + " is: ");
System.out.println(calculateLevenshteinDistance(str1, str2));
}
}

View File

@ -2,12 +2,13 @@ package com.thealgorithms.dynamicprogramming;
/*
* Problem Statement: -
* Problem Statement: -
* Find Longest Alternating Subsequence
* A sequence {x1, x2, .. xn} is alternating sequence if its elements satisfy one of the following relations :
* A sequence {x1, x2, .. xn} is alternating sequence if its elements satisfy one of the following
relations :
x1 < x2 > x3 < x4 > x5 < …. xn or
x1 < x2 > x3 < x4 > x5 < …. xn or
x1 > x2 < x3 > x4 < x5 > …. xn
*/
public class LongestAlternatingSubsequence {
@ -16,16 +17,16 @@ public class LongestAlternatingSubsequence {
static int AlternatingLength(int[] arr, int n) {
/*
las[i][0] = Length of the longest
alternating subsequence ending at
index i and last element is
greater than its previous element
las[i][0] = Length of the longest
alternating subsequence ending at
index i and last element is
greater than its previous element
las[i][1] = Length of the longest
alternating subsequence ending at
index i and last element is
smaller than its previous
element
las[i][1] = Length of the longest
alternating subsequence ending at
index i and last element is
smaller than its previous
element
*/
int[][] las = new int[n][2]; // las = LongestAlternatingSubsequence
@ -61,12 +62,9 @@ public class LongestAlternatingSubsequence {
}
public static void main(String[] args) {
int[] arr = { 10, 22, 9, 33, 49, 50, 31, 60 };
int[] arr = {10, 22, 9, 33, 49, 50, 31, 60};
int n = arr.length;
System.out.println(
"Length of Longest " +
"alternating subsequence is " +
AlternatingLength(arr, n)
);
System.out.println("Length of Longest "
+ "alternating subsequence is " + AlternatingLength(arr, n));
}
}

View File

@ -37,11 +37,7 @@ class LongestCommonSubsequence {
return lcsString(str1, str2, lcsMatrix);
}
public static String lcsString(
String str1,
String str2,
int[][] lcsMatrix
) {
public static String lcsString(String str1, String str2, int[][] lcsMatrix) {
StringBuilder lcs = new StringBuilder();
int i = str1.length(), j = str2.length();
while (i > 0 && j > 0) {

View File

@ -56,8 +56,8 @@ public class LongestIncreasingSubsequence {
} // array[i] will become end candidate of an existing subsequence or
// Throw away larger elements in all LIS, to make room for upcoming grater elements than
// array[i]
// (and also, array[i] would have already appeared in one of LIS, identify the location and
// replace it)
// (and also, array[i] would have already appeared in one of LIS, identify the location
// and replace it)
else {
tail[upperBound(tail, -1, length - 1, array[i])] = array[i];
}

View File

@ -31,32 +31,21 @@ public class LongestPalindromicSubsequence {
bestResult = "";
} else {
// if the last chars match, then remove it from both strings and recur
if (
original.charAt(original.length() - 1) ==
reverse.charAt(reverse.length() - 1)
) {
String bestSubResult = recursiveLPS(
original.substring(0, original.length() - 1),
reverse.substring(0, reverse.length() - 1)
);
if (original.charAt(original.length() - 1) == reverse.charAt(reverse.length() - 1)) {
String bestSubResult = recursiveLPS(original.substring(0, original.length() - 1),
reverse.substring(0, reverse.length() - 1));
bestResult =
reverse.charAt(reverse.length() - 1) + bestSubResult;
bestResult = reverse.charAt(reverse.length() - 1) + bestSubResult;
} else {
// otherwise (1) ignore the last character of reverse, and recur on original and updated
// reverse again
// (2) ignore the last character of original and recur on the updated original and reverse
// again
// then select the best result from these two subproblems.
// otherwise (1) ignore the last character of reverse, and recur on original and
// updated reverse again (2) ignore the last character of original and recur on the
// updated original and reverse again then select the best result from these two
// subproblems.
String bestSubResult1 = recursiveLPS(
original,
reverse.substring(0, reverse.length() - 1)
);
String bestSubResult2 = recursiveLPS(
original.substring(0, original.length() - 1),
reverse
);
String bestSubResult1
= recursiveLPS(original, reverse.substring(0, reverse.length() - 1));
String bestSubResult2
= recursiveLPS(original.substring(0, original.length() - 1), reverse);
if (bestSubResult1.length() > bestSubResult2.length()) {
bestResult = bestSubResult1;
} else {

View File

@ -31,10 +31,7 @@ public class LongestValidParentheses {
int index = i - res[i - 1] - 1;
if (index >= 0 && chars[index] == '(') {
// ()(())
res[i] =
res[i - 1] +
2 +
(index - 1 >= 0 ? res[index - 1] : 0);
res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0);
}
}
}

View File

@ -16,9 +16,7 @@ public class MatrixChainMultiplication {
public static void main(String[] args) {
int count = 1;
while (true) {
String[] mSize = input(
"input size of matrix A(" + count + ") ( ex. 10 20 ) : "
);
String[] mSize = input("input size of matrix A(" + count + ") ( ex. 10 20 ) : ");
int col = Integer.parseInt(mSize[0]);
if (col == 0) {
break;
@ -30,12 +28,7 @@ public class MatrixChainMultiplication {
count++;
}
for (Matrix m : mArray) {
System.out.format(
"A(%d) = %2d x %2d%n",
m.count(),
m.col(),
m.row()
);
System.out.format("A(%d) = %2d x %2d%n", m.count(), m.col(), m.row());
}
size = mArray.size();

View File

@ -28,10 +28,8 @@ public class MatrixChainRecursiveTopDownMemoisation {
return m[i][j];
} else {
for (int k = i; k < j; k++) {
int q =
Lookup_Chain(m, p, i, k) +
Lookup_Chain(m, p, k + 1, j) +
(p[i - 1] * p[k] * p[j]);
int q = Lookup_Chain(m, p, i, k) + Lookup_Chain(m, p, k + 1, j)
+ (p[i - 1] * p[k] * p[j]);
if (q < m[i][j]) {
m[i][j] = q;
}
@ -40,12 +38,10 @@ public class MatrixChainRecursiveTopDownMemoisation {
return m[i][j];
}
// in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5 respectively
// output should be Minimum number of multiplications is 38
// in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5
// respectively output should be Minimum number of multiplications is 38
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
System.out.println(
"Minimum number of multiplications is " + Memoized_Matrix_Chain(arr)
);
int[] arr = {1, 2, 3, 4, 5};
System.out.println("Minimum number of multiplications is " + Memoized_Matrix_Chain(arr));
}
}

View File

@ -28,22 +28,22 @@ For more information see https://www.geeksforgeeks.org/maximum-path-sum-matrix/
public class MinimumPathSum {
public void testRegular() {
int[][] grid = { { 1, 3, 1 }, { 1, 5, 1 }, { 4, 2, 1 } };
int[][] grid = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}};
System.out.println(minimumPathSum(grid));
}
public void testLessColumns() {
int[][] grid = { { 1, 2 }, { 5, 6 }, { 1, 1 } };
int[][] grid = {{1, 2}, {5, 6}, {1, 1}};
System.out.println(minimumPathSum(grid));
}
public void testLessRows() {
int[][] grid = { { 2, 3, 3 }, { 7, 2, 1 } };
int[][] grid = {{2, 3, 3}, {7, 2, 1}};
System.out.println(minimumPathSum(grid));
}
public void testOneRowOneColumn() {
int[][] grid = { { 2 } };
int[][] grid = {{2}};
System.out.println(minimumPathSum(grid));
}

View File

@ -82,8 +82,8 @@ public class MinimumSumPartition {
* Driver Code
*/
public static void main(String[] args) {
assert subSet(new int[] { 1, 6, 11, 5 }) == 1;
assert subSet(new int[] { 36, 7, 46, 40 }) == 23;
assert subSet(new int[] { 1, 2, 3, 9 }) == 3;
assert subSet(new int[] {1, 6, 11, 5}) == 1;
assert subSet(new int[] {36, 7, 46, 40}) == 23;
assert subSet(new int[] {1, 2, 3, 9}) == 3;
}
}

View File

@ -1,4 +1,5 @@
/** Author : Siddhant Swarup Mallick
/**
* Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/

View File

@ -22,9 +22,11 @@ public class OptimalJobScheduling {
* @param numberProcesses ,refers to the number of precedent processes(N)
* @param numberMachines ,refers to the number of different machines in our disposal(M)
* @param Run , N*M matrix refers to the cost of running each process to each machine
* @param Transfer ,M*M symmetric matrix refers to the transportation delay for each pair of machines
* @param Transfer ,M*M symmetric matrix refers to the transportation delay for each pair of
* machines
*/
public OptimalJobScheduling(int numberProcesses, int numberMachines, int[][] Run, int[][] Transfer) {
public OptimalJobScheduling(
int numberProcesses, int numberMachines, int[][] Run, int[][] Transfer) {
this.numberProcesses = numberProcesses;
this.numberMachines = numberMachines;
this.Run = Run;
@ -35,7 +37,7 @@ public class OptimalJobScheduling {
/**
* Function which computes the cost of process scheduling to a number of VMs.
*/
public void execute(){
public void execute() {
this.calculateCost();
this.showResults();
}
@ -43,11 +45,11 @@ public class OptimalJobScheduling {
/**
* Function which computes the cost of running each Process to each and every Machine
*/
private void calculateCost(){
private void calculateCost() {
for (int i=0; i < numberProcesses; i++){ //for each Process
for (int i = 0; i < numberProcesses; i++) { // for each Process
for (int j=0; j < numberMachines; j++) { //for each Machine
for (int j = 0; j < numberMachines; j++) { // for each Machine
Cost[i][j] = runningCost(i, j);
}
@ -55,10 +57,12 @@ public class OptimalJobScheduling {
}
/**
* Function which returns the minimum cost of running a certain Process to a certain Machine.In order for the Machine to execute the Process ,he requires the output
* of the previously executed Process, which may have been executed to the same Machine or some other.If the previous Process has been executed to another Machine,we
* have to transfer her result, which means extra cost for transferring the data from one Machine to another(if the previous Process has been executed to the same
* Machine, there is no transport cost).
* Function which returns the minimum cost of running a certain Process to a certain Machine.In
* order for the Machine to execute the Process ,he requires the output of the previously
* executed Process, which may have been executed to the same Machine or some other.If the
* previous Process has been executed to another Machine,we have to transfer her result, which
* means extra cost for transferring the data from one Machine to another(if the previous
* Process has been executed to the same Machine, there is no transport cost).
*
* @param process ,refers to the Process
* @param machine ,refers to the Machine
@ -66,32 +70,38 @@ public class OptimalJobScheduling {
*/
private int runningCost(int process, int machine) {
if (process==0) //refers to the first process,which does not require for a previous one to have been executed
if (process == 0) // refers to the first process,which does not require for a previous one
// to have been executed
return Run[process][machine];
else {
int[] runningCosts = new int[numberMachines]; //stores the costs of executing our Process depending on the Machine the previous one was executed
int[] runningCosts
= new int[numberMachines]; // stores the costs of executing our Process depending on
// the Machine the previous one was executed
for (int k=0; k < numberMachines; k++) //computes the cost of executing the previous process to each and every Machine
runningCosts[k] = Cost[process-1][k] + Transfer[k][machine] + Run[process][machine]; //transferring the result to our Machine and executing the Process to our Machine
for (int k = 0; k < numberMachines; k++) // computes the cost of executing the previous
// process to each and every Machine
runningCosts[k] = Cost[process - 1][k] + Transfer[k][machine]
+ Run[process][machine]; // transferring the result to our Machine and executing
// the Process to our Machine
return findMin(runningCosts); //returns the minimum running cost
return findMin(runningCosts); // returns the minimum running cost
}
}
/**
* Function used in order to return the minimum Cost.
* @param cost ,an Array of size M which refers to the costs of executing a Process to each Machine
* @param cost ,an Array of size M which refers to the costs of executing a Process to each
* Machine
* @return the minimum cost
*/
private int findMin(int[] cost) {
int min=0;
int min = 0;
for (int i=1;i<cost.length;i++){
for (int i = 1; i < cost.length; i++) {
if (cost[i]<cost[min])
min=i;
if (cost[i] < cost[min]) min = i;
}
return cost[min];
}
@ -99,11 +109,11 @@ public class OptimalJobScheduling {
/**
* Method used in order to present the overall costs.
*/
private void showResults(){
private void showResults() {
for (int i=0; i < numberProcesses; i++){
for (int i = 0; i < numberProcesses; i++) {
for (int j=0; j < numberMachines; j++) {
for (int j = 0; j < numberMachines; j++) {
System.out.print(Cost[i][j]);
System.out.print(" ");
}
@ -116,7 +126,7 @@ public class OptimalJobScheduling {
/**
* Getter for the running Cost of i process on j machine.
*/
public int getCost(int process,int machine) {
public int getCost(int process, int machine) {
return Cost[process][machine];
}
}

View File

@ -22,9 +22,9 @@ public class PalindromicPartitioning {
public static int minimalpartitions(String word) {
int len = word.length();
/* We Make two arrays to create a bottom-up solution.
minCuts[i] = Minimum number of cuts needed for palindrome partitioning of substring word[0..i]
isPalindrome[i][j] = true if substring str[i..j] is palindrome
Base Condition: C[i] is 0 if P[0][i]= true
minCuts[i] = Minimum number of cuts needed for palindrome partitioning of substring
word[0..i] isPalindrome[i][j] = true if substring str[i..j] is palindrome Base Condition:
C[i] is 0 if P[0][i]= true
*/
int[] minCuts = new int[len];
boolean[][] isPalindrome = new boolean[len][len];
@ -36,7 +36,8 @@ public class PalindromicPartitioning {
isPalindrome[i][i] = true;
}
/* L is substring length. Build the solution in bottom up manner by considering all substrings of length starting from 2 to n. */
/* L is substring length. Build the solution in bottom up manner by considering all
* substrings of length starting from 2 to n. */
for (L = 2; L <= len; L++) {
// For substring of length L, set different possible starting indexes
for (i = 0; i < len - L + 1; i++) {
@ -48,23 +49,20 @@ public class PalindromicPartitioning {
if (L == 2) {
isPalindrome[i][j] = (word.charAt(i) == word.charAt(j));
} else {
isPalindrome[i][j] = (word.charAt(i) == word.charAt(j)) &&
isPalindrome[i + 1][j - 1];
isPalindrome[i][j]
= (word.charAt(i) == word.charAt(j)) && isPalindrome[i + 1][j - 1];
}
}
}
//We find the minimum for each index
// We find the minimum for each index
for (i = 0; i < len; i++) {
if (isPalindrome[0][i]) {
minCuts[i] = 0;
} else {
minCuts[i] = Integer.MAX_VALUE;
for (j = 0; j < i; j++) {
if (
isPalindrome[j + 1][i] &&
1 + minCuts[j] < minCuts[i]
) {
if (isPalindrome[j + 1][i] && 1 + minCuts[j] < minCuts[i]) {
minCuts[i] = 1 + minCuts[j];
}
}
@ -84,11 +82,7 @@ public class PalindromicPartitioning {
// ans stores the final minimal cut count needed for partitioning
int ans = minimalpartitions(word);
System.out.println(
"The minimum cuts needed to partition \"" +
word +
"\" into palindromes is " +
ans
);
"The minimum cuts needed to partition \"" + word + "\" into palindromes is " + ans);
input.close();
}
}

View File

@ -27,14 +27,14 @@ public class PartitionProblem {
* @param nums the array contains integers.
* @return {@code true} if two subset exists, otherwise {@code false}.
*/
public static boolean partition(int[] nums)
{
public static boolean partition(int[] nums) {
// calculate the sum of all the elements in the array
int sum = Arrays.stream(nums).sum();
// it will return true if the sum is even and the array can be divided into two subarrays/subset with equal sum.
// and here i reuse the SubsetSum class from dynamic programming section to check if there is exists a
// subsetsum into nums[] array same as the given sum
return (sum & 1) == 0 && SubsetSum.subsetSum(nums, sum/2);
// it will return true if the sum is even and the array can be divided into two
// subarrays/subset with equal sum. and here i reuse the SubsetSum class from dynamic
// programming section to check if there is exists a subsetsum into nums[] array same as the
// given sum
return (sum & 1) == 0 && SubsetSum.subsetSum(nums, sum / 2);
}
}

View File

@ -52,12 +52,7 @@ public class RegexMatching {
// Method 2: Using Recursion and breaking string using virtual index
// Time Complexity=0(2^(N+M)) Space Complexity=Recursion Extra Space
static boolean regexRecursion(
String src,
String pat,
int svidx,
int pvidx
) {
static boolean regexRecursion(String src, String pat, int svidx, int pvidx) {
if (src.length() == svidx && pat.length() == pvidx) {
return true;
}
@ -90,13 +85,7 @@ public class RegexMatching {
// Method 3: Top-Down DP(Memoization)
// Time Complexity=0(N*M) Space Complexity=0(N*M)+Recursion Extra Space
static boolean regexRecursion(
String src,
String pat,
int svidx,
int pvidx,
int[][] strg
) {
static boolean regexRecursion(String src, String pat, int svidx, int pvidx, int[][] strg) {
if (src.length() == svidx && pat.length() == pvidx) {
return true;
}
@ -171,9 +160,7 @@ public class RegexMatching {
System.out.println("Method 1: " + regexRecursion(src, pat));
System.out.println("Method 2: " + regexRecursion(src, pat, 0, 0));
System.out.println(
"Method 3: " +
regexRecursion(src, pat, 0, 0, new int[src.length()][pat.length()])
);
"Method 3: " + regexRecursion(src, pat, 0, 0, new int[src.length()][pat.length()]));
System.out.println("Method 4: " + regexBU(src, pat));
}
}

View File

@ -25,7 +25,7 @@ public class RodCutting {
// main function to test
public static void main(String[] args) {
int[] arr = new int[] { 2, 5, 13, 19, 20 };
int[] arr = new int[] {2, 5, 13, 19, 20};
int result = cutRod(arr, arr.length);
System.out.println("Maximum Obtainable Value is " + result);
}

View File

@ -49,10 +49,7 @@ class ShortestSuperSequence {
String X = "AGGTAB";
String Y = "GXTXAYB";
System.out.println(
"Length of the shortest " +
"supersequence is " +
shortestSuperSequence(X, Y)
);
System.out.println("Length of the shortest "
+ "supersequence is " + shortestSuperSequence(X, Y));
}
}

View File

@ -2,68 +2,66 @@ package com.thealgorithms.dynamicprogramming;
/**
* Find the number of subsets present in the given array with a sum equal to target.
* Based on Solution discussed on StackOverflow(https://stackoverflow.com/questions/22891076/count-number-of-subsets-with-sum-equal-to-k)
* Based on Solution discussed on
* StackOverflow(https://stackoverflow.com/questions/22891076/count-number-of-subsets-with-sum-equal-to-k)
* @author Samrat Podder(https://github.com/samratpodder)
*/
public class SubsetCount {
/**
* Dynamic Programming Implementation.
* Method to find out the number of subsets present in the given array with a sum equal to target.
* Time Complexity is O(n*target) and Space Complexity is O(n*target)
* Method to find out the number of subsets present in the given array with a sum equal to
* target. Time Complexity is O(n*target) and Space Complexity is O(n*target)
* @param arr is the input array on which subsets are to searched
* @param target is the sum of each element of the subset taken together
*
*/
public int getCount(int[] arr, int target){
public int getCount(int[] arr, int target) {
/**
* Base Cases - If target becomes zero, we have reached the required sum for the subset
* If we reach the end of the array arr then, either if target==arr[end], then we add one to the final count
* Otherwise we add 0 to the final count
* If we reach the end of the array arr then, either if target==arr[end], then we add one to
* the final count Otherwise we add 0 to the final count
*/
int n = arr.length;
int[][] dp = new int[n][target+1];
int[][] dp = new int[n][target + 1];
for (int i = 0; i < n; i++) {
dp[i][0] = 1;
}
if(arr[0]<=target) dp[0][arr[0]] = 1;
for(int t=1;t<=target;t++){
if (arr[0] <= target) dp[0][arr[0]] = 1;
for (int t = 1; t <= target; t++) {
for (int idx = 1; idx < n; idx++) {
int notpick = dp[idx-1][t];
int pick =0;
if(arr[idx]<=t) pick+=dp[idx-1][target-t];
dp[idx][target] = pick+notpick;
int notpick = dp[idx - 1][t];
int pick = 0;
if (arr[idx] <= t) pick += dp[idx - 1][target - t];
dp[idx][target] = pick + notpick;
}
}
return dp[n-1][target];
return dp[n - 1][target];
}
/**
* This Method is a Space Optimized version of the getCount(int[], int) method and solves the same problem
* This approach is a bit better in terms of Space Used
* Time Complexity is O(n*target) and Space Complexity is O(target)
* This Method is a Space Optimized version of the getCount(int[], int) method and solves the
* same problem This approach is a bit better in terms of Space Used Time Complexity is
* O(n*target) and Space Complexity is O(target)
* @param arr is the input array on which subsets are to searched
* @param target is the sum of each element of the subset taken together
*/
public int getCountSO(int[] arr, int target){
public int getCountSO(int[] arr, int target) {
int n = arr.length;
int[] prev =new int[target+1];
prev[0] =1;
if(arr[0]<=target) prev[arr[0]] = 1;
for(int ind = 1; ind<n; ind++){
int[] cur =new int[target+1];
cur[0]=1;
for(int t= 1; t<=target; t++){
int[] prev = new int[target + 1];
prev[0] = 1;
if (arr[0] <= target) prev[arr[0]] = 1;
for (int ind = 1; ind < n; ind++) {
int[] cur = new int[target + 1];
cur[0] = 1;
for (int t = 1; t <= target; t++) {
int notTaken = prev[t];
int taken = 0;
if(arr[ind]<=t) taken = prev[t-arr[ind]];
cur[t]= notTaken + taken;
if (arr[ind] <= t) taken = prev[t - arr[ind]];
cur[t] = notTaken + taken;
}
prev = cur;
}
return prev[target];
}
}

View File

@ -6,7 +6,7 @@ public class SubsetSum {
* Driver Code
*/
public static void main(String[] args) {
int[] arr = new int[] { 50, 4, 10, 15, 34 };
int[] arr = new int[] {50, 4, 10, 15, 34};
assert subsetSum(arr, 64);
/* 4 + 10 + 15 + 34 = 64 */
assert subsetSum(arr, 99);

View File

@ -3,7 +3,7 @@ package com.thealgorithms.dynamicprogramming;
public class Sum_Of_Subset {
public static void main(String[] args) {
int[] arr = { 7, 3, 2, 5, 8 };
int[] arr = {7, 3, 2, 5, 8};
int Key = 14;
if (subsetSum(arr, arr.length - 1, Key)) {

View File

@ -1,12 +1,13 @@
/** Author : Siddhant Swarup Mallick
/**
* Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/
/**
* A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
* The robot can only move either down or right at any point in time.
* The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
* How many possible unique paths are there?
* The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram
* below). How many possible unique paths are there?
*/
/** Program description - To find the number of unique paths possible */
@ -51,11 +52,8 @@ public class UniquePaths {
/**
* OUTPUT :
* Input - m = 3, n = 7
* Output: it returns either true if expected answer matches with the predicted answer else it returns false
* 1st approach Time Complexity : O(n)
* Auxiliary Space Complexity : O(n)
* Input - m = 3, n = 7
* Output: it returns either true if expected answer matches with the predicted answer else it returns false
* 2nd approach Time Complexity : O(m*n)
* Auxiliary Space Complexity : O(m*n)
* Output: it returns either true if expected answer matches with the predicted answer else it
* returns false 1st approach Time Complexity : O(n) Auxiliary Space Complexity : O(n) Input - m =
* 3, n = 7 Output: it returns either true if expected answer matches with the predicted answer else
* it returns false 2nd approach Time Complexity : O(m*n) Auxiliary Space Complexity : O(m*n)
*/

View File

@ -73,12 +73,10 @@ public class WineProblem {
}
public static void main(String[] args) {
int[] arr = { 2, 3, 5, 1, 4 };
int[] arr = {2, 3, 5, 1, 4};
System.out.println("Method 1: " + WPRecursion(arr, 0, arr.length - 1));
System.out.println(
"Method 2: " +
WPTD(arr, 0, arr.length - 1, new int[arr.length][arr.length])
);
"Method 2: " + WPTD(arr, 0, arr.length - 1, new int[arr.length][arr.length]));
System.out.println("Method 3: " + WPBU(arr));
}
}