Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 57e670c

Browse files
Merge branch 'master' into LakshmiSrikumar-patch-1
2 parents 87e162c + 649a145 commit 57e670c

File tree

7 files changed

+822
-65
lines changed

7 files changed

+822
-65
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@
340340
* [Sparse Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/range_queries/sparse_table.cpp)
341341

342342
## Search
343+
* [Longest Increasing Subsequence Using Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/search/Longest_Increasing_Subsequence_using_binary_search.cpp)
343344
* [Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/search/binary_search.cpp)
344345
* [Exponential Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/search/exponential_search.cpp)
345346
* [Fibonacci Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/search/fibonacci_search.cpp)
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
/**
2+
* @file
3+
* @brief Implementation of the Unbounded 0/1 Knapsack Problem
4+
*
5+
* @details
6+
* The Unbounded 0/1 Knapsack problem allows taking unlimited quantities of each item.
7+
* The goal is to maximize the total value without exceeding the given knapsack capacity.
8+
* Unlike the 0/1 knapsack, where each item can be taken only once, in this variation,
9+
* any item can be picked any number of times as long as the total weight stays within
10+
* the knapsack's capacity.
11+
*
12+
* Given a set of N items, each with a weight and a value, represented by the arrays
13+
* `wt` and `val` respectively, and a knapsack with a weight limit W, the task is to
14+
* fill the knapsack to maximize the total value.
15+
*
16+
* @note weight and value of items is greater than zero
17+
*
18+
* ### Algorithm
19+
* The approach uses dynamic programming to build a solution iteratively.
20+
* A 2D array is used for memoization to store intermediate results, allowing
21+
* the function to avoid redundant calculations.
22+
*
23+
* @author [Sanskruti Yeole](https://github.com/yeolesanskruti)
24+
* @see dynamic_programming/0_1_knapsack.cpp
25+
*/
26+
27+
#include <iostream> // Standard input-output stream
28+
#include <vector> // Standard library for using dynamic arrays (vectors)
29+
#include <cassert> // For using assert function to validate test cases
30+
#include <cstdint> // For fixed-width integer types like std::uint16_t
31+
32+
/**
33+
* @namespace dynamic_programming
34+
* @brief Namespace for dynamic programming algorithms
35+
*/
36+
namespace dynamic_programming {
37+
38+
/**
39+
* @namespace Knapsack
40+
* @brief Implementation of unbounded 0-1 knapsack problem
41+
*/
42+
namespace unbounded_knapsack {
43+
44+
/**
45+
* @brief Recursive function to calculate the maximum value obtainable using
46+
* an unbounded knapsack approach.
47+
*
48+
* @param i Current index in the value and weight vectors.
49+
* @param W Remaining capacity of the knapsack.
50+
* @param val Vector of values corresponding to the items.
51+
* @note "val" data type can be changed according to the size of the input.
52+
* @param wt Vector of weights corresponding to the items.
53+
* @note "wt" data type can be changed according to the size of the input.
54+
* @param dp 2D vector for memoization to avoid redundant calculations.
55+
* @return The maximum value that can be obtained for the given index and capacity.
56+
*/
57+
std::uint16_t KnapSackFilling(std::uint16_t i, std::uint16_t W,
58+
const std::vector<std::uint16_t>& val,
59+
const std::vector<std::uint16_t>& wt,
60+
std::vector<std::vector<int>>& dp) {
61+
if (i == 0) {
62+
if (wt[0] <= W) {
63+
return (W / wt[0]) * val[0]; // Take as many of the first item as possible
64+
} else {
65+
return 0; // Can't take the first item
66+
}
67+
}
68+
if (dp[i][W] != -1) return dp[i][W]; // Return result if available
69+
70+
int nottake = KnapSackFilling(i - 1, W, val, wt, dp); // Value without taking item i
71+
int take = 0;
72+
if (W >= wt[i]) {
73+
take = val[i] + KnapSackFilling(i, W - wt[i], val, wt, dp); // Value taking item i
74+
}
75+
return dp[i][W] = std::max(take, nottake); // Store and return the maximum value
76+
}
77+
78+
/**
79+
* @brief Wrapper function to initiate the unbounded knapsack calculation.
80+
*
81+
* @param N Number of items.
82+
* @param W Maximum weight capacity of the knapsack.
83+
* @param val Vector of values corresponding to the items.
84+
* @param wt Vector of weights corresponding to the items.
85+
* @return The maximum value that can be obtained for the given capacity.
86+
*/
87+
std::uint16_t unboundedKnapsack(std::uint16_t N, std::uint16_t W,
88+
const std::vector<std::uint16_t>& val,
89+
const std::vector<std::uint16_t>& wt) {
90+
if(N==0)return 0; // Expect 0 since no items
91+
std::vector<std::vector<int>> dp(N, std::vector<int>(W + 1, -1)); // Initialize memoization table
92+
return KnapSackFilling(N - 1, W, val, wt, dp); // Start the calculation
93+
}
94+
95+
} // unbounded_knapsack
96+
97+
} // dynamic_programming
98+
99+
/**
100+
* @brief self test implementation
101+
* @return void
102+
*/
103+
static void tests() {
104+
// Test Case 1
105+
std::uint16_t N1 = 4; // Number of items
106+
std::vector<std::uint16_t> wt1 = {1, 3, 4, 5}; // Weights of the items
107+
std::vector<std::uint16_t> val1 = {6, 1, 7, 7}; // Values of the items
108+
std::uint16_t W1 = 8; // Maximum capacity of the knapsack
109+
// Test the function and assert the expected output
110+
assert(unboundedKnapsack(N1, W1, val1, wt1) == 48);
111+
std::cout << "Maximum Knapsack value " << unboundedKnapsack(N1, W1, val1, wt1) << std::endl;
112+
113+
// Test Case 2
114+
std::uint16_t N2 = 3; // Number of items
115+
std::vector<std::uint16_t> wt2 = {10, 20, 30}; // Weights of the items
116+
std::vector<std::uint16_t> val2 = {60, 100, 120}; // Values of the items
117+
std::uint16_t W2 = 5; // Maximum capacity of the knapsack
118+
// Test the function and assert the expected output
119+
assert(unboundedKnapsack(N2, W2, val2, wt2) == 0);
120+
std::cout << "Maximum Knapsack value " << unboundedKnapsack(N2, W2, val2, wt2) << std::endl;
121+
122+
// Test Case 3
123+
std::uint16_t N3 = 3; // Number of items
124+
std::vector<std::uint16_t> wt3 = {2, 4, 6}; // Weights of the items
125+
std::vector<std::uint16_t> val3 = {5, 11, 13};// Values of the items
126+
std::uint16_t W3 = 27;// Maximum capacity of the knapsack
127+
// Test the function and assert the expected output
128+
assert(unboundedKnapsack(N3, W3, val3, wt3) == 27);
129+
std::cout << "Maximum Knapsack value " << unboundedKnapsack(N3, W3, val3, wt3) << std::endl;
130+
131+
// Test Case 4
132+
std::uint16_t N4 = 0; // Number of items
133+
std::vector<std::uint16_t> wt4 = {}; // Weights of the items
134+
std::vector<std::uint16_t> val4 = {}; // Values of the items
135+
std::uint16_t W4 = 10; // Maximum capacity of the knapsack
136+
assert(unboundedKnapsack(N4, W4, val4, wt4) == 0);
137+
std::cout << "Maximum Knapsack value for empty arrays: " << unboundedKnapsack(N4, W4, val4, wt4) << std::endl;
138+
139+
std::cout << "All test cases passed!" << std::endl;
140+
141+
}
142+
143+
/**
144+
* @brief main function
145+
* @return 0 on successful exit
146+
*/
147+
int main() {
148+
tests(); // Run self test implementation
149+
return 0;
150+
}
151+

