Skip to content

added algorithms #3924

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 82 additions & 20 deletions docs/dsa/algorithms/DynamicProgramming.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<Tabs>
<TabItem value="Python" label="Python" default>
```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]
```
</TabItem>
<TabItem value="cpp" label="C++" >
```cpp
#include <iostream>
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;
}
```
</TabItem>
<TabItem value="Java" label="Java">
``` 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
}
}
```
</TabItem>

<TabItem value="JavaScript" label="JavaScript">
``` 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
```
</TabItem>

return fib(n)

# Test the function
print(fibonacci(5)) # Output: 5
print(fibonacci(10)) # Output: 55
```
</Tabs>

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.

Expand Down
157 changes: 155 additions & 2 deletions docs/dsa/algorithms/Greedy.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):
<Tabs>
<TabItem value="Python" label="Python" default>
```Python showLineNumbers
def knapsack_greedy(values, weights, capacity):
# Create a list of items with their values and weights
items = list(zip(values, weights))

Expand Down Expand Up @@ -93,7 +96,157 @@ capacity = 50

max_value = knapsack_greedy(values, weights, capacity)
print("Maximum value:", max_value)

```
</TabItem>
<TabItem value="cpp" label="C++" >
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
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<int>& values, vector<int>& weights, int capacity) {
vector<Item> 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<int> values = {60, 100, 120};
vector<int> weights = {10, 20, 30};
int capacity = 50;

int max_value = knapsack_greedy(values, weights, capacity);
cout << "Maximum value: " << max_value << endl;

return 0;
}

```
</TabItem>
<TabItem value="Java" label="Java">
``` 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<Item> items = new ArrayList<>();
for (int i = 0; i < values.length; i++) {
items.add(new Item(values[i], weights[i]));
}

Collections.sort(items, new Comparator<Item>() {
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);
}
}

```
</TabItem>

<TabItem value="JavaScript" label="JavaScript">
``` 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);


```
</TabItem>


</Tabs>

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.

Expand Down
Loading
Loading