Advertisement
epsilon413

all

May 14th, 2024
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 37.16 KB | Source Code | 0 0
  1. --- .\make-one.py
  2. import os
  3. from typing import List, Tuple
  4. from dotenv import load_dotenv
  5.  
  6. load_dotenv()
  7.  
  8. delimiter = os.environ.get('DELIMITER')
  9.  
  10.  
  11. def get_files(path=".", excludes=['.exe', '.txt', '.env']) -> List[str]:
  12.  
  13. # Items in the current folder
  14. folder_items = os.listdir(path)
  15.  
  16. # Filter out the folders
  17. folders = list(
  18. filter(lambda x: '.' not in x, folder_items)
  19. )
  20. # Filter out the files
  21. files = list(
  22. map(
  23. lambda file_name: os.path.join(path, file_name),
  24. filter(lambda x: ('.' in x) and all(
  25. [exclude not in x for exclude in excludes]), folder_items)
  26. )
  27. )
  28.  
  29. # It means we're at the deepest level
  30. if len(folders) == 0:
  31. return files
  32.  
  33. # Iterate over all the folders to the files
  34. for folder in folders:
  35. files += get_files(path=os.path.join(path, folder))
  36.  
  37. # Return the files we got
  38. return files
  39.  
  40.  
  41. def dump_into_one(files: list[str], output: str = "out.txt"):
  42. """
  43. Dumps all the files into big text file,
  44. delimiter=''
  45. """
  46.  
  47. with open(output, encoding='utf-8', mode='w+') as outFile:
  48. # Read and write from every single file
  49. content = ""
  50.  
  51. content_string = "{0} {1}\n{2}\n{0}\n"
  52.  
  53. for file in files:
  54. with open(file, encoding='utf-8', mode='r') as inFile:
  55. content += content_string.format(delimiter,
  56. file, inFile.read())
  57.  
  58. # Write the read content
  59. outFile.write(content)
  60. return
  61.  
  62.  
  63. def extract_from_dump(out_file: str = "out.txt") -> List[Tuple[str, str]]:
  64.  
  65. # Output filenames with their content
  66. output: List[Tuple[str, str]] = []
  67.  
  68. # Read the file and split on the delimiter
  69. content = ""
  70.  
  71. with open(out_file, encoding='utf-8', mode='r+') as readFile:
  72. content = readFile.read().split(delimiter)
  73.  
  74. # Filters for the content
  75. content = list(
  76. filter(lambda x: x != '\n' and x != delimiter and x != '', content)
  77. )
  78.  
  79. # Iterate over the content
  80. for i, file_content in enumerate(content):
  81. filename = file_content.split('\n')[0].strip()
  82. content = file_content.replace(filename, '')
  83. # Record this
  84. output.append((filename, content))
  85.  
  86. return output
  87.  
  88.  
  89. if __name__ == '__main__':
  90.  
  91. def bundle_files():
  92. # To compress the files
  93. files = get_files()
  94.  
  95. for file in files:
  96. print(file)
  97.  
  98. dump_into_one(files)
  99.  
  100. def debundle_files():
  101. # To debundle the files
  102. files = extract_from_dump(out_file="out.txt")
  103. # Make the directories exist
  104. for (filename, file_content) in files:
  105. # Split the path of the file
  106. head, tail = os.path.split(filename)
  107.  
  108. try:
  109. os.mkdir(head)
  110. except FileExistsError:
  111. pass
  112.  
  113. # Write the file
  114. with open(filename, encoding='utf-8', mode='w+') as writeFile:
  115. writeFile.write(file_content)
  116. # end-with
  117. # end-for
  118.  
  119. bundle_files()
  120. # structure = extract_from_dump()
  121.  
  122. # for (filename, _) in structure:
  123. # print(filename)
  124.  
  125. # debundle_files()
  126.  
  127. ---
  128. --- .\graphs\bipartite.cpp
  129. #include <iostream>
  130. #include <vector>
  131. #include <queue>
  132. using namespace std;
  133.  
  134. class Solution
  135. {
  136. // colors a component
  137. private:
  138. bool check(int start, int V, vector<int> adj[], int color[])
  139. {
  140. queue<int> q;
  141. q.push(start);
  142. color[start] = 0;
  143. while (!q.empty())
  144. {
  145. int node = q.front();
  146. q.pop();
  147.  
  148. for (auto it : adj[node])
  149. {
  150. // if the adjacent node is yet not colored
  151. // you will give the opposite color of the node
  152. if (color[it] == -1)
  153. {
  154.  
  155. color[it] = !color[node];
  156. q.push(it);
  157. }
  158. // is the adjacent guy having the same color
  159. // someone did color it on some other path
  160. else if (color[it] == color[node])
  161. {
  162. return false;
  163. }
  164. }
  165. }
  166. return true;
  167. }
  168.  
  169. public:
  170. bool isBipartite(int V, vector<int> adj[])
  171. {
  172. int *color = new int[V];
  173. for (int i = 0; i < V; i++)
  174. color[i] = -1;
  175.  
  176. for (int i = 0; i < V; i++)
  177. {
  178. // if not coloured
  179. if (color[i] == -1)
  180. {
  181. if (check(i, V, adj, color) == false)
  182. {
  183. delete[] color;
  184. return false;
  185. }
  186. }
  187. }
  188.  
  189. delete[] color;
  190. return true;
  191. }
  192. };
  193.  
  194. void addEdge(vector<int> adj[], int u, int v)
  195. {
  196. adj[u].push_back(v);
  197. adj[v].push_back(u);
  198. }
  199.  
  200. int main()
  201. {
  202.  
  203. // V = 4, E = 4
  204. vector<int> adj[4];
  205.  
  206. addEdge(adj, 0, 2);
  207. addEdge(adj, 0, 3);
  208. addEdge(adj, 2, 3);
  209. addEdge(adj, 3, 1);
  210.  
  211. Solution obj;
  212. bool ans = obj.isBipartite(4, adj);
  213. if (ans)
  214. cout << "1\n";
  215. else
  216. cout << "0\n";
  217.  
  218. return 0;
  219. }
  220. ---
  221. --- .\graphs\cycles.cpp
  222. // A C++ Program to detect cycle in a graph
  223. #include <iostream>
  224. #include <list>
  225. using namespace std;
  226.  
  227. class Graph
  228. {
  229. // No. of vertices
  230. int V;
  231.  
  232. // Pointer to an array containing adjacency lists
  233. list<int> *adj;
  234.  
  235. // Used by isCyclic()
  236. bool isCyclicUtil(int v, bool visited[], bool *rs);
  237.  
  238. public:
  239. Graph(int V);
  240. void addEdge(int v, int w);
  241. bool isCyclic();
  242. };
  243.  
  244. Graph::Graph(int V)
  245. {
  246. this->V = V;
  247. adj = new list<int>[V];
  248. }
  249.  
  250. void Graph::addEdge(int v, int w)
  251. {
  252. // Add w to v’s list.
  253. adj[v].push_back(w);
  254. }
  255.  
  256. // DFS function to find if a cycle exists
  257. bool Graph::isCyclicUtil(int v, bool visited[],
  258. bool *recStack)
  259. {
  260. if (visited[v] == false)
  261. {
  262. // Mark the current node as visited
  263. // and part of recursion stack
  264. visited[v] = true;
  265. recStack[v] = true;
  266.  
  267. // Recur for all the vertices adjacent to this
  268. // vertex
  269. list<int>::iterator i;
  270. for (i = adj[v].begin(); i != adj[v].end(); ++i)
  271. {
  272. if (!visited[*i] && isCyclicUtil(*i, visited, recStack))
  273. return true;
  274. else if (recStack[*i])
  275. return true;
  276. }
  277. }
  278.  
  279. // Remove the vertex from recursion stack
  280. recStack[v] = false;
  281. return false;
  282. }
  283.  
  284. // Returns true if the graph contains a cycle, else false
  285. bool Graph::isCyclic()
  286. {
  287. // Mark all the vertices as not visited
  288. // and not part of recursion stack
  289. bool *visited = new bool[V];
  290. bool *recStack = new bool[V];
  291. for (int i = 0; i < V; i++)
  292. {
  293. visited[i] = false;
  294. recStack[i] = false;
  295. }
  296.  
  297. // Call the recursive helper function
  298. // to detect cycle in different DFS trees
  299. for (int i = 0; i < V; i++)
  300. if (!visited[i] && isCyclicUtil(i, visited, recStack))
  301. return true;
  302.  
  303. return false;
  304. }
  305.  
  306. // Driver code
  307. int main()
  308. {
  309. // Create a graph
  310. Graph g(4);
  311. g.addEdge(0, 1);
  312. g.addEdge(0, 2);
  313. g.addEdge(1, 2);
  314. g.addEdge(2, 0);
  315. g.addEdge(2, 3);
  316. g.addEdge(3, 3);
  317.  
  318. // Function call
  319. if (g.isCyclic())
  320. cout << "Graph contains cycle";
  321. else
  322. cout << "Graph doesn't contain cycle";
  323. return 0;
  324. }
  325.  
  326. ---
  327. --- .\graphs\main.cpp
  328. #include <iostream>
  329. #include "paths.hpp"
  330. #include "prims.hpp"
  331.  
  332. int main()
  333. {
  334. /*
  335. Graph *g = new Graph(13);
  336.  
  337. g->addNeighbors(0, {7, 9, 11});
  338. g->addNeighbors(1, {8, 10});
  339. g->addNeighbors(2, {3, 12});
  340. g->addNeighbors(3, {2, 4, 7});
  341. g->addNeighbors(4, {3});
  342. g->addNeighbors(5, {6});
  343. g->addNeighbors(6, {5});
  344. g->addNeighbors(7, {3, 6, 11});
  345. g->addNeighbors(8, {1, 12});
  346. g->addNeighbors(9, {8, 10});
  347. g->addNeighbors(10, {1});
  348. g->addNeighbors(11, {0});
  349. g->addNeighbors(12, {2, 8});
  350.  
  351. int src = 4, dest = 1;
  352.  
  353. std::cout << "Breadth First ";
  354. int level = g->breadthFirstSearch(src, dest);
  355. std::cout << std::endl;
  356. if (level == -1)
  357. {
  358. std::cout << "Couldn't find a path from " << src << " to " << dest << "\n";
  359. }
  360.  
  361. std::cout << "Depth First ";
  362. int dfsLevel = g->depthFirstSearch(src, dest);
  363. std::cout << std::endl;
  364. if (dfsLevel == -1)
  365. {
  366. std::cout << "Couldn't find a path from " << src << " to " << dest << "\n";
  367. }
  368.  
  369. // Free the taken memory
  370. delete g;
  371. */
  372.  
  373. vector<vector<pair<int, int>>> adjList{
  374. {{1, 1}, {2, 6}, {3, 5}}, // 0
  375. {{0, 1}, {2, 6}}, // 1
  376. {{0, 6}, {1, 6}, {4, 7}, {5, 3}}, // 2
  377. {{0, 5}, {5, 2}, {6, 10}}, // 3
  378. {{2, 7}, {7, 12}}, // 4
  379. {{2, 3}, {3, 2}, {7, 8}}, // 5
  380. {{3, 10}, {7, 7}, {8, 3}}, // 6
  381. {{4, 12}, {5, 8}, {6, 7}, {8, 8}}, // 7
  382. {{6, 3}, {7, 8}}, // 8
  383. };
  384.  
  385. int start = 1;
  386. int cost = primsMinimumCostSpanningTree(start, adjList);
  387.  
  388. std::cout << "The cost of the minimum spanning tree is: " << cost << "\n";
  389.  
  390. return 0;
  391. }
  392. ---
  393. --- .\graphs\paths.hpp
  394. #ifndef PATHS
  395. #define PATHS
  396.  
  397. #include <vector>
  398. #include <queue>
  399. #include <stack>
  400.  
  401. template <class T>
  402. using vector = std::vector<T>;
  403.  
  404. template <class T>
  405. using queue = std::queue<T>;
  406.  
  407. template <class T>
  408. using stack = std::stack<T>;
  409.  
  410. template <class T1, class T2>
  411. using pair = std::pair<T1, T2>;
  412.  
  413. /**
  414. * Class to represent graphs
  415. */
  416. class Graph
  417. {
  418. private:
  419. vector<vector<int>> adjList;
  420. int vertexCount;
  421.  
  422. /**
  423. * Prints the shortest path found in the graph
  424. * @param parent The list containing parent for each vertex
  425. * @param src The starting vertex of the journey
  426. * @param dest The ending vertex of the journey
  427. */
  428. int printShortestPath(vector<int> const &parent, const int src, const int dest)
  429. {
  430. static int level = 0;
  431.  
  432. // If we've reached the root of the shortest path tree
  433. if (parent[src] == -1)
  434. {
  435. std::cout << "Shortest path between " << src << " and " << dest << " is " << src << " ";
  436. return level;
  437. }
  438. // Recursively find the path
  439. printShortestPath(parent, parent[src], dest);
  440. level++;
  441.  
  442. if (src < vertexCount)
  443. {
  444. std::cout << src << " ";
  445. }
  446. return level;
  447. }
  448.  
  449. public:
  450. /**
  451. * The vertex numbers start from '0'
  452. */
  453. Graph(int vertices)
  454. {
  455. // Add empty list for the adjacency
  456. for (int i = 0; i < vertices; i++)
  457. adjList.push_back({});
  458. // Store the number of the vertices
  459. vertexCount = vertices;
  460. }
  461.  
  462. /**
  463. * Adds an edge to the graph from u -> v
  464. * @param u The first vertex of the dge
  465. * @param v The second vertex of the edge
  466. */
  467. void addEdge(int u, int v)
  468. {
  469. // Check if the vertex is within the bounds
  470. if (0 > u || vertexCount <= u)
  471. return;
  472.  
  473. if (0 > v || vertexCount <= v)
  474. return;
  475.  
  476. // Add the vertex to the list
  477. adjList[u].push_back(v);
  478. }
  479.  
  480. /**
  481. * Adds a whole list for the adjacency list
  482. * @param vertex The vertex to add neighbors to
  483. * @param neighbors The neighbor list for the vertex
  484. */
  485. void addNeighbors(const int &vertex, const vector<int> &neighbors)
  486. {
  487. adjList[vertex] = neighbors;
  488. }
  489.  
  490. /**
  491. * To perform a breadth first search on the graph
  492. * @param start The starting vertex of the graph
  493. * @param end The destination for the search
  494. */
  495. int breadthFirstSearch(int const start, int const end)
  496. {
  497. // Create a queue frontier for the search
  498. queue<int> q;
  499. // Add the start to the queue
  500. q.push(start);
  501.  
  502. // Make a list to keep track of parents
  503. vector<int> parent(vertexCount, -1);
  504.  
  505. // Make a visited list
  506. vector<bool> visited(vertexCount, false);
  507. // Mark the current node as visited
  508. visited[start] = true;
  509.  
  510. while (!q.empty())
  511. {
  512. // Get the current element to explore, pop it from the queue
  513. int current = q.front();
  514. q.pop();
  515.  
  516. // Check if we've reached our goal
  517. if (current == end)
  518. {
  519. return printShortestPath(parent, current, end);
  520. }
  521.  
  522. // Iterate over all the neighbors to the find the
  523. for (int const &neighbor : adjList[current])
  524. {
  525. if (!visited[neighbor])
  526. {
  527. q.push(neighbor);
  528. visited[neighbor] = true;
  529. parent[neighbor] = current;
  530. }
  531. }
  532. }
  533.  
  534. // Return -1, if we don't find any path
  535. return -1;
  536. }
  537.  
  538. /**
  539. * To perform a depth-first search on the graph
  540. * @param start The starting vertex of the graph
  541. * @param end The destination for the search
  542. */
  543. int depthFirstSearch(int const start, int const end)
  544. {
  545. // Create a stack frontier
  546. stack<int> stack;
  547. // Keep track of the visited nodes
  548. vector<bool> visited(vertexCount, false);
  549.  
  550. // Make a list of parents to create a path later
  551. vector<int> parent(vertexCount, -1);
  552.  
  553. // Add the current node to frontier, and mark it visited
  554. stack.push(start);
  555. visited[start] = true;
  556.  
  557. // Repeat till the stack is empty
  558. while (!stack.empty())
  559. {
  560.  
  561. // Get the element at top of the stack
  562. int current = stack.top();
  563. stack.pop();
  564.  
  565. // Check if we've reached our destination
  566. if (current == end)
  567. {
  568. return printShortestPath(parent, current, end);
  569. }
  570.  
  571. // Mark this node as visited
  572. visited[current] = true;
  573.  
  574. // Explore all the neighbors
  575. for (int const &neighbor : adjList[current])
  576. {
  577. if (!visited[neighbor])
  578. {
  579. // Add this node to the frontier to explore later
  580. stack.push(neighbor);
  581. // Mark the current element as parent of the neighbor (in dfs tree)
  582. parent[neighbor] = current;
  583. // Mark this node as visited
  584. visited[neighbor] = true;
  585. }
  586. }
  587. }
  588.  
  589. // Return -1, if we didn't find any path
  590. return -1;
  591. }
  592. };
  593.  
  594. #endif
  595. ---
  596. --- .\graphs\prims.cpp
  597. #include <stdio.h>
  598. #include <limits.h>
  599. #define vertices 5 /*Define the number of vertices in the graph*/
  600. /* create minimum_key() method for finding the vertex that has minimum key-value and that is not added in MST yet */
  601. int minimum_key(int k[], int mst[])
  602. {
  603. int minimum = INT_MAX, min, i;
  604.  
  605. /*iterate over all vertices to find the vertex with minimum key-value*/
  606. for (i = 0; i < vertices; i++)
  607. if (mst[i] == 0 && k[i] < minimum)
  608. minimum = k[i], min = i;
  609. return min;
  610. }
  611. /* create prim() method for constructing and printing the MST.
  612. The g[vertices][vertices] is an adjacency matrix that defines the graph for MST.*/
  613. void prim(int g[vertices][vertices])
  614. {
  615. /* create array of size equal to total number of vertices for storing the MST*/
  616. int parent[vertices];
  617. /* create k[vertices] array for selecting an edge having minimum weight*/
  618. int k[vertices];
  619. int mst[vertices];
  620. int i, count, edge, v; /*Here 'v' is the vertex*/
  621. for (i = 0; i < vertices; i++)
  622. {
  623. k[i] = INT_MAX;
  624. mst[i] = 0;
  625. }
  626. k[0] = 0; /*It select as first vertex*/
  627. parent[0] = -1; /* set first value of parent[] array to -1 to make it root of MST*/
  628. for (count = 0; count < vertices - 1; count++)
  629. {
  630. /*select the vertex having minimum key and that is not added in the MST yet from the set of vertices*/
  631. edge = minimum_key(k, mst);
  632. mst[edge] = 1;
  633. for (v = 0; v < vertices; v++)
  634. {
  635. if (g[edge][v] && mst[v] == 0 && g[edge][v] < k[v])
  636. {
  637. parent[v] = edge, k[v] = g[edge][v];
  638. }
  639. }
  640. }
  641. /*Print the constructed Minimum spanning tree*/
  642. printf("\n Edge \t Weight\n");
  643. for (i = 1; i < vertices; i++)
  644. printf(" %d <-> %d %d \n", parent[i], i, g[i][parent[i]]);
  645. }
  646. int main()
  647. {
  648. int g[vertices][vertices] = {
  649. {0, 0, 3, 0, 0},
  650. {0, 0, 10, 4, 0},
  651. {3, 10, 0, 2, 6},
  652. {0, 4, 2, 0, 1},
  653. {0, 0, 6, 1, 0},
  654. };
  655. prim(g);
  656. return 0;
  657. }
  658. ---
  659. --- .\graphs\strongly.cpp
  660. // Program to check if the given directed graph
  661. // is strongly connected or not.
  662. #include <iostream>
  663. #include <list>
  664. #include <queue>
  665. using namespace std;
  666.  
  667. class Graph
  668. {
  669. int vertices; // To store no. of vertices
  670. list<int> *adjList;
  671.  
  672. // Function to print DFS starting from v
  673. void BFSUtil(int v, bool visited[]);
  674.  
  675. public:
  676. Graph(int V)
  677. {
  678. this->vertices = V;
  679. adjList = new list<int>[V];
  680. }
  681. ~Graph() { delete[] adjList; }
  682.  
  683. // Function to add an edge
  684. void addEdge(int v, int w);
  685.  
  686. // Function that returns if the
  687. // graph is strongly connected or not.
  688. bool isStronglyConnected();
  689.  
  690. // Function that returns reverse (or transpose)
  691. // of this graph
  692. Graph getTranspose();
  693. };
  694.  
  695. // A recursive function to print DFS starting from v
  696. void Graph::BFSUtil(int v, bool visited[])
  697. {
  698. // Creating a queue for BFS traversal
  699. list<int> queue;
  700. visited[v] = true;
  701. queue.push_back(v);
  702.  
  703. list<int>::iterator i;
  704.  
  705. while (!queue.empty())
  706. {
  707. // Dequeue a vertex from queue
  708. v = queue.front();
  709. queue.pop_front();
  710. for (i = adjList[v].begin(); i != adjList[v].end(); ++i)
  711. {
  712. if (!visited[*i])
  713. {
  714. visited[*i] = true;
  715. queue.push_back(*i);
  716. }
  717. }
  718. }
  719. }
  720.  
  721. Graph Graph::getTranspose()
  722. {
  723. Graph g(vertices);
  724. for (int v = 0; v < vertices; v++)
  725. {
  726. list<int>::iterator i;
  727. for (i = adjList[v].begin(); i != adjList[v].end(); ++i)
  728. g.adjList[*i].push_back(v);
  729. }
  730. return g;
  731. }
  732.  
  733. void Graph::addEdge(int v, int w)
  734. {
  735. adjList[v].push_back(w);
  736. }
  737.  
  738. // Function that returns true if graph
  739. // is strongly connected
  740. bool Graph::isStronglyConnected()
  741. {
  742. // Step 1: Mark all the vertices as not
  743. // visited (For first BFS)
  744. bool *visited = new bool[vertices];
  745. for (int i = 0; i < vertices; i++)
  746. visited[i] = false;
  747.  
  748. // Do BFS traversal starting from the first vertex.
  749. BFSUtil(0, visited);
  750.  
  751. // If BFS traversal doesn’t visit all vertices
  752. // return false.
  753. for (int i = 0; i < vertices; i++)
  754. if (visited[i] == false)
  755. {
  756. delete[] visited;
  757. return false;
  758. }
  759.  
  760. // Create a reversed graph
  761. Graph gr = getTranspose();
  762.  
  763. // Step 4: Mark all the vertices as not
  764. // visited (For second BFS)
  765. for (int i = 0; i < vertices; i++)
  766. visited[i] = false;
  767.  
  768. gr.BFSUtil(0, visited);
  769.  
  770. // If all vertices are not visited in the second DFS
  771. // return false
  772. for (int i = 0; i < vertices; i++)
  773. if (visited[i] == false)
  774. {
  775. delete[] visited;
  776. return false;
  777. }
  778.  
  779. delete[] visited;
  780. return true;
  781. }
  782.  
  783. // Driver program to test the above functions
  784. int main()
  785. {
  786. Graph g1(7);
  787. g1.addEdge(0, 1);
  788. g1.addEdge(1, 2);
  789. g1.addEdge(2, 3);
  790. g1.addEdge(3, 0);
  791. g1.addEdge(2, 4);
  792. g1.addEdge(4, 2);
  793. g1.addEdge(4, 5);
  794. g1.addEdge(5, 6);
  795. g1.addEdge(6, 4);
  796.  
  797. g1.isStronglyConnected() ? cout << "Yes" : cout << "No";
  798. return 0;
  799. }
  800. ---
  801. --- .\graphs\topologicalSorting.cpp
  802. #include <iostream>
  803. #include <vector>
  804. #include <stack>
  805. using namespace std;
  806.  
  807. // Function to perform DFS and topological sorting
  808. void topologicalSortUtil(int v, vector<vector<int>> &adj,
  809. vector<bool> &visited,
  810. stack<int> &Stack)
  811. {
  812. // Mark the current node as visited
  813. visited[v] = true;
  814.  
  815. // Recur for all adjacent vertices
  816. for (int i : adj[v])
  817. {
  818. if (!visited[i])
  819. topologicalSortUtil(i, adj, visited, Stack);
  820. }
  821.  
  822. // Push current vertex to stack which stores the result
  823. Stack.push(v);
  824. }
  825.  
  826. // Function to perform Topological Sort
  827. void topologicalSort(vector<vector<int>> &adj, int V)
  828. {
  829. stack<int> Stack; // Stack to store the result
  830. vector<bool> visited(V, false);
  831.  
  832. // Call the recursive helper function to store
  833. // Topological Sort starting from all vertices one by
  834. // one
  835. for (int i = 0; i < V; i++)
  836. {
  837. if (!visited[i])
  838. topologicalSortUtil(i, adj, visited, Stack);
  839. }
  840.  
  841. // Print contents of stack
  842. while (!Stack.empty())
  843. {
  844. cout << Stack.top() << " ";
  845. Stack.pop();
  846. }
  847. }
  848.  
  849. int main()
  850. {
  851.  
  852. // Number of nodes
  853. int V = 4;
  854.  
  855. // Edges
  856. vector<vector<int>> edges = {{0, 1}, {1, 2}, {3, 1}, {3, 2}};
  857.  
  858. // Graph represented as an adjacency list
  859. vector<vector<int>> adj(V);
  860.  
  861. for (auto i : edges)
  862. {
  863. adj[i[0]].push_back(i[1]);
  864. }
  865.  
  866. cout << "Topological sorting of the graph: ";
  867. topologicalSort(adj, V);
  868.  
  869. return 0;
  870. }
  871. ---
  872. --- .\knapsack\knapsack.cpp
  873. #include <iostream>
  874. #include <vector>
  875. using namespace std;
  876.  
  877. /**
  878. * @param itemCount The number of items to pick from
  879. * @param sackWeight The weight of the knapsack
  880. * @param weights The weights to pick from
  881. * @param profits The profits relating to the weights
  882. * @param pickSeq The picking sequence of the items (0 or 1)
  883. */
  884. int knapsackForItem(int itemCount, int sackWeight, vector<int> const &weights, vector<int> const &profits, vector<bool> &pickSeq, vector<vector<int>> memTable = {})
  885. {
  886.  
  887. // If the item is non-existent or the sack weight
  888. // is non-existent, then return
  889. if (itemCount <= 0 || sackWeight <= 0)
  890. return 0;
  891.  
  892. // Check if we have memoized answer
  893. if (memTable.size() != 0 && memTable[itemCount - 1][sackWeight - 1] != -1)
  894. {
  895. return memTable[itemCount - 1][sackWeight - 1];
  896. }
  897.  
  898. // If the weight of the current item is more than
  899. // the sack weight, then return
  900. if (weights[itemCount - 1] > sackWeight)
  901. {
  902. // We cannot fit this item in the sack
  903. pickSeq[itemCount - 1] = false;
  904.  
  905. // Get the result from the table if possible
  906. if (memTable.size() != 0 && memTable[itemCount - 1][sackWeight - 1] != -1)
  907. return memTable[itemCount - 1][sackWeight - 1];
  908.  
  909. // Memoize the result
  910. int result = knapsackForItem(itemCount - 1, sackWeight, weights, profits, pickSeq);
  911.  
  912. if (memTable.size() != 0)
  913. {
  914. memTable[itemCount - 1][sackWeight - 1] = result;
  915. return memTable[itemCount - 1][sackWeight - 1];
  916. }
  917.  
  918. // We're not given a memTable
  919. return result;
  920. }
  921.  
  922. /* Else, we need to get the result where the profit is maximum */
  923.  
  924. // Not picking the item
  925. int notPicking = knapsackForItem(itemCount - 1, sackWeight, weights, profits, pickSeq);
  926. // Picking the item
  927. int picking = knapsackForItem(itemCount - 1, sackWeight - weights[itemCount - 1], weights, profits, pickSeq) + profits[itemCount - 1];
  928.  
  929. // If we're given a memTable
  930. if (memTable.size() != 0)
  931. {
  932. memTable[itemCount - 1][sackWeight - 1] = max(notPicking, picking);
  933. }
  934.  
  935. if (notPicking > picking)
  936. {
  937. pickSeq[itemCount - 1] = false;
  938. std::cout << "Not picking the item with weight: " << weights[itemCount - 1] << "\n";
  939. return notPicking;
  940. }
  941. else
  942. {
  943. pickSeq[itemCount - 1] = true;
  944. std::cout << "Picking the item with weight: " << weights[itemCount - 1] << "\n";
  945. return picking;
  946. }
  947. }
  948.  
  949. /**
  950. * Returns the answer using memoized
  951. */
  952. int optimalKnapsack(int itemCount, int sackWeight, vector<int> const &weights, vector<int> const &profits, vector<bool> &pickSeq)
  953. {
  954. // Make a memoized table
  955. vector<vector<int>> memTable(itemCount, vector<int>(sackWeight, -1));
  956.  
  957. // Return the memoized version
  958. return knapsackForItem(itemCount, sackWeight, weights, profits, pickSeq, memTable);
  959. }
  960.  
  961. int main()
  962. {
  963.  
  964. /*
  965. Consider the problem where
  966. weights = {3, 4, 6, 5}
  967. profits = {2, 3, 1, 4}
  968.  
  969. The max weight is: 8 Kgs
  970. */
  971.  
  972. // The weights for the item to pick
  973. vector<int> weights{3, 4, 6, 5};
  974.  
  975. // The profits corresponding to those items
  976. vector<int> profits{2, 3, 1, 4};
  977.  
  978. // Number of items to pick from
  979. const int itemCount = 4;
  980.  
  981. // The maximum carry weight for the sack
  982. const int maxWeight = 8;
  983.  
  984. // The picking sequence
  985. vector<bool> pickSeq(itemCount, false);
  986.  
  987. int maxProfit = optimalKnapsack(itemCount, maxWeight, weights, profits, pickSeq);
  988.  
  989. std::cout << "Max profit from the knapsack is: " << maxProfit << std::endl;
  990.  
  991. // Picking sequence
  992. std::cout << "Answer to 0-1 Knapsack: [ ";
  993. for (bool const &didPick : pickSeq)
  994. {
  995. std::cout << didPick << " ";
  996. }
  997. std::cout << "]" << std::endl;
  998.  
  999. return 0;
  1000. }
  1001. ---
  1002. --- .\multilpication\strassen.cpp
  1003. #include <iostream>
  1004. #include <vector>
  1005.  
  1006. using namespace std;
  1007.  
  1008. // Function to add two matrices
  1009. vector<vector<int>> matrixAdd(const vector<vector<int>> &A, const vector<vector<int>> &B)
  1010. {
  1011. int n = A.size();
  1012. vector<vector<int>> C(n, vector<int>(n));
  1013. for (int i = 0; i < n; i++)
  1014. {
  1015. for (int j = 0; j < n; j++)
  1016. {
  1017. C[i][j] = A[i][j] + B[i][j];
  1018. }
  1019. }
  1020. return C;
  1021. }
  1022.  
  1023. // Function to subtract two matrices
  1024. vector<vector<int>> matrixSubtract(const vector<vector<int>> &A, const vector<vector<int>> &B)
  1025. {
  1026. int n = A.size();
  1027. vector<vector<int>> C(n, vector<int>(n));
  1028. for (int i = 0; i < n; i++)
  1029. {
  1030. for (int j = 0; j < n; j++)
  1031. {
  1032. C[i][j] = A[i][j] - B[i][j];
  1033. }
  1034. }
  1035. return C;
  1036. }
  1037.  
  1038. // Function to multiply two matrices using Strassen's algorithm
  1039. vector<vector<int>> strassenMultiply(const vector<vector<int>> &A, const vector<vector<int>> &B)
  1040. {
  1041. int n = A.size();
  1042.  
  1043. // Base case: If the matrix size is 1x1
  1044. if (n == 1)
  1045. {
  1046. vector<vector<int>> C(1, vector<int>(1));
  1047. C[0][0] = A[0][0] * B[0][0];
  1048. return C;
  1049. }
  1050.  
  1051. // Splitting matrices into quadrants
  1052. int mid = n / 2;
  1053. vector<vector<int>> A11(mid, vector<int>(mid)), A12(mid, vector<int>(mid)), A21(mid, vector<int>(mid)), A22(mid, vector<int>(mid));
  1054. vector<vector<int>> B11(mid, vector<int>(mid)), B12(mid, vector<int>(mid)), B21(mid, vector<int>(mid)), B22(mid, vector<int>(mid));
  1055.  
  1056. for (int i = 0; i < mid; i++)
  1057. {
  1058. for (int j = 0; j < mid; j++)
  1059. {
  1060. A11[i][j] = A[i][j];
  1061. A12[i][j] = A[i][j + mid];
  1062. A21[i][j] = A[i + mid][j];
  1063. A22[i][j] = A[i + mid][j + mid];
  1064.  
  1065. B11[i][j] = B[i][j];
  1066. B12[i][j] = B[i][j + mid];
  1067. B21[i][j] = B[i + mid][j];
  1068. B22[i][j] = B[i + mid][j + mid];
  1069. }
  1070. }
  1071.  
  1072. // Calculating intermediate matrices
  1073. vector<vector<int>> M1 = strassenMultiply(matrixAdd(A11, A22), matrixAdd(B11, B22));
  1074. vector<vector<int>> M2 = strassenMultiply(matrixAdd(A21, A22), B11);
  1075. vector<vector<int>> M3 = strassenMultiply(A11, matrixSubtract(B12, B22));
  1076. vector<vector<int>> M4 = strassenMultiply(A22, matrixSubtract(B21, B11));
  1077. vector<vector<int>> M5 = strassenMultiply(matrixAdd(A11, A12), B22);
  1078. vector<vector<int>> M6 = strassenMultiply(matrixSubtract(A21, A11), matrixAdd(B11, B12));
  1079. vector<vector<int>> M7 = strassenMultiply(matrixSubtract(A12, A22), matrixAdd(B21, B22));
  1080.  
  1081. // Calculating result matrix
  1082. vector<vector<int>> C(n, vector<int>(n));
  1083. vector<vector<int>> C11 = matrixAdd(matrixSubtract(matrixAdd(M1, M4), M5), M7);
  1084. vector<vector<int>> C12 = matrixAdd(M3, M5);
  1085. vector<vector<int>> C21 = matrixAdd(M2, M4);
  1086. vector<vector<int>> C22 = matrixAdd(matrixSubtract(matrixAdd(M1, M3), M2), M6);
  1087.  
  1088. // Combining result quadrants into the result matrix
  1089. for (int i = 0; i < mid; i++)
  1090. {
  1091. for (int j = 0; j < mid; j++)
  1092. {
  1093. C[i][j] = C11[i][j];
  1094. C[i][j + mid] = C12[i][j];
  1095. C[i + mid][j] = C21[i][j];
  1096. C[i + mid][j + mid] = C22[i][j];
  1097. }
  1098. }
  1099.  
  1100. return C;
  1101. }
  1102.  
  1103. // Function to print a matrix
  1104. void printMatrix(const vector<vector<int>> &matrix)
  1105. {
  1106. int n = matrix.size();
  1107. for (int i = 0; i < n; i++)
  1108. {
  1109. for (int j = 0; j < n; j++)
  1110. {
  1111. cout << matrix[i][j] << " ";
  1112. }
  1113. cout << endl;
  1114. }
  1115. }
  1116.  
  1117. int main()
  1118. {
  1119. vector<vector<int>> A = {{1, 2}, {3, 4}};
  1120. vector<vector<int>> B = {{5, 6}, {7, 8}};
  1121.  
  1122. cout << "Matrix A:" << endl;
  1123. printMatrix(A);
  1124. cout << endl;
  1125.  
  1126. cout << "Matrix B:" << endl;
  1127. printMatrix(B);
  1128. cout << endl;
  1129.  
  1130. cout << "Result of matrix multiplication (Strassen's algorithm):" << endl;
  1131. vector<vector<int>> C = strassenMultiply(A, B);
  1132. printMatrix(C);
  1133.  
  1134. return 0;
  1135. }
  1136. ---
  1137. --- .\sorting\countSort.hpp
  1138. #ifndef COUNT_SORT
  1139. #define COUNT_SORT
  1140.  
  1141. /**
  1142. * Sorts the array using count-sort
  1143. * @param array The array to sort
  1144. * @param size The length of the array to sort
  1145. */
  1146. void countSort(int array[], int size)
  1147. {
  1148. int maxElement = array[0];
  1149. for (int i = 1; i < size; i++)
  1150. {
  1151. if (array[i] > maxElement)
  1152. maxElement = array[i];
  1153. }
  1154.  
  1155. // Initialize count array with all elements as 0
  1156. int *count = new int[maxElement + 1];
  1157. // Initialize it with zeros
  1158. for (size_t j = 0; j < maxElement + 1; j++)
  1159. count[j] = 0;
  1160.  
  1161. // Count the occurrences of each element
  1162. for (int i = 0; i < size; i++)
  1163. {
  1164. count[array[i]]++;
  1165. }
  1166.  
  1167. // Fill the original array with sorted elements
  1168. int index = 0;
  1169. for (int i = 0; i <= maxElement; i++)
  1170. {
  1171. while (count[i] > 0)
  1172. {
  1173. array[index++] = i;
  1174. count[i]--;
  1175. }
  1176. }
  1177. delete[] count;
  1178. }
  1179.  
  1180. #endif
  1181. ---
  1182. --- .\sorting\heapSort.hpp
  1183. #ifndef HEAP_SORT
  1184. #define HEAP_SORT
  1185.  
  1186. /**
  1187. * Swaps two values
  1188. * @param a The first value to swap
  1189. * @param b The second value to swap with
  1190. */
  1191. template <class T>
  1192. void swap(T &a, T &b)
  1193. {
  1194. T temp = a;
  1195. a = b;
  1196. b = temp;
  1197. }
  1198.  
  1199. /**
  1200. * Builds a max heap from the given array
  1201. * @param array The array to perform max-heapify on
  1202. * @param size The length of the array
  1203. * @param i The index to start heapify with '0' for root
  1204. */
  1205. void maxHeapify(int array[], int size, int i)
  1206. {
  1207. int largest = i; // Initialize largest as the root
  1208. int left = 2 * i + 1; // Left child of the root
  1209. int right = 2 * i + 2; // Right child of the root
  1210.  
  1211. // Find the new largest element
  1212. if (left < size && array[left] > array[largest])
  1213. largest = left;
  1214. if (right < size && array[right] > array[largest])
  1215. largest = right;
  1216.  
  1217. // If the largest is not the root, then swap
  1218. if (largest != i)
  1219. {
  1220. swap(array[i], array[largest]);
  1221. // Recursively heapify the affected sub-tree
  1222. maxHeapify(array, size, largest);
  1223. }
  1224. }
  1225.  
  1226. /**
  1227. * Sorts the array using heap sort
  1228. * @param array The array to sort
  1229. * @param size The length of the array
  1230. */
  1231. void heapSort(int array[], int size)
  1232. {
  1233. // Build a max-heap (rearrange array)
  1234. for (int i = (size / 2) - 1; i >= 0; i--)
  1235. {
  1236. maxHeapify(array, size, i);
  1237. }
  1238.  
  1239. // One-by-one extract an element from the heap
  1240. for (int i = size - 1; i >= 0; i--)
  1241. {
  1242. // Move the current root to the end
  1243. swap(array[0], array[i]);
  1244.  
  1245. // Call the max heapify on the reduced heap
  1246. maxHeapify(array, i, 0);
  1247. }
  1248. }
  1249.  
  1250. #endif
  1251. ---
  1252. --- .\sorting\insertionSort.hpp
  1253.  
  1254. #ifndef INSERTION_SORT
  1255. #define INSERTION_SORT
  1256.  
  1257. /**
  1258. * Insertion Sort (in-place)
  1259. * @param array The array to sort
  1260. * @param size The size of the array
  1261. */
  1262. void insertionSort(int array[], int size)
  1263. {
  1264. for (int i = 1; i < size; i++)
  1265. {
  1266. int key = array[i];
  1267. int j = i - 1;
  1268.  
  1269. while (j >= 0 && array[j] > key)
  1270. {
  1271. // Shift the elements to the right
  1272. array[j + 1] = array[j];
  1273. j = j - 1;
  1274. }
  1275. array[j + 1] = key;
  1276. }
  1277. }
  1278.  
  1279. #endif
  1280. ---
  1281. --- .\sorting\main.cpp
  1282. #include <iostream>
  1283.  
  1284. // Internal Dependencies
  1285. #include "insertionSort.hpp"
  1286. #include "mergeSort.hpp"
  1287. // #include "heapSort.hpp"
  1288. #include "quickSort.hpp"
  1289.  
  1290. /**
  1291. * @param array The array to print
  1292. * @param size The size of the array
  1293. * @param endline The character at the end of the line
  1294. */
  1295. template <class T>
  1296. void printArray(T array[], int size, char endline = '\0')
  1297. {
  1298. std::cout << "[ ";
  1299. for (int i = 0; i < size; i++)
  1300. std::cout << array[i] << " ";
  1301. std::cout << "]" << endline;
  1302. }
  1303.  
  1304. #include "countSort.hpp"
  1305.  
  1306. /**
  1307. * The driver function of the code
  1308. */
  1309. int main()
  1310. {
  1311.  
  1312. int a[] = {1, 4, 7, 4, 2, 8, 1, 9, 0, 3};
  1313.  
  1314. // Get the size of the array
  1315. int size = sizeof(a) / sizeof(a[0]);
  1316.  
  1317. // Before sorting
  1318. printArray(a, size, '\n');
  1319.  
  1320. // quickSort(a, 0, size - 1);
  1321. countSort(a, size);
  1322.  
  1323. // After sorting
  1324. printArray(a, size, '\n');
  1325.  
  1326. return 0;
  1327. }
  1328.  
  1329. ---
  1330. --- .\sorting\mergeSort.hpp
  1331. #ifndef MERGE_SORT
  1332. #define MERGE_SORT
  1333.  
  1334. /**
  1335. * Merges the sub-arrays
  1336. */
  1337. void merge(int array[], int const left, int const mid, int const right)
  1338. {
  1339. int const subArrayLeft = mid - left + 1;
  1340. int const subArrayRight = right - mid;
  1341.  
  1342. // Create new temporary arrays
  1343. int *leftArray = new int[subArrayLeft];
  1344. int *rightArray = new int[subArrayRight];
  1345.  
  1346. // Copy the data of sub-arrays to this new array
  1347. for (size_t i = 0; i < subArrayLeft; i++)
  1348. {
  1349. leftArray[i] = array[left + i];
  1350. }
  1351. for (size_t i = 0; i < subArrayRight; i++)
  1352. {
  1353. rightArray[i] = array[mid + 1 + i];
  1354. }
  1355.  
  1356. int i = 0; // Iterator for the left sub-array
  1357. int j = 0; // Iterator for the right sub-array
  1358. int k = left; // Iterator for the merged array
  1359.  
  1360. while (i < subArrayLeft && j < subArrayRight)
  1361. {
  1362. if (leftArray[i] <= rightArray[j])
  1363. {
  1364. // Choose the element from the left sub-array
  1365. array[k] = leftArray[i];
  1366. i++;
  1367. }
  1368. else
  1369. {
  1370. // Choose the element from the right sub-array
  1371. array[k] = rightArray[j];
  1372. j++;
  1373. }
  1374. // Increment the sub-array iterator
  1375. k++;
  1376. }
  1377.  
  1378. // Add the remaining left array elements
  1379. while (i < subArrayLeft)
  1380. {
  1381. array[k] = leftArray[i];
  1382. i++;
  1383. k++;
  1384. }
  1385.  
  1386. // Add the remaining right array elements
  1387. while (j < subArrayRight)
  1388. {
  1389. array[k] = rightArray[j];
  1390. j++;
  1391. k++;
  1392. }
  1393.  
  1394. delete[] leftArray;
  1395. delete[] rightArray;
  1396. }
  1397.  
  1398. /**
  1399. * Sorts the array using merge sort, (in-place)
  1400. * @param array The array to sort
  1401. * @param begin The beginning of the index in the array
  1402. * @param end The end index of the array (should be 'length-1')
  1403. */
  1404. void mergeSort(int array[], int const begin, int const end)
  1405. {
  1406. if (begin >= end)
  1407. return;
  1408. // Get the middle of the array and divide it there
  1409. int mid = (begin + end) / 2;
  1410. // Sort the left half of the array
  1411. mergeSort(array, begin, mid);
  1412. // Sort the right half of the array
  1413. mergeSort(array, mid + 1, end);
  1414. // Merge the two halves
  1415. merge(array, begin, mid, end);
  1416. }
  1417.  
  1418. #endif
  1419. ---
  1420. --- .\sorting\quickSort.hpp
  1421. #ifndef QUICK_SORT
  1422. #define QUICK_SORT
  1423.  
  1424. /**
  1425. * Swaps two values
  1426. * @param a The first value to swap
  1427. * @param b The second value to swap with
  1428. */
  1429. template <class T>
  1430. void swap(T &a, T &b)
  1431. {
  1432. T temp = a;
  1433. a = b;
  1434. b = temp;
  1435. }
  1436.  
  1437. /**
  1438. * Function to partition the array and return the pivot index
  1439. */
  1440. int partition(int array[], int low, int high)
  1441. {
  1442. // Choosing the last element as pivot
  1443. int pivot = array[high];
  1444. // Index of the smaller element
  1445. int i = low - 1;
  1446.  
  1447. for (int j = low; j <= high - 1; j++)
  1448. {
  1449. // If the current element is smaller than or equal to pivot
  1450. if (array[j] <= pivot)
  1451. {
  1452. i++; // Increment the index of smaller element
  1453. swap(array[i], array[j]);
  1454. }
  1455. }
  1456. swap(array[i + 1], array[high]);
  1457. return (i + 1);
  1458. }
  1459.  
  1460. void quickSort(int array[], int low, int high)
  1461. {
  1462. if (low >= high)
  1463. return;
  1464.  
  1465. // Partitioning index
  1466. int pi = partition(array, low, high);
  1467. // Separately sort elements before and after partition
  1468. quickSort(array, low, pi - 1);
  1469. quickSort(array, pi + 1, high);
  1470. }
  1471.  
  1472. #endif
  1473. ---
  1474.  
Tags: Code
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement