id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
10,236
inserting_a_node.cpp
OpenGenus_cosmos/code/data_structures/src/Linked_List/inserting_a_node.cpp
#include <iostream> using namespace std; typedef struct node Node; struct node { int data; Node *next_pointer; }; Node *create_node(); void insert_in_beginning(int value, Node **start); void insert_in_ending(int value, Node **start); void insert_in_specific_position(int value, Node *start); void linked_list_print(Node *start); int main() { int arr[] = {5, 3, 9, 42, 0, 10}; int length = 6; Node *start = NULL; for (int i = 0; i < length; i++) { // insert_in_beginning(arr[i], &start); insert_in_ending(arr[i], &start); } linked_list_print(start); } Node *create_node() { Node *node = (Node *)malloc(sizeof(Node)); if (node == NULL) { cout << "Error while creating new node" << endl; } return node; } void insert_in_beginning(int value, Node **start) { Node *new_node = create_node(); new_node->data = value; new_node->next_pointer = *start; *start = new_node; } void linked_list_print(Node *start) { if (start == NULL) { cout << "Empty Linked List" << endl; exit(1); } Node *current_node = start; while (current_node != NULL) { cout << current_node->data << " "; current_node = current_node->next_pointer; } cout << endl; } void insert_in_ending(int value, Node **start) { Node *current_node = *start; Node *new_node = create_node(); if (current_node == NULL) { *start = new_node; current_node = new_node; current_node->next_pointer = NULL; } while (current_node->next_pointer != NULL) { current_node = current_node->next_pointer; } new_node->data = value; current_node->next_pointer = new_node; new_node->next_pointer = NULL; }
1,756
C++
.cpp
62
23.693548
57
0.610351
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,237
sort_a_linked_list.cpp
OpenGenus_cosmos/code/data_structures/src/Linked_List/sort_a_linked_list.cpp
#include <iostream> using namespace std; typedef struct node Node; struct node { int data; Node *next_pointer; }; Node *create_node(); void insert_in_beginning(int value, Node **start); void insert_in_ending(int value, Node **start); void insert_in_specific_position(int value, Node *start); void linked_list_print(Node *start); void sort_linked_lis(Node **start); void insert_sorted_linked_list(int value, Node *start); int main() { int arr[] = {5, 3, 9, 42, 0, 10}; int length = 6; Node *start = NULL; for (int i = 0; i < length; i++) { // insert_in_beginning(arr[i], &start); insert_in_ending(arr[i], &start); } linked_list_print(start); } Node *create_node() { Node *node = (Node *)malloc(sizeof(Node)); if (node == NULL) { cout << "Error while creating new node" << endl; } return node; } void linked_list_print(Node *start) { if (start == NULL) { cout << "Empty Linked List" << endl; exit(1); } Node *current_node = start; while (current_node != NULL) { cout << current_node->data << " "; current_node = current_node->next_pointer; } cout << endl; } void insert_in_ending(int value, Node **start) { Node *current_node = *start; Node *new_node = create_node(); if (current_node == NULL) { *start = new_node; current_node = new_node; current_node->next_pointer = NULL; } while (current_node->next_pointer != NULL) { current_node = current_node->next_pointer; } new_node->data = value; current_node->next_pointer = new_node; new_node->next_pointer = NULL; } void sort_linked_lis(Node **start) { Node *current_node = *start; Node *new_node = create_node(); *start = new_node; new_node->data = current_node->data; current_node = current_node->next_pointer; while (current_node != NULL) { insert_sorted_linked_list(current_node->data, *start); current_node = current_node->next_pointer; } } void insert_sorted_linked_list(int value, Node *start) { Node *current_node = start; while (current_node->next_pointer != NULL && current_node->data) { current_node = current_node->next_pointer; } }
2,261
C++
.cpp
75
25.533333
70
0.625287
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,238
linked_list_palindrome.cpp
OpenGenus_cosmos/code/data_structures/src/Linked_List/linked_list_palindrome.cpp
// Check if the liked list is palindrome or not bool checkpalindrome(vector<int> arr){ int s = 0; int e = arr.size() -1; while(s<=e){ if(arr[s] != arr[e]){ return 0; } s++; e--; } return 1; } bool isPalindrome(Node *head) { vector<int>arr; Node* temp = head; while(temp != NULL){ arr.push_back(temp -> data); temp = temp -> next; } return checkpalindrome(arr); }
551
C++
.cpp
23
14.782609
48
0.442966
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,239
Count_nodes_of_Linked_List.cpp
OpenGenus_cosmos/code/data_structures/src/Linked_List/Count_nodes_of_Linked_List.cpp
// count the Number of Nodes n a Linked List int getCount(struct Node* head){ int cnt=0; Node *curr = head; while(curr != NULL){ cnt++; curr = curr->next; } return cnt; }
230
C++
.cpp
10
16.1
44
0.525346
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,240
reverse_linked_list_in_k_groups.cpp
OpenGenus_cosmos/code/data_structures/src/Linked_List/reverse_linked_list_in_k_groups.cpp
#include <iostream> using namespace std; // Definition for singly-linked list. struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(nullptr) {} }; class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { if (k <= 1 || !head) { return head; // No need to reverse if k <= 1 or the list is empty. } ListNode* dummy = new ListNode(0); dummy->next = head; ListNode* prev_group_tail = dummy; ListNode* current = head; while (true) { int count = 0; ListNode* group_start = current; ListNode* group_end = current; // Find the kth node in the group. while (count < k && group_end) { group_end = group_end->next; count++; } if (count < k || !group_end) { // If the remaining group has fewer than k nodes, stop. break; } ListNode* next_group_start = group_end->next; // Reverse the current group. ListNode* prev = next_group_start; ListNode* curr = group_start; while (curr != next_group_start) { ListNode* temp = curr->next; curr->next = prev; prev = curr; curr = temp; } prev_group_tail->next = group_end; group_start->next = next_group_start; prev_group_tail = group_start; current = next_group_start; } ListNode* new_head = dummy->next; delete dummy; return new_head; } }; // Helper function to create a linked list from an array. ListNode* createLinkedList(int arr[], int n) { if (n == 0) { return nullptr; } ListNode* head = new ListNode(arr[0]); ListNode* current = head; for (int i = 1; i < n; i++) { current->next = new ListNode(arr[i]); current = current->next; } return head; } // Helper function to print a linked list. void printLinkedList(ListNode* head) { ListNode* current = head; while (current != nullptr) { cout << current->val << " -> "; current = current->next; } cout << "nullptr" << endl; } int main() { int arr[] = {1, 2, 3, 4, 5}; int k = 2; ListNode* head = createLinkedList(arr, 5); Solution solution; ListNode* reversed = solution.reverseKGroup(head, k); printLinkedList(reversed); return 0; }
2,543
C++
.cpp
82
22.768293
78
0.542366
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,242
deleting_a_node.cpp
OpenGenus_cosmos/code/data_structures/src/Linked_List/deleting_a_node.cpp
#include <iostream> using namespace std; typedef struct node Node; struct node { int data; Node *next_pointer; }; Node *create_node(); void insert_in_ending(int value, Node **start); void insert_in_specific_position(int value, Node *start); void linked_list_print(Node *start); void deleting(int value, Node **start); int main() { int arr[] = {5, 3, 9, 42, 0, 10}; int length = 6; Node *start = NULL; for (int i = 0; i < length; i++) { insert_in_ending(arr[i], &start); } linked_list_print(start); deleting(5, &start); linked_list_print(start); } Node *create_node() { Node *node = (Node *)malloc(sizeof(Node)); if (node == NULL) { cout << "Error while creating new node" << endl; } return node; } void linked_list_print(Node *start) { if (start == NULL) { cout << "Empty Linked List" << endl; exit(1); } Node *current_node = start; while (current_node != NULL) { cout << current_node->data << " "; current_node = current_node->next_pointer; } cout << endl; } void insert_in_ending(int value, Node **start) { Node *current_node = *start; Node *new_node = create_node(); if (current_node == NULL) { *start = new_node; current_node = new_node; current_node->next_pointer = NULL; } while (current_node->next_pointer != NULL) { current_node = current_node->next_pointer; } new_node->data = value; current_node->next_pointer = new_node; new_node->next_pointer = NULL; } /* Deleting */ void deleting(int value, Node **start) { Node *current_node = *start; Node *next_node = current_node->next_pointer; if (current_node == NULL) { cout << "Underflow" << endl; exit(1); } else if (current_node->data == value) { *start = current_node->next_pointer; return; } while (current_node->next_pointer != NULL && next_node->data != value) { current_node = current_node->next_pointer; next_node = current_node->next_pointer; } current_node->next_pointer = next_node->next_pointer; free(next_node); }
2,178
C++
.cpp
77
23.441558
76
0.606989
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,243
Remove_duplicates_in_unsorted_linked_list.cpp
OpenGenus_cosmos/code/data_structures/src/Linked_List/Remove_duplicates_in_unsorted_linked_list.cpp
// Removethe duplicate elements in the linked list Node * removeDuplicates( Node *head) { Node* temp1=head; Node* temp2=head->next; unordered_set<int> s; while(temp2!=NULL) { s.insert(temp1->data); if(s.find(temp2->data)!=s.end()) { Node* del=temp2; temp2=temp2->next; temp1->next=temp2; delete del; } else { temp1=temp1->next; temp2=temp2->next; } } return head; }
635
C++
.cpp
24
14.25
50
0.43686
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,244
pairwise_swap_on_linked_list.cpp
OpenGenus_cosmos/code/data_structures/src/Linked_List/pairwise_swap_on_linked_list.cpp
// Swaps the data of linked list in pairs struct Node* pairwise_swap(struct Node* head) { Node* curr = head; while(curr!= NULL && curr->next != NULL){ swap(curr->data, curr->next->data); curr = curr->next->next; } return head; }
266
C++
.cpp
10
22
46
0.611111
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,245
reversing_linkedlist.cpp
OpenGenus_cosmos/code/data_structures/src/Linked_List/reversing_linkedlist.cpp
#include<bits/stdc++.h> using namespace std; struct Node{ int value; struct Node* next; Node(int value){ this->value=value; next=NULL; } }; struct LL{ Node* head; LL(){ head=NULL; } void reverse(){ Node* curr=head; Node* prev=NULL,*next=NULL; while(curr!=NULL){ next=curr->next; curr->next=prev; prev=current; current=next; } head=prev; } void print(){ struct Node* temp=head; while(temp!=NULL){ cout<<temp->value<<" "; temp=temp->next; } } void push(int value){ Node* temp=new Node(value); temp->next=head; head=temp; } }; int main(){ LL obj; obj.push(5); obj.push(60); obj.push(4); obj.push(9); cout<<"Entered linked list is: "<<endl; obj.print(); obj.reverse(); cout<<"Reversed linked list is: "<<endl; obj.print(); return 0; } }
805
C++
.cpp
53
12.830189
40
0.65287
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,247
support_vector_machine.cpp
OpenGenus_cosmos/code/artificial_intelligence/src/support_vector_machine/support_vector_machine.cpp
#include <iostream> #include <vector> using namespace std; class SVMModel { public: vector<double> weights; double bias; SVMModel(int numFeatures) : weights(numFeatures, 0), bias(0) {} }; class SVM { private: static const double LEARNING_RATE; static const int MAX_ITERATIONS; public: static SVMModel train(const vector<vector<double>>& features, const vector<int>& labels) { int numFeatures = features[0].size(); SVMModel model(numFeatures); for (int iteration = 0; iteration < MAX_ITERATIONS; iteration++) { for (size_t i = 0; i < features.size(); i++) { const vector<double>& x = features[i]; int y = labels[i]; double prediction = predict(model.weights, x, model.bias); double hingeLoss = max(0.0, 1 - y * prediction); // Update weights and bias using gradient descent if (hingeLoss > 0) { for (int j = 0; j < numFeatures; j++) { model.weights[j] -= LEARNING_RATE * (-y * x[j]); } model.bias -= LEARNING_RATE * (-y); } } } return model; } static double predict(const vector<double>& weights, const vector<double>& x, double bias) { double result = bias; for (size_t i = 0; i < weights.size(); i++) { result += weights[i] * x[i]; } return result; } }; const double SVM::LEARNING_RATE = 0.01; const int SVM::MAX_ITERATIONS = 1000; int main() { vector<vector<double>> features = {{1, 2}, {2, 3}, {3, 4}}; // Add more training examples as needed vector<int> labels = {1, 1, -1}; // Add corresponding labels for each training example SVMModel model = SVM::train(features, labels); // Test the trained model vector<double> testExample = {4, 5}; double prediction = SVM::predict(model.weights, testExample, model.bias); cout << "Prediction: " << prediction << endl; return 0; }
2,070
C++
.cpp
56
28.910714
96
0.578289
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,248
k_nearest_neighbours.cpp
OpenGenus_cosmos/code/artificial_intelligence/src/k_nearest_neighbours/k_nearest_neighbours.cpp
// Part of Cosmos by OpenGenus #include <cmath> #include <iomanip> #include <iostream> #include <vector> struct Point { float w, x, y, z; // w, x, y and z are the values of the dataset float distance; // distance will store the distance of dataset point from // the unknown test point int op; // op will store the class of the point }; int main() { int n, k; Point p; std::cout << "Number of data points: "; std::cin >> n; std::vector<Point> vec; std::cout << "\nEnter the dataset values: \n"; std::cout << "w\tx\ty\tz\top\n"; // Taking dataset for (int i = 0; i < n; ++i) { float wCoordinate, xCoordinate, yCoordinate, zCoordinate; int opCoordinate; std::cin >> wCoordinate >> xCoordinate >> yCoordinate >> zCoordinate >> opCoordinate; vec.push_back(Point()); vec[i].w = wCoordinate; vec[i].x = xCoordinate; vec[i].y = yCoordinate; vec[i].z = zCoordinate; vec[i].op = opCoordinate; } std::cout << "\nw\tx\ty\tz\top\n"; for (int i = 0; i < n; ++i) { std::cout << std::fixed << std::setprecision(2) << vec[i].w << '\t' << vec[i].x << '\t' << vec[i].y << '\t' << vec[i].z << '\t' << vec[i].op << '\n'; } std::cout << "\nEnter the feature values of the unknown point: \nw\tx\ty\tz\n"; std::cin >> p.w >> p.x >> p.y >> p.z; float euclideanDistance(Point p, Point v); for (int i = 0; i < n; ++i) { vec[i].distance = euclideanDistance(p, vec[i]); } // Sorting the training data with respect to distance for (int i = 1; i < n; ++i) { for (int j = 0; j < n - i; ++j) { if (vec[j].distance > vec[j + 1].distance) { Point temp; temp = vec[j]; vec[j] = vec[j + 1]; vec[j + 1] = temp; } } } std::cout << "\nw\tx\ty\tz\top\tdistance\n"; for (int i = 0; i < n; ++i) { std::cout << std::fixed << std::setprecision(2) << vec[i].w << '\t' << vec[i].x << '\t' << vec[i].y << '\t' << vec[i].z << '\t' << vec[i].op << '\t' << vec[i].distance << '\n'; } // Taking the K nearest neighbors std::cout << "\nNumber of nearest neighbors(k): "; std::cin >> k; int freq[1000] = {0}; int index = 0, maxfreq = 0; // Creating frequency array of the class of k nearest neighbors for (int i = 0; i < k; ++i) { freq[vec[i].op]++; } // Finding the most frequent occurring class for (int i = 0; i < 1000; ++i) { if (freq[i] > maxfreq) { maxfreq = freq[i]; index = i; } } std::cout << "The class of the unknown point is " << index; return 0; } // Measuring the Euclidean distance float euclideanDistance(Point p, Point v) { float result; result = sqrt(((v.w - p.w) * (v.w - p.w)) + ((v.x - p.x) * (v.x - p.x)) + ((v.y - p.y) * (v.y - p.y)) + ((v.z - p.z) * (v.z - p.z))); return result; } // Sample Output /* Number of data points: 5 Enter the dataset values: w x y z op 1 2 3 4 5 10 20 30 40 50 5 2 40 7 10 40 30 100 28 3 20 57 98 46 8 w x y z op 1.00 2.00 3.00 4.00 5 10.00 20.00 30.00 40.00 50 5.00 2.00 40.00 7.00 10 40.00 30.00 100.00 28.00 3 20.00 57.00 98.00 46.00 8 Enter the feature values of the unknown point: w x y z 40 30 80 30 w x y z op distance 40.00 30.00 100.00 28.00 3 20.10 20.00 57.00 98.00 46.00 8 41.34 10.00 20.00 30.00 40.00 50 60.00 5.00 2.00 40.00 7.00 10 64.33 1.00 2.00 3.00 4.00 5 94.39 Number of nearest neighbors(k): 3 The class of unknown point is 3 */
4,070
C++
.cpp
116
29.146552
79
0.485634
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,250
main.cpp
OpenGenus_cosmos/code/artificial_intelligence/src/image_processing/canny/main.cpp
// // main.cpp // Canny Edge Detector // #include <iostream> #include <string.h> #define _USE_MATH_DEFINES #include <cmath> #include <vector> #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "canny.h" int main() { std::string filePath = "lena.jpg"; //Filepath of input image canny cny(filePath); return 0; }
364
C++
.cpp
18
18.333333
64
0.722222
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,256
salesman.cpp
OpenGenus_cosmos/code/artificial_intelligence/src/tsp/salesman.cpp
#include <climits> #include <vector> #include <iostream> #include <algorithm> #include <cmath> using namespace std; #define fio std::ios_base::sync_with_stdio(false); cin.tie(NULL) #define ll long long #define vi vector<int> #define all(a) a.begin(), a.end() #define pb push_back const ll mod = 1e9 + 7; const ll N = 1e5; const ll MAX = 1e18; #define epsilon 1e-6 vector<vector<long double>> adjacency_matrix; // Initial Temperature long double temperature = 10000000000000; long long num_cities; long double answer = INT_MAX; void initialize_vectors(vector<long long> &best_path, vector<long long> &current_path, vector<long long> &suggested_path) { for (long long i = 0; i < num_cities; i++) { current_path[i] = i; suggested_path[i] = i; best_path[i] = i; } random_shuffle(current_path.begin(), current_path.end()); } long double evaluation(vector<long long> vec) { long double cost = 0; for (long long i = 0; i < num_cities - 1; i++) cost += adjacency_matrix[vec[i]][vec[i + 1]]; cost += adjacency_matrix[vec[vec.size() - 1]][vec[0]]; return cost; } // swaps random edges pair<long, long> random_edge() { long long start_ind = rand() % num_cities; long long end_ind = (rand() % num_cities) + 1; if (start_ind > end_ind) swap(start_ind, end_ind); return make_pair(start_ind, end_ind); } // Uses triangle law to swap longer edges void Optimization(vector<long long> &auxiliary_best) { for (size_t i = 0; i < auxiliary_best.size() - 3; i++) { long double AB = adjacency_matrix[auxiliary_best[i]][auxiliary_best[i + 1]]; long double CD = adjacency_matrix[auxiliary_best[i + 2]][auxiliary_best[i + 3]]; long double AC = adjacency_matrix[auxiliary_best[i]][auxiliary_best[i + 2]]; long double BD = adjacency_matrix[auxiliary_best[i + 1]][auxiliary_best[i + 3]]; if (AB + CD > AC + BD) { swap(auxiliary_best[i + 1], auxiliary_best[i + 2]); i += 3; } else i++; } } void simulated_annealing() { vector<long long> best_path(num_cities, 0), current_path(num_cities, 0), suggested_path( num_cities, 0); initialize_vectors(best_path, current_path, suggested_path); int limit = 10000000; long double best_path_cost = 0; long long tabu_tenure = 0, break_counter = 0; while (limit-- && break_counter <= 200000) { suggested_path = current_path; pair<long long, long long> edges = random_edge(); long long start = edges.first, end = edges.second; reverse(suggested_path.begin() + start, suggested_path.begin() + end); Optimization(suggested_path); long double current_path_cost = evaluation(current_path); long double suggested_path_cost = evaluation(suggested_path); long double net_gain = suggested_path_cost - current_path_cost; long double rand_num = (double) (rand() / (double) RAND_MAX); long double probability = 1 / (1 + std::pow(M_E, (net_gain / temperature))); best_path_cost = evaluation(best_path); if (probability > rand_num) current_path = suggested_path; if (suggested_path_cost < best_path_cost) { best_path = suggested_path; answer = min(answer, suggested_path_cost); tabu_tenure = 0; current_path = suggested_path; break_counter = 0; for (size_t i = 0; i < best_path.size(); i++) cout << best_path[i] + 1 << " "; cout << best_path[0] + 1 << endl; } else tabu_tenure++; if (tabu_tenure >= 500) { Optimization(best_path); if (best_path_cost > evaluation(best_path)) { best_path_cost = evaluation(best_path); answer = best_path_cost; current_path = best_path; break_counter = 0; for (size_t i = 0; i < best_path.size(); i++) cout << best_path[i] + 1 << " "; cout << best_path[0] + 1 << endl; } tabu_tenure = 0; } cout << "Best_Path_till now " << best_path_cost << endl; // Cooling Rate temperature *= 0.999; break_counter++; } cout << "Final Path:\n"; for (size_t i = 0; i < best_path.size(); i++) cout << best_path[i] + 1 << " "; cout << best_path[0] + 1 << endl; cout << endl; } void processing_data() { vector<pair<long double, long double>> location; string type; cin >> type; long double x, y; cin >> num_cities; srand (time(NULL)); for (long long i = 0; i < num_cities; i++) { cin >> x >> y; location.push_back(make_pair(x, y)); } for (long long i = 0; i < num_cities; i++) { vector<long double> temp; for (long long j = 0; j < num_cities; j++) { cin >> x; temp.push_back(x); } adjacency_matrix.push_back(temp); } } int main() { processing_data(); simulated_annealing(); cout << "Minimum Path found so far " << answer << endl; return 0; }
5,356
C++
.cpp
159
26.90566
92
0.563342
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,257
naive_bayes.cpp
OpenGenus_cosmos/code/artificial_intelligence/src/naive_bayes/naive_bayes.cpp
#include <iostream> #include <string> #include <vector> #include <random> #include <set> #include <map> #include <unordered_map> using namespace std; unordered_map<string, int> count(pair<vector<string>, vector<string>> &feature, vector<string> &position) { unordered_map<string, int> d; for (int i = 0; i < 2; i++) // because pairs only have 2 values { for (int j = 0; j < feature.first.size(); j++) { if (i == 0) { d.emplace(feature.first[j], 0); } else { d.emplace(feature.second[j], 0); } } } for (int i = 0; i < position.size(); i++) { d.emplace(position[i], 0); } for (int i = 0; i < 2; i++) { for (int j = 0; j < feature.first.size(); j++) { if (i == 0) { d[feature.first[j]] = d[feature.first[j]] + 1; } else { d[feature.second[j]] = d[feature.second[j]] + 1; } } } for (int i = 0; i < position.size(); i++) { d[position[i]] = d[position[i]] + 1; } for (int i = 0; i < 2; i++) // because pairs only have 2 values { for (int j = 0; j < feature.first.size(); j++) { for (int k = 0; k < position.size(); k++) { if (i == 0) { d.emplace(feature.first[j] + "/" + position[k], 0); } else { d.emplace(feature.second[j] + "/" + position[k], 0); } } } } for (int i = 0; i < position.size(); i++) { d[feature.first[i] + "/" + position[i]] = d[feature.first[i] + "/" + position[i]] + 1; d[feature.second[i] + "/" + position[i]] = d[feature.second[i] + "/" + position[i]] + 1; } return d; } unordered_map<string, double> calcProb(unordered_map<string, int> &d, pair<vector<string>, vector<string>> &feature, vector<string> &position) { int sum = 0; unordered_map<string, double> x; sum = position.size(); for (int i = 0; i < position.size(); i++) { x.emplace(position[i], (double)d[position[i]] / (double)sum); } for (int i = 0; i < sum; i++) { x.emplace(feature.first[i] + "/" + position[i], (double)d[feature.first[i] + "/" + position[i]] / (double)d[position[i]]); x.emplace(feature.second[i] + "/" + position[i], (double)d[feature.second[i] + "/" + position[i]] / (double)d[position[i]]); } return x; } vector<string> finalPredictions(unordered_map<string, double> &x, pair<vector<string>, vector<string>> &feature, vector<string> &position) { vector<string> predict_array; vector<double> predict_array_prob; double temp; int size = position.size(); for (int i = 0; i < size; i++) { predict_array.push_back(""); predict_array_prob.push_back(0.0); } for (int k = 0; k < size; k++) { for (int i = 0; i < size; i++) { temp = 1.0; for (int j = 0; j < 2; j++) { if (j == 0) { temp = temp * x[feature.first[i] + "/" + position[k]]; } else { temp = temp * x[feature.second[i] + "/" + position[k]]; } } if (predict_array_prob[i] < temp * x[position[k]]) { predict_array[i] = position[k]; predict_array_prob[i] = temp * x[position[k]]; } } } return predict_array; } int main() { vector<string> weather = { "sunny", "rainy", "sunny", "sunny", "sunny", "rainy", "rainy", "sunny", "sunny", "rainy", }; vector<string> car = { "working", "broken", "working", "working", "working", "broken", "broken", "working", "broken", "broken", }; vector<string> position = { "go-out", "go-out", "go-out", "go-out", "go-out", "stay-home", "stay-home", "stay-home", "stay-home", "stay-home", }; pair<vector<string>, vector<string>> feature; feature.first = weather; feature.second = car; unordered_map<string, int> d = count(feature, position); unordered_map<string, double> x = calcProb(d, feature, position); vector<string> predictions = finalPredictions(x, feature, position); for (int i = 0; i < weather.size(); i++) { cout << weather[i] << " " << car[i] << " prediction is -> " << predictions[i] << endl; } // test cases from naive_bayes.py file return 0; }
4,940
C++
.cpp
174
19.885057
142
0.468143
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,260
addition_using_bits_test.cpp
OpenGenus_cosmos/code/bit_manipulation/test/addition_using_bits_test.cpp
#include <assert.h> #include "./../src/addition_using_bits/addition_using_bits.cpp" // Part of Cosmos by OpenGenus Foundation int main() { // Testing bitwiseAddition function assert(bitwiseAddition(10, 5) == (10 + 5)); assert(bitwiseAddition(5, 10) == (5 + 10)); assert(bitwiseAddition(0, 1) == (0 + 1)); assert(bitwiseAddition(2, 0) == (2 + 0)); assert(bitwiseAddition(-27, 3) == (-27 + 3)); assert(bitwiseAddition(27, -3) == (27 + -3)); assert(bitwiseAddition(-1, -1) == (-1 + -1)); // Testing bitwiseAdditionRecursive function assert(bitwiseAdditionRecursive(2, 3) == (2 + 3)); assert(bitwiseAdditionRecursive(3, 2) == (3 + 2)); assert(bitwiseAdditionRecursive(1, 0) == (1 + 0)); assert(bitwiseAdditionRecursive(0, 3) == (0 + 3)); assert(bitwiseAdditionRecursive(25, -50) == (25 + -50)); assert(bitwiseAdditionRecursive(-25, 50) == (-25 + 50)); assert(bitwiseAdditionRecursive(-5, -10) == (-5 + -10)); std::cout << "Testing Complete" << "\n"; }
1,018
C++
.cpp
23
40.217391
63
0.628399
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,261
xor_swap.cpp
OpenGenus_cosmos/code/bit_manipulation/src/xor_swap/xor_swap.cpp
#include <iostream> using namespace std; void xor_swap(int * a, int * b) { *a = *a ^ *b; *b = *a ^ *b; *a = *a ^ *b; } int main() { int a = 10, b = 15; cout << "Before swapping: A = " << a << " and B = " << b << "\n"; xor_swap(&a, &b); cout << "After swapping: A = " << a << " and B = " << b << "\n"; return 0; }
351
C++
.cpp
16
18.5625
69
0.43465
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,262
first_set_bit.cpp
OpenGenus_cosmos/code/bit_manipulation/src/first_set_bit/first_set_bit.cpp
// Part of Cosmos (OpenGenus) #include <bits/stdc++.h> using namespace std; int returnFirstSetBit(int n) { if(n == 0) return 0; int position = 1; int m = 1; while (!(n & m)) { m = m << 1; position++; } return (1 << (position - 1)); } int main() { int n; cin >> n; cout << returnFirstSetBit(n) << endl; return 0; }
386
C++
.cpp
23
12.652174
41
0.523677
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,265
thrice_unique_number.cpp
OpenGenus_cosmos/code/bit_manipulation/src/thrice_unique_number/thrice_unique_number.cpp
/* * * Part of Cosmos by OpenGenus Foundation * Find unique number in an array where every element occours thrice except one.Find that unique Number * */ #include <iostream> using namespace std; int n; int a[104] = {1, 1, 1, 3, 3, 2, 3}; int f() { int count[65] = {0}; for (int i = 0; i < n; i++) { int j = 0; int temp = a[i]; while (temp) { count[j] += (temp & 1); j++; temp = temp >> 1; } } int p = 1, ans = 0; for (int i = 0; i <= 64; i++) { count[i] %= 3; ans += (count[i] * p); p = p << 1; } return ans; } int main() { n = sizeof(a) / sizeof(a[0]); cout << f(); return 0; }
732
C++
.cpp
39
13.846154
103
0.464646
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,267
subset_mask_generator.cpp
OpenGenus_cosmos/code/bit_manipulation/src/subset_generation/subset_mask_generator.cpp
#include <iostream> typedef unsigned long long ll; //Loops over all subsets of the bits in to_mask. Except to_mask itself //For test input (111) //110 //101 //100 //010 //001 //000 void generate_masks(ll to_mask) { for (int mask = to_mask; mask;) { --mask &= to_mask; std::cout << mask << std::endl; } } int main() { generate_masks(7); }
374
C++
.cpp
22
14.363636
70
0.635057
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,270
maximum_xor_value.cpp
OpenGenus_cosmos/code/bit_manipulation/src/maximum_xor_value/maximum_xor_value.cpp
#include <iostream> using namespace std; int maxXor(int l, int r) { int num = l ^ r, max = 0; while (num > 0) { max <<= 1; max |= 1; num >>= 1; } return max; } int main() { int res, _l, _r; cin >> _l; cin >> _r; res = maxXor(_l, _r); cout << res; return 0; }
332
C++
.cpp
22
10.772727
29
0.455738
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,271
addition_using_bits.cpp
OpenGenus_cosmos/code/bit_manipulation/src/addition_using_bits/addition_using_bits.cpp
#include <iostream> // Part of Cosmos by OpenGenus Foundation int bitwiseAddition(int n, int m) { while (m != 0) { int carry = n & m; // Variable carry keeps track of bits that carry over n = n ^ m; // This adds up the individual bits m = carry << 1; // Shift carry over bits so they can be added } return n; } int bitwiseAdditionRecursive(int n, int m) { if (m == 0) return n; else { int carry = n & m; return bitwiseAdditionRecursive(n ^ m, carry << 1); } }
556
C++
.cpp
22
20.545455
81
0.580827
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,272
hamming_distance.cpp
OpenGenus_cosmos/code/bit_manipulation/src/hamming_distance/hamming_distance.cpp
/* * * Part of Cosmos by OpenGenus Foundation * * The Hamming distance between two integers is the number of positions * at which the corresponding bits are different. * * Given two integers x and y, calculate the Hamming distance. */ int hammingDistance(int x, int y) { int temp = x ^ y; int count = 0; //count the number of set bits in the xor of two numbers while (temp) { temp = temp & (temp - 1); count++; } return count; }
482
C++
.cpp
21
19.428571
71
0.658696
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,275
power_of_4.cpp
OpenGenus_cosmos/code/bit_manipulation/src/power_of_4/power_of_4.cpp
// part of cosmos repository #include <iostream> using namespace std ; // Function to check if the number is a power of 4 bool isPowerOfFour(int num) { // First if the num is +ve , // then it is a power of 2 , // then (4^n - 1) % 3 == 0 // another proof: // (1) 4^n - 1 = (2^n + 1) * (2^n - 1) // (2) among any 3 consecutive numbers, there must be one that is a multiple of 3 // among (2^n-1), (2^n), (2^n+1), one of them must be a multiple of 3, and (2^n) cannot be the one, therefore either (2^n-1) or (2^n+1) must be a multiple of 3, and 4^n-1 must be a multiple of 3 as well. return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0; } int main() { int n ; cin>>n ; isPowerOfFour(n)?cout<<"YES":cout<<"NO" ; return 0; }
819
C++
.cpp
21
33.761905
211
0.560203
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,278
lonely_integer.cpp
OpenGenus_cosmos/code/bit_manipulation/src/lonely_integer/lonely_integer.cpp
/* * Part of Cosmos by OpenGenus Foundation * The Lonely Integer Problem * Given an array in which all the no. are present twice except one, find that lonely integer. */ #include <iostream> using namespace std; int LonelyInteger(int *a, int n) { int lonely = 0; //finds the xor sum of the array. for (int i = 0; i < n; i++) lonely ^= a[i]; return lonely; } int main() { int a[] = {2, 3, 4, 5, 3, 2, 4}; cout << LonelyInteger(a, sizeof(a) / sizeof(a[0])); return 0; }
510
C++
.cpp
21
21.238095
94
0.631687
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,279
sum_equals_xor.cpp
OpenGenus_cosmos/code/bit_manipulation/src/sum_equals_xor/sum_equals_xor.cpp
/* * Counts the number of values between 0 and a given number that satisfy the condition x+n = x^n (0<=x<=n) */ #include <iostream> #include <cmath> using namespace std; long solve(long n) { long c = 0; while (n) { c += n % 2 ? 0 : 1; n /= 2; } c = pow(2, c); return c; } int main() { long n; cin >> n; long result = solve(n); cout << result << endl; return 0; }
427
C++
.cpp
25
13.52
106
0.5475
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,281
count_set_bits_lookup_table.cpp
OpenGenus_cosmos/code/bit_manipulation/src/count_set_bits/count_set_bits_lookup_table.cpp
// Part of Cosmos by OpenGenus Foundation #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <random> #include <chrono> // I'm not crazy, I generated this lookup table with a Ruby script ;) const unsigned bits[] = { 0, // 0 1, // 1 1, // 10 2, // 11 1, // 100 2, // 101 2, // 110 3, // 111 1, // 1000 2, // 1001 2, // 1010 3, // 1011 2, // 1100 3, // 1101 3, // 1110 4, // 1111 1, // 10000 2, // 10001 2, // 10010 3, // 10011 2, // 10100 3, // 10101 3, // 10110 4, // 10111 2, // 11000 3, // 11001 3, // 11010 4, // 11011 3, // 11100 4, // 11101 4, // 11110 5, // 11111 1, // 100000 2, // 100001 2, // 100010 3, // 100011 2, // 100100 3, // 100101 3, // 100110 4, // 100111 2, // 101000 3, // 101001 3, // 101010 4, // 101011 3, // 101100 4, // 101101 4, // 101110 5, // 101111 2, // 110000 3, // 110001 3, // 110010 4, // 110011 3, // 110100 4, // 110101 4, // 110110 5, // 110111 3, // 111000 4, // 111001 4, // 111010 5, // 111011 4, // 111100 5, // 111101 5, // 111110 6, // 111111 1, // 1000000 2, // 1000001 2, // 1000010 3, // 1000011 2, // 1000100 3, // 1000101 3, // 1000110 4, // 1000111 2, // 1001000 3, // 1001001 3, // 1001010 4, // 1001011 3, // 1001100 4, // 1001101 4, // 1001110 5, // 1001111 2, // 1010000 3, // 1010001 3, // 1010010 4, // 1010011 3, // 1010100 4, // 1010101 4, // 1010110 5, // 1010111 3, // 1011000 4, // 1011001 4, // 1011010 5, // 1011011 4, // 1011100 5, // 1011101 5, // 1011110 6, // 1011111 2, // 1100000 3, // 1100001 3, // 1100010 4, // 1100011 3, // 1100100 4, // 1100101 4, // 1100110 5, // 1100111 3, // 1101000 4, // 1101001 4, // 1101010 5, // 1101011 4, // 1101100 5, // 1101101 5, // 1101110 6, // 1101111 3, // 1110000 4, // 1110001 4, // 1110010 5, // 1110011 4, // 1110100 5, // 1110101 5, // 1110110 6, // 1110111 4, // 1111000 5, // 1111001 5, // 1111010 6, // 1111011 5, // 1111100 6, // 1111101 6, // 1111110 7, // 1111111 1, // 10000000 2, // 10000001 2, // 10000010 3, // 10000011 2, // 10000100 3, // 10000101 3, // 10000110 4, // 10000111 2, // 10001000 3, // 10001001 3, // 10001010 4, // 10001011 3, // 10001100 4, // 10001101 4, // 10001110 5, // 10001111 2, // 10010000 3, // 10010001 3, // 10010010 4, // 10010011 3, // 10010100 4, // 10010101 4, // 10010110 5, // 10010111 3, // 10011000 4, // 10011001 4, // 10011010 5, // 10011011 4, // 10011100 5, // 10011101 5, // 10011110 6, // 10011111 2, // 10100000 3, // 10100001 3, // 10100010 4, // 10100011 3, // 10100100 4, // 10100101 4, // 10100110 5, // 10100111 3, // 10101000 4, // 10101001 4, // 10101010 5, // 10101011 4, // 10101100 5, // 10101101 5, // 10101110 6, // 10101111 3, // 10110000 4, // 10110001 4, // 10110010 5, // 10110011 4, // 10110100 5, // 10110101 5, // 10110110 6, // 10110111 4, // 10111000 5, // 10111001 5, // 10111010 6, // 10111011 5, // 10111100 6, // 10111101 6, // 10111110 7, // 10111111 2, // 11000000 3, // 11000001 3, // 11000010 4, // 11000011 3, // 11000100 4, // 11000101 4, // 11000110 5, // 11000111 3, // 11001000 4, // 11001001 4, // 11001010 5, // 11001011 4, // 11001100 5, // 11001101 5, // 11001110 6, // 11001111 3, // 11010000 4, // 11010001 4, // 11010010 5, // 11010011 4, // 11010100 5, // 11010101 5, // 11010110 6, // 11010111 4, // 11011000 5, // 11011001 5, // 11011010 6, // 11011011 5, // 11011100 6, // 11011101 6, // 11011110 7, // 11011111 3, // 11100000 4, // 11100001 4, // 11100010 5, // 11100011 4, // 11100100 5, // 11100101 5, // 11100110 6, // 11100111 4, // 11101000 5, // 11101001 5, // 11101010 6, // 11101011 5, // 11101100 6, // 11101101 6, // 11101110 7, // 11101111 4, // 11110000 5, // 11110001 5, // 11110010 6, // 11110011 5, // 11110100 6, // 11110101 6, // 11110110 7, // 11110111 5, // 11111000 6, // 11111001 6, // 11111010 7, // 11111011 6, // 11111100 7, // 11111101 7, // 11111110 8, // 11111111 }; unsigned long long popcount_naive(unsigned size, uint16_t* data) { unsigned long long acc = 0; for (unsigned i = 0; i < size; ++i) { uint16_t num = data[i]; while (num) { // Naive approach: Get the last bit and shift the number acc += num & 1; num = num >> 1; } } return acc; } unsigned long long popcount_lookup_table(unsigned size, uint8_t* data) { unsigned long long acc = 0; for (unsigned i = 0; i < size; ++i) // Look it up! acc += bits[data[i]]; return acc; } unsigned long long popcount_builtin(unsigned size, uint64_t* data) { unsigned long long acc = 0; for (unsigned i = 0; i < size; ++i) // https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html // This is really fast if your CPU has a dedicated instruction (and it should) acc += __builtin_popcountll(data[i]); return acc; } // Usage: // ./count_set_bits_lookup_table <amount of random numbers>, e.g: // ./count_set_bits_lookup_table 2017 // -> Naive approach: 7962 in 107μs // -> Lookup table: 7962 in 20μs // -> GCC builtin: 7962 in 5μs int main(int argc, char* argv[]) { if (argc < 2) return -1; unsigned amount; std::stringstream ss; ss << argv[1]; ss >> amount; // we want length divisible by 4 unsigned length = amount + (-amount) % 4; uint16_t* numbers = new uint16_t[length]; std::default_random_engine generator; std::uniform_int_distribution<uint16_t> dist(0, 255); for (unsigned n = 0; n < amount; ++n) numbers[n] = dist(generator); // pad with zeros for (unsigned n = amount; n < length; ++n) numbers[n] = 0; unsigned long long count; std::chrono::high_resolution_clock a_clock; auto start = a_clock.now(); count = popcount_naive(amount, numbers); auto end = a_clock.now(); std::cout << "Naive approach: " << count << " in " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << "μs" << std::endl; start = a_clock.now(); count = popcount_lookup_table(2 * amount, (uint8_t*)(numbers)); end = a_clock.now(); std::cout << "Lookup table: " << count << " in " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << "μs" << std::endl; start = a_clock.now(); count = popcount_builtin(length / 4, (uint64_t*)(numbers)); end = a_clock.now(); std::cout << "GCC builtin: " << count << " in " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << "μs" << std::endl; }
7,545
C++
.cpp
343
16.965015
93
0.524042
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
10,282
brian_kernighan_algorithm.cpp
OpenGenus_cosmos/code/bit_manipulation/src/count_set_bits/brian_kernighan_algo/brian_kernighan_algorithm.cpp
//Brian Kernighan’s Algorithm. This programme uses O(logn) to count set bits. #include <iostream> int countSetBits(int n) { // base case if (n == 0) { return 0; } else { // if last bit is set, add 1 else add 0 return (n & 1) + countSetBits(n >> 1); } } int main() { int n; std::cout << "Enter a positive integer : "; std::cin >> n; std::cout << countSetBits(n); return 0; }
413
C++
.cpp
23
15.347826
79
0.620779
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,283
twice_unique_number.cpp
OpenGenus_cosmos/code/bit_manipulation/src/twice_unique_number/twice_unique_number.cpp
#include <iostream> using namespace std; //Part of Cosmos by OpenGenus Foundation void findUnique2(int *a, int n) { int res = 0; for (int i = 0; i < n; i++) res = res ^ a[i]; // find the rightmost set bit in res int i = 0; int temp = res; while (temp > 0) { if (temp & 1) break; i++; temp = temp >> 1; } int mask = (1 << i); int firstNo = 0; for (int i = 0; i < n; i++) if ((mask & a[i]) != 0) firstNo = firstNo ^ a[i]; int secondNo = res ^ firstNo; cout << firstNo << endl; cout << secondNo << endl; } int main() { int n; int a[] = {1, 3, 5, 6, 3, 2, 1, 2}; n = sizeof(a) / sizeof(int); findUnique2(a, n); return 0; }
768
C++
.cpp
35
16.685714
40
0.491713
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,286
bit_division.cpp
OpenGenus_cosmos/code/bit_manipulation/src/bit_division/bit_division.cpp
/* Problem Statement : Divide two numbers using bitwise operators (i.e without using arithmetic operators) */ #include <iostream> using namespace std; int bitDivision(int numerator, int denominator) { int current = 1; int answer = 0; if (denominator > numerator) return 0; else if (denominator == numerator) return 1; while (denominator < numerator) { denominator <<= 1; current <<= 1; } denominator >>= 1; current >>= 1; while (current != 0) { if (numerator >= denominator) { numerator -= denominator; answer |= current; } current >>= 1; denominator >>= 1; } return answer; } int main() { int numerator, denominator; // numerator -> represents dividend // denominator -> represents divisor cout << "Enter numerator and denominator : "; cin >> numerator >> denominator; cout << "\nQuotient after bitwise division : " << bitDivision(numerator, denominator) << endl; return 0; } /* Enter numerator and denominator : 10 4 Quotient after bitwise division : 2 */
1,154
C++
.cpp
48
18.958333
98
0.623626
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,288
worst_fit.cpp
OpenGenus_cosmos/code/operating_system/src/memory_management/partitioned_allocation/worst_fit.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> #include <queue> #include <unistd.h> class process { public: size_t size; pid_t id; }; class memory { public: size_t size; pid_t id; std::queue<process> allocated_processess; void push(const process p) { if(p.size <= size) { allocated_processess.push(p); size -= p.size; } } process pop(){ if(!allocated_processess.empty()) { process process_to_pop = allocated_processess.front(); allocated_processess.pop(); size += process_to_pop.size; return process_to_pop; } } bool empty() { return allocated_processess.empty(); } }; std::vector<memory> worst_fit(std::vector<memory>memory_blocks, std::queue<process>unallocated_processess) { memory nonAllocatedProcessess; nonAllocatedProcessess.id = -1; nonAllocatedProcessess.size = 0; while(!unallocated_processess.empty()) { int candidate_best_index = 0; bool is_process_allocated = false; for(int i = 0; i < memory_blocks.size(); ++i) { if(memory_blocks.at(i).size > unallocated_processess.front().size) { candidate_best_index = (candidate_best_index == -1)? i : (memory_blocks.at(i).size > memory_blocks.at(candidate_best_index).size)? i : candidate_best_index; is_process_allocated = true; } } if(is_process_allocated) { memory_blocks.at(candidate_best_index).push(unallocated_processess.front()); unallocated_processess.pop(); } else { nonAllocatedProcessess.size += unallocated_processess.front().size; nonAllocatedProcessess.push(unallocated_processess.front()); unallocated_processess.pop(); } } if(!nonAllocatedProcessess.empty()) { memory_blocks.push_back(nonAllocatedProcessess); } return memory_blocks; } void display(std::vector<memory> memory_blocks) { int i = 0, temp = 0; process p; std::cout << "+-------------+--------------+--------------+" << std::endl; std::cout << "| Process Id | Process size | Memory block |" << std::endl; std::cout << "+-------------+--------------+--------------+" << std::endl; // Traverse memory blocks size for (i = 0; i < memory_blocks.size(); i++) { // While memory block size is not empty while (!memory_blocks.at(i).empty()) { p = memory_blocks.at(i).pop(); temp = std::to_string(p.id).length(); std::cout << "|" << std::string(7 - temp / 2 - temp % 2, ' ') << p.id << std::string(6 - temp / 2, ' ') << "|"; temp = std::to_string(p.size).length(); std::cout << std::string(7 - temp / 2 - temp % 2, ' ') << p.size << std::string(7 - temp / 2, ' ') << "|"; temp = std::to_string(memory_blocks.at(i).id).length(); std::cout << std::string(7 - temp / 2 - temp % 2, ' '); // If memory blocks is assigned if (memory_blocks.at(i).id != -1) { std::cout << memory_blocks.at(i).id; } // Else memory blocks is assigned else { std::cout << "N/A"; } std::cout << std::string(7 - temp / 2, ' ') << "|" << std::endl; } } std::cout << "+-------------+--------------+--------------+" << std::endl; } int main() { std::vector<memory> memory_blocks(5); std::vector<memory> worst_fit_blocks; std::queue<process> processess; process temp; memory_blocks[0].id = 1; memory_blocks[0].size = 400; memory_blocks[1].id = 2; memory_blocks[1].size = 500; memory_blocks[2].id = 3; memory_blocks[2].size = 300; memory_blocks[3].id = 4; memory_blocks[3].size = 200; memory_blocks[4].id = 5; memory_blocks[4].size = 100; temp.id = 1; temp.size = 88; processess.push(temp); temp.id = 2; temp.size = 192; processess.push(temp); temp.id = 3; temp.size = 277; processess.push(temp); temp.id = 4; temp.size = 365; processess.push(temp); temp.id = 5; temp.size = 489; processess.push(temp); worst_fit_blocks = worst_fit(memory_blocks, processess); display(worst_fit_blocks); memory_blocks.clear(); memory_blocks.shrink_to_fit(); worst_fit_blocks.clear(); worst_fit_blocks.shrink_to_fit(); return 0; }
4,841
C++
.cpp
143
25.153846
138
0.526896
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,289
next_fit.cpp
OpenGenus_cosmos/code/operating_system/src/memory_management/partitioned_allocation/next_fit.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> #include <queue> #include <unistd.h> class process { public: size_t size; pid_t id; }; class memory { public: size_t size; pid_t id; std::queue<process> allocated_processess; void push(const process p) { if(p.size <= size) { allocated_processess.push(p); size -= p.size; } } process pop(){ if(!allocated_processess.empty()) { process process_to_pop = allocated_processess.front(); allocated_processess.pop(); size += process_to_pop.size; return process_to_pop; } } bool empty() { return allocated_processess.empty(); } }; std::vector<memory> next_fit(std::vector<memory>memory_blocks, std::queue<process>unallocated_processess) { memory nonAllocatedProcessess; nonAllocatedProcessess.id = -1; nonAllocatedProcessess.size = 0; while(!unallocated_processess.empty()) { int temp_p_id = unallocated_processess.front().id; for(int i = 0; i < memory_blocks.size(); i = ((i+1)%memory_blocks.size())) { //this modules needed to shift memory blocks to the beggnings after iterating till the its end. if(memory_blocks.at(i).size >= unallocated_processess.front().size) { memory_blocks.at(i).push(unallocated_processess.front()); unallocated_processess.pop(); break; } } if(temp_p_id == unallocated_processess.front().id) { nonAllocatedProcessess.size += unallocated_processess.front().size; nonAllocatedProcessess.push(unallocated_processess.front()); unallocated_processess.pop(); } } if(!nonAllocatedProcessess.empty()) { memory_blocks.push_back(nonAllocatedProcessess); } return memory_blocks; } void display(std::vector<memory> memory_blocks) { int i = 0, temp = 0; process p; std::cout << "+-------------+--------------+--------------+" << std::endl; std::cout << "| Process Id | Process size | Memory block |" << std::endl; std::cout << "+-------------+--------------+--------------+" << std::endl; // Traverse memory blocks size for (i = 0; i < memory_blocks.size(); i++) { // While memory block size is not empty while (!memory_blocks.at(i).empty()) { p = memory_blocks.at(i).pop(); temp = std::to_string(p.id).length(); std::cout << "|" << std::string(7 - temp / 2 - temp % 2, ' ') << p.id << std::string(6 - temp / 2, ' ') << "|"; temp = std::to_string(p.size).length(); std::cout << std::string(7 - temp / 2 - temp % 2, ' ') << p.size << std::string(7 - temp / 2, ' ') << "|"; temp = std::to_string(memory_blocks.at(i).id).length(); std::cout << std::string(7 - temp / 2 - temp % 2, ' '); // If memory blocks is assigned if (memory_blocks.at(i).id != -1) { std::cout << memory_blocks.at(i).id; } // Else memory blocks is assigned else { std::cout << "N/A"; } std::cout << std::string(7 - temp / 2, ' ') << "|" << std::endl; } } std::cout << "+-------------+--------------+--------------+" << std::endl; } int main() { std::vector<memory> memory_blocks(5); std::vector<memory> next_fit_blocks; std::queue<process> processess; process temp; memory_blocks[0].id = 1; memory_blocks[0].size = 400; memory_blocks[1].id = 2; memory_blocks[1].size = 500; memory_blocks[2].id = 3; memory_blocks[2].size = 300; memory_blocks[3].id = 4; memory_blocks[3].size = 200; memory_blocks[4].id = 5; memory_blocks[4].size = 100; temp.id = 1; temp.size = 88; processess.push(temp); temp.id = 2; temp.size = 192; processess.push(temp); temp.id = 3; temp.size = 277; processess.push(temp); temp.id = 4; temp.size = 365; processess.push(temp); temp.id = 5; temp.size = 489; processess.push(temp); next_fit_blocks = next_fit(memory_blocks, processess); display(next_fit_blocks); memory_blocks.clear(); memory_blocks.shrink_to_fit(); next_fit_blocks.clear(); next_fit_blocks.shrink_to_fit(); return 0; }
4,694
C++
.cpp
138
25.550725
180
0.53109
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,290
best_fit.cpp
OpenGenus_cosmos/code/operating_system/src/memory_management/partitioned_allocation/best_fit.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> #include <queue> #include <unistd.h> class process { public: size_t size; pid_t id; }; class memory { public: size_t size; pid_t id; std::queue<process> allocated_processess; void push(const process p) { if(p.size <= size) { allocated_processess.push(p); size -= p.size; } } process pop(){ if(!allocated_processess.empty()) { process process_to_pop = allocated_processess.front(); allocated_processess.pop(); size += process_to_pop.size; return process_to_pop; } } bool empty() { return allocated_processess.empty(); } }; std::vector<memory> best_fit(std::vector<memory>memory_blocks, std::queue<process>unallocated_processess) { memory nonAllocatedProcessess; nonAllocatedProcessess.id = -1; nonAllocatedProcessess.size = 0; while(!unallocated_processess.empty()) { int candidate_best_index = 0; bool is_process_allocated = false; for(int i = 0; i < memory_blocks.size(); ++i) { if(memory_blocks.at(i).size == unallocated_processess.front().size) { candidate_best_index = i; is_process_allocated = true; break; } if(memory_blocks.at(i).size > unallocated_processess.front().size) { candidate_best_index = (candidate_best_index == -1)? i : (memory_blocks.at(i).size < memory_blocks.at(candidate_best_index).size)? i : candidate_best_index; is_process_allocated = true; } } if(is_process_allocated) { memory_blocks.at(candidate_best_index).push(unallocated_processess.front()); unallocated_processess.pop(); } else { nonAllocatedProcessess.size += unallocated_processess.front().size; nonAllocatedProcessess.push(unallocated_processess.front()); unallocated_processess.pop(); } } if(!nonAllocatedProcessess.empty()) { memory_blocks.push_back(nonAllocatedProcessess); } return memory_blocks; } void display(std::vector<memory> memory_blocks) { int i = 0, temp = 0; process p; std::cout << "+-------------+--------------+--------------+" << std::endl; std::cout << "| Process Id | Process size | Memory block |" << std::endl; std::cout << "+-------------+--------------+--------------+" << std::endl; // Traverse memory blocks size for (i = 0; i < memory_blocks.size(); i++) { // While memory block size is not empty while (!memory_blocks.at(i).empty()) { p = memory_blocks.at(i).pop(); temp = std::to_string(p.id).length(); std::cout << "|" << std::string(7 - temp / 2 - temp % 2, ' ') << p.id << std::string(6 - temp / 2, ' ') << "|"; temp = std::to_string(p.size).length(); std::cout << std::string(7 - temp / 2 - temp % 2, ' ') << p.size << std::string(7 - temp / 2, ' ') << "|"; temp = std::to_string(memory_blocks.at(i).id).length(); std::cout << std::string(7 - temp / 2 - temp % 2, ' '); // If memory blocks is assigned if (memory_blocks.at(i).id != -1) { std::cout << memory_blocks.at(i).id; } // Else memory blocks is assigned else { std::cout << "N/A"; } std::cout << std::string(7 - temp / 2, ' ') << "|" << std::endl; } } std::cout << "+-------------+--------------+--------------+" << std::endl; } int main() { std::vector<memory> memory_blocks(5); std::vector<memory> best_fit_blocks; std::queue<process> processess; process temp; memory_blocks[0].id = 1; memory_blocks[0].size = 400; memory_blocks[1].id = 2; memory_blocks[1].size = 500; memory_blocks[2].id = 3; memory_blocks[2].size = 300; memory_blocks[3].id = 4; memory_blocks[3].size = 200; memory_blocks[4].id = 5; memory_blocks[4].size = 100; temp.id = 1; temp.size = 88; processess.push(temp); temp.id = 2; temp.size = 192; processess.push(temp); temp.id = 3; temp.size = 277; processess.push(temp); temp.id = 4; temp.size = 365; processess.push(temp); temp.id = 5; temp.size = 489; processess.push(temp); best_fit_blocks = best_fit(memory_blocks, processess); display(best_fit_blocks); memory_blocks.clear(); memory_blocks.shrink_to_fit(); best_fit_blocks.clear(); best_fit_blocks.shrink_to_fit(); return 0; }
5,040
C++
.cpp
148
25.128378
138
0.524362
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,291
first_fit.cpp
OpenGenus_cosmos/code/operating_system/src/memory_management/partitioned_allocation/first_fit.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> #include <queue> #include <unistd.h> class process { public: size_t size; pid_t id; }; class memory { public: size_t size; pid_t id; std::queue<process> allocated_processess; void push(const process p) { if(p.size <= size) { allocated_processess.push(p); size -= p.size; } } process pop(){ if(!allocated_processess.empty()) { process process_to_pop = allocated_processess.front(); allocated_processess.pop(); size += process_to_pop.size; return process_to_pop; } } bool empty() { return allocated_processess.empty(); } }; std::vector<memory> first_fit(std::vector<memory>memory_blocks, std::queue<process>unallocated_processess) { memory nonAllocatedProcessess; nonAllocatedProcessess.id = -1; nonAllocatedProcessess.size = 0; while(!unallocated_processess.empty()) { int temp_p_id = unallocated_processess.front().id; for(int i = 0; i < memory_blocks.size(); ++i) { if(memory_blocks.at(i).size >= unallocated_processess.front().size) { memory_blocks.at(i).push(unallocated_processess.front()); unallocated_processess.pop(); break; } } if(temp_p_id == unallocated_processess.front().id) { nonAllocatedProcessess.size += unallocated_processess.front().size; nonAllocatedProcessess.push(unallocated_processess.front()); unallocated_processess.pop(); } } if(!nonAllocatedProcessess.empty()) { memory_blocks.push_back(nonAllocatedProcessess); } return memory_blocks; } void display(std::vector<memory> memory_blocks) { int i = 0, temp = 0; process p; std::cout << "+-------------+--------------+--------------+" << std::endl; std::cout << "| Process Id | Process size | Memory block |" << std::endl; std::cout << "+-------------+--------------+--------------+" << std::endl; // Traverse memory blocks size for (i = 0; i < memory_blocks.size(); i++) { // While memory block size is not empty while (!memory_blocks.at(i).empty()) { p = memory_blocks.at(i).pop(); temp = std::to_string(p.id).length(); std::cout << "|" << std::string(7 - temp / 2 - temp % 2, ' ') << p.id << std::string(6 - temp / 2, ' ') << "|"; temp = std::to_string(p.size).length(); std::cout << std::string(7 - temp / 2 - temp % 2, ' ') << p.size << std::string(7 - temp / 2, ' ') << "|"; temp = std::to_string(memory_blocks.at(i).id).length(); std::cout << std::string(7 - temp / 2 - temp % 2, ' '); // If memory blocks is assigned if (memory_blocks.at(i).id != -1) { std::cout << memory_blocks.at(i).id; } // Else memory blocks is assigned else { std::cout << "N/A"; } std::cout << std::string(7 - temp / 2, ' ') << "|" << std::endl; } } std::cout << "+-------------+--------------+--------------+" << std::endl; } int main() { std::vector<memory> memory_blocks(5); std::vector<memory> first_fit_blocks; std::queue<process> processess; process temp; memory_blocks[0].id = 1; memory_blocks[0].size = 400; memory_blocks[1].id = 2; memory_blocks[1].size = 500; memory_blocks[2].id = 3; memory_blocks[2].size = 300; memory_blocks[3].id = 4; memory_blocks[3].size = 200; memory_blocks[4].id = 5; memory_blocks[4].size = 100; temp.id = 1; temp.size = 88; processess.push(temp); temp.id = 2; temp.size = 192; processess.push(temp); temp.id = 3; temp.size = 277; processess.push(temp); temp.id = 4; temp.size = 365; processess.push(temp); temp.id = 5; temp.size = 489; processess.push(temp); first_fit_blocks = first_fit(memory_blocks, processess); display(first_fit_blocks); memory_blocks.clear(); memory_blocks.shrink_to_fit(); first_fit_blocks.clear(); first_fit_blocks.shrink_to_fit(); return 0; }
4,576
C++
.cpp
138
24.695652
108
0.525292
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,292
lru.cpp
OpenGenus_cosmos/code/operating_system/src/memory_management/least_recently_used/lru.cpp
/* Least Recently Used Page Replacement Algorithm implemented using a stack */ #include <bits/stdc++.h> using namespace std; /* A function that finds and returns the index of the current page in the page table If it is not present it would return -1 */ int find(int current_page,vector<int>& page_table){ for(int i=0;i<page_table.size();i++) if(page_table[i]==current_page) return i; return -1; } int main(){ int frames,pages,page_fault=0,page_hit=0; cout<<"Enter the number of Frames"<<endl; cin>>frames; cout<<"Enter the number of Page numbers in memory references"<<"\nNote : The page number has to be non - negative "<<endl; cin>>pages; vector<int>page_numbers(pages,-1); // Stores the sequence of page numbers given as I/P by the user // Note : The page number has to be non - negative cout<<"Enter the sequence of memory references i.e page numbers"<<endl; // Storing the sequence of page numbers for(int i=0;i<pages;i++){ cin>>page_numbers[i]; } // Initialising the storage matrix int matrix[frames][pages]; // A storage matrix, that we will use to visualise the LRU algorithm and the stack for(int i=0;i<frames;i++){ for(int j=0;j<pages;j++) matrix[i][j] = 0; } vector<int>page_table(frames,-1); // page_table is the stack that is used for LRU Page Replacement // Note I'm using -1 as my reference to indicate that the frame is empty /* Loops through each page number from the sequence given by user and implements demand paging i.e replaces Least Recently Used (LRU) page for this page if there is a shortage of pages, else would add the page to the stack i.e allot a frame */ for(int i=0;i<pages;i++){ int index_of_current_page; // The index of the page if present,else -1 int current_page = page_numbers[i]; index_of_current_page = find(current_page,page_table); // If current page is not there in the page table i.e a page fault if(index_of_current_page ==-1){ page_fault++; page_table.erase(page_table.begin()); // Erase the LRU Page i.e the bottom of the stack } // The current page is already present in the page table i.e page hit else{ page_hit++; page_table.erase(page_table.begin() + index_of_current_page); } /* Update the page to the top of the stack -> this is indepent of page fault or page hit Because the top of the stack contains the Most Recently used page and bottom of the stack hold the Least Recently used page */ page_table.push_back(current_page); // Storing the snapshot of the present page table in the matrix for(int j=0;j<frames;j++) matrix[j][i] = page_table[frames-j-1]; } cout<<"\n \n"; // Displaying all the snapshots of the page table taken for each time unit i.e page hit or page fault for(int i=0;i<frames;i++){ if(i==frames-1) cout<<"LRU Page ->"<<" "; else cout<<" "; for(int j=0;j<pages;j++){ printf("%2d ",matrix[i][j]); } cout<<endl; } float page_hit_ratio = page_hit; page_hit_ratio = page_hit_ratio/pages; float page_fault_ratio = page_fault; page_fault_ratio = page_fault_ratio/pages; cout<<"Page Hit ratio : "<<page_hit_ratio<<endl; cout<<"Page Fault ratio : "<<page_fault_ratio<<endl; cout<<"Note I'm using -1 as my reference to indicate that the frame is empty"<<endl; return 0; } // Note I'm using -1 as my reference to indicate that the frame is empty in the page table and it would reflect in the output also /* Example : I/P : Frames : 3, Number of pages in sequence : 20 Memory reference sequence of page numbers : 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1 O/P : 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1 -1 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 LRU Page -> -1 -1 7 0 1 2 2 3 0 4 2 2 0 3 3 1 2 0 1 7 Page Hit ratio : 0.4 Page Fault ratio : 0.6 */
4,221
C++
.cpp
99
36.070707
130
0.625307
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
10,293
shortest_seek_time_first.cpp
OpenGenus_cosmos/code/operating_system/src/scheduling/shortest_seek_time_first/shortest_seek_time_first.cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int n; cout << "Enter number of process: "; cin >> n; vector<int> burstTime(n); // Array of burst times of processes cout << "Enter Burst time: \n"; for (int i = 0; i < n; i++) { cout << "Process[" << i + 1 << "]: "; cin >> burstTime[i]; } sort(burstTime.begin(), burstTime.end()); // Sort the burst times vector<int> waitingTime(n); int total = 0; for (int i = 1; i < n; i++) { waitingTime[i] = 0; for (int j = 0; j < i; j++) waitingTime[i] += burstTime[j]; total += waitingTime[i]; } // Average waiting time = Total waiting time / no of processes int averageWaitingTime = (float)total / n; total = 0; vector<int> turnAroundTime(n); cout << "\nProcess\t Burst Time \tWaiting Time\tTurnaround Time"; for (int i = 0; i < n; i++) { turnAroundTime[i] = burstTime[i] + waitingTime[i]; //Calculating Turnaround Time total += turnAroundTime[i]; cout << "\np" << i + 1 << "\t\t" << burstTime[i] << "\t\t" << waitingTime[i] << "\t\t" << turnAroundTime[i]; } // Average Turnaround Time = total turn around time / no of processes int averageTurnAroundTime = (float)total / n; cout << "\nAverage Waiting Time: " << averageWaitingTime << "\n"; cout << "Average Turnaround Time: " << averageTurnAroundTime << "\n"; return 0; }
1,513
C++
.cpp
44
28.863636
97
0.572988
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,294
job_sequencing.cpp
OpenGenus_cosmos/code/operating_system/src/scheduling/job_sequencing/job_sequencing.cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct Job { char id; int deadline; int profit; }; bool jobComparator(const Job &a, const Job &b) { return a.profit > b.profit; } void jobSequence(vector<Job> &jobs) { int n = jobs.size(); sort(jobs.begin(), jobs.end(), jobComparator); int maxDeadline = 0; for (const Job &job : jobs) { maxDeadline = max(maxDeadline, job.deadline); } vector<bool> slot(maxDeadline, false); vector<char> sequence; int totalProfit = 0; for (const Job &job : jobs) { for (int i = min(maxDeadline - 1, job.deadline - 1); i >= 0; i--) { if (!slot[i]) { slot[i] = true; sequence.push_back(job.id); totalProfit += job.profit; break; } } } cout << "Job sequence: "; for (char jobId : sequence) { cout << jobId << " "; } cout << "\nTotal profit: " << totalProfit << endl; } int main() { vector<Job> jobs = { {'a', 2, 100}, {'b', 1, 19}, {'c', 2, 27}, {'d', 1, 25}, {'e', 3, 15} }; jobSequence(jobs); return 0; }
1,260
C++
.cpp
49
18.734694
75
0.524014
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,295
round_robin_scheduling.cpp
OpenGenus_cosmos/code/operating_system/src/scheduling/round_robin_scheduling/round_robin_scheduling.cpp
#include <iostream> #include <vector> using namespace std; int main() { int flag = 0, timeQuantum; int n, remain; int waitTime = 0; cout << "Enter Total Process:\n"; cin >> n; remain = n; vector<int> arrivalTime(n); vector<int> burstTime(n); vector<int> remainingTime(n); for (int i = 0; i < n; i++) { cout << "Enter Arrival Time and Burst Time for Process\n"; cin >> arrivalTime[i]; cin >> burstTime[i]; remainingTime[i] = burstTime[i]; } cout << "Enter Time Quantum:\n"; cin >> timeQuantum; int turnaroundTime; for (int time = 0, count = 0; remain != 0;) { if (remainingTime[count] <= timeQuantum && remainingTime[count] > 0) { time += remainingTime[count]; remainingTime[count] = 0; flag = 1; } else if (remainingTime[count] > 0) { remainingTime[count] -= timeQuantum; time += timeQuantum; } if (remainingTime[count] == 0 && flag == 1) { remain--; waitTime += time - arrivalTime[count] - burstTime[count]; turnaroundTime += time - arrivalTime[count]; flag = 0; } if (count == n - 1) count = 0; else if (arrivalTime[count + 1] <= time) count++; else count = 0; } cout << "\nAverage Waiting Time is " << waitTime * 1.0 / n; cout << "\nAvg Turnaround Time is " << turnaroundTime * 1.0 / n << "\n"; return 0; }
1,568
C++
.cpp
55
21
76
0.523494
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,298
banker_safety.cpp
OpenGenus_cosmos/code/operating_system/src/deadlocks/bankers_algorithm/banker_safety.cpp
// Part of Cosmos by OpenGenus Foundation. // Banker's Algorithm: Safety Algorithm #include <cstdio> int main() { // Initialize int available[10], allocation [10][10], maximum[10][10]; int noOfProcesses, noOfResources, need[10][10]; int work[10], finish[10] = {0}, i; //Inputs printf("Enter no. of processes ... "); scanf("%d", &noOfProcesses ); printf("Enter no. of resources available ... "); scanf("%d", &noOfResources); printf("Enter instances ...\n"); for (i = 0; i < noOfResources; i++) { printf("Resource %d: ", i + 1); scanf("%d", &available[i]); //Initializing Work work[i] = available[i]; } printf("Enter allocation array ... \n"); for (i = 0; i < noOfProcesses; i++) for (int j = 0; j < noOfResources; j++) scanf("%d", &allocation[i][j]); printf("Enter maximum array ... \n"); for (i = 0; i < noOfProcesses; i++) for (int j = 0; j < noOfResources; j++) scanf("%d", &maximum[i][j]); printf("Need matrix is ... \n"); for (i = 0; i < noOfProcesses; i++) { for (int j = 0; j < noOfResources; j++) { need[i][j] = maximum[i][j] - allocation[i][j]; printf("%d ", need[i][j]); } printf("\n"); } // Safety Algorithm int processesNotCompleted = noOfProcesses; int cp = 0, op[10]; while (processesNotCompleted) { int aProcessCompleted = 0; for (int x = 0; x < noOfProcesses; x++) //Check if process is yet to finish if (!finish[x]) { int possible = 1; for (int y = 0; y < noOfResources; y++) if (need[x][y] > work[y]) possible = 0; // and if it's possible to complete a process if (possible) { printf("Work after executing process %d : ", x); for (int y = 0; y < noOfResources; y++) { work[y] += allocation[x][y]; printf("%d ", work[y]); } printf("\n"); finish[x] = 1; op[cp++] = x; processesNotCompleted--; aProcessCompleted = 1; } } // if it's not possible to complete a proceess if (!aProcessCompleted) break; } // if all proccesses not completed if (processesNotCompleted) printf("Safe sequence not possible !"); // else if all processes completed else { printf("Safe Sequence is : "); for (i = 0; i < cp; i++) printf("P%d ", op[i]); } return 0; }
2,916
C++
.cpp
86
22.860465
69
0.463371
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,300
producer_consumer.cpp
OpenGenus_cosmos/code/operating_system/src/concurrency/producer_consumer/producer_consumer.cpp
#include <iostream> #include <ctime> #include <cstdlib> #include <thread> #include <mutex> #include <vector> #include <condition_variable> const int N = 100; std::vector<int> shared_buffer(N); std::mutex lock_buffer; std::condition_variable cond; void producer() { while (true) { std::unique_lock<std::mutex> guard_producer(lock_buffer); if (shared_buffer.size() == N) cond.wait(guard_producer); int item_produced = rand() % 100 + 1; // ranges 1 to 100 shared_buffer.push_back(item_produced); if (shared_buffer.size() == 1) cond.notify_one(); std::cout << "Item " << item_produced << " was inserted into the buffer" << std::endl; } } void consumer() { while (true) { std::unique_lock<std::mutex> guard_consumer(lock_buffer); if (shared_buffer.empty()) cond.wait(guard_consumer); int item_consumed = shared_buffer.back(); // gets item shared_buffer.pop_back(); // removes item if (shared_buffer.size() == N - 1) cond.notify_one(); std::cout << "Item " << item_consumed << " was removed from the buffer" << std::endl; } } int main() { srand (time(0)); std::thread t_consumer(producer); std::thread t_producer(consumer); t_consumer.join(); t_producer.join(); return 0; }
1,406
C++
.cpp
50
22.36
66
0.59584
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,301
test_subset_sum.cpp
OpenGenus_cosmos/code/dynamic_programming/test/subset_sum/test_subset_sum.cpp
/* Part of Cosmos by OpenGenus Foundation */ #ifndef SUBSET_SUM_TEST #define SUBSET_SUM_TEST #include <iostream> #include <list> #include <cassert> #include "../../src/subset_sum/subset_sum.cpp" int main() { using namespace std; int vz[0]; int v[] = {1, 2, 15, 8, 5}; list<int> l{1, 2, 15, 8, 5}; assert(isSubsetSum(vz, vz, 0)); assert(isSubsetSum(v, v + sizeof(v) / sizeof(v[0]), 13)); assert(isSubsetSum(l.begin(), l.end(), 13)); assert(isSubsetSum(vz, vz, 13) == false); assert(isSubsetSum(v, v + sizeof(v) / sizeof(v[0]), 4) == false); assert(isSubsetSum(l.begin(), l.end(), 4) == false); return 0; } #endif // SUBSET_SUM_TEST
682
C++
.cpp
23
26.434783
69
0.627301
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,302
longest_repeating_subsequence_test.cpp
OpenGenus_cosmos/code/dynamic_programming/test/longest_repeating_subsequence/longest_repeating_subsequence_test.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <string> #include <cassert> #include "../../src/longest_repeating_subsequence/longest_repeating_subsequence.cpp" int main() { using namespace std; std::string s1 = "aab"; assert(longestRepeatingSubsequence(s1) == 1); }
308
C++
.cpp
11
25.636364
84
0.734694
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,307
longest_palindromic_substring.cpp
OpenGenus_cosmos/code/dynamic_programming/src/longest_palindromic_substring/longest_palindromic_substring.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <string> using namespace std; int longestPalSubstr(string str) { int n = str.size(); bool ispal[n][n]; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) ispal[i][j] = false; // All substrings of length 1 are palindromes int maxLength = 1; for (int i = 0; i < n; ++i) ispal[i][i] = true; // check for sub-string of length 2. for (int i = 0; i < n - 1; ++i) if (str[i] == str[i + 1]) { ispal[i][i + 1] = true; maxLength = 2; } // Check for lengths greater than 2. k is length // of substring for (int k = 3; k <= n; ++k) for (int i = 0; i < n - k + 1; ++i) { // Get the ending index of substring from // starting index i and length k int j = i + k - 1; if (ispal[i + 1][j - 1] && str[i] == str[j]) { ispal[i][j] = true; if (k > maxLength) maxLength = k; } } return maxLength; } int main() { string str = "hacktoberfestsefrisawesome"; cout << "Length of longest palindromic substring is " << longestPalSubstr(str); return 0; }
1,298
C++
.cpp
45
21.311111
83
0.493966
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,308
friends_pairing.cpp
OpenGenus_cosmos/code/dynamic_programming/src/friends_pairing/friends_pairing.cpp
// Dynamic Programming solution to friends pairing problem in C++ // Contributed by Santosh Vasisht // Given n friends, each one can remain single or can be paired up with some other friend. // Each friend can be paired only once. // Find out the total number of ways in which friends can remain single or can be paired up. #include <bits/stdc++.h> using namespace std; int countFriendsPairings(int n) { int table[n+1]; // Filling the table recursively in bottom-up manner for(int i = 0; i <= n; ++i) { if(i <= 2) table[i] = i; else table[i] = table[i-1] + (i-1) * table[i-2]; } return table[n]; } // Driver code int main() { int n = 7; cout << countFriendsPairings(n) << endl; return 0; }
807
C++
.cpp
27
24.555556
93
0.624837
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,309
unique_paths.cpp
OpenGenus_cosmos/code/dynamic_programming/src/unique_paths/unique_paths.cpp
// Part of Cosmos by OpenGenus Foundation #include<bits/stdc++.h> using namespace std; //Tabulation method // Time complexity: O(m*n) int uniquePaths(int m, int n) { int dp[m][n]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(i==0 || j==0) dp[i][j]=1; else dp[i][j]=dp[i-1][j]+dp[i][j-1]; } } return dp[m-1][n-1]; } //nCr method // Time complexity: O(m+n) int uniquePaths1(int m, int n) { int N=m+n-2; int r=m-1; double res=1; for(int i=1;i<=r;i++){ res=res*(N-r+i)/i; } return (int)res; } // Brute force recursive method // Time complexity: O(2^(m+n)) int uniquePaths2(int m, int n) { if(m==1 || n==1) return 1; return uniquePaths2(m-1,n)+uniquePaths2(m,n-1); } //Time complexity: O(m*n) int solve(int i, int j, vector<vector<int>> &dp, int &m, int &n){ if (i == m - 1 || j == n - 1) return 1; if (dp[i][j] != 0) return dp[i][j]; dp[i][j] = solve(i + 1, j, dp, m, n) + solve(i, j + 1, dp, m, n); return dp[i][j]; } int uniquePaths3(int m, int n){ vector<vector<int>> dp(m, vector<int>(n, 0)); return solve(0, 0, dp, m, n); } int main(){ int m,n; cin>>m>>n; cout<<uniquePaths(m,n)<< endl; cout<<uniquePaths1(m,n) << endl; cout<<uniquePaths2(m,n) << endl; cout<<uniquePaths3(m,n) << endl; return 0; }
1,618
C++
.cpp
55
20.836364
73
0.466278
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,311
numeric_keypad_problem.cpp
OpenGenus_cosmos/code/dynamic_programming/src/numeric_keypad_problem/numeric_keypad_problem.cpp
#include <bits/stdc++.h> using namespace std; vector<vector<int>> nums; void populate() { nums.resize(10); nums[0].push_back(0); nums[0].push_back(8); nums[1].push_back(1); nums[1].push_back(2); nums[1].push_back(4); nums[2].push_back(1); nums[2].push_back(2); nums[2].push_back(3); nums[2].push_back(5); nums[3].push_back(2); nums[3].push_back(3); nums[3].push_back(6); nums[4].push_back(1); nums[4].push_back(4); nums[4].push_back(5); nums[4].push_back(7); nums[5].push_back(2); nums[5].push_back(4); nums[5].push_back(5); nums[5].push_back(6); nums[5].push_back(8); nums[6].push_back(3); nums[6].push_back(5); nums[6].push_back(6); nums[6].push_back(9); nums[7].push_back(4); nums[7].push_back(7); nums[7].push_back(8); nums[8].push_back(0); nums[8].push_back(5); nums[8].push_back(7); nums[8].push_back(8); nums[8].push_back(9); nums[9].push_back(6); nums[9].push_back(8); nums[9].push_back(9); } int main() { int t; cin >> t; populate(); while (t--) { int n; cin >> n; int arr[10][n + 1]; for (int i = 0; i < 10; i++) { arr[i][0] = 0; arr[i][1] = 1; arr[i][2] = nums[i].size(); } for (int i = 3; i <= n; i++) for (int j = 0; j < 10; j++) { arr[j][i] = 0; for (std::size_t k = 0; k < nums[j].size(); k++) arr[j][i] += arr[nums[j][k]][i - 1]; } int count = 0; for (int i = 0; i < 10; i++) count += arr[i][n]; cout << count << endl; } return 0; }
1,744
C++
.cpp
73
17.479452
64
0.470624
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,314
Longest_Common_Substring_rename.cpp
OpenGenus_cosmos/code/dynamic_programming/src/longest_common_substring/Longest_Common_Substring_rename.cpp
// Space Complexity: O(n) // Time Complexity: O(m*n) #include <iostream> #include <vector> std::string LongestCommonSubstring(std::string string1, std::string string2) { std::string temp; // longest string is string1 and the smallest string is string2 if (string2.size() > string1.size()) { temp = string1; string1 = string2; string2 = temp; } int m = string1.size(); int n = string2.size(); int maxLength = 0; // length of longest common Substring int end; // ending point of longest common Substring int curr = 0; // current row in the matrix std::vector<std::vector<int>> consecutiveRows(2, std::vector<int>(n + 1, 0)); // store result of 2 consecutive rows // maintaing the array for consequtive two rows for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (string1[i - 1] == string2[j - 1]) { consecutiveRows[curr][j] = consecutiveRows[1 - curr][j - 1] + 1; if (consecutiveRows[curr][j] > maxLength) { maxLength = consecutiveRows[curr][j]; end = i - 1; } } else consecutiveRows[curr][j] = 0; } curr = 1 - curr; // changing the row alternatively } if (maxLength == 0) return ""; else { std::string s = ""; // string is from end-maxLength+1 to end as maxLength is the length of // the common substring. for (int i = end - maxLength + 1; i <= end; i++) s += string1[i]; return s; } } int main() { std::string string1; std::string string2; std::cout << "Enter String1: "; std::cin >> string1; std::cout << "Enter String2: "; std::cin >> string2; std::cout << "String1: " << string1 << "\nString2: " << string2 << "\n"; std::string lcsStr = LongestCommonSubstring(string1, string2); if (lcsStr == "") std::cout << "No common substring\n"; else std::cout << "Longest Common Substring: " << lcsStr << " (of length: " << lcsStr.size() << ")\n"; return 0; }
2,213
C++
.cpp
67
25.597015
119
0.541452
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,315
longest_common_substring_2.cpp
OpenGenus_cosmos/code/dynamic_programming/src/longest_common_substring/longest_common_substring_2.cpp
/* * Part of Cosmos by OpenGenus Foundation * finding longest common substring between two strings by dynamic programming */ #include <string> #include <iostream> #include <cstring> using namespace std; int longestCommonSubString(string s1, string s2) { int T[600][600]; //array length can be adjusted by string length of vector can be used memset(T, 0, sizeof(T)); //intialising T to zero int maximum = 0; //filling by recurrence relation for (int i = 1; i <= (int)s1.length(); i++) { for (int j = 1; j <= (int)s2.length(); j++) if (s1[i - 1] == s2[j - 1]) //matching of characters { T[i][j] = T[i - 1][j - 1] + 1; if (maximum < T[i][j]) maximum = T[i][j]; } } return maximum; } //longest common substring int main() { string s1, s2; //standard input stream //cin >> s1 >> s2; s1 = "abcdedwwop"; s2 = "abeeedcedwcdedop"; int maximum = longestCommonSubString(s1, s2); cout << "Length of longest substring = "; cout << maximum << "\n"; //maximum length substring above -- "cded" -- length = 4 }
1,237
C++
.cpp
39
26.282051
117
0.553691
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,316
Solution.cpp
OpenGenus_cosmos/code/dynamic_programming/src/Count_Subsequence_Having_Product_Less_Than_K/Solution.cpp
#include<iostream> #include<cstring> using namespace std; int dp[10005][10005]; int helper(int a[], int n, int k , int product) { // base case if(n==0) { return 0; } if(product > k) { return 0; } if(dp[n][product] !=-1) { return dp[n][product]; } int include = product * a[n-1]; int exclude =product; int count =0; if( include < k) { count++; } count += helper(a,n-1,k,include) + helper(a,n-1,k,exclude); dp[n][product] =count; return dp[n][product]; } int solve(int a[], int n, int k) { dp[k+1][n+1]; memset(dp,-1,sizeof(dp)); int product =1; return helper(a,n,k,product); } int main() { int n; cin>>n; int a[n]; for(int i=0;i<n;i++) { cin>>a[i]; } int k; cout<<"Enter the value of k"<<endl; cin>>k; cout<<solve(a,n,k)<<endl; return 0; }
939
C++
.cpp
52
13.230769
63
0.52662
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,318
maximum_product_subarray.cpp
OpenGenus_cosmos/code/dynamic_programming/src/maximum_product_subarray/maximum_product_subarray.cpp
/* Read Problem Description Here - https://leetcode.com/problems/maximum-product-subarray/ Test Cases - Input: [2,3,-2,4] Output: 6 Input: [-2,0,-1] Output: 0 */ #include<iostream> #include<climits> using namespace std; int maxProdSub(int* arr, int n) { int positiveProd = 1, negativeProd = 1; int ans = INT_MIN; for(int i = 0 ; i < n ; i++) { int extraPositive = max(positiveProd * arr[i], max(negativeProd * arr[i], arr[i])); // dummy variable for getting the current max int extraNegative = min(positiveProd * arr[i], min(negativeProd * arr[i], arr[i])); // dummy variable for getting the current min positiveProd = extraPositive; // save current max negativeProd = extraNegative; // save current min if(ans < positiveProd) // if global ans is lesser than current answer, save ans = positiveProd; if(arr[i] == 0) // if 0 is encountered we reset the values of max and min { positiveProd = 1; negativeProd = 1; } } return ans; } int main() { int n; // size input cin>>n; int arr[n]; // array input for(int i = 0 ; i < n ; i++) cin>>arr[i]; cout<<maxProdSub(arr, n); }
1,128
C++
.cpp
42
24.452381
87
0.684407
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,321
longest_increasing_subsequence.cpp
OpenGenus_cosmos/code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> #include <algorithm> using namespace std; // Bottom-up O(n^2) approach int lis(int v[], int n) { int dp[n], ans = 0; for (int i = 0; i < n; ++i) { dp[i] = 1; for (int j = 0; j < i; ++j) if (v[j] < v[i]) dp[i] = max(dp[i], 1 + dp[j]); ans = max(ans, dp[i]); } return ans; } // Bottom-up O(n*log(n)) approach int lis2(int v[], int n) { // tail[i] stores the value of the lower possible value // of the last element in a increasing sequence of size i vector<int> tail; for (int i = 0; i < n; ++i) { vector<int>::iterator it = lower_bound(tail.begin(), tail.end(), v[i]); if (it == tail.end()) tail.push_back(v[i]); else *it = v[i]; } return tail.size(); } int main() { int v[9] = {10, 22, 9, 33, 21, 50, 41, 60, 80}; cout << lis(v, 9) << ", " << lis2(v, 9) << '\n'; return 0; }
1,025
C++
.cpp
41
19.926829
79
0.507677
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,323
best_time_to_sell_stock_II.cpp
OpenGenus_cosmos/code/dynamic_programming/src/best_time_to_sell_stock_II/best_time_to_sell_stock_II.cpp
// You are given an integer array prices where prices[i] is the price of a given stock on the ith day. // On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. // Find and return the maximum profit you can achieve. // Example 1: // Input: prices = [7,1,5,3,6,4] // Output: 7 // Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. // Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. // Total profit is 4 + 3 = 7. #include<bits/stdc++.h> class Solution { public: int maxProfit(vector<int>& arr) { int pr = 0; for(int i=1; i<arr.size(); i++){ if(arr[i]>arr[i-1]){ pr+= arr[i]-arr[i-1]; } } return pr; } };
887
C++
.cpp
22
35.363636
188
0.607226
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,325
Printing_longest_common_subsequence.cpp
OpenGenus_cosmos/code/dynamic_programming/src/longest_common_subsequence/Printing_longest_common_subsequence.cpp
//Printing longest common sub-sequence #include <iostream> #include<bits/stdc++.h> using namespace std; //Helper function to print LCA string LCA(string s1,string s2){ int m=s1.length(); int n=s2.length(); int dp[m+1][n+1]; //initialising first row for(int i=0; i<=m; i++){ dp[0][i]=0; } //initialising first column for(int j=0; j<=n; j++){ dp[j][0]=0; } //creating DP table for(int i=1; i<=m; i++){ for(int j=1; j<=n; j++){ if(s1[i-1]==s2[j-1]) dp[i][j]=1+dp[i-1][j-1]; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } int i=m,j=n; string result; while(i>0&&j>0){ if(s1[i-1]==s2[j-1]){ result.push_back(s1[i-1]); i--; j--; } else{ if(dp[i][j-1]>dp[i-1][j]) j--; else i--; } } reverse(result.begin(),result.end()); return result; } int main() { string s1="abcdaf"; string s2="acbcf"; string answer=LCA(s1,s2); cout<<"The LCA is: "<<answer; return 0; }
1,239
C++
.cpp
51
15.647059
53
0.449606
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,327
min_skips.cpp
OpenGenus_cosmos/code/dynamic_programming/src/min_rests_skipped_to_reach_on_time/min_skips.cpp
// Part of Cosmos by OpenGenus Foundation #include<bits/stdc++.h> int minSkips(vector<int>& dist, int speed, int reachTime) { /* dist: array containing lengths of roads speed: the constant speed of travel reachTime: the time before/at which you have to reach the office. You start at time=0. */ int n = dist.size(); double time[n]; // Find times taken to cover the roads. for(int i=0; i<n ; i++) { time[i] = dist[i]*1.0/speed; } // Make a dp table where dp[i][j]=minimum time to cover i roads using j skips double dp[n][n]; memset(dp, 0, sizeof(dp)); /* Note that, while taking ceiling and floor of floats and doubles, we can get precision errors due to inability of computers to represent floating point numbers precisely in memory. This is why we subtract a very small number eps (epsilon) while taking ceiling of float. Eg. ceil(1.0000000001)=2 which is unintended in our case. */ double eps = 0.00000001; // The dp table is going to be a lower triangular matrix as the number // of skips cannot exceed the number of roads. for(int i=0;i<n;i++) { for(int j=0;j<=i;j++) { // cover road 0 with 0 skips if(i == 0 && j == 0) dp[i][j]=time[i]; // no sop is skipped else if (j == 0) dp[i][0] = ceil(dp[i-1][0]- eps)+time[i]; // all the stops are skipped else if (i == j) dp[i][j] = dp[i-1][j-1]+time[i]; // we've used j skips to cover i roads else dp[i][j] = min( ceil (dp[i-1][j] - eps), dp[i-1][j-1]) + time[i]; } } // check the minimum number of skips required to reach on time for(int j=0;j<n;j++) { if( dp[n-1][j] <= reachTime ) return j; } // we cannot reach on time even if we skip all stops. return -1; }
2,028
C++
.cpp
55
28.272727
117
0.570231
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,332
trapping_rain_water.cpp
OpenGenus_cosmos/code/dynamic_programming/src/trapping_rain_water/trapping_rain_water.cpp
/* Problem Description - https://leetcode.com/problems/trapping-rain-water/description/ Test Cases - Input: [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 */ #include<iostream> #include<vector> using namespace std; int trapRainWater(int *arr, int n) { if(n < 3) return 0; vector<pair<int,int>>indexes; for(int i = 0 ; i < n ; i++) { bool check = false; int j = i + 1; int maxVal = 0; int index = i + 1; for(; j < n ; j++) // finding the corresponding value for the given start index { if(maxVal <= arr[j]) { maxVal = arr[j]; index = j; if(maxVal >= arr[i]) // if current value exceeds or is equal to arr[i] break break; } } if(index != i + 1) { pair<int,int>e; e.first = i; e.second = index; // insert it as a pair to show (start, end) for our water segment indexes.push_back(e); i = index - 1; } } int totalVol = 0; for(int i = 0 ; i < indexes.size() ; i++) { pair<int,int>p = indexes[i]; int minHeight = min(arr[p.first], arr[p.second]); // choose the minimum of the two boundaries to get max height of water enclosed // compute water stored corresponding to each cell inside a segment for(int j = p.first + 1 ; j < p.second ; j++) totalVol += abs(minHeight - arr[j]); } return totalVol; } int main() { int n; cin>>n; int arr[n]; for(int i = 0 ; i < n ; i++) cin>>arr[i]; cout<<trapRainWater(arr, n)<<endl; }
1,750
C++
.cpp
60
20.666667
95
0.528338
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,333
subset_sum.cpp
OpenGenus_cosmos/code/dynamic_programming/src/subset_sum/subset_sum.cpp
/* Part of Cosmos by OpenGenus Foundation */ #ifndef SUBSET_SUM #define SUBSET_SUM #include <iterator> /* * Check whether is possible to * get value sum from a subset * of the [begin:end) */ // complexity: time: O(sum * n), space: O(sum) template<typename _BidirectionalIter, typename _ValueType = typename std::iterator_traits<_BidirectionalIter>::value_type> bool isSubsetSum(_BidirectionalIter begin, _BidirectionalIter end, _ValueType sum) { auto sz = std::distance(begin, end); bool subset[2][sum + 1]; for (int i = 0; i <= sz; i++) { auto x = begin; std::advance(x, i - 1); for (int j = 0; j <= sum; j++) { // A subset with sum 0 is always possible if (j == 0) subset[i % 2][j] = true; // If there exists no element // no sum is possible else if (i == 0) subset[i % 2][j] = false; else if (*x <= j) subset[i % 2][j] = subset[(i + 1) % 2][j - *x] || subset[(i + 1) % 2][j]; else subset[i % 2][j] = subset[(i + 1) % 2][j]; } } return subset[sz % 2][sum]; } /* * // complexity: time: O(sum * n), space: O(sum * n) * template<typename _BidirectionalIter, * typename _ValueType = typename std::iterator_traits<_BidirectionalIter>::value_type> * bool * isSubsetSum(_BidirectionalIter begin, _BidirectionalIter end, _ValueType sum) * { * auto sz = std::distance(begin, end); * bool subset[sum + 1][sz + 1]; * * for (int i = 0; i <= sz; ++i) * subset[0][i] = true; * * for (int i = 1; i <= sum; ++i) * subset[i][0] = false; * * for (int i = 1; i <= sum; ++i) * for (int j = 1; j <= sz; ++j) * { * auto x = begin; * std::advance(x, j - 1); * * subset[i][j] = subset[i][j - 1]; * if (i >= *x) * subset[i][j] = subset[i][j] || subset[i - *x][j - 1]; * } * * return subset[sum][sz]; * } */ #endif // SUBSET_SUM
2,055
C++
.cpp
69
25
93
0.518444
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,334
longest_repeating_subsequence.cpp
OpenGenus_cosmos/code/dynamic_programming/src/longest_repeating_subsequence/longest_repeating_subsequence.cpp
// Part of Cosmos by OpenGenus Foundation //dynamic programming || Longest repeating subsequence #include <iostream> #include <string> #include <vector> int longestRepeatingSubsequence(std::string s) { int n = s.size(); // Obtaining the length of the string std::vector<std::vector<int>>dp(n + 1, std::vector<int>(n + 1, 0)); // Implementation is very similar to Longest Common Subsequence problem for (int x = 1; x <= n; ++x) for (int y = 1; y <= n; ++y) { if (s[x - 1] == s[y - 1] && x != y) dp[x][y] = 1 + dp[x - 1][y - 1]; else dp[x][y] = std::max(dp[x - 1][y], dp[x][y - 1]); } // Returning the value of the result return dp[n][n]; }
749
C++
.cpp
21
29.47619
75
0.556017
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,335
longest_common_subsequence_substring_problem.cpp
OpenGenus_cosmos/code/dynamic_programming/src/longest_common_subsequence_substring/longest_common_subsequence_substring_problem.cpp
// This is a new dynamic programming problem. I have published a research paper // about this problem under the guidance of Professor Rao Li (University of // South Carolina, Aiken) along with my friend. The paper has been accepted by // the Journal of Mathematics and Informatics.The problem is a variation of the // standard longest common subsequence problem. It says that--> "Suppose there // are two strings, X and Y. Now we need to find the longest string, which is a // subsequence of X and a substring of Y." // Link of the paper--> http://www.researchmathsci.org/JMIart/JMI-v25-8.pdf #include <iostream> #include <vector> class LCSubseqSubstr { public: static std::string LCSS(const std::string& X, const std::string& Y, int m, int n, std::vector<std::vector<int>>& W) { int maxLength = 0; // keeps the max length of LCSS int lastIndexOnY = n; // keeps the last index of LCSS in Y W = std::vector<std::vector<int>>(m + 1, std::vector<int>(n + 1, 0)); for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (X[i - 1] == Y[j - 1]) { W[i][j] = W[i - 1][j - 1] + 1; } else { W[i][j] = W[i - 1][j]; } if (W[i][j] > maxLength) { maxLength = W[i][j]; lastIndexOnY = j; } } } return Y.substr(lastIndexOnY - maxLength, maxLength); } }; int main() { std::string X, Y; std::cout << "Input the first string: "; std::getline(std::cin, X); std::cout << "Input the second string: "; std::getline(std::cin, Y); int m = X.length(), n = Y.length(); std::vector<std::vector<int>> W1(m + 1, std::vector<int>(n + 1, 0)); std::cout << "The longest string which is a subsequence of " << X << " and a substring of " << Y << " is " << LCSubseqSubstr::LCSS(X, Y, m, n, W1) << std::endl; std::cout << "The length of the longest string which is a subsequence of " << X << " and a substring of " << Y << " is " << LCSubseqSubstr::LCSS(X, Y, m, n, W1).length() << std::endl; return 0; }
2,198
C++
.cpp
46
39.847826
121
0.563755
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,336
newman_conway_dp.cpp
OpenGenus_cosmos/code/dynamic_programming/src/newman_conway/newman_conway_dp.cpp
#include <iostream> class NewmanConwaySequence { public: NewmanConwaySequence(unsigned int n) : n(n) {} void calculateNewmanConwaySequenceTermDP(bool flag); private: unsigned int n; }; void NewmanConwaySequence::calculateNewmanConwaySequenceTermDP(bool flag) { if(flag == true) { unsigned int ncs[n + 1]; ncs[0] = 0; ncs[1] = 1; ncs[2] = 1; for (int i = 3; i <= n; i++) ncs[i] = ncs[ncs[i - 1]] + ncs[i - ncs[i - 1]]; std::cout << "\nNewman Conway Sequence with " << n << " elements : "; for(int i = 1; i <= n; i++) std::cout << ncs[i] << " "; } else { unsigned int ncs[n + 1]; ncs[0] = 0; ncs[1] = 1; ncs[2] = 1; for (int i = 3; i <= n; i++) ncs[i] = ncs[ncs[i - 1]] + ncs[i - ncs[i - 1]]; std::cout << "\nNewman Conway Sequence term at " << n << " indexed : "; std::cout << ncs[n]; } } int main() { unsigned int nValue, value; bool flag; std::cout << "\nEnter the Index of Newman Conway Sequence : "; std::cin >> nValue; NewmanConwaySequence aNewmanConwaySequenceoj(nValue); std::cout << "\nEnter the non-zero to generate the Newman Conway Sequence or zero to generate particular term in Newman Conway Sequence : "; std::cin >> value; if(value) flag = true; else flag = false; if(flag == true) aNewmanConwaySequenceoj.calculateNewmanConwaySequenceTermDP(true); else aNewmanConwaySequenceoj.calculateNewmanConwaySequenceTermDP(false); }
1,605
C++
.cpp
53
24.245283
144
0.579935
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,338
weighted_job_scheduling.cpp
OpenGenus_cosmos/code/dynamic_programming/src/weighted_job_scheduling/weighted_job_scheduling.cpp
/* * Part of Cosmos by OpenGenus Foundation * C++ program for weighted job scheduling using Dynamic Programming and Binary Search */ #include <vector> #include <iostream> #include <algorithm> using namespace std; // A job has start time, finish time and profit. //index is used to store its given position as we will going to do sorting struct Job { int start, finish, profit, index; }; // A utility function that is used for sorting events // according to finish time bool jobComparator(Job s1, Job s2) { return s1.finish < s2.finish; } // A Binary Search based function to find the latest job // (before current job) that doesn't conflict with current // job. "index" is index of the current job. This function // returns -1 if all jobs before index conflict with it. The // array jobs[] is sorted in increasing order of finish time int latestNonConflict(const vector<Job> &jobs, int index) { // Initialize 'lo' and 'hi' for Binary Search int lo = 0, hi = index - 1; // Perform binary Search iteratively while (lo <= hi) { int mid = (lo + hi) / 2; if (jobs[mid].finish <= jobs[index].start) { if (jobs[mid + 1].finish <= jobs[index].start) lo = mid + 1; else return mid; } else hi = mid - 1; } return -11; //-11 just a flag value but kept as same to that given to index 0 see: MaxProfit func //so that backtracking can be done } // The main function that finds the subset of jobs // associated with maximum profit such that no two // jobs in the subset overlap. void MaxProfit(vector<Job> &arr) { int n = arr.size(); // Sort jobs according to finish time sort(arr.begin(), arr.end(), jobComparator); //reason for using index // Create an array to store solutions of subproblems. // DP[i] stores the Jobs involved and their total profit // till arr[i] (including arr[i]) vector<int> DP(n + 2); // initialize DP[0] to arr[0] DP[0] = arr[0].profit; //contain what is the latest non conflicting job with the current job vector<int> nConflict; //no job non-conflicting with one job nConflict.push_back(-11); //-11 is just a flag value for (int i = 1; i < n; i++) nConflict.push_back(latestNonConflict(arr, i)); // Fill entries in DP[] using recursive property //recurrence for (int i = 1; i < n; i++) { int val = nConflict[i]; DP[i] = max(DP[i - 1], DP[val] + arr[i].profit); } //finding jobs included in max profit int i = n - 1; cout << "Optimal jobs are - "; while (true) { //terminating condition if (i < 0) //basically checking case of if it is equal to index of any job --(-11) break; //DP[i] will be one of the two values from which it is derived(shown above) if (i == 0) { cout << arr[i].index + 1; break; } else if (DP[i] == DP[i - 1]) i--; else { cout << arr[i].index + 1 << " "; i = nConflict[i]; } } cout << "\nMaximum Profit = " << DP[n - 1] << "\n"; } int main() { //example test case vector<Job> arr(4); arr[0] = {3, 5, 20, 0}; arr[1] = {1, 2, 50, 1}; arr[2] = {6, 19, 100, 2}; arr[3] = {2, 100, 200, 3}; MaxProfit(arr); return 0; }
3,509
C++
.cpp
108
26.759259
113
0.589873
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,339
mincoinchange.cpp
OpenGenus_cosmos/code/dynamic_programming/src/coin_change/mincoinchange.cpp
// dynamic programming | coin change | C++ // Part of Cosmos by OpenGenus Foundation // A C++ program to find the minimum number of coins required from the list of given coins to make a given value // Given a value V, if we want to make change for V cents, and we have infinite supply of each of C = { C1, C2, .. , Cm} // valued coins, what is the minimum number of coins to make the change? #include <iostream> using namespace std; int main() { int t; cin >> t; // no. of test cases while (t--) { int v, n; cin >> v >> n; // v is value to made and n is the number of given coins int c[n + 1]; for (int i = 0; i < n; i++) cin >> c[i]; // c[i] holds denomination or value of different coins long long int dp[v + 1]; long long int m = 100000000; dp[0] = 0; for (int i = 1; i <= v; i++) dp[i] = m; for (int i = 0; i <= n - 1; i++) for (int j = 1; j <= v; j++) if (c[i] <= j) if (1 + dp[j - c[i]] < dp[j]) dp[j] = 1 + dp[j - c[i]]; if (dp[v] == m) cout << "-1" << endl; // prints -1 if it is not possible to make given amount v else cout << dp[v] << endl; // dp[v] gives the min coins required to make amount v } }
1,362
C++
.cpp
34
32.264706
120
0.511698
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,340
coinchange.cpp
OpenGenus_cosmos/code/dynamic_programming/src/coin_change/coinchange.cpp
// dynamic programming | coin change | C++ // Part of Cosmos by OpenGenus Foundation #include <iostream> #include <vector> using namespace std; int coinWays(int amt, vector<int>& coins) { // init the dp table vector<int> dp(amt+1, 0); int n = coins.size(); dp[0] = 1; // base case for (int j = 0; j < n; ++j) for (int i = 1; i <= amt; ++i) if (i - coins[j] >= 0) // if coins[j] < i then add no. of ways - // - to form the amount by using coins[j] dp[i] += dp[i - coins[j]]; // final result at dp[amt] return dp[amt]; } int main() { vector<int> coins = {1, 2, 3}; // coin denominations int amount = 4; // amount cout << coinWays(amount, coins) << '\n'; return 0; }
780
C++
.cpp
25
25.6
57
0.542553
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,341
boolean_parenthesization.cpp
OpenGenus_cosmos/code/dynamic_programming/src/boolean_parenthesization/boolean_parenthesization.cpp
// dynamic programming | boolean parenthesization | C++ // Part of Cosmos by OpenGenus Foundation #include <iostream> #include <cstring> // Dynamic programming implementation of the boolean // parenthesization problem using 'T' and 'F' as characters // and '&', '|' and '^' as the operators int boolean_parenthesization(char c[], char o[], int n) { int t[n][n], f[n][n]; for (int i = 0; i < n; ++i) { if (c[i] == 'T') { t[i][i] = 1; f[i][i] = 0; } else { t[i][i] = 0; f[i][i] = 1; } } for (int i = 1; i < n; ++i) for (int j = 0, k = i; k < n; ++j, ++k) { t[j][k] = 0; f[j][k] = 0; for (int a = 0; a < i; ++a) { int b = j + a; int d = t[j][b] + f[j][b]; int e = t[b + 1][k] + f[b + 1][k]; if (o[b] == '|') { t[j][k] += d * e - f[j][b] * f[b + 1][k]; f[j][k] += f[j][b] * f[b + 1][k]; } else if (o[b] == '&') { t[j][k] += t[j][b] * t[b + 1][k]; f[j][k] += d * e - t[j][b] * t[b + 1][k]; } else { t[j][k] += f[j][b] * t[b + 1][k] + t[j][b] * f[b + 1][k]; f[j][k] += t[j][b] * t[b + 1][k] + f[j][b] * f[b + 1][k]; } } } return t[0][n - 1]; } int main() { char c[] = "TFTTF"; char s[] = "|&|^"; int n = sizeof(c) - 1 / sizeof(c[0]); std::cout << boolean_parenthesization(c, s, n); return 0; }
1,734
C++
.cpp
60
18.8
77
0.334135
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,342
wildcard.cpp
OpenGenus_cosmos/code/dynamic_programming/src/wildcard_matching/wildcard.cpp
//Part of Cosmos by OpenGenus Foundation bool isMatch(string s, string p) { /* s is the string p is the pattern containing '?' and '*' apart from normal characters. */ int m=s.length(), n=p.length(); bool dp[m+1][n+1]; // Initialise each cell of the dp table with false for(int i=0;i<m+1;i++) for(int j=0;j<n+1;j++) dp[i][j]=false; for(int i=0;i<m+1;i++) { for(int j=0;j<n+1;j++) { // When both string s and pattern p is empty. if (i==0 && j==0) dp[i][j]=true; // When s is empty else if (i == 0) { dp[i][j]=(p[j-1]=='*' && dp[i][j-1]); } // When the pattern is empty else if (j == 0) dp[i][j]=false; // When the characters p[j-1] matches character s[i-1] or when // p[j-1] is a '?'. Both will consume 1 character of s. else if (p[j-1] == s[i-1] || p[j-1] == '?') dp[i][j]=dp[i-1][j-1]; // p[j-1]='*' // A '*' can consume 0 or multiple characters. else if (p[j-1]=='*') dp[i][j]=dp[i-1][j] || dp[i][j-1]; // If p[j-1] is any character other than those above. else dp[i][j]=false; } } return dp[m][n]; }
1,427
C++
.cpp
42
22.880952
75
0.431835
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,343
longest_common_increasing_subsequence.cpp
OpenGenus_cosmos/code/dynamic_programming/src/longest_common_increasing_subsequence/longest_common_increasing_subsequence.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> using namespace std; int main() { int n, m, a[502] = {}, b[502] = {}, d[502][502] = {}, z = 0; cin >> n >> m; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i <= m; i++) cin >> b[i]; for (int i = 1; i <= n; i++) { int k = 0; for (int j = 1; j <= m; j++) { d[i][j] = d[i - 1][j]; if (b[j] < a[i]) k = max(k, d[i - 1][j]); if (b[j] == a[i]) d[i][j] = max(d[i - 1][j], k + 1); z = max(z, d[i][j]); } } cout << z << '\n'; }
658
C++
.cpp
26
18.076923
64
0.336508
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,344
solution.cpp
OpenGenus_cosmos/code/dynamic_programming/src/Climbing Stairs/solution.cpp
// recursion // TC - O(2^n) , SC - O(1) class Solution { public: int func(int n){ if(n <= 1){ return n; } return func(n-1) + func(n-2); } int climbStairs(int n) { return func(n+1); } }; // memoisation // TC - O(n), SC - O(n) + O(n) class Solution { public: int func(int n, vector<int> &dp){ if(n <= 1){ return n; } if(dp[n] !=-1){ return dp[n]; } return dp[n] = func(n-1, dp) + func(n-2, dp); } int climbStairs(int n) { vector<int>dp(n+2, -1); return func(n+1, dp); } }; // tabulation // TC - O(n), SC - O(n) class Solution { public: int climbStairs(int n) { vector<int> dp(n+2, -1); dp[0] = 0, dp[1] = 1; for(int i = 2; i <= n+1 ;i++){ dp[i] = dp[i-1] + dp[i-2]; } return dp[n+1]; } }; // space optimised // TC - O(n) , SC - O(1) class Solution { public: int climbStairs(int n) { int prev1 = 1, prev2 = 0; for(int i = 1;i<=n;i++){ int ans = prev1 + prev2; prev2 = prev1; prev1 = ans; } return prev1; } };
1,222
C++
.cpp
59
14.372881
53
0.441921
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,345
bitmask_dp_prob#1.cpp
OpenGenus_cosmos/code/dynamic_programming/src/bitmask_dp/bitmask_dp_prob#1.cpp
/* Part of Cosmos by OpenGenus Foundation */ /* Problem Statement: There are k types ties, uniquely identified by id from 1 to k. n ppl are invited to a party. Each of them have a collection of ties. To look unique, they decide that none of them will wear same type of tie. Count the number of ways this is possible. Constraints: 1<=k<=100 1<=n<=10 */ #include <iostream> #include <vector> using namespace std; long long mod = 1e9 + 7; vector<int>tieList[105]; //stores list of ppl having tie with id i vector<vector<long long> >dp(1030,vector<long long>(15,-1)); int total; //mask = set of ppl, curTie = current tie-id long long countWays(int mask, int curTie){ if(total == mask)//found a way to assign unique ties to different ppl return 1; if(curTie > 100)//if tie id exceeds the highest available tie-id return 0; //if the query is already processed if(dp[mask][curTie]!=-1) return dp[mask][curTie]; long long notTake = countWays(mask,curTie+1)%mod; //number of ways to not take the curTie long long take; //trying all possible ways to take the curTie for(auto p : tieList[curTie]){ if(mask & (1<<p)) //if p is already wearing a tie, he cannot wear the curTie continue; take+=countWays(mask|(1<<p), curTie+1); take%=mod; } long long totWays = (take + notTake)%mod; return dp[mask][curTie] = totWays; } void solve(int n){ total = (1<<n) - 1; int x,m; for(int i=0;i<n;i++){ cin>>m; //number of types of ties available with i-th person for(int j=0;j<m;j++){ cin>>x; //tie id tieList[x].push_back(i); } } long long ans = countWays(0, 1); cout<<ans<<"\n"; } int main(){ int n; cin>>n; solve(n); return 0; }
1,846
C++
.cpp
56
27.678571
94
0.634615
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,347
maximum_weight_independent_set_of_path_graph.cpp
OpenGenus_cosmos/code/dynamic_programming/src/maximum_weight_independent_set_of_path_graph/maximum_weight_independent_set_of_path_graph.cpp
#include <iostream> using namespace std; int main() { int n; cout << "Enter the number of vertices of the path graph : "; cin >> n; int g[n]; cout << "Enter the vertices of the graph : "; for (int i = 0; i < n; i++) cin >> g[i]; int sol[n + 1]; sol[0] = 0; sol[1] = g[0]; for (int i = 2; i <= n; i++) sol[i] = max(sol[i - 1], sol[i - 2] + g[i - 1]); cout << "The maximum weighted independent set sum is : " << sol[n] << endl; int i = n; cout << "The selected verices are : "; while (i >= 1) { if (sol[i - 1] >= sol[i - 2] + g[i - 1]) i--; else { cout << g[i - 1] << " "; i -= 2; } } return 0; }
748
C++
.cpp
31
18.193548
79
0.435754
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,348
shortest_common_supersequence.cpp
OpenGenus_cosmos/code/dynamic_programming/src/shortest_common_supersequence/shortest_common_supersequence.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <cstring> using namespace std; const int MAX = 1010; int memo[MAX][MAX]; // used for memoization // Function to find length of shortest common supersequence // between sequences X[0..m-1] and Y[0..n-1] int SCSLength(string& X, string& Y, int m, int n) { // if we have reached the end of either sequence, return // length of other sequence if (m == 0 || n == 0) return n + m; // if we have already computed this state if (memo[m - 1][n - 1] > -1) return memo[m - 1][n - 1]; // if last character of X and Y matches if (X[m - 1] == Y[n - 1]) return memo[m - 1][n - 1] = SCSLength(X, Y, m - 1, n - 1) + 1; else // else if last character of X and Y don't match return memo[m - 1][n - 1] = 1 + min(SCSLength(X, Y, m, n - 1), SCSLength(X, Y, m - 1, n)); } // helper function int findSCSLength(string& X, string& Y) { memset(memo, -1, sizeof memo); return SCSLength(X, Y, X.length(), Y.length()); } // main function int main() { string X = "ABCBDAB", Y = "BDCABA"; cout << "The length of shortest common supersequence is " << findSCSLength(X, Y) << '\n'; return 0; }
1,289
C++
.cpp
39
28.051282
71
0.585149
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,350
no_consec_1.cpp
OpenGenus_cosmos/code/dynamic_programming/src/no_consec_ones/no_consec_1.cpp
#include <iostream> #include <vector> using namespace std; int countNonConsecutiveOnes(int n) { vector<int> endingZero(n), endingOne(n); endingZero[0] = endingOne[0] = 1; for (int i = 1; i < n; i++) { endingZero[i] = endingZero[i - 1] + endingOne[i - 1]; endingOne[i] = endingZero[i - 1]; } return endingZero[n - 1] + endingOne[n - 1]; } int main() { int binaryStringLength; cout << "Enter the length of binary string: "; cin >> binaryStringLength; cout << "\nCount of Binary representations of length " << binaryStringLength << " not having consecutive ones = "; cout << countNonConsecutiveOnes(binaryStringLength) << endl; return 0; }
712
C++
.cpp
24
25.541667
80
0.645773
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,351
longestbitonicseq.cpp
OpenGenus_cosmos/code/dynamic_programming/src/longest_bitonic_sequence/longestbitonicseq.cpp
#include <iostream> #include <vector> using namespace std; // Part of Cosmos by OpenGenus Foundation int lBitconSeq(vector<int> v, int n) { vector<int> lis, lds; // lis stands for longest increasing subsequence and lds stands for longest decreasing subsequence if (n == 0) return 0; // in case tha array is empty longest length will also be empty // finding lis for (int i = 0; i < n; i++) lis.push_back(1); for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (v[i] > v[j] && lis[j] + 1 > lis[i]) lis[i] = lis[j] + 1; //findin lds for (int i = 0; i < n; i++) lds.push_back(1); for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (v[i] < v[j] && lds[j] + 1 > lds[i]) lds[i] = lds[j] + 1; // result wil be max(lis[i] + lds[i] -1) int res = lis[0] + lds[0] - 1; for (int i = 1; i < n; i++) if ((lis[i] + lds[i] - 1) > res) res = lis[i] + lds[i] - 1; return res; } int main() { vector<int> v; int n; cout << "enter no. of elements in array\n"; cin >> n; cout << "enter elements of the array\n"; for (int i = 0; i < n; i++) { int temp; cin >> temp; v.push_back(temp); // filling the array with numbers } cout << "max length of the lingest bitconic sequence is " << lBitconSeq(v, n); }
1,434
C++
.cpp
45
25.8
128
0.509025
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,354
Knapsack_DP_all3tech.cpp
OpenGenus_cosmos/code/dynamic_programming/src/knapsack/Knapsack_DP_all3tech.cpp
///////////////////////////////RECURSIVE APPROACH//////////////////////////////////////////////////////// #include <iostream> #include <bits/stdc++.h> using namespace std; int knapSack(int W,int *wt,int *val,int n) { if(n==0||W==0) { return 0; } if(wt[n]<=W) { return max(val[n]+knapSack(W-wt[n],wt,val,n-1),knapSack(W,wt,val,n-1)); //(jab le liya uss wt ko, jab nhi liya uss wt ko) //(liya to uska price + baki bacha hua ka price, nhi liya to baki bacha hua ka price) //dono ka max nikalo(...,....) } else if(wt[n]>W) { return knapSack(W,wt,val,n-1); //jab W bada hai to bag me aega hi nhi to baki bacha hua part pe call karenge function } } int main() { int val[] = { 60, 100, 120 }; int wt[] = { 10, 20, 30 }; int W = 50; int n = sizeof(val) / sizeof(val[0]); cout << knapSack(W, wt, val, n-1); return 0; } //////////////////////////////////////MEMOIZATION APPROACH////////////////////////////////////////////// #include <iostream> #include <bits/stdc++.h> using namespace std; //memoisation = recursion + dp table ka use store karne ke liye int knapSack(int W,int *wt,int *val,int n,int **t) { if(n==0||W==0) { t[n][W]=0; return t[n][W]; } if(t[n][W]!=-1) { return t[n][W]; //agar -1 ki jagha ko value hai to seedha usse return karwa do } if(wt[n]<=W) { t[n][W]=max(val[n]+knapSack(W-wt[n],wt,val,n-1,t),knapSack(W,wt,val,n-1,t)); return t[n][W]; //agar -1 hai to recurssive call to karni padegi //aur uss jagha pe vo value store ho jaegi } else if(wt[n]>W) { t[n][W]=knapSack(W,wt,val,n-1,t); return t[n][W]; //agar -1 hai to recurssive call to karni padegi //aur uss jagha pe vo value store ho jaegi } return -1; } int main() { int val[] = { 60, 100, 120 }; int wt[] = { 10, 20, 30 }; int W = 50; // int t[4][52]={-1}; int n = sizeof(val) / sizeof(val[0]); //////////////////////////////////////// //to declare table dynamically int **t; t= new int*[n]; for (int i = 0; i < n; i++) { t[i] = new int[W + 1]; //we are creating cols for each row } for (int i = 0; i <n; i++) { for (int j = 0; j < W + 1; j++) { t[i][j] = -1; //initializing to -1 } } ////////////////////////////////////// cout <<knapSack(W, wt, val, n-1,t); return 0; } //////////////////////////////////////////TOP DOWN APPROACH///////////////////////////////////////////// #include <iostream> #include <bits/stdc++.h> using namespace std; //top-down approach me sabse pehli baat matrix banate //matrix bananne se pehle recursion wala code likho //usme jo variable change hore honge na uski table banegi //table ka size n+1 w+1 karne ka rehta hai //recurssion me jo base condition hoti hai usko hum top down me initialize ke roop me use karte //that is jab T[0][0] to value 0 kar diya isme matlab (recurssion me jab n==0||w==0 then return 0 kiya tha.) //table me ek point like 2,3 hume kya represent karta hai //2 hume bataega ki bhai humne pehle 2 item liya hai //aur 3 hume bataega uska weight matlab 3 wt ka bag hai //aur item 1 item 2 diya rakha hai to ab muje max profit itna tak ka batao //jab hum ye store kar diye to ye stored value humko aage wale i(items n),j(W) ke liye kaam aega //so sabse pehle recursion fir ya to memoizaition ya top down //top down me stack overflow hone ka chance nhi rehta to usse best mana jata haiii! int knapSack(int W,int *wt,int *val,int n,int **t) { //yaha i denotes n (num of item) and j denotes W (weight) for(int i=0;i<n+1;i++) { for(int j=0;j<W+1;j++) { if(i==0||j==0) { t[i][j]=0; } else if(wt[i]<=W) { t[i][j]=max(val[i]+t[i-1][j-wt[i]],t[i-1][j]); //max(jab include kiya,include nhi kiya) } else if(wt[i]>W) { t[i][j]=t[i-1][j]; } } } return t[n][W]; } int main() { int val[] = { 60, 100, 120 }; int wt[] = { 10, 20, 30 }; int W = 50; // int t[4][52]={-1}; int n = sizeof(val) / sizeof(val[0]); //////////////////////////////////////// //to declare table dynamically int **t; t= new int*[n]; for (int i = 0; i < n; i++) { t[i] = new int[W + 1]; //we are creating cols for each row } ////////////////////////////////////// cout <<knapSack(W, wt, val, n-1,t); return 0; }
4,798
C++
.cpp
153
25.078431
108
0.5
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,356
die_simulation.cpp
OpenGenus_cosmos/code/dynamic_programming/src/die_simulation/die_simulation.cpp
// Part of OpenGenus cosmos #define ll long long const int mod = 1e9+7; // Function to add in presence of modulus. We find the modded answer // as the number of sequences becomes exponential fairly quickly ll addmod(ll a, ll b) { return (a%mod + b%mod) % mod; } ll dieSimulator_util(int dex, vector<int>& maxroll, int noOfTimes, int prev, vector<vector<vector<ll> > >& dp, int n){ // Simulations are 0 indexed ie. 0 to n-1. Hence return 1 when n is reached if(dex==n) return 1; // If for the dex'th simulation, the number of sequences has already been found, return it. if(dp[dex][noOfTimes][prev] != -1) return dp[dex][noOfTimes][prev]%mod; // Initialise answer to 0. int ans=0; // Put all the digits in the dex'th simulation and for each of them, // move forward ie. do (dex+1)th simulation. for(int i=0;i<6;i++) { // Check if the current digit is the same as previous one if(i == prev) { /* Check if the number of times it has occurred has become equal to the allowed number of times. If yes, then don't put that digit, otherwise put that digit, add one to the noOfTimes it has occurred and move on. */ if(noOfTimes < maxroll[i]) ans = addmod(ans, dieSimulator_util(dex + 1, maxroll, noOfTimes + 1, prev, dp, n)); } else { ans = addmod(ans, dieSimulator_util(dex + 1, maxroll, 1, i, dp, n)); } } // Record the answer dp[dex][noOfTimes][prev] = ans; return ans; } int dieSimulator(int n, vector<int>& maxRolls) { // Loop over maxRolls array to find the maximum number of times a digit can be rolled. int maxi = 0; for(int i=0;i<maxRolls.size();i++) { if(maxRolls[i] > maxi) maxi = maxRolls[i]; } /* Initialise a 3d DP table with -1 where the row denotes the ith roll simulation, the column denotes the number of consecutive times the digit in depth has occurred and the depth denotes the number of distinct digits. */ vector<vector<vector<ll> > > dp(n, vector<vector<ll> >(maxi+1, vector<ll>(7, -1))); /* For the first call, current index = 0 noOfTimes it has occurred = 0 no of simulation = 6 */ return dieSimulator_util(0, maxRolls, 0, 6, dp, n); }
2,431
C++
.cpp
63
31.587302
120
0.620881
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,358
palindrome_partition.cpp
OpenGenus_cosmos/code/dynamic_programming/src/palindrome_partition/palindrome_partition.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <cstring> #include <string> #define MAX 1010 using namespace std; int isPal[MAX][MAX], memo[MAX]; /* * Checks if s[i...j] is palindrome * in a top-down fashion. Result is * stored in isPal matrix. * Time complexity: O(n^2) */ int isPalindrome(const string &s, int i, int j) { if (i > j) return isPal[i][j] = 0; if (isPal[i][j] > -1) return isPal[i][j]; if (j - i <= 1 && s[i] == s[j]) return isPal[i][j] = 1; if (s[i] == s[j]) return isPal[i][j] = isPalindrome(s, i + 1, j - 1); return isPal[i][j] = 0; } /* * Compute the minimum number of cuts * necessary to partition the string * s[0...i] in a set of palindromes. * Time complexity: O(n^2) */ int minPalPartition(const string &s, int i) { if (isPal[0][i]) return memo[i] = 0; if (memo[i] > -1) return memo[i]; int ans = i + 1; for (int j = 0; j < i; ++j) if (isPal[j + 1][i] == 1) ans = min(ans, 1 + minPalPartition(s, j)); return memo[i] = ans; } // Helper function int solve(const string &s) { memset(isPal, -1, sizeof isPal); memset(memo, -1, sizeof memo); int n = s.length(); for (int i = 0; i < n; ++i) for (int j = i; j < n; ++j) isPalindrome(s, i, j); return minPalPartition(s, n - 1); } int main() { cout << solve("aaabba") << '\n'; // 1: aa | abba cout << solve("ababbbabbababa") << '\n'; // 3: a | babbbab | b | ababa return 0; }
1,568
C++
.cpp
60
21.95
74
0.556153
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,359
number_of_substrings.cpp
OpenGenus_cosmos/code/dynamic_programming/src/number_of_substring_divisible_by_8_but_not_3/number_of_substrings.cpp
#include <bits/stdc++.h> using namespace std; int no_of_substr(string str, int len, int k) { int count = 0; // iterate over the string for (int i = 0; i < len; i++) { int n = 0; // consider every substring starting from index 'i' for (int j = i; j < len; j++) { n = n * 10 + (str[j] - '0'); // if substring is divisible by k, increase the counter if (n % k == 0) count++; } } return count; } int main() { string str; int len; cout << "Enter the string: "; cin >> str; len = str.length(); cout << "Desired Count: " << no_of_substr(str, len, 8) - no_of_substr(str, len, 24); return 0; }
746
C++
.cpp
28
19.892857
89
0.49789
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,360
maximum_sum_increasing_subsequence.cpp
OpenGenus_cosmos/code/dynamic_programming/src/maximum_sum_increasing_subsequence/maximum_sum_increasing_subsequence.cpp
#include <bits/stdc++.h> #include <vector> using namespace std; int maxSum(int arr[], int n){ int i, j, max = 0; vector<int> dp(n); for (i = 0; i < n; i++){ dp[i] = arr[i]; } for (i = 1; i < n; i++ ){ for (j = 0; j < i; j++ ){ if (arr[i] > arr[j] && dp[i] < dp[j] + arr[i]){ dp[i] = dp[j] + arr[i]; } } } for (i = 0; i < n; i++){ if (max < dp[i]){ max = dp[i]; } } return max; } // Driver Code int main() { int arr[] = {4, 6, 1, 3, 8, 4, 6}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Sum of maximum sum increasing subsequence is " << maxSum(arr, n) << ".\n"; return (0); }
621
C++
.cpp
31
17.645161
84
0.499142
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,362
test_sort.cpp
OpenGenus_cosmos/code/sorting/test/test_sort.cpp
/* * Part of Cosmos by OpenGenus Foundation */ /* * guide * * 1. substitute iterator (col:28) * 2. substitute sort algorithm (col: 70) * 3. run */ #define CATCH_CONFIG_MAIN #ifndef SORT_TEST #define SORT_TEST #include "../../../test/c++/catch.hpp" #include <forward_list> #include <list> #include <deque> #include <iterator> #include <iostream> #include <algorithm> #include "../src/merge_sort/merge_sort.cpp" #include "../src/quick_sort/quick_sort.cpp" #include "../src/insertion_sort/insertion_sort.cpp" #include "../src/selection_sort/selection_sort.cpp" #include "../src/bubble_sort/bubble_sort.cpp" // substitute iterator // #define AT_LEAST_INPUT_ITERATOR // #define AT_LEAST_BIDIRECTIONAL_ITERATOR #define AT_LEAST_RANDOM_ITERATOR #ifdef AT_LEAST_INPUT_ITERATOR template<typename _T> using ContainerType = std::forward_list<_T>; #endif #ifdef AT_LEAST_BIDIRECTIONAL_ITERATOR template<typename _T> using ContainerType = std::list<_T>; #endif #ifdef AT_LEAST_RANDOM_ITERATOR template<typename _T> using ContainerType = std::deque<_T>; #endif template<typename _Iter1, typename _Iter2, typename _Tp = typename std::iterator_traits<_Iter1>::value_type> bool isSame(_Iter1 aBegin, _Iter1 aEnd, _Iter2 bBegin) { auto aIt = aBegin; auto bIt = bBegin; for (; aIt != aEnd; ++aIt, ++bIt) if (*aIt != *bIt) return false; return true; } TEST_CASE("sort algorithm") { srand(static_cast<unsigned int>(clock())); void (*psf)(int *, int *); void (*vsf)(ContainerType<int>::iterator, ContainerType<int>::iterator); // substitute sort algorithm vsf = mergeSort; psf = mergeSort; // vsf = bubbleSort; // psf = bubbleSort; // vsf = insertionSort; // psf = insertionSort; // vsf = selectionSort; // psf = selectionSort; // vsf = quickSort; // psf = quickSort; auto stdSort = [](ContainerType<int>&expectStdContainer) { #ifdef AT_LEAST_RANDOM_ITERATOR std::sort(expectStdContainer.begin(), expectStdContainer.end()); #else expectStdContainer.sort(); #endif }; auto testSTLContainer = [&](int sz) { ContainerType<int> actualStdContainer, expectStdContainer; // randomize elems for (int i = 0; i < sz; ++i) { int randomValue = std::rand() % (sz / 2 + 1); actualStdContainer.push_front(randomValue); expectStdContainer.push_front(randomValue); } stdSort(expectStdContainer); vsf(actualStdContainer.begin(), actualStdContainer.end()); CHECK(isSame(actualStdContainer.begin(), actualStdContainer.end(), expectStdContainer.begin())); }; auto testPODPtr = [&](int sz) { int *actualDynamicArray = new int[sz]; int *actualDynamicArrayEnd = actualDynamicArray + sz; ContainerType<int> expectStdContainer; // randomize elems for (int i = 0; i < sz; ++i) { int randomValue = std::rand() % (sz / 2 + 1); actualDynamicArray[i] = randomValue; expectStdContainer.push_front(randomValue); } stdSort(expectStdContainer); psf(actualDynamicArray, actualDynamicArrayEnd); CHECK(isSame(actualDynamicArray, actualDynamicArrayEnd, expectStdContainer.begin())); delete[] actualDynamicArray; }; SECTION("empty") { testPODPtr(0); testSTLContainer(0); }; SECTION("1 elem") { testPODPtr(1); testSTLContainer(1); } SECTION("2 elems") { for (int i = 0; i < 1000; ++i) { testPODPtr(2); testSTLContainer(2); } } SECTION("3 elems") { for (int i = 0; i < 1000; ++i) { testPODPtr(3); testSTLContainer(3); } } SECTION("large size") { testPODPtr(1e6); testSTLContainer(1e6); } SECTION("multiple random size") { for (int i = 0; i < 10000; ++i) { testPODPtr(100 + std::rand() % 50); testSTLContainer(100 + std::rand() % 50); } } } #endif // SORT_TEST
4,996
C++
.cpp
153
22.006536
90
0.51858
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,365
merge_sort.cpp
OpenGenus_cosmos/code/sorting/src/merge_sort/merge_sort.cpp
/* * Part of Cosmos by OpenGenus Foundation * * merge sort synopsis * * namespace merge_sort_impl { * template<typename _Random_Acccess_Iter> * _Random_Acccess_Iter * advance(_Random_Acccess_Iter it, std::ptrdiff_t n); * } // merge_sort_impl * * template<typename _Random_Acccess_Iter, typename _Compare> * void mergeSort(_Random_Acccess_Iter begin, _Random_Acccess_Iter end, _Compare comp); * * template<typename _Random_Acccess_Iter> * void mergeSort(_Random_Acccess_Iter begin, _Random_Acccess_Iter end); */ #include <list> #include <iterator> #include <cstddef> namespace merge_sort_impl { template<typename _Random_Acccess_Iter> _Random_Acccess_Iter advance(_Random_Acccess_Iter it, std::ptrdiff_t n) { std::advance(it, n); return it; } template<typename _Random_Acccess_Iter, typename _Compare> void merge(_Random_Acccess_Iter begin, _Random_Acccess_Iter end, _Compare comp) { using value_type = typename std::iterator_traits<_Random_Acccess_Iter>::value_type; auto end1 = begin; std::advance(end1, std::distance(begin, end) >> 1); auto begin1 = begin, begin2 = end1, end2 = end; std::list<value_type> tmp{}; while (begin1 < end1 && begin2 < end2) tmp.push_back(comp(*begin1, *begin2) ? *begin1++ : *begin2++); while (begin1 < end1) *--begin2 = *--end1; while (!tmp.empty()) { *--begin2 = tmp.back(); tmp.pop_back(); } } } // merge_sort_impl template<typename _Random_Acccess_Iter, typename _Compare> void mergeSort(_Random_Acccess_Iter begin, _Random_Acccess_Iter end, _Compare comp) { size_t dist = std::distance(begin, end); if (dist > 1) { auto mid = begin; std::advance(mid, dist >> 1); mergeSort(begin, mid, comp); mergeSort(mid, end, comp); merge_sort_impl::merge(begin, end, comp); } } template<typename _Random_Acccess_Iter> void mergeSort(_Random_Acccess_Iter begin, _Random_Acccess_Iter end) { using value_type = typename std::iterator_traits<_Random_Acccess_Iter>::value_type; mergeSort(begin, end, std::less<value_type>()); }
2,157
C++
.cpp
72
26.013889
87
0.671491
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,366
merge_sort_linked_list.cpp
OpenGenus_cosmos/code/sorting/src/merge_sort/merge_sort_linked_list.cpp
/* Here ListNode is class containing 'next' for next node, and value for value at node. */ ListNode* mergeSort(ListNode* head) { if (head==NULL||head->next==NULL) { return head; } ListNode* mid = getMid(head); ListNode* leftHalf = mergeSort(head); ListNode* rightHalf = mergeSort(mid); return merge(leftHalf, rightHalf); } ListNode* getMid(ListNode* head) { ListNode* prev = NULL; ListNode *s_ptr = head; ListNode* f_ptr = head; while (f_ptr != NULL && f_ptr->next != NULL) { prev = s_ptr; s_ptr = s_ptr->next; f_ptr = f_ptr->next->next; } prev->next = NULL; return s_ptr; } ListNode* merge(ListNode* l1, ListNode* l2) { ListNode* n_head = new ListNode(0); ListNode* rear = n_head; while (l1!=NULL && l2!=NULL) { if (l1->value < l2->value) { rear->next = l1; l1 = l1->next; } else { rear->next = l2; l2 = l2->next; } rear = rear->next; } if (l1 != NULL) { rear->next = l1; } if (l2!= NULL) { rear->next = l2; } return n_head->next; }
1,321
C++
.cpp
57
15.385965
69
0.49183
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,367
slow_sort.cpp
OpenGenus_cosmos/code/sorting/src/slow_sort/slow_sort.cpp
/* Part of Cosmos by OpenGenus Foundation */ #pragma once #include <bits/stdc++.h> using namespace std; /** * @brief implement the slowSort Algorithm * * @param vect_ vector to be sorted * @param i ith index of vector * @param j jth index of vector */ void slowSort( vector<int32_t>& vect_, int i, int j ) { if( i >= j ) { return; } int m = floor( ( i+j ) / 2 ); slowSort( vect_, i, m ); slowSort( vect_, m+1, j ); if( vect_[j] < vect_[m] ) { swap( vect_[j], vect_[m] ); } slowSort( vect_, i, j-1 ); } /** * @brief print the contents of vector A * * @param vect_ vector whose index has to be printed */ void printVector( vector<int32_t>& vect_ ) { for(const auto& a : vect_) { cout << a << " "; } } int main() { vector<int32_t> vect_; cout << " Enter elements of the vector: [Enter any character to end the while loop]\n"; int32_t input; while(cin>>input) { vect_.push_back(input); } int i = 0; int j = vect_.size() - 1; cout << "Vector before sorting : \n"; printVector( vect_ ); slowSort(vect_, i, j); cout<<"\n"; cout << "Vector after sorting : \n"; printVector( vect_ ); return 0; }
1,256
C++
.cpp
57
18.070175
91
0.570826
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,368
comb_sort.cpp
OpenGenus_cosmos/code/sorting/src/comb_sort/comb_sort.cpp
#include <iostream> // Part of Cosmos by OpenGenus Foundation using namespace std; int updateGap(int gap) { gap = (gap * 10) / 13; if (gap < 1) return 1; else return gap; } void combSort(int ar[], int n) { int gap = n; int flag = 0; while (gap > 1 || flag == 1) { gap = updateGap(gap); flag = 0; for (int i = 0; i < (n - gap); i++) { int x; if (ar[i] > ar[i + 1]) { x = ar[i]; ar[i] = ar[i + 1]; ar[i + 1] = x; flag = 1; } } } } int main() { int n; cout << "Input number of elements in the array - "; cin >> n; int ar[n]; for (int i = 0; i < n; i++) cin >> ar[i]; combSort(ar, n); cout << "Array after sorting - "; for (int i = 0; i < n; i++) cout << ar[i] << endl; }
919
C++
.cpp
45
13.844444
55
0.41791
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,371
selection_sort.cpp
OpenGenus_cosmos/code/sorting/src/selection_sort/selection_sort.cpp
/* * Part of Cosmos by OpenGenus Foundation * * selection sort synopsis * * template<typename _Input_Iter, typename _Compare> * void * selectionSort(_Input_Iter begin, _Input_Iter end, _Compare compare); * * template<typename _Input_Iter> * void * selectionSort(_Input_Iter begin, _Input_Iter end); */ #include <functional> template<typename _Input_Iter, typename _Compare> void selectionSort(_Input_Iter begin, _Input_Iter end, _Compare compare) { if (begin != end) for (auto curr = begin; curr != end; ++curr) { auto minimum = curr; auto forward = curr; while (++forward != end) if (compare(*forward, *minimum)) minimum = forward; std::iter_swap(minimum, curr); } } template<typename _Input_Iter> void selectionSort(_Input_Iter begin, _Input_Iter end) { using value_type = typename std::iterator_traits<_Input_Iter>::value_type; selectionSort(begin, end, std::less<value_type>()); }
1,022
C++
.cpp
36
23.583333
78
0.648318
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,375
pancake_sort.cpp
OpenGenus_cosmos/code/sorting/src/pancake_sort/pancake_sort.cpp
#include <iostream> #include <vector> #include <algorithm> template <typename T> void pancakeSort(std::vector<T>& container) { for (int size = container.size(); size > 1; --size) { // Find position of max element int maxPos = std::max_element(container.begin(), container.begin() + size) - container.begin(); // Reverse the vector from begin to maxPos (max element becomes first element) std::reverse(container.begin(), container.begin() + maxPos + 1); // Reverse the vector from begin to size (max element to correct position) std::reverse(container.begin(), container.begin() + size); } } template <typename T> void printVector(std::vector<T> v) { for (auto i : v) std::cout << i << " "; std::cout << std::endl; } int main() { // Sample vector of ints std::vector<int> v1 = {72, 23, 9, 31, 6, 8}; // Sort vector using pancake sort pancakeSort(v1); // Print sorted vector printVector(v1); // Sample vector of doubles std::vector<double> v2 = {9.82, 7.36, 13.87, 2.28, 6.15, 45.56}; // Sort vector using pancake sort pancakeSort(v2); // Print sorted vector printVector(v2); // Sample vector of floats std::vector<float> v3 = {74.25, 13.32, 25.71, 36.82, 10.11, 47.00}; // Sort vector using pancake sort pancakeSort(v3); // Print sorted vector printVector(v3); return 0; }
1,443
C++
.cpp
45
27.266667
104
0.637219
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
10,377
sleep_sort.cpp
OpenGenus_cosmos/code/sorting/src/sleep_sort/sleep_sort.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <chrono> #include <vector> #include <thread> using namespace std; int main(int argc, char** argv) { vector<thread> threads; for (auto i = 1; i < argc; ++i) { threads.emplace_back( [i, &argv]() { int arg = stoi(argv[i]); this_thread::sleep_for(chrono::seconds(arg)); cout << argv[i] << endl; } ); } for (auto &thread: threads) thread.join(); return 0; }
548
C++
.cpp
24
16.791667
57
0.543353
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,378
shell_sort.cpp
OpenGenus_cosmos/code/sorting/src/shell_sort/shell_sort.cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; // Part of Cosmos by OpenGenus Foundation void shellSort(vector<int> &ar) { size_t j; for (size_t gap = ar.size() / 2; gap > 0; gap /= 2) for (size_t i = gap; i < ar.size(); i++) { int temp = ar[i]; for (j = i; j >= gap && temp < ar[j - gap]; j -= gap) ar[j] = ar[j - gap]; ar[j] = temp; } } int main() { vector<int> inputArray; cout << "Enter the elements of the array: "; for (int i; cin >> i;) inputArray.push_back(i); shellSort(inputArray); for (size_t i = 0; i < inputArray.size(); i++) cout << inputArray[i] << " "; cout << endl; return 0; }
758
C++
.cpp
29
20.655172
65
0.522696
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,382
dutch_national_flag.cpp
OpenGenus_cosmos/code/sorting/src/quick_sort/dutch_national_flag.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <vector> #include <stdlib.h> #include <iostream> using namespace std; // Dutch National Flag Sort for array items 0,1,2 void flagSort(vector<int> &v) { int lo = 0; int hi = v.size() - 1; int mid = 0; while (mid <= hi) switch (v[mid]) { case 0: swap(v[lo++], v[mid++]); break; case 1: mid++; break; case 2: swap(v[mid], v[hi--]); break; } } /* UTILITY FUNCTIONS */ void swap(int &a, int &b) { int temp = a; a = b; b = temp; } void printarr(vector<int> &v) { for (size_t i = 0; i < v.size(); ++i) cout << v[i] << " "; cout << endl; } void flagFill(vector<int> &v) { for (size_t i = 0; i < v.size(); ++i) v[i] = rand() % 3; } // Driver program int main() { int size = 10; cout << "Input test array size: "; cin >> size; vector<int> v(size); flagFill(v); cout << "Unsorted: "; printarr(v); flagSort(v); cout << "Sorted: "; printarr(v); return 0; }
1,131
C++
.cpp
58
14.517241
49
0.501883
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,383
quick_sort.cpp
OpenGenus_cosmos/code/sorting/src/quick_sort/quick_sort.cpp
/* * Part of Cosmos by OpenGenus Foundation * * quick sort synopsis * * namespace quick_sort_impl { * struct quick_sort_tag {}; * struct iterative_quick_sort_tag :quick_sort_tag {}; * struct recursive_quick_sort_tag :quick_sort_tag {}; * * template<typename _Random_Acccess_Iter, typename _Compare> * _Random_Acccess_Iter * partition(_Random_Acccess_Iter first, _Random_Acccess_Iter last, _Compare comp); * * template<typename _Random_Acccess_Iter, typename _Compare> * void * quickSortImpl(_Random_Acccess_Iter first, * _Random_Acccess_Iter last, * _Compare comp, * std::random_access_iterator_tag, * recursive_quick_sort_tag); * * template<typename _Random_Acccess_Iter, typename _Compare> * void * quickSortImpl(_Random_Acccess_Iter first, * _Random_Acccess_Iter last, * _Compare comp, * std::random_access_iterator_tag, * iterative_quick_sort_tag); * } // quick_sort_impl * * template<typename _Random_Acccess_Iter, typename _Compare> * void * quickSort(_Random_Acccess_Iter begin, _Random_Acccess_Iter end, _Compare comp); * * template<typename _Random_Acccess_Iter> * void * quickSort(_Random_Acccess_Iter begin, _Random_Acccess_Iter end); */ #include <stack> #include <functional> namespace quick_sort_impl { struct quick_sort_tag {}; struct iterative_quick_sort_tag : quick_sort_tag {}; struct recursive_quick_sort_tag : quick_sort_tag {}; template<typename _Random_Acccess_Iter, typename _Compare> _Random_Acccess_Iter partition(_Random_Acccess_Iter first, _Random_Acccess_Iter last, _Compare comp) { _Random_Acccess_Iter i = first, j = last + 1; while (true) { while (i + 1 <= last && comp(*++i, *first)) ; while (j - 1 >= first && comp(*first, *--j)) ; if (i >= j) break; std::swap(*i, *j); } std::swap(*first, *j); return j; } template<typename _Random_Acccess_Iter, typename _Compare> void quickSortImpl(_Random_Acccess_Iter first, _Random_Acccess_Iter last, _Compare comp, std::random_access_iterator_tag, recursive_quick_sort_tag) { if (first < last) { // first is pivot auto mid = quick_sort_impl::partition(first, last, comp); quickSortImpl(first, mid - 1, comp, std::random_access_iterator_tag(), recursive_quick_sort_tag()); quickSortImpl(mid + 1, last, comp, std::random_access_iterator_tag(), recursive_quick_sort_tag()); } } template<typename _Random_Acccess_Iter, typename _Compare> void quickSortImpl(_Random_Acccess_Iter first, _Random_Acccess_Iter last, _Compare comp, std::random_access_iterator_tag, iterative_quick_sort_tag) { if (first < last) { std::stack<std::pair<_Random_Acccess_Iter, _Random_Acccess_Iter>> st; st.push(std::make_pair(first, last)); while (!st.empty()) { _Random_Acccess_Iter left, right, i, j; left = st.top().first; right = st.top().second; st.pop(); // ignore if only one elem if (left >= right) continue; auto mid = quick_sort_impl::partition(left, right, comp); st.push(std::make_pair(left, mid - 1)); st.push(std::make_pair(mid + 1, right)); } } } } // quick_sort_impl template<typename _Random_Acccess_Iter, typename _Compare> void quickSort(_Random_Acccess_Iter begin, _Random_Acccess_Iter end, _Compare comp) { using namespace quick_sort_impl; if (begin == end) return; --end; auto category = typename std::iterator_traits<_Random_Acccess_Iter>::iterator_category(); return quickSortImpl(begin, end, comp, category, iterative_quick_sort_tag()); } template<typename _Random_Acccess_Iter> void quickSort(_Random_Acccess_Iter begin, _Random_Acccess_Iter end) { using value_type = typename std::iterator_traits<_Random_Acccess_Iter>::value_type; return quickSort(begin, end, std::less<value_type>()); }
4,359
C++
.cpp
133
26.601504
93
0.609687
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,384
quick_sort_three_way.cpp
OpenGenus_cosmos/code/sorting/src/quick_sort/quick_sort_three_way.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <vector> #include <stdlib.h> #include <iostream> using namespace std; /* UTILITY FUNCTIONS */ void swap(int &a, int &b) { int temp = a; a = b; b = temp; } void printarr(vector<int> &v) { for (size_t i = 0; i < v.size(); ++i) cout << v[i] << " "; cout << endl; } void fill(vector<int> &v, int max) { for (size_t i = 0; i < v.size(); ++i) v[i] = rand() % max + 1; } // three-way-partioning void partition(vector<int> &v, int low, int high, int &i, int &j) { if (high - low <= 1) { if (v[high] < v[low]) swap(v[high], v[low]); i = low; j = high; return; } int mid = low; int pivot = v[high]; while (mid <= high) { if (v[mid] < pivot) swap(v[low++], v[mid++]); else if (v[mid] == pivot) mid++; else if (v[mid] > pivot) swap(v[mid], v[high--]); } i = low - 1; j = mid; } void quicksort(vector<int> &v, int low, int high) { if (low >= high) return; int i, j; partition(v, low, high, i, j); // Recursively sort two halves quicksort(v, low, i); quicksort(v, j, high); } // Driver program int main() { int size = 10; int maxRand = 10; cout << "Input test array size: "; cin >> size; vector<int> v(size); cout << "Maximum random number: "; cin >> maxRand; fill(v, maxRand); cout << "Unsorted: "; printarr(v); quicksort(v, 0, size - 1); cout << "Sorted: "; printarr(v); return 0; }
1,614
C++
.cpp
76
16.460526
65
0.516087
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,386
counting_sort.cpp
OpenGenus_cosmos/code/sorting/src/counting_sort/counting_sort.cpp
#include <iostream> #include <vector> #include <climits> /* * Part of Cosmos by OpenGenus Foundation */ using namespace std; void countingSort(vector<int> arr, vector<int>& sortedA) { int m = INT_MIN; for (size_t i = 0; i < arr.size(); i++) if (arr[i] > m) m = arr[i]; int freq[m + 1]; //m is the maximum number in the array for (int i = 0; i <= m; i++) freq[i] = 0; for (size_t i = 0; i < arr.size(); i++) freq[arr[i]]++; int j = 0; for (int i = 0; i <= m; i++) { int tmp = freq[i]; while (tmp--) { sortedA[j] = i; j++; } } } int main() { vector<int> arr{1, 4, 12, 34, 16, 11, 9, 1, 3, 33, 5}; vector<int> sortedA(arr.size() + 1); // stores sorted array countingSort(arr, sortedA); cout << "Sorted Array: "; for (size_t i = 0; i < arr.size(); i++) cout << sortedA[i] << " "; return 0; }
958
C++
.cpp
39
19.333333
65
0.496725
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,388
radix_sort.cpp
OpenGenus_cosmos/code/sorting/src/radix_sort/radix_sort.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> #include <cmath> void radix_sort(std::vector<int> &data) { using namespace std; vector<int> tmp[10]; //store 0~9; int max_data = *(max(std::begin(data), std::end(data))); int n = 1; while (n <= max_data) { for (auto v : data) { int lsd = (v / n) % 10; tmp[lsd].emplace_back(v); } int k = 0; for (auto &v: tmp) //vector { if (v.size() <= 0) continue; for (auto num: v) data[k++] = num; v.clear(); } n *= 10; } } int main() { using namespace std; vector<int> data = {34, 12, 51, 52, 612, 456, 12, 31, 412, 123, 1, 3}; cout << "before sorting" << endl; for (auto v: data) cout << v << " "; cout << endl; radix_sort(data); cout << "after sorting" << endl; for (auto v: data) cout << v << " "; cout << endl; }
1,034
C++
.cpp
43
17.372093
74
0.474059
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,390
insertion_sort.cpp
OpenGenus_cosmos/code/sorting/src/insertion_sort/insertion_sort.cpp
/* * Part of Cosmos by OpenGenus Foundation * * insertion sort synopsis * * template<typename _Bidirectional_Iter, typename _Compare> * void * insertionSort(_Bidirectional_Iter begin, _Bidirectional_Iter end, _Compare compare); * * template<typename _Bidirectional_Iter> * void * insertionSort(_Bidirectional_Iter begin, _Bidirectional_Iter end); */ #include <functional> template<typename _Bidirectional_Iter, typename _Compare> void insertionSort(_Bidirectional_Iter begin, _Bidirectional_Iter end, _Compare compare) { if (begin != end) { auto backOfBegin = begin; --backOfBegin; auto curr = begin; for (++curr; curr != end; ++curr) { auto pivot = *curr; auto backward = curr; auto nextOfBackward = curr; while (--backward != backOfBegin && compare(pivot, *backward)) { *nextOfBackward = *backward; --nextOfBackward; } *nextOfBackward = pivot; } } } template<typename _Bidirectional_Iter> void insertionSort(_Bidirectional_Iter begin, _Bidirectional_Iter end) { using value_type = typename std::iterator_traits<_Bidirectional_Iter>::value_type; insertionSort(begin, end, std::less<value_type>()); }
1,302
C++
.cpp
44
24.022727
87
0.655227
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,391
median_sort.cpp
OpenGenus_cosmos/code/sorting/src/median_sort/median_sort.cpp
#include <iostream> using namespace std; // Part of Cosmos by OpenGenus Foundation void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } int Partition(int a[], int low, int high) { int pivot, index, i; index = low; pivot = high; for (i = low; i < high; i++) if (a[i] < a[pivot]) { swap(&a[i], &a[index]); index++; } swap(&a[pivot], &a[index]); return index; } int QuickSort(int a[], int low, int high) { int pindex; if (low < high) { pindex = Partition(a, low, high); QuickSort(a, low, pindex - 1); QuickSort(a, pindex + 1, high); } return 0; } int main() { int n, m, bi, ai, i, k; double median; cout << "Enter the number of element in the first data set: "; cin >> n; int a[n]; for (i = 0; i < n; i++) { cout << "Enter " << i + 1 << "th element: "; cin >> a[i]; } cout << "\nEnter the number of element in the second data set: "; cin >> m; int b[m]; for (i = 0; i < m; i++) { cout << "Enter " << i + 1 << "th element: "; cin >> b[i]; } QuickSort(a, 0, n - 1); QuickSort(b, 0, m - 1); cout << "\tThe Median from these data set is: "; ai = 0; bi = 0; if ((m + n) % 2 == 1) { k = (n + m) / 2 + 1; while (k > 0) { if (a[ai] <= b[bi] && ai < n) { k--; if (k == 0) cout << a[ai]; ai++; } else if (a[ai] > b[bi] && bi < m) { k--; if (k == 0) cout << b[bi]; bi++; } } } else { k = (n + m) / 2 + 1; while (k > 0) { if (a[ai] <= b[bi] && ai < n) { k--; if (k <= 1) median += a[ai]; ai++; } else if (a[ai] > b[bi] && bi < m) { k--; if (k <= 1) median += b[bi]; bi++; } } cout << median / 2; } }
2,275
C++
.cpp
104
13.451923
69
0.357973
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,392
median_sort_fast.cpp
OpenGenus_cosmos/code/sorting/src/median_sort/median_sort_fast.cpp
#include <vector> using namespace std; // Part of Cosmos by OpenGenus Foundation int selectPivotIndex(const vector<int>& A, const int left, const int right) { const int mid = (left + right) / 2; // median of three if (A[left] > A[mid]) // this is really insertion sort { if (A[left] > A[right]) { if (A[right] > A[mid]) return right; else return mid; } else return left; } else { if (A[mid] > A[right]) { if (A[left] > A[right]) return left; else return right; } else return mid; } } int partition(vector<int>& A, const int left, const int right, const int pivot) { swap(A[pivot], A[right]); int store = left; for (int i = left; i < right; i++) if (A[i] <= A[right]) { swap(A[i], A[store]); store++; } swap(A[store], A[right]); return store; } int selectKth(vector<int>& A, const int k, const int left, const int right) { const int idx = selectPivotIndex(A, left, right); // pivot around element const int pivot = partition(A, left, right, idx); const int kth = left + k - 1; if (kth == pivot) return pivot; if (kth < pivot) return selectKth(A, k, left, pivot - 1); else return selectKth(A, kth - pivot, pivot + 1, right); } void medianSort(vector<int>& A, const int left, const int right) { if (left >= right) return; const int medianIdx = selectKth(A, 1 + (right - left) / 2, left, right); const int mid = (right + left) / 2; swap(A[mid], A[medianIdx]); // median valued element is now the middle int k = mid + 1; for (int i = left; i < mid; i++) if (A[i] > A[mid]) { while (A[k] > A[mid]) k++; // find element on right to move left of mid swap(A[i], A[k]); } medianSort(A, left, mid - 1); medianSort(A, mid + 1, right); } void sort(vector<int>& A) { medianSort(A, 0, A.size() - 1); }
2,157
C++
.cpp
78
20.782051
77
0.523855
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,393
bubble_sort_efficient.cpp
OpenGenus_cosmos/code/sorting/src/bubble_sort/bubble_sort_efficient.cpp
#include <vector> #include <iostream> using namespace std; void bubbleSort(vector<int> &v) { for (size_t i = 0; i < v.size() - 1; i++) { bool isSorted = 1; for (size_t j = 0; j < v.size() - 1 - i; j++) if (v[j] > v[j + 1]) { swap(v[j], v[j + 1]); isSorted = 0; } for (size_t j = v.size() - 2; j >= i; j--) if (v[j] > v[j + 1]) { swap(v[j], v[j + 1]); isSorted = 0; } if (isSorted) break; } /* * In this implementation, * Modification From Normal Bubble Sort: * 1) Sorting From Both the Sides Simultaneously * 2) A variable isSorted which automatically breaks out of loop when elements get sorted reducing the total number of iterations. */ } int main() { int n; cout << "Enter the number of elements you want to enter: " << endl; cin >> n; vector<int> v(n); cout << "Enter the elements: " << endl; for (int i = 0; i < n; i++) cin >> v[i]; bubbleSort(v); cout << "Sorted Elements: " << endl; for (size_t i = 0; i < v.size(); i++) cout << v[i] << " "; cout << endl; return 0; }
1,266
C++
.cpp
46
20.217391
134
0.479769
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,394
bubble_sort_recursive.cpp
OpenGenus_cosmos/code/sorting/src/bubble_sort/bubble_sort_recursive.cpp
#include <iostream> #include <vector> // using namespace std; /* This program is the bubble sort implementation in C++ using recursion*/ void bubbleSort(std::vector<int>& v, int n) { // Base Case if (n == 1) return; // sorting in a pass for (int i = 0; i < n - 1; i++){ //comparing the elements and swapping accordingly if (v[i] > v[i + 1]){ std::swap(v[i], v[i + 1]); } } // recursive call for the next pass bubbleSort(v, n - 1); } int main() { int n; // number of elements to be sorted std::cout << "Enter the number of element:" << '\n'; std::cin >> n; std::vector<int> v; // vector of all the elements to be sorted std::cout << "Enter elements:" << '\n'; for (int i = 0; i < n; i++) { // input all the elements int x; std::cin >> x; v.push_back(x); } bubbleSort(v, n); // calling the sort function std::cout << "Sorted Elements:" << '\n'; // showing output of the sorted vector for (int element : v){ std::cout << element << " "; } std::cout << '\n'; return 0; }
1,135
C++
.cpp
41
22.585366
83
0.550046
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,395
bubble_sort.cpp
OpenGenus_cosmos/code/sorting/src/bubble_sort/bubble_sort.cpp
/* * Part of Cosmos by OpenGenus Foundation * * bubble sort synopsis * * template<typename _Bidirectional_Iter, typename _Compare> * void * bubbleSort(_Bidirectional_Iter begin, _Bidirectional_Iter end, _Compare compare); * * template<typename _Bidirectional_Iter> * void * bubbleSort(_Bidirectional_Iter begin, _Bidirectional_Iter end); */ #include <functional> template<typename _Bidirectional_Iter, typename _Compare> void bubbleSort(_Bidirectional_Iter begin, _Bidirectional_Iter end, _Compare compare) { if (begin != end) { auto frontOfSorted = end; for (--frontOfSorted; frontOfSorted != begin; --frontOfSorted) { bool swapped{}; for (auto j = begin; j != frontOfSorted; ++j) { auto nextOfJ = j; if (compare(*++nextOfJ, *j)) { std::iter_swap(nextOfJ, j); swapped = true; } } if (swapped == false) break; } } } template<typename _Bidirectional_Iter> void bubbleSort(_Bidirectional_Iter begin, _Bidirectional_Iter end) { using value_type = typename std::iterator_traits<_Bidirectional_Iter>::value_type; bubbleSort(begin, end, std::less<value_type>()); }
1,308
C++
.cpp
45
22.533333
86
0.616057
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,397
cycle_sort.cpp
OpenGenus_cosmos/code/sorting/src/cycle_sort/cycle_sort.cpp
// C++ program to impleament cycle sort #include <iostream> #include <vector> using namespace std; // Part of Cosmos by OpenGenus Foundation // Function sort the array using Cycle sort void cycleSort (vector<int>& arr) { // traverse array elements and put it to on // the right place for (size_t cycle_start = 0; cycle_start <= arr.size() - 2; cycle_start++) { // initialize item as starting point int item = arr[cycle_start]; // Find position where we put the item. We basically // count all smaller elements on right side of item. size_t pos = cycle_start; for (size_t i = cycle_start + 1; i < arr.size(); i++) if (arr[i] < item) pos++; // If item is already in correct position if (pos == cycle_start) continue; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (pos != cycle_start) swap(item, arr[pos]); // Rotate rest of the cycle while (pos != cycle_start) { pos = cycle_start; // Find position where we put the element for (size_t i = cycle_start + 1; i < arr.size(); i++) if (arr[i] < item) pos += 1; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (item != arr[pos]) swap(item, arr[pos]); } } } // Main Function int main() { vector<int> arr; cout << "Enter the elements of the array: "; int n; while (cin >> n) arr.push_back(n); cycleSort(arr); cout << "\nAfter sort : " << endl; for (size_t i = 0; i < arr.size(); i++) cout << arr[i] << " "; return 0; }
1,910
C++
.cpp
60
23.8
78
0.532609
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,398
policy_design.cpp
OpenGenus_cosmos/code/design_pattern/src/policy_based_design/policy_design.cpp
/* * policy_design.cpp * * Created: 3/15/2018 1:14:41 AM * Author: n-is * email: 073bex422.nischal@pcampus.edu.np */ #include <iostream> class Classical { public: Classical(int a) { } void solve() { std::cout << "The differential equation was solved by the classical" << " method." << std::endl; } }; class Laplace { public: void solve() { std::cout << "The differential equation was solved by the Laplace" << " Transform method." << std::endl; } }; template <class Method> class DifferentialEquaton { private: Method m_; public: DifferentialEquaton(const Method & m = Method()) : m_(m) { } void solve() { m_.solve(); } }; int main() { DifferentialEquaton<Laplace> eqn1; DifferentialEquaton<Classical> eqn2(Classical(1)); eqn1.solve(); eqn2.solve(); return 0; }
920
C++
.cpp
52
13.711538
79
0.607683
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,400
singleton_pattern.cpp
OpenGenus_cosmos/code/design_pattern/src/OOP_patterns/singleton_pattern/singleton_pattern.cpp
#include <string> #include <iostream> template<typename T> class Singleton { public: static T* GetInstance(); static void destroy(); private: Singleton(Singleton const&) { }; Singleton& operator=(Singleton const&) { }; protected: static T* m_instance; Singleton() { m_instance = static_cast <T*> (this); }; ~Singleton() { }; }; template<typename T> T * Singleton<T>::m_instance = 0; template<typename T> T* Singleton<T>::GetInstance() { if (!m_instance) Singleton<T>::m_instance = new T(); return m_instance; } template<typename T> void Singleton<T>::destroy() { delete Singleton<T>::m_instance; Singleton<T>::m_instance = 0; } class TheCow : public Singleton<TheCow> { public: void SetSays(std::string &whatToSay) { whatISay = whatToSay; }; void Speak(void) { std::cout << "I say" << whatISay << "!" << std::endl; }; private: std::string whatISay; }; void SomeFunction(void) { std::string say("moo"); TheCow::GetInstance()->SetSays(say); } int main () { std::string say("meow"); TheCow::GetInstance()->SetSays(say); SomeFunction(); TheCow::GetInstance()->Speak(); }
1,239
C++
.cpp
66
15.166667
61
0.628768
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,401
factorial.cpp
OpenGenus_cosmos/code/divide_conquer/src/factorial/factorial.cpp
#include<iostream> int factorial(int num) { if (num == 0 || num == 1) { return num; } return (num * factorial(num - 1)); } int main() { int num; while (true) { std::cin >> num; std::cout << "> " << factorial(num) << '\n'; } return 0; }
291
C++
.cpp
15
14.733333
52
0.481752
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
10,402
search_in_a_rotated_array.cpp
OpenGenus_cosmos/code/divide_conquer/src/search_in_a_rotated_array/search_in_a_rotated_array.cpp
/* Problem statement: Given a sorted and rotated array A of N distinct elements which is rotated at some point, and given an element K. The task is to find the index of the given element K in the array A. */ #include <iostream> #include <vector> #define ll long long int ll findPivot(std::vector<ll> &v, ll low, ll high) { while (low < high) { // find mid element ll mid = low + (high - low) / 2; if (v[mid] < v[0]) { high = mid; } else { low = mid + 1; } } if (v[low] < arr[0]) { return low; } else { // pivot element does not exist return -1; } } ll findAns(std::vector<ll> &v, ll k, ll low, ll high) { while (low < high) { // find mid element ll mid = low + (high - low) / 2; if (v[mid] == k) { return mid; } if (v[mid] >= k) { high = mid; } else { low = mid + 1; } } if (v[low] == k) { return low; } else { // element does not exist in array return -1; } } int main() { ll test, n, k, pivot; std::cin >> test; // no. of test cases std::vector<ll> v; while (test--) { std::cin >> n; // size of array for (ll i = 0; i < n; i++) { ll num; std::cin >> num; v.push_back(num); } std::cin >> k; // element to be searched pivot = findPivot(v, 0, n - 1); // find pivot element if (pivot == -1) { // if pivot element does not exist, elements are // whole array is in ascending order std::cout << findAns(v, k, 0, n - 1) << "\n"; } else { if (k >= v[0]) { std::cout << findAns(v, k, 0, pivot - 1) << "\n"; } else { std::cout << findAns(v, k, pivot, n - 1) << "\n"; } } v.clear(); } return 0; } /* Input: 3 9 5 6 7 8 9 10 1 2 3 10 3 3 1 2 1 4 3 5 1 2 6 Output: 5 1 -1 */
2,170
C++
.cpp
91
16.175824
75
0.44836
OpenGenus/cosmos
13,556
3,669
2,596
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false