0% found this document useful (0 votes)
46 views46 pages

Ilovepdf Merged

1. The document describes an experiment conducted by a computer science student involving two programming tasks. 2. The first task involves comparing two linked lists and finding missing elements. The second task involves inserting a node into a sorted linked list and minimizing financial loss when buying and selling a house. 3. Code solutions are provided for both tasks along with expected input/output formats. The student aims to understand concepts of searching and sorting through completing these programming problems.

Uploaded by

Anshul Somani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views46 pages

Ilovepdf Merged

1. The document describes an experiment conducted by a computer science student involving two programming tasks. 2. The first task involves comparing two linked lists and finding missing elements. The second task involves inserting a node into a sorted linked list and minimizing financial loss when buying and selling a house. 3. Code solutions are provided for both tasks along with expected input/output formats. The student aims to understand concepts of searching and sorting through completing these programming problems.

Uploaded by

Anshul Somani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

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.

3. Script and Output:


Program 1:-
#include<bits/stdc++.h>

using namespace std;

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;
}
}

void topView(Node * root) {


queue<pair<int,Node*>> q; q.push(make_pair(0,root));
map<int,Node*> ans;
for(auto i=q.front();!q.empty();q.pop(),i=q.front()){
if(!i.second) continue;
ans.insert(i);
q.push(make_pair(i.first+1,i.second->right));
q.push(make_pair(i.first-1,i.second->left));
}
for(auto i:ans) cout<<i.second->data<<" ";
}

};

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>

using namespace std;

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:

void preOrder(Node *root) {

if( root == NULL )


return;

std::cout << root->data << " ";

preOrder(root->left);
preOrder(root->right);
}

Node * insert(Node * root, int value) {

if(root==NULL) {
Node* newNode;
newNode = (Node*)malloc(sizeof(Node));
newNode->left = NULL;
newNode->right = NULL;
newNode->data = value;
return newNode;
}

if(value <= root->data)


root->left = insert(root->left, value);
else
root->right = insert(root->right, value);

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.

3. Script and Output:


Program 1:-
#include <bits/stdc++.h>
using namespace std;
int main(){
int q;
cin >> q;
for(int a0 = 0; a0 < q; a0++){
string s;
cin >> s;
// your code goes here
bool poss=false;
long long int ans=0;
if(s[0]=='0'){
string ns="0";
long long int next=1;
while(ns.size()<s.size()){
ns+=to_string(next);
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

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.

2. Objective: To understand the concept of searching and sorting.

3. Source Code:
TASK-1:
#!/bin/python3

import math
import os
import random
import re
import sys

def missingNumbers(arr, brr):


# Write your code here
values=[]
brr_1=set(brr)
for i in brr_1:
a=arr.count(i)
b=brr.count(i)
if a<b:
values.append(i)
return values

if __name__ == '__main__':
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
fptr = open(os.environ['OUTPUT_PATH'], 'w')

n = int(input().strip())

arr = list(map(int, input().rstrip().split()))

m = int(input().strip())

brr = list(map(int, input().rstrip().split()))

result = missingNumbers(arr, brr)

fptr.write(' '.join(map(str, result)))


fptr.write('\n')

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())

price = list(map(int, input().rstrip().split()))

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 .

3. Script and Output:


Program 1:-
#include <bits/stdc++.h>
using namespace std;
class SinglyLinkedListNode {
public:
int data;
SinglyLinkedListNode *next;

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');

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


int llist1_item;
cin >> llist1_item;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
llist1->insert_node(llist1_item);
}
SinglyLinkedList* llist2 = new SinglyLinkedList();
int llist2_count;
cin >> llist2_count;
cin.ignore(numeric_limits<streamsize>::max(), '\n');

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


int llist2_item;
cin >> llist2_item;
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

fout << result << "\n";


}
fout.close();
return 0;
}
Output:-

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

void print_doubly_linked_list(DoublyLinkedListNode* node, string sep, ofstream& fout) {


while (node) {
fout << node->data;

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;

while (curr && curr->data < data) {


prev = curr;
curr = curr->next;
}
DoublyLinkedListNode* newNode = new DoublyLinkedListNode(data);
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

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

NAME: Alasso UID: 21BCS


Branch: Computer Science and Eng. Section/Group:
Semester: 5th Semester DOP: 8/10/2023
Subject Name: Advance Programming Subject Code: 21CSP-314

AIM: Implement the Stacks and Queues in Hackerrank.

Q1) TRUCK TOUR


Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0
to (N-1). You have two pieces of information corresponding to each of the petrol pump: (1) the
amout of petrol that particular petrol pump will give…

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:

QUES 2) GAME OF STACKS:


Alexa has two stacks of non-negative intergers, stack a[n] and stack b[m] where index 0 denotes
the top of the stack. Alexa challenfes Nick to play the following game:
• In each moves, Nick can remove one integer from the top of either stack a or stack b.
• Nick keeps a running sum of the integers he removes from the two stacks.
• Nick’s final score is the total numver of integers he has removed from the two stacks.
CODE:
def brute(a,b):
# Harshit Singh Bisht
# 21 BCS 5431

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

if i < 1 and total > x:


break
ans = max(ans, i + j - 2)
ans_total = min(total, ans_total)

return ans if ans_total <= x else ans - 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

Student Name: Alasso.me UID: 21BCS


Branch: CSE Section/Group:
Semester: 5th Date of Performance:07/08/23
Subject Name: Advanced Programming Lab Subject Code:21CSP314

TASK 1

1. Aim: The aim is to compare the ratings of two challenges created by


Alice and Bob, calculate their respective scores based on the
comparisons, and return the scores as a list with Alice's score first and
Bob's score second.

2. Objective:The objective is to develop a program that takes the


ratings of two challenges created by Alice and Bob, compares the
ratings for each category, calculates their scores, and produces a list
representing the comparison points, with Alice's score first and Bob's
score second.

3. Script :

import math
import os
import random
import re
import sys

def compareTriplets(a, b):


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
alice,bob=0,0
for i,j in zip(a,b):
if i>j: alice+=1
if i<j: bob+=1
return alice,bob

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.write(' '.join(map(str, result)))


fptr.write('\n')

fptr.close()

4.OUTPUT
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

LEARNING OUTCOMES

(I) Array Manipulation: This task involves working with arrays


(triplets) to compare corresponding elements. Learning how to
iterate through arrays, access specific elements, and perform
comparisons is a fundamental skill in programming.

(II) Conditional Logic: The use of conditional statements (if-elif-


else) to determine the points awarded to Alice and Bob based on
the comparisons helps learners understand how to make decisions
in code and handle different scenarios.

TASK 2

1.AIM: The Aim is to , calculate the absolute difference between the


sums of its diagonals of square matrix.

2.OBJECTIVE : The objective is to create a function that takes a


square matrix as input, calculates the sums of its left-to-right and
right-to-left diagonals, and then calculates the absolute difference
between these two diagonal sums. The function should return this
absolute difference as the final output.

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

(I). Algorithmic Thinking: This problem encourages you to think


algorithmically, breaking down the task into smaller steps to efficiently
calculate the diagonal sums and absolute difference.

(II). Mathematical Logic: You'll use mathematical concepts to


calculate the diagonal sums and the absolute difference, enhancing your
ability to apply mathematical logic in programming.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

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

3. Script and Output:


Program 1:-
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
vector<int> calories(n);
for(int calories_i = 0; calories_i < n; calories_i++){
cin >> calories[calories_i];
}
sort(calories.begin(),calories.end());
reverse(calories.begin(),calories.end());
long long temp=1,ans=0;
for(int i=0;i<n;i++)
{
ans+=calories[i]*temp;
temp*=2;
}
printf("%lld\n",ans);
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

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:

3. Script and Output:


Program 1:-
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define mp make_pair
#define pb push_back
#define pob pop_back()
#define mod 1000000007
#define max INT_MAX
#define min INT_MIN
#define fi first
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

#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>

using namespace std;

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.

3. Script and Output:


Program 1:-
#include <bits/stdc++.h>

using namespace std;

const int MOD = 1000000007;

void print(long arr[2][2]) {


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cout << i << ' ' << j << ' ' << arr[i][j] << endl;
}
}
}

