0% found this document useful (0 votes)
3 views

Lab Report New (1)

Uploaded by

rafi2305101053
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lab Report New (1)

Uploaded by

rafi2305101053
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Lab Report

Course Code: CSE214

Course title: Algorithms LAB

Assignment Name: Bin Packing, LCS & LIS

Submitted To
Name: Mr. Mehadi Hasan

Designation: Lecturer

Department of CSE

Daffodil International University

Submitted By
Name: Jahid Hosain
ID: 232-15-542
Section: 65_M
Department of CSE
Daffodil International University

Date of Submission: 08/09/2024


Bin Packing:

#include<stdio.h>
Void bin packing (int *a, int size, int n)
Int bin count=1, i;
Int s= size;
For ( i=0; i<n; i++){
If(s_ *(a+i)>0){
S_=*(a+i);
Continue;
}
Else{
Bincount++;
I --;
}
}
Printf (“number of bins require: %d”, bincount );
}
Int main (int argc, char**argv){
Int n;
Int size;
Printf(“enter the number of items in set :”);
Scanf(“%d”,&n);
Printf(“enter %d items”,n);
For(i=0;i<n;i++0{
Scanf(“%d”,&a[i]);
Printf(“enter the bin size:”);
Scanf(“%d”,&size);
Binpacking(a,size,n);
Return 0;
}
Longest Common Subsequence (LCS):
#include<stdio.h>
#include<string.h>
Int i, j, m, n, c[20][20];
Char x[20],y[20],b[20][20];
Void print (int I, int j){
If(i==0||j==0){
Return;
}
If(b[i][j]==”c”){
Printf(i-1;j-1);
Printf(“%d”,x[i-1]);
}
else if(b[i][j]==u){
printf(i-1,j);
}else{
Printf(I,j-1);
}
}
Void Lcs(){
M=strlen(x);
N=strlen(y);
For(i=0;i<=m;i++){
C[o][i]=0;
}
for(i=1i<=m;i++){
for(j=1;j<=n;j++){
if(x[i-1]==y[j-1]{
c[i][j]=c=[i-1][j-1]+1;
b[i][j]=’c’;
}
else if (c[i-1][j]>=c[i][j-1]){
c[i][j]=c[i-1][j];
b[i][j]=’u’’
}
else{
c[i][j]=c[i][j-1];
b[i][j]=’1’;
}
}
}
}
Int main(){
Printf(“enter 1st sequence:”);
Scanf(“%s”,&x);
Printf(“enter 2nd sequence :”);
Scanf(“%s”,&y);
Printf(“in the longest common subsequence lcs);
Printf(m,n);
Return 0;
}

longest increasing subsequence (LIS)


#include <iostream>
#include <vector>
using namespace std;
int lisEndingAtIdx(vector<int>& arr, int idx) {
if (idx == 0)
return 1;
int mx = 1;
for (int prev = 0; prev < idx; prev++)
if (arr[prev] < arr[idx])
mx = max(mx, lisEndingAtIdx(arr, prev) + 1);
return mx;
}

int lis(vector<int>& arr) {


int n = arr.size();
int res = 1;
for (int i = 1; i < n; i++)
res = max(res, lisEndingAtIdx(arr, i));
return res;
}

int main() {
vector<int> arr = { 10, 22, 9, 33, 21, 50, 41, 60 };
cout << lis(arr);
return 0;
}
Lab Report
Course Code: CSE214

Course title: Algorithms LAB

Assignment Name: Depth First Search (DFS)

Submitted To
Name: Mr. Mehadi Hasan

Designation: Lecturer

Department of CSE

Daffodil International University

Submitted By
Name: Jahid Hosain
ID: 232-15-542
Section: 65_M
Department of CSE
Daffodil International University

Date of Submission: 22/09/2024


Depth First Search (DFS)
Introduction:
Depth First Search (DFS) is an algorithm to traversing or searching tree or graph data structure. DFS
algorithm is a recursive algorithm that uses the idea of backtracking. It involves exhaustive searches
of all the nodes by going ahead, if possible, or by backtracking. Charles Pierre Tremaux investigated
DFS in the 19th Century.
Time Complexity:
The time complexity of DFS is Big-O(V+E) for explicit Graph and Big-O (V) for graph is traversed.
Advantage:
1. It consumes very little memory space.
2. It will reach the goal node faster than BFS if it traverses in the right path.
3. It may find a solution without examining much of a search because we may get the desired solution
in the very first go.
4. Find the larger distant element in less time.
Disadvantage:
1. It is possible that many states keep repeating.
2. There is no guarantee of finding the goal node.
3. Sometimes the states may also enter into infinite loops.
4. May not find an optimal solution to the problem.
5. May get trapped in searching useless path.
Outcomes:
In this lesson, we learn about DFS and its implementation. We use this concept in real life- using DFS
a virtualization layer between clients and file servers is numerous, including better organization of a
company file shares, increased flexibility for storage administrators, efficient solutions to several
business critical problems, etc.
Code Implementation of DFS Algorithm:
#include <stdio.h>
#include <stdlib.h>
struct node {
int vertex;
struct node* next;
};

struct node* createNode(int v);


struct Graph {
int numVertices;
int* visited;
};
void DFS(struct Graph* graph, int vertex) {
struct node* adjList = graph->adjLists[vertex];
struct node* temp = adjList;

graph->visited[vertex] = 1;
printf("Visited %d \n", vertex);
while (temp != NULL) {
int connectedVertex = temp->vertex;
if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*));
graph->visited = malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
void addEdge(struct Graph* graph, int src, int dest) {
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
void printGraph(struct Graph* graph) {
int v;

for (v = 0; v < graph->numVertices; v++) {


struct node* temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n ", v);

while (temp) {
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}
int main() {
struct Graph* graph = createGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);
printGraph(graph);
DFS(graph, 2);
return 0;
}
Lab Report
Course Code: CSE214

Course title: Algorithms LAB

Assignment Name: Binary search & Marge sort

Submitted To
Name: Mr. Mehadi Hasan

Designation: Lecturer

Department of CSE

Daffodil International University

Submitted By
Name: Jahid Hosain
ID: 232-15-542
Section: 65_M
Department of CSE
Daffodil International University

Date of Submission: 20/10/2024


Binary Search:

Binary search is an efficient algorithm for finding anitem for a sorted list of items.

. binary search is the search technique that works efficiently on sorted lists.

. Binary search follows the divides conquer approach into two halves , and the items is compared
with is compared with the middle element of the middle element of the list . if the match is found
then the location of the middle element is returned . otherwise , we search into either of the halve
depending upon the result produce through the match .

Binary search working procedure:

1.Initial step:

Binary search requires a sored array to work efficiently . Ensure that the array is stored in ascending
or decending order before starting the search .

2.Define Search Interval :

Set two pointers ‘low’&’high’ , initially pointing to the first and last elements of the array
repectively . these pointers define the search interval with in which the target value may exist.

3.Calculate midpoint:

Calculate the mid point index of the current search interval . using the formula Mid=(low+high)/2;

4. check mid point value :

Retrieve the value at the mid point index of the array .

5.Compare with target value :

. if the value at the midpoint is equal to the target value ,The search is successful , and the index of
the target value is returned .

.If the value at the midpoint is greater than the target value , update interval to the lower half of the
array .

.If the value at the midpoint is less than the target value , update the low pointer to ‘mid+1 ‘ , n
arrowing the search interval to the upper half of the array .
6.Repat:

Repeat steps 3-5 until one of the following conditions is met .

.The target value is found .

.The low pointer exceed the high pointer indicating that the target value is not present in the
array .

7. Result:

If the target value is found , return its index in the array . otherwish indicate that the target value is
not present in the array .

Binary search visualization:

Search 23;

0 1 2 3 4 5 6 7 8 9

2 5 8 12 16 23 38 56 72 91

Search 23;

0 1 2 3 4 5 6 7 8 9

2 5 8 12 16 23 38 56 72 91

23>16 ; take 2nd half

L=0 1 2 3 mid=4 5 6 7 8 9

2 5 8 12 16 23 38 56 72 91

23<56 ; take 1st half

L=0 1 2 3 4 5 6 mid= 7 8 9

2 5 8 12 16 23 38 56 72 91
Found 23 , returns

L=0 1 2 3 4 5 6 7 8 9

2 5 8 12 16 23 38 56 72 91

Code:
#include <stdio.h>
Int binarysearch (int array [ ], int size , int search)
{
Int l=0;
Int h=size-1;
Int middle ;
While(l<=h)
{
Middle=(l+h)/2;
If (array[middle]==search)
{
Return middle;
}else if(array [middle]<search)
{
L=middle+1;
}else
{
H=middle-1;
}
}
Return-1;
}
Int main()
{
Int array [100];
Int size,search, index, I;
Printf(“Enter the size of the array”);
Scanf(“%d”,&size);
Printf(“Enter the array ascending order:”);
For(i=0;i<size;i++)
{
Scanf(“%d”,&search);
Index= binarysearch(array, size, search);
If(index==-1)
{
Printf(“Element %d is not found in the array \n”,search);

}else
{
Printf(“Element %d is found at indedx %d”. in, search,index)
}
}
Return 0;
}

Input out put :

Enter the size of the array :10;


Enter the array ascending order:
2 5 8 12 16 23 38 56 72 91
Enter the element of search :23
Element 23 is found at index 5

Merge sort:

Merge sort is a sorting technique based on the divide and conquer technique .
. Merge sort is one of the most popular and efficient sorting algoritham . it divides the given list

into two equal halves , calls itself for the two halves and then merge the two sorted halves , we
have to define the merge function to performance the merging .

. The sun-list are divided again and again into halves until the list can not be divided furthers . then

we combine the pair of one element lists into two elements lists sorting them in the process . the
sorted two elements pairs is merged into the four-element lists , and so , on until we get the sorted
list .

Working procedure for merge sort:


6
1.Divide: The unsorted array is divided into equal halves .

2.Recursively sort: Recursively sort the two halves using the merge sort algoritham until each half
conditions only one elements

3.Merge: Merge the sorted halves back together in sorted manner. This is done by comparing the
elements from the two halves and placing then in the correct order into a temporary array .

4.Repeat : Continue this process of dividing sorting and merging until the entire array is sorted.

Merge sort visualization:

11 6 3 24 46 22 7

11 6 3 24 46 22 7

11 6 3 24 46 22 7

11 3 24 46 22 7
6 11 3 24 22 46 7

3 6 11 24 7 22 46

3 6 7 11 22 24 46

Code:
#include<stdio.h>
Void merge(int arr[ ] , int l int m,int r)
{
Int I, j,k;
Int n1=m-l+1;
Int n2=r-m;
Int l[n1],R[n2];
For(i=0;j<n1;i++)
{
L[i]=arr[l+i];
}
For(j=0;j<n2;j++)
{
R[j]=arr[m+1+j];
}
I=0;
J=0;
K=1;
While(i<n1&&j<n2)
{
If(L[i]<=R[j]
{
Arra[k]=L[i]
i++;
}else
{
Arr[k]=R[j];
J++;
}
K++;
}
While(i<n1)
{
Arr[k]=L[i];
I++;
K++;

}
While(j<n2)
{
Arr[k]=R[j];
J++;
K++;

}
}
Void merge sort(int arr[ ],int l, int r)
{
If(l<r)
{
Int m=l+(r-l)/2;
Merge sort(arr,l,m);
Merge sort(arr,m+1,r);
Merge sort(arr,l,m,r);
}
}
Void printArray(int A[ ],int size)
{
Int I;
For(i=0;i<size;i++)
{
Printf(“%d”,A[i]);
}
Int main( )
{
Int arr[100];
Int size*I;
Printf(“Enter the size of array:”);
Scanf(“%d”,&size);
Printf(“Enter the element of array :”);
For(i=0;i<size;i++)
{
Scanf(“%d”,&size);

}
Printf(“Given array printed:”);
printArray(arr,arr-size);
mergesort(arr,arr,-size-1);
printf(“sorted array printed”);
printArray(arr,arr-size);
return 0;
}
Inpput out put:
Enter the size of array:7
Enter the element of array:
11 6 3 24 46 22 7
Given Array printed: 11 6 3 24 46 22 7
Sorted Array printed: 3 6 7 11 22 24 46
Lab Report
Course Code: CSE214

Course title: Algorithms LAB

Assignment Name: Greedy & DP

Submitted To
Name: Mr. Mehadi Hasan

Designation: Lecturer

Department of CSE

Daffodil International University

Submitted By
Name: Jahid Hosain
ID: 232-15-542
Section: 65_M
Department of CSE
Daffodil International University

Date of Submission: 03/11/2024

Greedy Approach:
A Greedy algorithm is any algorithm that follows the problem-solving heuristic of making the locally
optimal choice at each stage with the intent of finding a global optimal . In many problems, a greedy
strategy does not usually produce an optimal solution,but nonetheless a greedy heuristic may yield
locally optimal solutions that approximate a globally optimal solution in a reasonable amount of
time.

Application:

Suppose you are a shopkeeper and there is customer in your shop and you have to return total
11 taka to him.And have coins of 1,5,6 and 8. Now suppose you are willing to give it by using
minimum number of coins. So, that's where it will come handy.

And moreover,coin change problem is actually a very good example to illustrate the difference
between strategy and dynamic programming.

Advantage & Disadvantage (DP):


Advantages are:

1. They are easier to implement.

2. They require fewer computing resources.

3. They are much faster to execute.

4. Greedy algorithms are used to solve optimization problem.

Disadvantages are:

1. Their only disadvantage is that they do not always reach up to optimum solution.

2. On the other hand, even when the global optimum solution is not reached most of the
times the reached sub optimal solution is very good solution.

Basic code of coin change:


#include <stdio.h>
void insertion(int A[],int x){
int item,i;
for(i=0;i<x;i++){
item = A[i];
int j = i-1;
while(j>=0&&A[j]<item){
A[j+1]=A[j];
j=j-1;
}
A[j+1]=item;
}
}
int main(){
int m,i,back,total_coin;
int taka[100];
printf("Enter total coin :");
scanf("%d",&total_coin);
printf("Enter coin:");
for(i=0;i<total_coin;i++){
scanf("%d",&taka[i]);
}
insertion(taka,total_coin);
printf("\n Minimum coin:\n");
for(i=0;i<total_coin;i++){
if(taka[i]<=back){
m=back/taka[i];
printf("%d coin %d times\n",taka[i],m);
back= back%taka[i];
}
}
}

Dynamic Programming:

Dynamic programming is mainly an optimization over plain recursion. Whenever we see a


recursive solution that has repeated called for same inputs,we can optimize it using Dynamic
programming. The idea is to simply store the results of sub - problems, so that we don’t have to
re-compute them when needed later. This simple optimization reduces time complexities from
exponential to polynomial. For example,if we write simple recursive solution for Fibonacci
Numbers, we get exponential time complexity and if we optimize it by storing solutions of sub-
problems, time complexity reduces to linear.

How does Dynamic Programming work?

1. Identify Sub-problem: Divide the main problem into smaller independent sub problems.

2. Store Solution: Solve each sub-problem and store the solution in a table or array.

3. Build Up solution : Use the stored solutions to build up tje solution to the main problem.

4. Avoid Redundancy: By storing slotutions, DP ensures that each sub-prolem is solved only once
reducing computation time.
Advantages & Disadvantages (DP):

Advantages are:

1.For the various problem in area such as inventory,chemical engineering design and control
theory.Dynamic programming is the only technique used to solve the problem.

2. It is well suited for multi-stage or multi-point or sequential decision process.

3. It is suitable for linear or non linear problems, discrete or continuous variable and deterministic
problems.

Disadvantages are:

1. No general for mation of dynamic programming is available ; every problem has to be solving
in it’s own way.

2. Dividing problem in sub problem and storing inter mediate results consumes memory.

Basic code of Fractional Knapsack:


#include <stdio.h>
int max(int a, int b) {
return (a > b) ? a : b;
}

int knapsack(int w, int wt[], int val[], int n) {


int i, j;
int k[n + 1][w + 1];
for (i = 0; i <= n; i++) {
for (j = 0; j <= w; j++) {
if (i == 0 || j == 0) {
k[i][j] = 0;
} else if (wt[i - 1] <= j) {
k[i][j] = max(val[i - 1] + k[i - 1][j - wt[i - 1]], k[i - 1][j]);
} else {
k[i][j] = k[i - 1][j];
}
}
}

return k[n][w];
}

int main() {
int i, n, val[20], wt[20], w;
printf("Enter number of items: ");
scanf("%d", &n);
printf("Enter value and weight of items:\n");
for (i = 0; i < n; ++i) {
scanf("%d %d", &val[i], &wt[i]);
}
printf("Enter size of knapsack: ");
scanf("%d", &w);
printf("Maximum value: %d\n", knapsack(w, wt, val, n));
return 0;
}
Lab Report
Course Code: CSE214

Course title: Algorithms LAB

Assignment Name: Solution of contest problem

Submitted To
Name: Mr. Mehadi Hasan

Designation: Lecturer

Department of CSE

Daffodil International University

Submitted By
Name: Jahid Hosain
ID: 232-15-542
Section: 65_M
Department of CSE
Daffodil International University

Date of Submission: 24/11/2024

A- Unique Numbers:-
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios base:: sync_with_stdio (0);
Cin.tie (0);
int n;
cin>>n;
Vector <int> a;
a. resize (n);
for (int i=0; i<n; i++) {
cin >> a[i];
}
Sort (a.begin(), a.end());
int ans = 0;
for (int i=0; i<n; i++) {
if (i == 0) {
ans++;
continue; }
if (a[i] != a[i-1])
{
ans++;
}
}
cout << ans << endl;
return 0;
}
B-Sum
#include <bits/stdc++.h>
using namespace std;
void Solve () {
int n;
cin >> n;
int a[n];
for (int i=0; i<n; i++) cin >> a[i];
Long Long ans=-1e18, sum=-1e18;
for (int i=0; i<n; i++) {
sum = max (Long Long (*a[i], a[i]+sum);
ans = max (ans, sum);
cout << ans <<< endl;
}
int 32-t main (){
ios-base:: syne-with-Stdio(false);
cin.tie (nullptr) cout.tie (nullptr);
Solve();
return 0;
}

C-Search:
#include<bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int N, Q;
cin >> N >> Q;
int a[N];
for (int i = 0; i < N; i++)
cin >> a[i];
for (int i = 0; i < Q; i++) {
int x;
cin >> x;
int l = 0, h = N - 1, index = -1;
while (l <= h) {
int mid = (l + h) / 2;
if (a[mid] == x) {
index = mid;
h = mid - 1;
} else if (a[mid] > x) {
h = mid - 1;
} else {
l = mid + 1;
}
}
cout << index << endl; }
}
4.#include <iostream>
#include <algorithm>
using namespace std;

int main() {
int n, m;
cin >> n;

int a[n], prefix_sum[n];


int sum = 0;

for (int i = 0; i < n; ++i) {


cin >> a[i];
sum += a[i];
prefix_sum[i] = sum;
}

cin >> m;
int b[m];
for (int i = 0; i < m; ++i) {
cin >> b[i];
}
for (int j = 0; j < m; ++j) {
cout << lower_bound(prefix_sum, prefix_sum + n, b[j]) - prefix_sum + 1 << endl;
}

return 0;
}
5.#include <stdio.h>

int main() {
int n, k;
scanf("%d %d", &n, &k);

int sc[n];
for (int i = 0; i < n; i++) {
scanf("%d", &sc[i]);
}
int count = 0;
for (int i = 0; i < n; i++) {
if (sc[k-1] != 0) {
if (sc[i] >= sc[k-1]) {
count++;
}
} else if (sc[k-1] == 0) {
if (sc[i] > sc[k-1]) {
count++;
}
} else {
break;
}
}
printf("%d\n", count);
return 0;
}

6.#include <iostream>
#include <limits>
urring namespace std;
int main(){
int T;
cin >> T;
white (T--) {
int numStore, min = INT_MAX;
cin >> numstore;
For (int i=0; i<numstore; ++i) {
int temp;
cin >> temp;
if (temp < min)
min = temp;
if (temp>max)
max = temp;
}
cout << (max-món) * 2 <<< endl;
}
return 0;
}

You might also like