greedy_algorithms/binary_addition.cpp

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
/**
2+
* @file binary_addition.cpp
3+
* @brief Adds two binary numbers and outputs resulting string
4+
*
5+
* @details The algorithm for adding two binary strings works by processing them
6+
* from right to left, similar to manual addition. It starts by determining the
7+
* longer string's length to ensure both strings are fully traversed. For each
8+
* pair of corresponding bits and any carry from the previous addition, it
9+
* calculates the sum. If the sum exceeds 1, a carry is generated for the next
10+
* bit. The results for each bit are collected in a result string, which is
11+
* reversed at the end to present the final binary sum correctly. Additionally,
12+
* the function validates the input to ensure that only valid binary strings
13+
* (containing only '0' and '1') are processed. If invalid input is detected,
14+
* it returns an empty string.
15+
* @author [Muhammad Junaid Khalid](https://github.com/mjk22071998)
16+
*/
17+
18+
#include <algorithm> /// for reverse function
19+
#include <cassert> /// for tests
20+
#include <iostream> /// for input and outputs
21+
#include <string> /// for string class
22+
23+
/**
24+
* @namespace
25+
* @brief Greedy Algorithms
26+
*/
27+
namespace greedy_algorithms {
28+
/**
29+
* @brief A class to perform binary addition of two binary strings.
30+
*/
31+
class BinaryAddition {
32+
public:
33+
/**
34+
* @brief Adds two binary strings and returns the result as a binary string.
35+
* @param a The first binary string.
36+
* @param b The second binary string.
37+
* @return The sum of the two binary strings as a binary string, or an empty
38+
* string if either input string contains non-binary characters.
39+
*/
40+
std::string addBinary(const std::string& a, const std::string& b) {
41+
if (!isValidBinaryString(a) || !isValidBinaryString(b)) {
42+
return ""; // Return empty string if input contains non-binary
43+
// characters
44+
}
45+
46+
std::string result;
47+
int carry = 0;
48+
int maxLength = std::max(a.size(), b.size());
49+
50+
// Traverse both strings from the end to the beginning
51+
for (int i = 0; i < maxLength; ++i) {
52+
// Get the current bits from both strings, if available
53+
int bitA = (i < a.size()) ? (a[a.size() - 1 - i] - '0') : 0;
54+
int bitB = (i < b.size()) ? (b[b.size() - 1 - i] - '0') : 0;
55+
56+
// Calculate the sum of bits and carry
57+
int sum = bitA + bitB + carry;
58+
carry = sum / 2; // Determine the carry for the next bit
59+
result.push_back((sum % 2) +
60+
'0'); // Append the sum's current bit to result
61+
}
62+
if (carry) {
63+
result.push_back('1');
64+
}
65+
std::reverse(result.begin(), result.end());
66+
return result;
67+
}
68+
69+
private:
70+
/**
71+
* @brief Validates whether a string contains only binary characters (0 or 1).
72+
* @param str The string to validate.
73+
* @return true if the string is binary, false otherwise.
74+
*/
75+
bool isValidBinaryString(const std::string& str) const {
76+
return std::all_of(str.begin(), str.end(),
77+
[](char c) { return c == '0' || c == '1'; });
78+
}
79+
};
80+
} // namespace greedy_algorithms
81+
82+
/**
83+
* @brief run self test implementation.
84+
* @returns void
85+
*/
86+
static void tests() {
87+
greedy_algorithms::BinaryAddition binaryAddition;
88+
89+
// Valid binary string tests
90+
assert(binaryAddition.addBinary("1010", "1101") == "10111");
91+
assert(binaryAddition.addBinary("1111", "1111") == "11110");
92+
assert(binaryAddition.addBinary("101", "11") == "1000");
93+
assert(binaryAddition.addBinary("0", "0") == "0");
94+
assert(binaryAddition.addBinary("1111", "1111") == "11110");
95+
assert(binaryAddition.addBinary("0", "10101") == "10101");
96+
assert(binaryAddition.addBinary("10101", "0") == "10101");
97+
assert(binaryAddition.addBinary("101010101010101010101010101010",
98+
"110110110110110110110110110110") ==
99+
"1100001100001100001100001100000");
100+
assert(binaryAddition.addBinary("1", "11111111") == "100000000");
101+
assert(binaryAddition.addBinary("10101010", "01010101") == "11111111");
102+
103+
// Invalid binary string tests (should return empty string)
104+
assert(binaryAddition.addBinary("10102", "1101") == "");
105+
assert(binaryAddition.addBinary("ABC", "1101") == "");
106+
assert(binaryAddition.addBinary("1010", "1102") == "");
107+
assert(binaryAddition.addBinary("111", "1x1") == "");
108+
assert(binaryAddition.addBinary("1x1", "111") == "");
109+
assert(binaryAddition.addBinary("1234", "1101") == "");
110+
}
111+
112+
/**
113+
* @brief main function
114+
* @returns 0 on successful exit
115+
*/
116+
int main() {
117+
tests(); /// To execute tests
118+
return 0;
119+
}

0 commit comments

Comments
 (0)