Format code with prettier (#3375)

This commit is contained in:
acbin
2022-10-03 17:23:00 +08:00
committed by GitHub
parent 32b9b11ed5
commit e96f567bfc
464 changed files with 11483 additions and 6189 deletions

View File

@ -5,7 +5,7 @@ package com.thealgorithms.dynamicprogramming;
* @author Akshay Dubey (https://github.com/itsAkshayDubey)
*/
public class BoundaryFill {
/**
* Get the color at the given co-odrinates of a 2D image
*
@ -13,12 +13,14 @@ 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) {
return image[x_co_ordinate][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];
}
/**
* Put the color at the given co-odrinates of a 2D image
*
@ -26,12 +28,15 @@ public class BoundaryFill {
* @param x_co_ordinate The x co-ordinate at which color is to be filled
* @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) {
image[x_co_ordinate][y_co_ordinate] = new_color;
}
public static void putPixel(
int[][] image,
int x_co_ordinate,
int y_co_ordinate,
int new_color
) {
image[x_co_ordinate][y_co_ordinate] = new_color;
}
/**
* Fill the 2D image with new color
*
@ -41,60 +46,110 @@ public class BoundaryFill {
* @param new_color The new color which to be filled in the image
* @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) {
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);
}
}
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
) {
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
);
}
}
/**
* This method will print the 2D image matrix
*
* @param image The image to be printed on the console
*/
public static void printImageArray(int[][] image) {
for(int i=0 ; i<image.length ; i++) {
for(int j=0 ; j<image[0].length ; j++) {
System.out.print(image[i][j]+" ");
}
System.out.println();
}
}
// Driver Program
public static void main(String[] args) {
//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}
};
boundaryFill(image,2,2,5,3);
/* Output ==>
public static void printImageArray(int[][] image) {
for (int i = 0; i < image.length; i++) {
for (int j = 0; j < image[0].length; j++) {
System.out.print(image[i][j] + " ");
}
System.out.println();
}
}
// Driver Program
public static void main(String[] args) {
//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 },
};
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
@ -103,9 +158,8 @@ public class BoundaryFill {
0 0 0 3 5 5 3
0 0 0 3 3 3 3
* */
//print 2D image matrix
printImageArray(image);
}
}
//print 2D image matrix
printImageArray(image);
}
}

View File

@ -29,14 +29,17 @@ public class BruteForceKnapsack {
// (1) nth item included
// (2) not included
else {
return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1));
return 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

