TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
subset_sum.cpp
Go to the documentation of this file.
1
12#include <cassert>
13#include <cstdint>
14#include <iostream>
15#include <vector>
16
21namespace backtracking {
27namespace subset_sum {
34uint64_t number_of_subsets(int32_t sum, const std::vector<int32_t> &in_arr) {
35 int32_t nelement = in_arr.size();
36 uint64_t count_of_subset = 0;
37
38 for (int32_t i = 0; i < (1 << (nelement)); i++) {
39 int32_t check = 0;
40 for (int32_t j = 0; j < nelement; j++) {
41 if (i & (1 << j)) {
42 check += (in_arr[j]);
43 }
44 }
45 if (check == sum) {
46 count_of_subset++;
47 }
48 }
49 return count_of_subset;
50}
51} // namespace subset_sum
52} // namespace backtracking
53
58static void test() {
59 // 1st test
60 std::cout << "1st test ";
61 std::vector<int32_t> array1 = {-7, -3, -2, 5, 8}; // input array
62 assert(backtracking::subset_sum::number_of_subsets(0, array1) ==
63 2); // first argument in subset_sum function is the required sum and
64 // second is the input array
65 std::cout << "passed" << std::endl;
66
67 // 2nd test
68 std::cout << "2nd test ";
69 std::vector<int32_t> array2 = {1, 2, 3, 3};
70 assert(backtracking::subset_sum::number_of_subsets(6, array2) ==
71 3); // here we are expecting 3 subsets which sum up to 6 i.e.
72 // {(1,2,3),(1,2,3),(3,3)}
73 std::cout << "passed" << std::endl;
74
75 // 3rd test
76 std::cout << "3rd test ";
77 std::vector<int32_t> array3 = {1, 1, 1, 1};
78 assert(backtracking::subset_sum::number_of_subsets(1, array3) ==
79 4); // here we are expecting 4 subsets which sum up to 1 i.e.
80 // {(1),(1),(1),(1)}
81 std::cout << "passed" << std::endl;
82
83 // 4th test
84 std::cout << "4th test ";
85 std::vector<int32_t> array4 = {3, 3, 3, 3};
86 assert(backtracking::subset_sum::number_of_subsets(6, array4) ==
87 6); // here we are expecting 6 subsets which sum up to 6 i.e.
88 // {(3,3),(3,3),(3,3),(3,3),(3,3),(3,3)}
89 std::cout << "passed" << std::endl;
90
91 // Test 5
92 std::cout << "5th test ";
93 std::vector<int32_t> array5 = {};
94 assert(backtracking::subset_sum::number_of_subsets(6, array5) ==
95 0); // here we are expecting 0 subsets which sum up to 6 i.e. we
96 // cannot select anything from an empty array
97 std::cout << "passed" << std::endl;
98}
99
104int main() {
105 test(); // run self-test implementations
106 return 0;
107}
for vector container
Functions for [Sub-set sum problem] (https://en.wikipedia.org/wiki/Subset_sum_problem) algorithm.
uint64_t number_of_subsets(int32_t sum, const std::vector< int32_t > &in_arr)
The main function implements count of subsets.
static void test()
Test implementations.
int main()
Main function.