Ilovepdf Merged
Ilovepdf Merged
Experiment 2.2
Student Name:Shashi Ranjan Mehta UID: 21BCS7093
Branch:BE-CSE Section/Group: IoT-624
Semester:5 Date of Performance:22-09-2023
Subject Name: Advance Programming Lab
Subject Code: 21CSP-314
1. Aim:
1.WAP to find the top of tree
2.WAP to implement bst insertion
2. Objective:
1. Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen
from the top the nodes, is called the top view of the tree
2. You are given a pointer to the root of a binary search tree and values to be inserted into the
tree. Insert the values into their appropriate position in the binary search tree and return the root
of the updated binary tree. You just have to complete the function.
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
class Solution {
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
public:
Node* insert(Node* root, int data) {
if(root == NULL) {
return new Node(data);
} else {
Node* cur;
if(data <= root->data) {
cur = insert(root->left, data);
root->left = cur;
} else {
cur = insert(root->right, data);
root->right = cur;
}
return root;
}
}
};
int main() {
Solution myTree;
Node* root = NULL;
int t;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
int data;
std::cin >> t;
while(t-- > 0) {
std::cin >> data;
root = myTree.insert(root, data);
}
myTree.topView(root);
return 0;
}
Output:-
Program 2:-
#include <bits/stdc++.h>
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
right = NULL;
}
};
class Solution {
public:
preOrder(root->left);
preOrder(root->right);
}
if(root==NULL) {
Node* newNode;
newNode = (Node*)malloc(sizeof(Node));
newNode->left = NULL;
newNode->right = NULL;
newNode->data = value;
return newNode;
}
return root;
}
};
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
int main() {
Solution myTree;
Node* root = NULL;
int t;
int data;
std::cin >> t;
while(t-- > 0) {
std::cin >> data;
root = myTree.insert(root, data);
}
myTree.preOrder(root);
return 0;
}
Output:-
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Experiment 2.3
Student Name: Shashi Ranjan Mehta UID: 21BCS7093
Branch:BE-CSE Section/Group: IoT-624
Semester:5 Date of Performance:29-09-2023
Subject Name: Advance Programming Lab
Subject Code: 21CSP-314
1. Aim:
1.WAP to separate a number
2.WAP to pangram string
2. Objective:
1. Perform queries where each query consists of some integer string . For each query, print
whether or not the string is beautiful on a new line. If it is beautiful, print YES x, where is the
first number of the increasing sequence. If there are multiple such values of , choose the smallest.
Otherwise, print NO.
2. A pangram is a string that contains every letter of the alphabet. Given a sentence determine
whether it is a pangram in the English alphabet. Ignore case. Return either pangram or not
pangram as appropriate.
next++;
}
if(ns==s) poss=true;
}
else{
for(int i=1;i<=(s.size()/2);i++){
ans*=10;
ans+=(s[i-1]-'0');
long long int next=ans+1;
string ns=s.substr(0,i);
while(ns.size()<s.size()){
ns+=to_string(next);
next++;
}
if(ns==s){
poss=true;
break;
}
}
}
if(poss&&s.size()>1) cout<<"YES "<<ans<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
Output:-
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Program 2:-
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define float long double
#define LL long long
#define itn int
#define mp make_pair
#define x first
#define y second
using namespace std;
int main(){
string s;
vector<int> a(256, 0);
getline(cin, s);
for (int i = 0; i < s.length(); i++){
a[s[i]]++;
}
for (char c = 'a'; c <= 'z'; c++){
if (a[c] + a[c - 'a' + 'A'] == 0){
cout << "not pangram\n";
return 0;
}
}cout << "pangram\n";
return 0;}
Output:-
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Experiment-4
Student Name: Alasso UID: 21BCS
Branch: CSE Section/Group:
Semester: 5th Date of Performance: 28/8/23
Subject Name: Advance Programming Lab Subject Code: 21CSP-259
1. Aim:
TASK-1: Given two arrays of integers, find which elements in the second
array are missing from the first array.
TASK-2: Lauren has a chart of distinct projected prices for a house over
the next several years. She must buy the house in one year and sell it in
another, and she must do so at a loss. She wants to minimize her financial
loss.
3. Source Code:
TASK-1:
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
m = int(input().strip())
fptr.close()
TASK-2:
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'minimumLoss' function below.
#
# The function is expected to return an INTEGER.
# The function accepts LONG_INTEGER_ARRAY price as parameter.
#
def minimumLoss(price):
# Write your code here
r_index = sorted(range(len(price)), key=lambda x: price[x], reverse=True)
min_loss = 10**16
for i in range(len(r_index)-1):
if r_index[i] < r_index[i+1]:
index1 = r_index[i]
index2 = r_index[i+1]
loss = price[index1] - price[index2]
min_loss = min(min_loss, loss)
return min_loss
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
result = minimumLoss(price)
fptr.write(str(result) + '\n')
fptr.close()
4. Output:
TASK-1:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
TASK-2:
5. Learning Outcomes:
1. Understood the concept of searching and sorting.
2. Understood the concept how to search and sort elements.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Experiment 1.3
Student Name: Alasso UID: 21BCS
Branch: BE-CSE Section/Group: IoT-624
Semester:5 Date of Performance:24-08-2023
Subject Name: Advance Programming Lab
Subject Code: 21CSP-314
1. Aim:
1.WAP to compare two linkedlist
2.WAP to insert a node in sorted linketlist
2. Objective:
1. You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes
of the linked lists to check if they are equal. If all data attributes are equal and the lists are the
same length, return . Otherwise, return .
2. You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes
of the linked lists to check if they are equal. If all data attributes are equal and the lists are the
same length, return . Otherwise, return .
SinglyLinkedListNode(int node_data) {
this->data = node_data;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
this->next = nullptr;
}
};
class SinglyLinkedList {
public:
SinglyLinkedListNode *head;
SinglyLinkedListNode *tail;
SinglyLinkedList() {
this->head = nullptr;
this->tail = nullptr;
}
void insert_node(int node_data) {
SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data);
if (!this->head) {
this->head = node;
} else {
this->tail->next = node;
}
this->tail = node;
}
};
void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) {
while (node) {
fout << node->data;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
node = node->next;
if (node) {
fout << sep;
}
}
}
void free_singly_linked_list(SinglyLinkedListNode* node) {
while (node) {
SinglyLinkedListNode* temp = node;
node = node->next;
free(temp);
}
}
bool compare_lists(SinglyLinkedListNode* llist1_head, SinglyLinkedListNode* llist2_head) {
while (llist1_head && llist2_head) {
if (llist1_head->data != llist2_head->data) {
return false;
}
llist1_head = llist1_head->next;
llist2_head = llist2_head->next;
}
return (llist1_head == nullptr && llist2_head == nullptr);
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
int tests;
cin >> tests;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int tests_itr = 0; tests_itr < tests; tests_itr++) {
SinglyLinkedList* llist1 = new SinglyLinkedList();
int llist1_count;
cin >> llist1_count;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
llist2->insert_node(llist2_item);
}
bool result = compare_lists(llist1->head, llist2->head);
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Program 2:-
#include <bits/stdc++.h>
using namespace std;
class DoublyLinkedListNode {
public:
int data;
DoublyLinkedListNode *next;
DoublyLinkedListNode *prev;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
DoublyLinkedListNode(int node_data) {
this->data = node_data;
this->next = nullptr;
this->prev = nullptr;
}
};
class DoublyLinkedList {
public:
DoublyLinkedListNode *head;
DoublyLinkedListNode *tail;
DoublyLinkedList() {
this->head = nullptr;
this->tail = nullptr;
}
void insert_node(int node_data) {
DoublyLinkedListNode* node = new DoublyLinkedListNode(node_data);
if (!this->head) {
this->head = node;
} else {
this->tail->next = node;
node->prev = this->tail;
}
this->tail = node;
}
};
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
node = node->next;
if (node) {
fout << sep;
}
}
}
void free_doubly_linked_list(DoublyLinkedListNode* node) {
while (node) {
DoublyLinkedListNode* temp = node;
node = node->next;
free(temp);
}
}
DoublyLinkedListNode* sortedInsert(DoublyLinkedListNode* head, int data) {
DoublyLinkedListNode* prev = nullptr;
DoublyLinkedListNode* curr = head;
if (prev == nullptr) {
newNode->next = head;
head->prev = newNode;
head = newNode;
} else {
newNode->next = curr;
newNode->prev = prev;
prev->next = newNode;
if (curr != nullptr) {
curr->prev = newNode;
}
}
return head;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int t;
cin >> t;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int t_itr = 0; t_itr < t; t_itr++) {
DoublyLinkedList* llist = new DoublyLinkedList();
int llist_count;
cin >> llist_count;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int i = 0; i < llist_count; i++) {
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
int llist_item;
cin >> llist_item;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
llist->insert_node(llist_item);
}
int data;
cin >> data;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
DoublyLinkedListNode* llist1 = sortedInsert(llist->head, data);
print_doubly_linked_list(llist1, " ", fout);
fout << "\n";
free_doubly_linked_list(llist1);
}
fout.close();
return 0;
}
Output:-
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Experiment 1.2
Brute Force Approach:We can start from each index and check whether we are able to
complete the loop. If not we start again from the next index. We keep on doing this till we get the
first index from which we start and are able to complete the whoole loop.
CODE:
# Harshit Singh Bisht
# 21 BCS 5431
def solve(petrol,distance,n):
start,tank=0,0
for i in range(n): #Start from each index
start=i
tank=0 #Reset the tank for each iteration
for j in range(n):
current=(start+j)%n #To make the index in range fo
r circular array
tank+=petrol[current]-
distance[current] #Add the petrol and subtract the petrol required
to reach next station
if tank<0: #If petrol in tank becomes negative, we ca
nnot complete the loop
break
if j==n-
1: #If we visit all n pumps, task is completed
return start
n=int(input())
petrol,distance=[],[]
for i in range(n):
p,d=[int(x) for x in input().split()]
petrol.append(p),distance.append(d)
print(solve(petrol,distance,n))
OUTPUT:
ans = 0
a = [0]+a
b = [0]+b
for i in range(len(a)):
for j in range(len(b)):
sa = sum(a[:i+1])
sb = sum(b[:j+1])
if sa+sb > x:
break
ans = max(ans, i+j)
return ans
def solve(a,b):
total = 0
i = len(a)
ans = i
j = 1
for i in range(len(a)):
total += a[i]
if total > x:
ans = i
break
ans_total = x + 1
total = sum(a[:i])
while (total <= x and i > 0) or j < len(b):
if total < x:
total += b[j - 1]
j += 1
elif total > x:
total -= a[i - 1]
i -= 1
else:
total -= a[i - 1]
i -= 1
total += b[j - 1]
j += 1
for _ in range(int(input())):
n, m, x = map(int, input().split())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
_sum_a, _sum_b = sum(a), sum(b)
if _sum_a + _sum_b <= x:
print(n+m)
elif n <= 200 and m <= 200:
print(brute(a,b))
else:
ans = solve(a,b) if _sum_a < _sum_b else solve(b,a)
print(ans)
OUTPUT:
COMPLEXITY:
The time complexity for the QUEUE is O(N2).
The time complexity for the STACK is O(1), except for the search operation which has a time
complexity of O(n).
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Experiment 1
TASK 1
3. Script :
import math
import os
import random
import re
import sys
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
a = list(map(int, input().rstrip().split()))
b = list(map(int, input().rstrip().split()))
result = compareTriplets(a, b)
fptr.close()
4.OUTPUT
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
LEARNING OUTCOMES
TASK 2
3.SCRIPT :
import math
import os
import random
import re
import sys
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
def diagonalDifference(arr):
final = len(arr) - 1
diferenca_diagonais = 0
for indice, linha in enumerate(arr):
diferenca_diagonais += linha[indice] -
linha[final - indice]
return abs(diferenca_diagonais)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
result = diagonalDifference(arr)
fptr.write(str(result) + '\n')
fptr.close()
4.OUTPUT
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
5. LEARNING OUTCOMES
Experiment 3.3
Student Name: Nikita UID: 21BCS2785
Branch:BE-CSE Section/Group: IoT-26B
Semester:5 Date of Performance:12-10-2023
Subject Name: Advance Programming Lab
Subject Code: 21CSP-314
1. Aim:
1.WAP to Marc’s Cake walk
2.WAP to solve grid Challenge
2. Objective:
1. Marc loves cupcakes, but he also likes to stay fit. Each cupcake has a calorie count, and Marc
can walk a distance to expend those calories. If Marc has eaten cupcakes so far, after eating a
cupcake with calories he must walk at least miles to maintain his weight.
2. Given a square grid of characters in the range ascii[a-z], rearrange elements of each row
alphabetically, ascending. Determine if the columns are also in ascending alphabetical order, top
to bottom. Return YES if they are or NO if they are not
return 0;
}
Output:-
Program 2:-
#include <bits/stdc++.h>
using namespace std;
string s[111];
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> s[i], sort(s[i].begin(),
s[i].end());
bool flag = true;
for (int i = 0; i < n; i++) for (int j = 0; j + 1 < n; j++)
if (s[j][i] > s[j + 1][i]) flag = false;
puts(flag ? "YES" : "NO");
}
return 0;
}
Output:-
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Experiment 3.2
Student Name: Nikita UID: 21BCS2785
Branch:BE-CSE Section/Group: IoT-626 B
Semester:5 Date of Performance:05-10-2023
Subject Name: Advance Programming Lab
Subject Code: 21CSP-314
1. Aim:
1.WAP to check palindrome
2.WAP to solve Fibonacci sequence
2. Objective:
1. You are given a number . In one operation, you can either increase the value of by 1 or decrease
the value of by 1. Determine the minimum number of operations required (possibly zero) to convert
number to a number such that binary representation of is a palindrome. Note: A binary
representation is said to be a palindrome if it reads the same from left-right and right-left.
2. The Fibonacci sequence appears in nature all around us, in the arrangement of seeds in a
sunflower and the spiral of a nautilus for example. The Fibonacci sequence begins with and as its
first and second terms. After these first two elements, each subsequent element is equal to the sum
of the previous two elements. Programmatically:
#define se second
#define fast_cin() ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL)
set < int > v;
void binarypalindrome(int s, int e, int x) {
if (s > e) {
v.insert(x);
return;
}
binarypalindrome(s + 1, e - 1, x);
if (s == e)
binarypalindrome(s + 1, e - 1, x + pow(2, s));
else
binarypalindrome(s + 1, e - 1, x + pow(2, s) + pow(2, e));
return;
}
int main() {
fast_cin();
int n, t;
v.insert(0);
v.insert(1);
v.insert(3);
for (int i = 3; i < 32; i++) {
int c = pow(2, i - 1) + 1;
binarypalindrome(1, i - 2, c);
}
cin >> t;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
while (t--) {
cin >> n;
auto ptr = v.lower_bound(n);
auto ptr2 = ptr--;
if (abs(n - * ptr) < abs(n - * ptr2))
cout << abs(n - * ptr) << endl;
else
cout << abs(n - * ptr2) << endl;
}
return 0;
}
Output:-
Program 2:-
#include <iostream>
int fibonacci(int n) {
if (n ==0)
return 0;
else if (n== 1)
return 1;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
else
return fibonacci(n-1) + fibonacci (n-2);
}
int main() {
int n;
cin >> n;
cout << fibonacci(n);
return 0;
}
Output:-
Experiment 3.1
Student Name: Saksham Sharma UID: 21BCS1138
Branch:BE-CSE Section/Group: IoT-615B
Semester:5 Date of Performance:15-10-2023
Subject Name: Advance Programming Lab
Subject Code: 21CSP-314
1. Aim:
1.WAP to construct the array
2.WAP to minima the operation on array
2. Objective:
1. Your goal is to find the number of ways to construct an array such that consecutive positions
contain different values. Specifically, we want to construct an array with elements such that each
element between and , inclusive. We also want the first and last elements of the array to be and .
Given , and , find the number of ways to construct such an array. Since the answer may be large,
only find it modulo
2. Christy is interning at HackerRank. One day she has to distribute some chocolates to her
colleagues. She is biased towards her friends and plans to give them more than the others. One of
the program managers hears of this and tells her to make sure everyone gets the same number. To
make things difficult, she must equalize the number of chocolates in a series of operations. For
each operation, she can give pieces to all but one colleague. Everyone who gets a piece in a round
receives the same number of pieces.
long answer;
if (x == 1) {
answer = (ways[fillSecond][1] * (k - 1)) % MOD;
}
else {
answer = (ways[fillSecond][1] * (k - 2) + ways[fillSecond][0])
% MOD;
}
return answer;
}
int main() {
int n;
int k;
int x;
cin >> n >> k >> x;
long answer = countArray(n, k, x);
cout << answer << endl;
return 0;
}
Output:-
Program 2:-
#include <bits/stdc++.h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);
int equal(vector<int> arr) {
vector<int> possibilities(5, 0);
int minimum = *min_element(arr.begin(), arr.end());
string t_temp;
getline(cin, t_temp);
int t = stoi(ltrim(rtrim(t_temp)));
int n = stoi(ltrim(rtrim(n_temp)));
string arr_temp_temp;
getline(cin, arr_temp_temp);
vector<int> arr(n);
arr[i] = arr_item;
}
int result = equal(arr);
Output:-