From c376bdd1c498d2bd0a8f02b68401802255c22b5e Mon Sep 17 00:00:00 2001 From: Jayanth Date: Fri, 26 Jul 2024 22:45:34 +0530 Subject: [PATCH] added algorithms --- docs/dsa/algorithms/DynamicProgramming.md | 102 +++++++++--- docs/dsa/algorithms/Greedy.md | 157 +++++++++++++++++- docs/dsa/algorithms/backtracking.md | 126 +++++++++++++- docs/dsa/algorithms/patternsearchalgorithm.md | 124 +++++++++++++- 4 files changed, 480 insertions(+), 29 deletions(-) diff --git a/docs/dsa/algorithms/DynamicProgramming.md b/docs/dsa/algorithms/DynamicProgramming.md index 9c47936a5..f397c7131 100644 --- a/docs/dsa/algorithms/DynamicProgramming.md +++ b/docs/dsa/algorithms/DynamicProgramming.md @@ -59,32 +59,94 @@ Dynamic programming can be applied to a wide range of problems, including optimi ## Example Here's an example of dynamic programming in Python: +#### Codes in Different Languages -```python + + +```Python showLineNumbers def fibonacci(n): - # Create a memoization table to store computed values - memo = {} + if n <= 1: + return n + + a, b = 0, 1 + for _ in range(2, n + 1): + a, b = b, a + b + return b - # Base cases - memo[0] = 0 - memo[1] = 1 - - # Recursive function to compute Fibonacci numbers - def fib(n): - # Check if value is already computed - if n in memo: - return memo[n] +# Test the function +print("Fibonacci of 5:", fibonacci(5)) # Output: 5 +print("Fibonacci of 10:", fibonacci(10)) # Output: 55 - # Compute and store the value - memo[n] = fib(n-1) + fib(n-2) - return memo[n] +``` + + + ```cpp + #include +using namespace std; +int fibonacci(int n) { + if (n <= 1) return n; + + int a = 0, b = 1, c; + for (int i = 2; i <= n; i++) { + c = a + b; + a = b; + b = c; + } + return b; +} + +int main() { + cout << "Fibonacci of 5: " << fibonacci(5) << endl; // Output: 5 + cout << "Fibonacci of 10: " << fibonacci(10) << endl; // Output: 55 + return 0; +} + ``` + + +``` jsx showLineNumbers +public class Fibonacci { + public static int fibonacci(int n) { + if (n <= 1) return n; + + int a = 0, b = 1, c; + for (int i = 2; i <= n; i++) { + c = a + b; + a = b; + b = c; + } + return b; + } + + public static void main(String[] args) { + System.out.println("Fibonacci of 5: " + fibonacci(5)); // Output: 5 + System.out.println("Fibonacci of 10: " + fibonacci(10)); // Output: 55 + } +} +``` + + + +``` jsx showLineNumbers +function fibonacci(n) { + if (n <= 1) return n; + + let a = 0, b = 1, c; + for (let i = 2; i <= n; i++) { + c = a + b; + a = b; + b = c; + } + return b; +} + +// Test the function +console.log("Fibonacci of 5:", fibonacci(5)); // Output: 5 +console.log("Fibonacci of 10:", fibonacci(10)); // Output: 55 +``` + - return fib(n) -# Test the function -print(fibonacci(5)) # Output: 5 -print(fibonacci(10)) # Output: 55 -``` + In this example, we use dynamic programming to efficiently compute Fibonacci numbers. We create a memoization table to store the computed values and avoid redundant computations. The recursive function `fib` checks if the value is already computed in the memoization table before computing it. This approach significantly improves the efficiency of the algorithm. diff --git a/docs/dsa/algorithms/Greedy.md b/docs/dsa/algorithms/Greedy.md index de59fa0b4..7baf470ff 100644 --- a/docs/dsa/algorithms/Greedy.md +++ b/docs/dsa/algorithms/Greedy.md @@ -63,9 +63,12 @@ These are just a few examples of greedy algorithms. Each algorithm has its own s Note that the Greedy algorithm may not always be the best choice. Analyze the problem and consider other approaches for the most efficient solution. **Here's an example code using the Greedy algorithm:** +#### Codes in Different Languages -```python - def knapsack_greedy(values, weights, capacity): + + +```Python showLineNumbers +def knapsack_greedy(values, weights, capacity): # Create a list of items with their values and weights items = list(zip(values, weights)) @@ -93,7 +96,157 @@ capacity = 50 max_value = knapsack_greedy(values, weights, capacity) print("Maximum value:", max_value) + +``` + + + ```cpp + #include +#include +#include +using namespace std; + +struct Item { + int value; + int weight; +}; + +bool compare(Item a, Item b) { + double r1 = (double)a.value / a.weight; + double r2 = (double)b.value / b.weight; + return r1 > r2; +} + +int knapsack_greedy(vector& values, vector& weights, int capacity) { + vector items(values.size()); + for (size_t i = 0; i < values.size(); ++i) { + items[i] = {values[i], weights[i]}; + } + + sort(items.begin(), items.end(), compare); + + int total_value = 0; + int total_weight = 0; + + for (auto& item : items) { + if (total_weight + item.weight <= capacity) { + total_value += item.value; + total_weight += item.weight; + } + } + + return total_value; +} + +int main() { + vector values = {60, 100, 120}; + vector weights = {10, 20, 30}; + int capacity = 50; + + int max_value = knapsack_greedy(values, weights, capacity); + cout << "Maximum value: " << max_value << endl; + + return 0; +} + + ``` + + +``` jsx showLineNumbers +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +class Item { + int value; + int weight; + + Item(int value, int weight) { + this.value = value; + this.weight = weight; + } +} + +public class KnapsackGreedy { + + public static int knapsackGreedy(int[] values, int[] weights, int capacity) { + List items = new ArrayList<>(); + for (int i = 0; i < values.length; i++) { + items.add(new Item(values[i], weights[i])); + } + + Collections.sort(items, new Comparator() { + public int compare(Item a, Item b) { + double r1 = (double) a.value / a.weight; + double r2 = (double) b.value / b.weight; + return Double.compare(r2, r1); + } + }); + + int totalValue = 0; + int totalWeight = 0; + + for (Item item : items) { + if (totalWeight + item.weight <= capacity) { + totalValue += item.value; + totalWeight += item.weight; + } + } + + return totalValue; + } + + public static void main(String[] args) { + int[] values = {60, 100, 120}; + int[] weights = {10, 20, 30}; + int capacity = 50; + + int maxValue = knapsackGreedy(values, weights, capacity); + System.out.println("Maximum value: " + maxValue); + } +} + ``` + + + +``` jsx showLineNumbers +function knapsackGreedy(values, weights, capacity) { + let items = []; + for (let i = 0; i < values.length; i++) { + items.push({ value: values[i], weight: weights[i] }); + } + + items.sort((a, b) => (b.value / b.weight) - (a.value / a.weight)); + + let totalValue = 0; + let totalWeight = 0; + + for (let item of items) { + if (totalWeight + item.weight <= capacity) { + totalValue += item.value; + totalWeight += item.weight; + } + } + + return totalValue; +} + +// Example usage +let values = [60, 100, 120]; +let weights = [10, 20, 30]; +let capacity = 50; + +let maxValue = knapsackGreedy(values, weights, capacity); +console.log("Maximum value:", maxValue); + + +``` + + + + This code demonstrates the Greedy algorithm in action by solving the Knapsack problem. The goal is to maximize the total value of items that can be put into a knapsack with a given capacity. The algorithm selects items based on their value-to-weight ratio, choosing the most valuable items first until the knapsack is full. diff --git a/docs/dsa/algorithms/backtracking.md b/docs/dsa/algorithms/backtracking.md index 5d40e2e36..9d15acdfd 100644 --- a/docs/dsa/algorithms/backtracking.md +++ b/docs/dsa/algorithms/backtracking.md @@ -83,10 +83,53 @@ For each letter: Add the letter to the current_perm. Make a recursive call to permute with the updated current_perm and the remaining letters (excluding the chosen letter). After the recursive call (exploring possibilities with the chosen letter), remove the letter from current_perm to backtrack and explore other options (avoiding duplicates). -Code: - -Python -```python +#### Codes in Different Languages + + + + + + ```cpp +#include +#include +using namespace std; +void permute(vector& letters, vector& current_perm, vector>& all_permutations) { + if (current_perm.size() == letters.size()) { + all_permutations.push_back(current_perm); + return; + } + + for (size_t i = 0; i < letters.size(); ++i) { + if (find(current_perm.begin(), current_perm.end(), letters[i]) == current_perm.end()) { + current_perm.push_back(letters[i]); + permute(letters, current_perm, all_permutations); + current_perm.pop_back(); + } + } +} + +int main() { + vector letters = {'a', 'b', 'c'}; + vector current_perm; + vector> all_permutations; + + permute(letters, current_perm, all_permutations); + + cout << "All permutations:\n"; + for (const auto& perm : all_permutations) { + for (char c : perm) { + cout << c << ' '; + } + cout << '\n'; + } + + return 0; +} + + ``` + + +```Python showLineNumbers def permute(letters, current_perm=[], all_permutations=[]): """Finds all permutations (arrangements) of the given letters.""" if len(current_perm) == len(letters): @@ -104,4 +147,77 @@ letters = ['a', 'b', 'c'] permute(letters, all_permutations=[]) print("All permutations:", all_permutations) -``` \ No newline at end of file + +``` + + +``` jsx showLineNumbers +import java.util.ArrayList; +import java.util.List; + +public class Permutations { + public static void permute(char[] letters, List currentPerm, List> allPermutations) { + if (currentPerm.size() == letters.length) { + allPermutations.add(new ArrayList<>(currentPerm)); + return; + } + + for (char letter : letters) { + if (!currentPerm.contains(letter)) { + currentPerm.add(letter); + permute(letters, currentPerm, allPermutations); + currentPerm.remove(currentPerm.size() - 1); + } + } + } + + public static void main(String[] args) { + char[] letters = {'a', 'b', 'c'}; + List currentPerm = new ArrayList<>(); + List> allPermutations = new ArrayList<>(); + + permute(letters, currentPerm, allPermutations); + + System.out.println("All permutations:"); + for (List perm : allPermutations) { + for (char c : perm) { + System.out.print(c + " "); + } + System.out.println(); + } + } +} + + +``` + + + +``` jsx showLineNumbers +function permute(letters, currentPerm = [], allPermutations = []) { + if (currentPerm.length === letters.length) { + allPermutations.push([...currentPerm]); // Append a copy + return; + } + + for (let i = 0; i < letters.length; i++) { + if (!currentPerm.includes(letters[i])) { + currentPerm.push(letters[i]); + permute(letters, currentPerm, allPermutations); + currentPerm.pop(); // Backtrack + } + } +} + +// Example usage +let letters = ['a', 'b', 'c']; +let allPermutations = []; +permute(letters, [], allPermutations); +console.log("All permutations:", allPermutations); + + +``` + + + + \ No newline at end of file diff --git a/docs/dsa/algorithms/patternsearchalgorithm.md b/docs/dsa/algorithms/patternsearchalgorithm.md index 4e62f9432..f371a50e5 100644 --- a/docs/dsa/algorithms/patternsearchalgorithm.md +++ b/docs/dsa/algorithms/patternsearchalgorithm.md @@ -27,8 +27,11 @@ This algorithm compares the pattern with each possible substring of the text, st Here's an example code problem to illustrate the usage of the Pattern Searching Algorithm: -```python -```python +#### Codes in Different Languages + + + +```Python showLineNumbers def pattern_search(text, pattern): result = [] text_length = len(text) @@ -49,7 +52,124 @@ text = "ABABDABACDABABCABAB" pattern = "ABABC" matches = pattern_search(text, pattern) print("Pattern found at positions:", matches) + +``` + + + ```cpp + #include +#include +#include +#include +using namespace std; +vector pattern_search(const string &text, const string &pattern) { + vector result; + int text_length = text.length(); + int pattern_length = pattern.length(); + + for (int i = 0; i <= text_length - pattern_length; i++) { + int j = 0; + while (j < pattern_length && text[i + j] == pattern[j]) { + j++; + } + if (j == pattern_length) { + result.push_back(i); + } + } + + return result; +} + +int main() { + string text = "ABABDABACDABABCABAB"; + string pattern = "ABABC"; + vector matches = pattern_search(text, pattern); + + cout << "Pattern found at positions: "; + for (int position : matches) { + cout << position << " "; + } + cout << endl; + + return 0; +} + + + ``` + + +``` jsx showLineNumbers +import java.util.ArrayList; +import java.util.List; + +public class PatternSearch { + public static List patternSearch(String text, String pattern) { + List result = new ArrayList<>(); + int textLength = text.length(); + int patternLength = pattern.length(); + + for (int i = 0; i <= textLength - patternLength; i++) { + int j = 0; + while (j < patternLength && text.charAt(i + j) == pattern.charAt(j)) { + j++; + } + if (j == patternLength) { + result.add(i); + } + } + + return result; + } + + public static void main(String[] args) { + String text = "ABABDABACDABABCABAB"; + String pattern = "ABABC"; + List matches = patternSearch(text, pattern); + + System.out.print("Pattern found at positions: "); + for (int position : matches) { + System.out.print(position + " "); + } + System.out.println(); + } +} + + ``` + + + +``` jsx showLineNumbers +function patternSearch(text, pattern) { + let result = []; + let textLength = text.length; + let patternLength = pattern.length; + + for (let i = 0; i <= textLength - patternLength; i++) { + let j = 0; + while (j < patternLength && text[i + j] === pattern[j]) { + j++; + } + if (j === patternLength) { + result.push(i); + } + } + + return result; +} + +let text = "ABABDABACDABABCABAB"; +let pattern = "ABABC"; +let matches = patternSearch(text, pattern); +console.log("Pattern found at positions:", matches); + + + +``` + + + + In this example, we have a text string "ABABDABACDABABCABAB" and we want to search for the pattern "ABABC" within it. The `patternSearch` function implements the Naive Pattern Searching Algorithm. It iterates through the text, comparing each substring of the same length as the pattern with the pattern itself. If a match is found, the starting position of the match is added to the result array. Finally, the function returns the array of positions where the pattern was found.