@ -22,11 +22,10 @@ public class CatalanNumber {
* @return catalanArray[n] the nth Catalan number
*/
static long findNthCatalan(int n) {
// Array to store the results of subproblems i.e Catalan numbers from [1...n-1]
long catalanArray[] = new long[n + 1];
// Initialising C₀ = 1 and C₁ = 1
// Initialising C₀ = 1 and C₁ = 1
catalanArray[0] = 1;
catalanArray[1] = 1;
@ -48,7 +47,9 @@ 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

@ -7,17 +7,21 @@ 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));
"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));
"Minimum number of coins required for amount :" +
amount +
" is: " +
minimumCoins(coins, amount)
);
}
/**
@ -29,7 +33,6 @@ public class CoinChange {
* number of combinations of change
*/
public static int change(int[] coins, int amount) {
int[] combinations = new int[amount + 1];
combinations[0] = 1;
@ -64,7 +67,10 @@ 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

@ -14,6 +14,7 @@
package com.thealgorithms.dynamicprogramming;
public class CountFriendsPairing {
public static boolean countFriendsPairing(int n, int a[]) {
int dp[] = new int[n + 1];
// array of n+1 size is created

View File

@ -11,13 +11,12 @@ keep on counting the results that sum to X. This can be done using recursion. */
And it can be done using Dynamic Programming(DP).
Following is implementation of Dynamic Programming approach. */
// Code ---->
// Java program to find number of ways to get sum 'x' with 'n'
// dice where every dice has 'm' faces
// Java program to find number of ways to get sum 'x' with 'n'
// 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. */
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).
@ -50,7 +49,6 @@ class DP {
System.out.println(findWays(4, 3, 5));
}
}
/*
OUTPUT:
0
@ -60,4 +58,3 @@ OUTPUT:
6
*/
// Time Complexity: O(m * n * x) where m is number of faces, n is number of dice and x is given sum.

View File

@ -20,7 +20,8 @@ public class DyanamicProgrammingKnapsack {
if (i == 0 || w == 0) {
K[i][w] = 0;
} else if (wt[i - 1] <= w) {
K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);
K[i][w] =
max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);
} else {
K[i][w] = K[i - 1][w];
}
@ -32,8 +33,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,7 +77,13 @@ 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();
}
@ -85,7 +91,6 @@ public class EditDistance {
public static int editDistance(String s1, String s2) {
int[][] storage = new int[s1.length() + 1][s2.length() + 1];
return editDistance(s1, s2, storage);
}
public static int editDistance(String s1, String s2, int[][] storage) {
@ -93,22 +98,19 @@ public class EditDistance {
int n = s2.length();
if (storage[m][n] > 0) {
return storage[m][n];
}
if (m == 0) {
storage[m][n] = n;
return storage[m][n];
}
if (n == 0) {
storage[m][n] = m;
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);
return storage[m][n];
} else {
int op1 = editDistance(s1, s2.substring(1), storage);
int op2 = editDistance(s1.substring(1), s2, storage);

View File

@ -7,7 +7,6 @@ public class EggDropping {
// min trials with n eggs and m floors
private static int minTrials(int n, int m) {
int[][] eggFloor = new int[n + 1][m + 1];
int result, x;
@ -26,7 +25,9 @@ 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

@ -12,7 +12,6 @@ public class Fibonacci {
private static Map<Integer, Integer> map = new HashMap<>();
public static void main(String[] args) {
// Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...]
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
@ -52,7 +51,6 @@ public class Fibonacci {
* Outputs the nth fibonacci number
*/
public static int fibBotUp(int n) {
Map<Integer, Integer> fib = new HashMap<>();
for (int i = 0; i <= n; i++) {

View File

@ -26,7 +26,9 @@ 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) {
@ -44,7 +46,10 @@ 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);
}
@ -58,7 +63,11 @@ 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

@ -3,24 +3,22 @@
*/
/** Program description - To find the maximum subarray sum */
package com.thealgorithms.dynamicprogramming;
package com.thealgorithms.dynamicprogramming;
public class KadaneAlgorithm {
public static boolean max_Sum(int a[] , int predicted_answer)
{
int sum=a[0],running_sum=0;
for(int k:a)
{
running_sum=running_sum+k;
public static boolean max_Sum(int a[], int predicted_answer) {
int sum = a[0], running_sum = 0;
for (int k : a) {
running_sum = running_sum + k;
// running sum of all the indexs are stored
sum=Math.max(sum,running_sum);
sum = Math.max(sum, running_sum);
// the max is stored inorder to the get the maximum sum
if(running_sum<0)
running_sum=0;
if (running_sum < 0) running_sum = 0;
// if running sum is negative then it is initialized to zero
}
// for-each loop is used to iterate over the array and find the maximum subarray sum
return sum==predicted_answer;
return sum == predicted_answer;
// It returns true if sum and predicted answer matches
// The predicted answer is the answer itself. So it always return true
}
@ -31,4 +29,4 @@ public class KadaneAlgorithm {
* 1st approach Time Complexity : O(n)
* Auxiliary Space Complexity : O(1)
*/
}
}

View File

@ -5,7 +5,8 @@ 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();
}
@ -18,7 +19,11 @@ 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];
}
@ -30,8 +35,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

@ -40,8 +40,8 @@ public class KnapsackMemoization {
// Driver code
public static void main(String args[]) {
int[] wt = {1, 3, 4, 5};
int[] value = {1, 4, 5, 7};
int[] wt = { 1, 3, 4, 5 };
int[] value = { 1, 4, 5, 7 };
int W = 10;
t = new int[wt.length + 1][W + 1];
Arrays.stream(t).forEach(a -> Arrays.fill(a, -1));

View File

@ -35,9 +35,13 @@ public class LevenshteinDistance {
} else {
cost = 1;
}
distance_mat[i][j]
= minimum(distance_mat[i - 1][j], distance_mat[i - 1][j - 1], distance_mat[i][j - 1])
+ cost;
distance_mat[i][j] =
minimum(
distance_mat[i - 1][j],
distance_mat[i - 1][j - 1],
distance_mat[i][j - 1]
) +
cost;
}
}
return distance_mat[len_a - 1][len_b - 1];
@ -47,7 +51,9 @@ public class LevenshteinDistance {
String a = ""; // enter your string here
String b = ""; // enter your string here
System.out.print("Levenshtein distance between " + a + " and " + b + " is: ");
System.out.print(
"Levenshtein distance between " + a + " and " + b + " is: "
);
System.out.println(calculate_distance(a, b));
}
}

View File

@ -38,10 +38,8 @@ public class LongestAlternatingSubsequence {
/* Compute values in bottom up manner */
for (int i = 1; i < n; i++) {
/* Consider all elements as previous of arr[i]*/
for (int j = 0; j < i; j++) {
/* If arr[i] is greater, then check with las[j][1] */
if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) {
las[i][0] = las[j][1] + 1;
@ -63,8 +61,12 @@ 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

@ -3,7 +3,6 @@ package com.thealgorithms.dynamicprogramming;
class LongestCommonSubsequence {
public static String getLCS(String str1, String str2) {
// At least one string is null
if (str1 == null || str2 == null) {
return null;
@ -31,15 +30,21 @@ class LongestCommonSubsequence {
if (arr1[i - 1].equals(arr2[j - 1])) {
lcsMatrix[i][j] = lcsMatrix[i - 1][j - 1] + 1;
} else {
lcsMatrix[i][j]
= lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1] ? lcsMatrix[i - 1][j] : lcsMatrix[i][j - 1];
lcsMatrix[i][j] =
lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1]
? lcsMatrix[i - 1][j]
: lcsMatrix[i][j - 1];
}
}
}
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

@ -8,7 +8,6 @@ import java.util.Scanner;
public class LongestIncreasingSubsequence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
@ -48,7 +47,6 @@ public class LongestIncreasingSubsequence {
tail[0] = array[0];
for (int i = 1; i < N; i++) {
// new smallest value
if (array[i] < tail[0]) {
tail[0] = array[i];
@ -86,6 +84,7 @@ public class LongestIncreasingSubsequence {
}
return lis;
}
// O(logn)
private static int binarySearchBetween(int[] t, int end, int key) {

View File

@ -30,15 +30,18 @@ public class LongestPalindromicSubsequence {
if (original.length() == 0 || reverse.length() == 0) {
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
@ -46,8 +49,14 @@ public class LongestPalindromicSubsequence {
// 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

@ -24,7 +24,6 @@ public class LongestPalindromicSubstring {
int start = 0, end = 0;
for (int g = 0; g < input.length(); g++) {
for (int i = 0, j = g; j < input.length(); i++, j++) {
if (g == 0) {
arr[i][j] = true;
} else if (g == 1) {
@ -34,8 +33,9 @@ public class LongestPalindromicSubstring {
arr[i][j] = false;
}
} else {
if (input.charAt(i) == input.charAt(j) && arr[i + 1][j - 1]) {
if (
input.charAt(i) == input.charAt(j) && arr[i + 1][j - 1]
) {
arr[i][j] = true;
} else {
arr[i][j] = false;
@ -50,5 +50,4 @@ public class LongestPalindromicSubstring {
}
return input.substring(start, end + 1);
}
}

View File

@ -31,7 +31,10 @@ 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,7 +16,9 @@ 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;
@ -28,7 +30,12 @@ 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

@ -2,7 +2,7 @@ package com.thealgorithms.dynamicprogramming;
// Matrix-chain Multiplication
// Problem Statement
// we have given a chain A1,A2,...,Ani of n matrices, where for i = 1,2,...,n,
// we have given a chain A1,A2,...,Ani of n matrices, where for i = 1,2,...,n,
// matrix Ai has dimension pi1 ×pi
// , fully parenthesize the product A1A2 ···An in a way that
// minimizes the number of scalar multiplications.
@ -28,7 +28,10 @@ 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,8 +43,9 @@ public class MatrixChainRecursiveTopDownMemoisation {
// 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

@ -1,4 +1,5 @@
package com.thealgorithms.dynamicprogramming;
// Here is the top-down approach of
// dynamic programming
@ -12,7 +13,6 @@ public class MemoizationTechniqueKnapsack {
// Returns the value of maximum profit
static int knapSackRec(int W, int wt[], int val[], int n, int[][] dp) {
// Base condition
if (n == 0 || W == 0) {
return 0;
@ -22,21 +22,25 @@ public class MemoizationTechniqueKnapsack {
return dp[n][W];
}
if (wt[n - 1] > W) // Store the value of function call
// stack in table before return
{
if (
wt[n - 1] > W
) { // stack in table before return // Store the value of function call
return dp[n][W] = knapSackRec(W, wt, val, n - 1, dp);
} else // Return value of table after storing
{
return dp[n][W]
= max(
(val[n - 1] + knapSackRec(W - wt[n - 1], wt, val, n - 1, dp)),
knapSackRec(W, wt, val, n - 1, dp));
} else { // Return value of table after storing
return (
dp[n][W] =
max(
(
val[n - 1] +
knapSackRec(W - wt[n - 1], wt, val, n - 1, dp)
),
knapSackRec(W, wt, val, n - 1, dp)
)
);
}
}
static int knapSack(int W, int wt[], int val[], int N) {
// Declare the table dynamically
int dp[][] = new int[N + 1][W + 1];
@ -53,8 +57,8 @@ public class MemoizationTechniqueKnapsack {
// Driver Code
public static void main(String[] args) {
int val[] = {60, 100, 120};
int wt[] = {10, 20, 30};
int val[] = { 60, 100, 120 };
int wt[] = { 10, 20, 30 };
int W = 50;
int N = val.length;

View File

@ -28,33 +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

@ -1,4 +1,5 @@
package com.thealgorithms.dynamicprogramming;
// Partition a set into two subsets such that the difference of subset sums is minimum
/*
@ -81,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

@ -2,25 +2,23 @@
* Github : https://github.com/siddhant2002
*/
/** Program description - To find the New Man Shanks Prime. */
/** Wikipedia Link - https://en.wikipedia.org/wiki/Newman%E2%80%93Shanks%E2%80%93Williams_prime */
package com.thealgorithms.dynamicprogramming;
public class NewManShanksPrime {
public static boolean nthManShanksPrime(int n , int expected_answer)
{
int a[] = new int[n+1];
public static boolean nthManShanksPrime(int n, int expected_answer) {
int a[] = new int[n + 1];
// array of n+1 size is initialized
a[0] = a[1] = 1;
// The 0th and 1st index position values are fixed. They are initialized as 1
for(int i=2;i<=n;i++)
{
a[i]=2*a[i-1]+a[i-2];
for (int i = 2; i <= n; i++) {
a[i] = 2 * a[i - 1] + a[i - 2];
}
// The loop is continued till n
return a[n]==expected_answer;
return a[n] == expected_answer;
// returns true if calculated answer matches with expected answer
}
}
}

View File

@ -48,12 +48,14 @@ public class PalindromicPartitioning {
if (L == 2) {
isPalindrome[i][j] = (word.charAt(i) == word.charAt(j));
} else {
if ((word.charAt(i) == word.charAt(j)) && isPalindrome[i + 1][j - 1]) {
if (
(word.charAt(i) == word.charAt(j)) &&
isPalindrome[i + 1][j - 1]
) {
isPalindrome[i][j] = true;
} else {
isPalindrome[i][j] = false;
}
}
}
}
@ -65,7 +67,10 @@ public class PalindromicPartitioning {
} else {
minCuts[i] = Integer.MAX_VALUE;
for (j = 0; j < i; j++) {
if (isPalindrome[j + 1][i] == true && 1 + minCuts[j] < minCuts[i]) {
if (
isPalindrome[j + 1][i] == true &&
1 + minCuts[j] < minCuts[i]
) {
minCuts[i] = 1 + minCuts[j];
}
}
@ -85,7 +90,11 @@ 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

@ -52,7 +52,12 @@ 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;
}
@ -85,7 +90,13 @@ 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;
}
@ -123,7 +134,6 @@ public class RegexMatching {
// Method 4: Bottom-Up DP(Tabulation)
// Time Complexity=0(N*M) Space Complexity=0(N*M)
static boolean regexBU(String src, String pat) {
boolean strg[][] = new boolean[src.length() + 1][pat.length() + 1];
strg[src.length()][pat.length()] = true;
for (int row = src.length(); row >= 0; row--) {
@ -156,16 +166,16 @@ public class RegexMatching {
}
public static void main(String[] args) {
String src = "aa";
String pat = "*";
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()]));
System.out.println(
"Method 3: " +
regexRecursion(src, pat, 0, 0, new int[src.length()][pat.length()])
);
System.out.println("Method 4: " + regexBU(src, pat));
}
}
// Memoization vs Tabulation : https://www.geeksforgeeks.org/tabulation-vs-memoization/
// Question Link : https://practice.geeksforgeeks.org/problems/wildcard-pattern-matching/1

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

@ -34,8 +34,7 @@ class ShortestSuperSequence {
} else if (X.charAt(i - 1) == Y.charAt(j - 1)) {
L[i][j] = L[i - 1][j - 1] + 1;
} else {
L[i][j] = Math.max(L[i - 1][j],
L[i][j - 1]);
L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]);
}
}
}
@ -50,8 +49,10 @@ 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

@ -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,8 +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

@ -2,7 +2,6 @@
* 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.
@ -17,51 +16,46 @@ package com.thealgorithms.dynamicprogramming;
import java.util.*;
public class UniquePaths {
public static boolean uniquePaths(int m , int n , int ans) {
int []dp = new int[n];
Arrays.fill(dp,1);
for (int i=1; i<m; i++)
{
for (int j=1; j<n; j++)
{
dp[j] += dp[j-1];
public static boolean uniquePaths(int m, int n, int ans) {
int[] dp = new int[n];
Arrays.fill(dp, 1);
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[j] += dp[j - 1];
}
}
return dp[n-1]==ans;
return dp[n - 1] == ans;
// return true if predicted answer matches with expected answer
}
// The above method runs in O(n) time
public static boolean uniquePaths2(int m , int n , int ans) {
public static boolean uniquePaths2(int m, int n, int ans) {
int dp[][] = new int[m][n];
for (int i=0; i<m; i++)
{
for (int i = 0; i < m; i++) {
dp[i][0] = 1;
}
for (int j=0; j<n; j++)
{
for (int j = 0; j < n; j++) {
dp[0][j] = 1;
}
for (int i=1; i<m; i++)
{
for (int j=1; j<n; j++)
{
dp[i][j]=dp[i-1][j]+dp[i][j-1];
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m-1][n-1]==ans;
return dp[m - 1][n - 1] == ans;
// return true if predicted answer matches with expected answer
}
// The above mthod takes O(m*n) time
}
/**
* 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 :
* 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)
*/

View File

@ -68,7 +68,6 @@ public class WineProblem {
int end = strg[si][ei - 1] + arr[ei] * year;
strg[si][ei] = Math.max(start, end);
}
}
}
@ -76,13 +75,14 @@ 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]));
System.out.println(
"Method 2: " +
WPTD(arr, 0, arr.length - 1, new int[arr.length][arr.length])
);
System.out.println("Method 3: " + WPBU(arr));
}
}
// Memoization vs Tabulation : https://www.geeksforgeeks.org/tabulation-vs-memoization/
// Question Link : https://www.geeksforgeeks.org/maximum-profit-sale-wines/