long countArray(int n, int k, int x) {


long ways[2][2];
ways[0][0] = 1;
ways[0][1] = 0;
bool fillSecond = true;
for (int i = 0; i < n-1; i++) {
ways[fillSecond][0] = (ways[!fillSecond][1] * (k - 1)) % MOD;
ways[fillSecond][1] = (ways[!fillSecond][1] * (k - 2) + ways[!f
illSecond][0]) % MOD;
fillSecond = !fillSecond;
}

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());

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


for (int k : arr) {
int diff = k - minimum;
int stepsRequired = diff / 5 + (diff % 5) / 2 + ((diff
% 5) % 2) / 1;
possibilities[i] += stepsRequired;
}
minimum--;
}
return *min_element(possibilities.begin(), possibilities.end())
;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));

string t_temp;
getline(cin, t_temp);
int t = stoi(ltrim(rtrim(t_temp)));

for (int t_itr = 0; t_itr < t; t_itr++) {


string n_temp;
getline(cin, n_temp);

int n = stoi(ltrim(rtrim(n_temp)));

string arr_temp_temp;
getline(cin, arr_temp_temp);

vector<string> arr_temp = split(rtrim(arr_temp_temp));

vector<int> arr(n);

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


int arr_item = stoi(arr_temp[i]);

arr[i] = arr_item;
}
int result = equal(arr);

fout << result << "\n";


}
fout.close();
return 0;
}

string ltrim(const string &str) {


string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)
))
);
return s;
}

string rtrim(const string &str) {


string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspac
e))).base(),
s.end()
);
return s;
}

vector<string> split(const string &str) {


vector<string> tokens;
string::size_type start = 0;
string::size_type end = 0;
while ((end = str.find(" ", start)) != string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end + 1;
}
tokens.push_back(str.substr(start));
return tokens;
}

Output:-

You might also like