Skip to content

Commit 97afa0e

Browse files
foo290github-actionsPanquesito7
authored
feat: add Sublist Search Algorithm (TheAlgorithms#1513)
* feat: add sublist search algorithm * updating DIRECTORY.md * clang-format and clang-tidy fixes for e59bc3b * Update search/sublist_search.cpp header docs Co-authored-by: David Leal <halfpacho@gmail.com> * Update search/sublist_search.cpp docs Co-authored-by: David Leal <halfpacho@gmail.com> * Update docs search/sublist_search.cpp Co-authored-by: David Leal <halfpacho@gmail.com> * Update docs search/sublist_search.cpp Co-authored-by: David Leal <halfpacho@gmail.com> * Update minor docs in search/sublist_search.cpp Co-authored-by: David Leal <halfpacho@gmail.com> * made test function non static Co-authored-by: David Leal <halfpacho@gmail.com> * test docs updated Co-authored-by: David Leal <halfpacho@gmail.com> * namespaces added for search algo, docs added for test cases * [feat/fix/docs]: Perform some necessary changes * clang-format and clang-tidy fixes for 5a02b33 * test cases docs added, merge fixed * clang-format and clang-tidy fixes for be0160b * one liner docs added * clang-format and clang-tidy fixes for 95b362f * some final docs fixes * clang-format and clang-tidy fixes for 798972e * Apply suggestions from code review * Apply suggestions from code review * Apply suggestions from code review * docs updated for one line docs * clang-format and clang-tidy fixes for aebae1d * added one liner docs * clang-format and clang-tidy fixes for f6913b7 * Update search/sublist_search.cpp Co-authored-by: David Leal <halfpacho@gmail.com> * Update search/sublist_search.cpp Co-authored-by: David Leal <halfpacho@gmail.com> * clang-format and clang-tidy fixes for 66d1b87 * Update search/sublist_search.cpp Co-authored-by: David Leal <halfpacho@gmail.com> * Update search/sublist_search.cpp Co-authored-by: David Leal <halfpacho@gmail.com> * Apply suggestions from code review * clang-format and clang-tidy fixes for dc5b0c6 * Apply suggestions from code review * clang-format and clang-tidy fixes for 6436932 * Apply suggestions from code review * clang-format and clang-tidy fixes for 35f39b5 * Update docs search/sublist_search.cpp Co-authored-by: David Leal <halfpacho@gmail.com> Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: David Leal <halfpacho@gmail.com>
1 parent 60ee52f commit 97afa0e

File tree

2 files changed

+371
-0
lines changed

2 files changed

+371
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,7 @@
268268
* [Linear Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/linear_search.cpp)
269269
* [Median Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/median_search.cpp)
270270
* [Saddleback Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/saddleback_search.cpp)
271+
* [Sublist Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/sublist_search.cpp)
271272
* [Ternary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/ternary_search.cpp)
272273
* [Text Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/text_search.cpp)
273274

search/sublist_search.cpp

Lines changed: 370 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,370 @@
1+
/**
2+
* @file
3+
* @brief Implementation of the [Sublist Search
4+
* Algorithm](https://www.geeksforgeeks.org/sublist-search-search-a-linked-list-in-another-list)
5+
* @details
6+
*
7+
* ### Algorithm
8+
*
9+
* * Sublist search is used to detect a presence of one list in another list.
10+
* * Suppose we have a single-node list (let's say the first list), and we
11+
* want to ensure that the list is present in another list (let's say the
12+
* second list), then we can perform the sublist search to find it.
13+
*
14+
* * For instance, the first list contains these elements: 23 -> 30 -> 41,
15+
* and the second list contains these elements: 10 -> 15 -> 23 -> 30 -> 41
16+
* -> 49. At a glance, we see that the first list presents in the second list.
17+
*
18+
* ### Working
19+
*
20+
* * The sublist search algorithm works by comparing the first element
21+
* of the first list with the first element of the second list.
22+
* * If the two values don't match, it goes to the next element of the
23+
* second list. It does this until the two values match.
24+
*
25+
* @author [Nitin Sharma](https://github.com/foo290)
26+
*/
27+
28+
#include <cassert> /// for assert
29+
#include <iostream> /// for IO operations
30+
#include <vector> /// for std::vector
31+
32+
/**
33+
* @namespace search
34+
* @brief Searching algorithms
35+
*/
36+
namespace search {
37+
/**
38+
* @namespace sublist_search
39+
* @brief Functions for the [Sublist
40+
* Search](https://www.geeksforgeeks.org/sublist-search-search-a-linked-list-in-another-list)
41+
* implementation
42+
*/
43+
namespace sublist_search {
44+
/**
45+
* @brief A Node structure representing a single link Node in a linked list
46+
*/
47+
struct Node {
48+
uint32_t data = 0; ///< the key/value of the node
49+
Node *next{}; ///< pointer to the next node
50+
};
51+
52+
/**
53+
* @brief A simple function to print the linked list
54+
* @param start The head of the linked list
55+
* @returns void
56+
*/
57+
void printLinkedList(Node *start) {
58+
while (start != nullptr) {
59+
std::cout << "->" << start->data;
60+
start = start->next;
61+
}
62+
std::cout << std::endl;
63+
}
64+
65+
/**
66+
* @brief Give a vector of data,
67+
* it adds each element of vector in the linked list and return the address of
68+
* head pointer.
69+
* @param data A vector of "int" containing the data that is supposed to be
70+
* stored in nodes of linked list.
71+
* @returns Node* A head pointer to the linked list.
72+
*/
73+
Node *makeLinkedList(const std::vector<uint64_t> &data) {
74+
/// This is used in test cases for rapidly creating linked list with 100+
75+
/// elements, instead of hard-coding 100 elements in test cases.
76+
Node *head = nullptr;
77+
Node *tail = nullptr;
78+
for (int i : data) {
79+
Node *node = new Node;
80+
node->data = i;
81+
node->next = nullptr;
82+
if (head == nullptr) {
83+
head = node;
84+
tail = node;
85+
} else {
86+
tail->next = node;
87+
tail = tail->next;
88+
}
89+
}
90+
return head;
91+
}
92+
93+
/**
94+
* @brief Main searching function
95+
* @param sublist A linked list which is supposed to be searched in mainList.
96+
* @param mainList A linked list in which sublist will be searched.
97+
* @returns true if the sublist is found
98+
* @returns false if the sublist is NOT found
99+
*/
100+
bool sublistSearch(Node *sublist, Node *mainList) {
101+
if (sublist == nullptr || mainList == nullptr) {
102+
return false;
103+
}
104+
105+
/// Initialize target pointer to the head node of sublist.
106+
Node *target_ptr = sublist;
107+
108+
while (mainList != nullptr) {
109+
/// Initialize main pointer to the current node of main list.
110+
Node *main_ptr = mainList;
111+
112+
while (target_ptr != nullptr) {
113+
if (main_ptr == nullptr) {
114+
return false;
115+
116+
} else if (main_ptr->data == target_ptr->data) {
117+
/// If the data of target node and main node is equal then move
118+
/// to the next node of both lists.
119+
target_ptr = target_ptr->next;
120+
main_ptr = main_ptr->next;
121+
122+
} else {
123+
break;
124+
}
125+
}
126+
127+
if (target_ptr == nullptr) {
128+
/// Is target pointer becomes null that means the target list is
129+
/// been traversed without returning false. Which means the sublist
130+
/// has been found and return ture.
131+
return true;
132+
}
133+
134+
/// set the target pointer again to stating point of target list.
135+
target_ptr = sublist;
136+
137+
/// set the main pointer to the next element of the main list and repeat
138+
/// the algo.
139+
mainList = mainList->next;
140+
}
141+
142+
/// If the main list is exhausted, means sublist does not found, return
143+
/// false
144+
return false;
145+
}
146+
147+
} // namespace sublist_search
148+
} // namespace search
149+
150+
/**
151+
* @brief class encapsulating the necessary test cases
152+
*/
153+
class TestCases {
154+
private:
155+
/**
156+
* @brief A function to print given message on console.
157+
* @tparam T Type of the given message.
158+
* @returns void
159+
* */
160+
template <typename T>
161+
void log(T msg) {
162+
// It's just to avoid writing cout and endl
163+
std::cout << "[TESTS] : ---> " << msg << std::endl;
164+
}
165+
166+
public:
167+
/**
168+
* @brief Executes test cases
169+
* @returns void
170+
* */
171+
void runTests() {
172+
log("Running Tests...");
173+
174+
testCase_1();
175+
testCase_2();
176+
testCase_3();
177+
178+
log("Test Cases over!");
179+
std::cout << std::endl;
180+
}
181+
182+
/**
183+
* @brief A test case contains edge case, Only contains one element.
184+
* @returns void
185+
* */
186+
void testCase_1() {
187+
const bool expectedOutput = true; ///< Expected output of this test
188+
189+
log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
190+
"~");
191+
log("This is test case 1 for sublist search Algorithm : ");
192+
log("Description:");
193+
log(" EDGE CASE : Only contains one element");
194+
195+
std::vector<uint64_t> sublistData = {
196+
6}; ///< Data to make linked list which will be the sublist
197+
std::vector<uint64_t> mainlistData = {
198+
2, 5, 6, 7,
199+
8}; ///< Data to make linked list which will be the main list
200+
201+
search::sublist_search::Node *sublistLL =
202+
search::sublist_search::makeLinkedList(
203+
sublistData); ///< Sublist to be searched
204+
search::sublist_search::Node *mainlistLL =
205+
search::sublist_search::makeLinkedList(
206+
mainlistData); ///< Main list in which sublist is to be
207+
///< searched
208+
209+
bool exists = search::sublist_search::sublistSearch(
210+
sublistLL, mainlistLL); ///< boolean, if sublist exist or not
211+
212+
log("Checking assert expression...");
213+
assert(exists == expectedOutput);
214+
log("Assertion check passed!");
215+
216+
log("[PASS] : TEST CASE 1 PASS!");
217+
log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
218+
"~");
219+
220+
delete (sublistLL);
221+
delete (mainlistLL);
222+
}
223+
224+
/**
225+
* @brief A test case which contains main list of 100 elements and sublist
226+
* of 20.
227+
* @returns void
228+
* */
229+
void testCase_2() {
230+
const bool expectedOutput = true; /// Expected output of this test
231+
232+
log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
233+
"~");
234+
log("This is test case 2 for sublist search Algorithm : ");
235+
log("Description:");
236+
log(" contains main list of 100 elements and sublist of 20");
237+
238+
std::vector<uint64_t> sublistData(
239+
20); ///< Data to make linked list which will be the sublist
240+
std::vector<uint64_t> mainlistData(
241+
100); ///< Main list in which sublist is to be searched
242+
243+
for (int i = 0; i < 100; i++) {
244+
/// Inserts 100 elements in main list
245+
mainlistData[i] = i + 1;
246+
}
247+
248+
int temp = 0;
249+
for (int i = 45; i < 65; i++) {
250+
/// Inserts 20 elements in sublist
251+
sublistData[temp] = i + 1;
252+
temp++;
253+
}
254+
255+
search::sublist_search::Node *sublistLL =
256+
search::sublist_search::makeLinkedList(
257+
sublistData); ///< Sublist to be searched
258+
search::sublist_search::Node *mainlistLL =
259+
search::sublist_search::makeLinkedList(
260+
mainlistData); ///< Main list in which sublist is to be
261+
///< searched
262+
263+
bool exists = search::sublist_search::sublistSearch(
264+
sublistLL, mainlistLL); ///< boolean, if sublist exist or not
265+
266+
log("Checking assert expression...");
267+
assert(exists == expectedOutput);
268+
log("Assertion check passed!");
269+
270+
log("[PASS] : TEST CASE 2 PASS!");
271+
log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
272+
"~");
273+
}
274+
275+
/**
276+
* @brief A test case which contains main list of 50 elements and sublist
277+
* of 20.
278+
* @returns void
279+
* */
280+
void testCase_3() {
281+
const bool expectedOutput = false; ///< Expected output of this test
282+
283+
log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
284+
"~");
285+
log("This is test case 3 for sublist search Algorithm : ");
286+
log("Description:");
287+
log(" contains main list of 50 elements and sublist of 20");
288+
289+
std::vector<uint64_t> sublistData(20); ///< Sublist to be searched
290+
std::vector<uint64_t> mainlistData(
291+
50); ///< Main list in which sublist is to be searched
292+
293+
for (int i = 0; i < 50; i++) {
294+
/// Inserts 100 elements in main list
295+
mainlistData.push_back(i + 1);
296+
}
297+
298+
for (int i = 45; i < 65; i++) {
299+
/// Inserts 20 elements in sublist
300+
sublistData.push_back(i + 1);
301+
}
302+
303+
search::sublist_search::Node *sublistLL =
304+
search::sublist_search::makeLinkedList(
305+
sublistData); ///< Sublist to be searched
306+
search::sublist_search::Node *mainlistLL =
307+
search::sublist_search::makeLinkedList(
308+
mainlistData); ///< Main list in which sublist is to be
309+
///< searched
310+
311+
bool exists = search::sublist_search::sublistSearch(
312+
sublistLL, mainlistLL); ///< boolean, if sublist exist or not
313+
314+
log("Checking assert expression...");
315+
assert(exists == expectedOutput);
316+
log("Assertion check passed!");
317+
318+
log("[PASS] : TEST CASE 3 PASS!");
319+
log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
320+
"~");
321+
}
322+
};
323+
324+
/**
325+
* @brief Self-test implementations
326+
* @returns void
327+
*/
328+
static void test() {
329+
TestCases tc;
330+
tc.runTests();
331+
}
332+
333+
/**
334+
* @brief Main function
335+
* @param argc commandline argument count (ignored)
336+
* @param argv commandline array of arguments (ignored)
337+
* @returns 0 on exit
338+
*/
339+
int main(int argc, char *argv[]) {
340+
test(); // run self-test implementations
341+
342+
std::vector<uint64_t> mainlistData = {
343+
2, 5, 6, 7, 8}; ///< Main list in which sublist is to be searched
344+
std::vector<uint64_t> sublistData = {6, 8}; ///< Sublist to be searched
345+
346+
search::sublist_search::Node *mainlistLL =
347+
search::sublist_search::makeLinkedList(mainlistData);
348+
search::sublist_search::Node *sublistLL =
349+
search::sublist_search::makeLinkedList(
350+
sublistData); ///< Main list in which sublist is to be
351+
///< searched
352+
353+
bool exists = search::sublist_search::sublistSearch(
354+
sublistLL,
355+
mainlistLL); ///< boolean to check if the sublist exists or not
356+
357+
std::cout << "Sublist: " << std::endl;
358+
search::sublist_search::printLinkedList(sublistLL);
359+
360+
std::cout << "Main list: " << std::endl;
361+
search::sublist_search::printLinkedList(mainlistLL);
362+
std::cout << std::endl;
363+
364+
if (exists) {
365+
std::cout << "[TRUE] - sublist found in main list\n";
366+
} else {
367+
std::cout << "[FALSE] - sublist NOT found in main list\n";
368+
}
369+
return 0;
370+
}

0 commit comments

Comments
 (0)