Professional Documents
Culture Documents
Lab Exam
Lab Exam
#include <bits/stdc++.h>
using namespace std;
string findSum(string str1, string str2)
{
if (str1.length() > str2.length())
swap(str1, str2);
string str = "";
int n1 = str1.length();
int n2 = str2.length();
reverse(str1.begin(), str1.end());
reverse(str2.begin(), str2.end());
int carry = 0;
for (int i = 0; i < n1; i++) {
int sum= ((str1[i] - '0') + (str2[i] - '0') + carry);
str.push_back(sum % 10 + '0');
carry = sum / 10;
}
for (int i = n1; i < n2; i++) {
int sum = ((str2[i] - '0') + carry);
str.push_back(sum % 10 + '0');
carry = sum / 10;
}
if (carry)
str.push_back(carry + '0');
reverse(str.begin(), str.end());
return str;
}
string findDiff(string str1, string str2)
{
// Stores the result of difference
string str = "";
// Calculate length of both string
int n1 = str1.length(), n2 = str2.length();
// Reverse both of strings
reverse(str1.begin(), str1.end());
reverse(str2.begin(), str2.end());
int carry = 0;
for (int i = 0; i < n2; i++) {
int sub
= ((str1[i] - '0')
- (str2[i] - '0')
- carry);
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str.push_back(sub + '0');
}
for (int i = n2; i < n1; i++) {
int sub = ((str1[i] - '0') - carry);
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str.push_back(sub + '0');
}
reverse(str.begin(), str.end());
return str;
}
string removeLeadingZeros(string str)
{
const regex pattern("^0+(?!$)");
str = regex_replace(str, pattern, "");
return str;
}
string multiply(string A, string B)
{
if (A.length() > B.length())
swap(A, B);
int n1 = A.length(), n2 = B.length();
while (n2 > n1) {
A = "0" + A;
n1++;
}
if (n1 == 1) {
int ans = stoi(A) * stoi(B);
return to_string(ans);
}
if (n1 % 2 == 1) {
n1++;
A = "0" + A;
B = "0" + B;
}
string Al, Ar, Bl, Br;
for (int i = 0; i < n1 / 2; ++i) {
Al += A[i];
Bl += B[i];
Ar += A[n1 / 2 + i];
Br += B[n1 / 2 + i];
}
string p = multiply(Al, Bl);
string q = multiply(Ar, Br);
string r = findDiff(
multiply(findSum(Al, Ar),
findSum(Bl, Br)),
findSum(p, q));
for (int i = 0; i < n1; ++i)
p = p + "0";
for (int i = 0; i < n1 / 2; ++i)
r = r + "0";
string ans = findSum(p, findSum(q, r));
ans = removeLeadingZeros(ans);
return ans;
}
int main()
{
string A = "743333";
string B = "300000";
cout << multiply(A, B);
return 0;
}
2) Sorting with time
CODE:
#include <bits/stdc++.h>
#include <sys/time.h>
using namespace std;
void merge(int arr[], int p, int q, int r)
{
int n1 = q - p + 1; int n2 = r - q;
int L[n1], M[n2];
for (int i = 0; i < n1; i++) L[i] = arr[p + i];
for (int j = 0; j < n2; j++) M[j] = arr[q + 1 + j];
int i, j, k; i = 0;
j = 0;
k = p;
while (i < n1 && j < n2)
{
if (L[i] <= M[j])
{
arr[k] = L[i]; i++;
}
else
{
arr[k] = M[j]; j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i]; i++;
k++;
}
while (j < n2)
{
arr[k] = M[j]; j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l + (r - l) / 2;
mergeSort(arr, l, m); mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void func()
{
int n, i;
cout<<"Enter number of elements : "; cin>>n;
int arr[n];
cout<<"Enter the elements : "; for(i = 0; i < n; i++)
{
cin>>arr[i];
}
mergeSort(arr, 0, n-1); cout<<"Minimum = "<<arr[0]<<endl; cout<<"Maximum = "<<arr[n-
1]<<endl;
}
int main()
{
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
ios_base::sync_with_stdio(false);
func();
clock_gettime(CLOCK_MONOTONIC, &end);
double time_taken;
time_taken = (end.tv_sec - start.tv_sec) * 1e9;
time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9;
cout << "Time taken by program is : " << fixed
<< time_taken << setprecision(9);
cout << " sec" << endl;
return 0;
}
Code:
#include <vector>
void DijkstrasTest();
class Node;
class Edge;
void Dijkstras();
vector<Node*> nodes;
vector<Edge*> edges;
class Node {
public:
Node(char id)
nodes.push_back(this);
public:
char id;
Node* previous;
int distanceFromStart;
};
class Edge {
public:
edges.push_back(this);
}
return (
node2 == this->node2) ||
node2 == this->node1));
public:
Node* node1;
Node* node2;
int distance;
};
///////////////////
void DijkstrasTest() {
Dijkstras();
PrintShortestRouteTo(f);
///////////////////
void Dijkstras() {
vector<Node*>* adjacentNodes =
AdjacentRemainingNodes(smallest);
smallest->distanceFromStart;
adjacent->distanceFromStart = distance;
adjacent->previous = smallest;
delete adjacentNodes;
}
int smallestPosition = 0;
if (current->distanceFromStart <
smallest->distanceFromStart) {
smallest = current;
smallestPosition = i;
nodes.erase(nodes.begin() + smallestPosition);
return smallest;
if (edge->node1 == node) {
adjacent = edge->node2;
adjacentNodes->push_back(adjacent);
return adjacentNodes;
if (edge->Connects(node1, node2)) {
return edge->distance;
if (node == nodes.at(i)) {
return true;
return false;
}
///////////////////
while (previous) {
previous = previous->previous;
if (edge->node1 == node) {
adjacentEdges->push_back(edge);
adjacentEdges->push_back(edge);
}
}
return adjacentEdges;
vector<Edge*>::iterator it;
if (*it == edge) {
edges.erase(it);
return;
int main() {
DijkstrasTest();
clock_gettime(CLOCK_MONOTONIC, &start);
ios_base::sync_with_stdio(false);
Dijkstras;
clock_gettime(CLOCK_MONOTONIC, &end);
double time_taken;
<< time_taken;
return 0;
#include<iostream>
#include<climits>
using namespace std;
// this method returns a minimum distance for the
// vertex which is not included in Tset.
int minimumDist(int dist[], bool Tset[])
{
int min=INT_MAX,index;
for(int i=0;i<6;i++)
{
if(Tset[i]==false && dist[i]<=min)
{
min=dist[i];
index=i;
}
}
return index;
}
int main()
{
int graph[6][6]={
{0, 10, 20, 0, 0, 0},
{10, 0, 0, 50, 10, 0},
{20, 0, 0, 20, 33, 0},
{0, 50, 20, 0, 20, 2},
{0, 10, 33, 20, 0, 1},
{0, 0, 0, 2, 1, 0}};
Dijkstra(graph,0);
return 0;
}
#include <bits/stdc++.h>
using namespace std;
class DSU {
int* parent;
int* rank;
public:
DSU(int n)
{
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = -1;
rank[i] = 1;
}
}
// Find function
int find(int i)
{
if (parent[i] == -1)
return i;
return parent[i] = find(parent[i]);
}
// union function
void unite(int x, int y)
{
int s1 = find(x);
int s2 = find(y);
if (s1 != s2) {
if (rank[s1] < rank[s2]) {
parent[s1] = s2;
rank[s2] += rank[s1];
}
else {
parent[s2] = s1;
rank[s1] += rank[s2];
}
}
}
};
class Graph {
vector<vector<int> > edgelist;
int V;
public:
Graph(int V) { this->V = V; }
void addEdge(int x, int y, int w)
{
edgelist.push_back({ w, x, y });
}
void kruskals_mst()
{
// 1. Sort all edges
sort(edgelist.begin(), edgelist.end());
// Initialize the DSU
DSU s(V);
int ans = 0;
cout << "Following are the edges in the "
"constructed MST"
<< endl;
for (auto edge : edgelist) {
int w = edge[0];
int x = edge[1];
int y = edge[2];
// take that edge in MST if it does form a cycle
if (s.find(x) != s.find(y)) {
s.unite(x, y);
ans += w;
cout << x << " -- " << y << " == " << w
<< endl;
}
}
cout << "Minimum Cost Spanning Tree: \n " << ans;
}
};
int main()
{
Graph g(4);
g.addEdge(0, 1, 10);
g.addEdge(1, 3, 15);
g.addEdge(2, 3, 4);
g.addEdge(2, 0, 6);
g.addEdge(0, 3, 5);
g.kruskals_mst();
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
ios_base::sync_with_stdio(false);
clock_gettime(CLOCK_MONOTONIC, &end);
double time_taken;
time_taken = (end.tv_sec - start.tv_sec) * 1e9;
time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9;
cout << "Time taken by program is : " << fixed
<< time_taken << setprecision(9);
cout << " sec" << endl;
return 0;
}
5) Kmp algorithm:
#include<iostream>
#include<string.h>
using namespace std;
void prefixSuffixArray(char* pat, int M, int* pps) {
int length = 0;
pps[0] = 0;
int i = 1;
while (i < M) {
if (pat[i] == pat[length]) {
length++;
pps[i] = length;
i++;
} else {
if (length != 0)
length = pps[length - 1];
else {
pps[i] = 0;
i++;
}
}
}
}
void KMPAlgorithm(char* text, char* pattern) {
int M = strlen(pattern);
int N = strlen(text);
int pps[M];
prefixSuffixArray(pattern, M, pps);
int i = 0;
int j = 0;
while (i < N) {
if (pattern[j] == text[i]) {
j++;
i++;
}
if (j == M) {
printf("Found pattern at index %d\n", i - j);
j = pps[j - 1];
}
else if (i < N && pattern[j] != text[i]) {
if (j != 0)
j = pps[j - 1];
else
i = i + 1;
}
}
}
int main() {
char text[] = "xyztrwqxyzfg";
char pattern[] = "xyz";
printf("The pattern is found in the text at the following
index : \n");
KMPAlgorithm(text, pattern);
return 0;
}
5) Matrix multiplication:
#include<stdio.h>
#include<limits.h>
int MatrixChainMultiplication(int p[], int n)
{
int m[n][n];
int i, j, k, L, q;
for (i=1; i<n; i++)
m[i][i] = 0; //number of multiplications are 0(zero) when there is only one matrix
//Here L is chain length. It varies from length 2 to length n.
for (L=2; L<n; L++)
{
for (i=1; i<n-L+1; i++)
{
j = i+L-1;
m[i][j] = INT_MAX; //assigning to maximum value
for (k=i; k<=j-1; k++)
{
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
if (q < m[i][j])
{
m[i][j] = q; //if number of multiplications found less that number will be updated.
}
}
}
}
return m[1][n-1]; //returning the final answer which is M[1][n]
}
int main()
{
int n,i;
printf("Enter number of matrices\n");
scanf("%d",&n);
n++;
int arr[n];
printf("Enter dimensions \n");
for(i=0;i<n;i++)
{
printf("Enter d%d :: ",i);
scanf("%d",&arr[i]);
}
int size = sizeof(arr)/sizeof(arr[0]);
printf("Minimum number of multiplications is %d ", MatrixChainMultiplication(arr, size));
return 0;
}
6) Rod cutting problems:
1. #include<iostream>
2. #include<climits>
3.
4. using namespace std;
5.
6. int rodCutting(int n, int value[])
7. {
8. int i,j;
9.
10. //we will calculate the maximum attainable value of rod in a bottom up
fashion by first calculating for smaller value of n and then using these values
to calculate higher values of n
11.
12. //create an array to store the results
13. int result[n+1];
14.
15. //result[i]=maximum attainable value of rod of size i
16.
17. //initialization
18. result[0]=0;
19.
20. //in every iteration, find the result for rod of size i
21. for(i=1;i<=n;i++)
22. {
23. result[i]=INT_MIN;
24.
25. //try to cut the rod of length i into various values of j and select the
one which gives the maximum value
26. for(j=0;j<i;j++)
27. {
28. result[i]=max(result[i],value[j]+result[i-(j+1)]);
29. }
30. }
31.
32.
33. return result[n];
34. }
35.
36. int main()
37. {
38. int n;
39. cout<<"Enter the length of the rod"<<endl;
40. cin>>n;
41.
42. int value[n];
43. //value[i]=value of rod of size i+1
44. //value[0]=value of rod of size 1
45. //value[1]=value of rod of size 2
46.
47. cout<<"Enter the values of pieces of rod of all size"<<endl;
48.
49. for(int i=0;i<n;i++)
50. cin>>value[i];
51.
52. cout<<"Maximum obtainable value by cutting up the rod in many pieces
are"<<endl;
53. cout<<rodCutting(n,value);
54.
55. cout<<endl;
56. return 0;
57. }
}
while (i < n1)
{
arr[k] = L[i]; i++;
k++;
}
while (j < n2)
{
arr[k] = M[j]; j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l + (r - l) / 2;
mergeSort(arr, l, m); mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void func()
{
int n, i;
cout<<"Enter number of elements : "; cin>>n;
int arr[n];
cout<<"Enter the elements : "; for(i = 0; i < n; i++)
{
cin>>arr[i];
}
mergeSort(arr, 0, n-1); cout<<"Minimum = "<<arr[0]<<endl; cout<<"Maximum = "<<arr[n-
1]<<endl;
}
int main()
{
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); ios_base::sync_with_stdio(false);
func(); clock_gettime(CLOCK_MONOTONIC, &end);