0% found this document useful (0 votes)
23 views18 pages

Ap 2

The document outlines a series of experiments conducted by students in the Department of Computer Science & Engineering, focusing on various programming concepts such as Graphs, Divide and Conquer algorithms, and Greedy algorithms. Each experiment includes aims, objectives, problems, solutions, and learning outcomes related to specific programming challenges. The document also features code implementations for solving problems like finding the difference in strings, predicting game winners, and optimizing cookie distribution.

Uploaded by

Lokesh Raj
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)
23 views18 pages

Ap 2

The document outlines a series of experiments conducted by students in the Department of Computer Science & Engineering, focusing on various programming concepts such as Graphs, Divide and Conquer algorithms, and Greedy algorithms. Each experiment includes aims, objectives, problems, solutions, and learning outcomes related to specific programming challenges. The document also features code implementations for solving problems like finding the difference in strings, predicting game winners, and optimizing cookie distribution.

Uploaded by

Lokesh Raj
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/ 18

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment-2.2
Student Name: Harshit Kesarwani UID: 21BCS11394
Branch: CSE Section/Group: 21BCS_CC-651 A
Semester: 6th Date of Performance: 05/03/24
Subject Name: Advanced Programming Subject Code: 21CSP-351

1. Aim:
To demonstrate the concept of the Graph.
1. Question-1: To check for the extra letter added to the string after jumbled.
2. Question-2: To check for the winner among the 2 players who are playing a
game.

2. Objective:
To solve the problems related to the Graph to understand and implement it more
effectively.

3. Script and output:

Problem-1:
You are given two strings s and t.
String t is generated by random shuffling string s and then add one more letter at
a random position.
Return the letter that was added to t.

Solution-1:
class Solution
{
public:
char findTheDifference(string s, string t)
{
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

int ans=0;
for(auto &x: t)
ans+=x;
for (auto &x: s)
ans-=x;
return char(ans);
}
};
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Problem-2:
You are given an integer array nums. Two players are playing a game with this
array: player 1 and player 2.
Player 1 and player 2 take turns, with player 1 starting first. Both players start the
game with a score of 0. At each turn, the player takes one of the numbers from
either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the
size of the array by 1. The player adds the chosen number to their score. The game
ends when there are no more elements in the array.
Return true if Player 1 can win the game. If the scores of both players are equal,
then player 1 is still the winner, and you should also return true. You may assume
that both players are playing optimally.

Solution-2:
class Solution {
public:
int solve(vector<int>& nums,int i,int j,int chance){
if(i>j) return 0;
if(chance==0)
return max(nums[i]+solve(nums,i+1,j,1),nums[j]+solve(nums,i,j-1,1));
else
return min(solve(nums,i+1,j,0),solve(nums,i,j-1,0));
}

bool predictTheWinner(vector<int>& nums) {


int n=nums.size();
long long sum=0;
for(int i=0;i<n;i++) sum=sum+nums[i];
long long one=(long long) solve(nums,0,n-1,0);
sum=sum-one;
return(one>=sum);
}
};
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Learning Outcomes:
1. Learned about Graphs.
2. Learned how to solve problems related to Graphs.
3. Validates lengths and iterates characters for solving and better understanding
of Hashing.
4. Learned various implementations of Graphs.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Experiment-2.3
Student Name: Harshit Kesarwani UID: 21BCS11394
Branch: CSE Section/Group: 21BCS_CC-651 A
Semester: 6th Date of Performance: 19/03/24
Subject Name: Advanced Programming Subject Code: 21CSP-351

1. Aim:
To demonstrate the concept of the Divide and Conquer algorithms.
1. Question-1: To check for the count for number of digits.
2. Question-2: To check for the game of snake and ladder.

2. Objective:
To solve the problems related to the Divide and Conquer algorithms to
understand and implement it more effectively.

3. Script and output:

Problem-1:
The count-and-say sequence is a sequence of digit strings defined by the recursive
formula: countAndSay(1) = "1"
countAndSay(n) is the way you would "say" the digit string from
countAndSay(n-1), which is then converted into a different digit string.
To determine how you "say" a digit string, split it into the minimal number of
substrings such that each substring contains exactly one unique digit. Then for
each substring, say the number of digits, then say the digit. Finally, concatenate
every said digit.

Solution-1:
class Solution {
public:
string countAndSay(int n) {
if(n==1) return "1";
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

string s = countAndSay(n-1);
int i=0, j=0;
string r;

while(i<s.size()){
j=i+1;
while(j<s.size() && s[j]==s[i])
++j;
string ct = to_string(j-i);
r+=ct + s[i];
i=j;
}
return r;
}
};
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Problem-2:
You are given an n x n integer matrix board where the cells are labeled from 1 to
n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n
- 1][0]) and alternating direction each row. You start on square 1 of the board. In
each move, starting from square curr, do the following:
Choose a destination square next with a label in the range [curr + 1, min(curr + 6,
n2)].
This choice simulates the result of a standard 6-sided die roll: i.e., there are always
at most 6 destinations, regardless of the size of the board. If next has a snake or
ladder, you must move to the destination of that snake or ladder. Otherwise, you
move to next.
The game ends when you reach the square n2.
A board square on row r and column c has a snake or ladder if board[r][c] != -1.
The destination of that snake or ladder is board[r][c]. Squares 1 and n2 do not have
a snake or ladder.
Note that you only take a snake or ladder at most once per move. If the destination
to a snake or ladder is the start of another snake or ladder, you do not follow the
subsequent snake or ladder.

Solution-2:
class Solution {
public:
int snakesAndLadders(vector<vector<int>> &board) {
int n = board.size(), lbl = 1;
vector<pair<int, int>> cells(n*n+1);
vector<int> columns(n);
iota(columns.begin(), columns.end(), 0);
for (int row = n - 1; row >= 0; row--) {
for (int column : columns) {
cells[lbl++] = {row, column};
}
reverse(columns.begin(), columns.end());
}
vector<int> dist(n*n+1, -1);
dist[1] = 0;
queue<int> q;
q.push(1);
while (!q.empty()) {
int curr = q.front();
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

q.pop();
for (int next = curr + 1; next <= min(curr+6, n*n); next++) {
auto [row, column] = cells[next];
int destination = board[row][column] != -1 ? board[row][column] : next;
if (dist[destination] == -1) {
dist[destination] = dist[curr] + 1;
q.push(destination);
}
}
}
return dist[n*n];
}
};

Learning Outcomes:
1. Learned about Divide and Conquer algorithms.
2. Learned how to solve problems related to Divide and Conquer algorithms.
3. Validates lengths and iterates characters for solving and better understanding
of Hashing.
4. Learned various implementations of Divide and Conquer algorithms.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Experiment-3.1
Student Name: Harshit Kesarwani UID: 21BCS11394
Branch: CSE Section/Group: 21BCS_CC-651 A
Semester: 6th Date of Performance: 26/03/24
Subject Name: Advanced Programming Subject Code: 21CSP-351

1. Aim:
To demonstrate the concept of the Greedy algorithms.
1. Question-1: To check for duplicate letter from the string and remove it.
2. Question-2: To check for assigning cookie to the children.

2. Objective:
To solve the problems related to the Greedy algorithms to understand and
implement it more effectively.

3. Script and output:

Problem-1:
Given a string s, remove duplicate letters so that every letter appears once and
only once. You must make sure your result is the smallest in lexicographical order
among all possible results.
Input: s = "bcabc"
Output: "abc"

Solution-1:
class Solution {
public:
string removeDuplicateLetters(string s) {
unordered_map<char, int> lastIdx;
unordered_map<char, bool> visited;
stack<char> st;
string ans = "";
for(int i = 0; i < s.size(); i++)
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

lastIdx[s.at(i)] = i;
for(int i = 0; i < s.size(); i++)
{
char ch = s.at(i);
if(visited[ch]) continue;
while(!st.empty() && ch < st.top() && i < lastIdx[st.top()])
{
visited[st.top()] = false;
st.pop();
}
st.push(ch);
visited[ch] = true;
}
while(!st.empty())
{
ans += st.top();
st.pop();
}
reverse(ans.begin(), ans.end());
return ans;
}
};
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Problem-2:
Assume you are an awesome parent and want to give your children some cookies.
But you should give each child at most one cookie. Each child i has a greed factor
g[i], which is the minimum size of a cookie that the child will be content with; and
each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i,
and the child i will be content. Your goal is to maximize the number of your
content children and output the maximum number.

Solution-2:
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
int ans = 0;
if (g.size() == 0 || s.size() == 0)
return 0;
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int gi = 0;
int si = 0;
for (auto child : g) {
while (s[si] < child) {
si++;
if (si >= s.size())
return ans;
}
si++;
ans++;
if (si >= s.size())
return ans;
}
return ans;
}
};
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Learning Outcomes:
1. Learned about Greedy algorithms.
2. Learned how to solve problems related to Greedy algorithms.
3. Validates lengths and iterates characters for solving and better understanding
of Hashing.
4. Learned various implementations of Greedy algorithms.
Experiment 3.2
Student Name: Lokesh Raj UID: 21BCS8668
Branch: BE-CSE Section/Group:CC-625-A
Semester: 6 Date of Performance:15-03-2024
Subject Name: Advance Programming lab
Subject Code:21CSP-251

1. Aim:
● To Solve the binary watch
● To Solve the Sticker to spell word
2. Objective:

● A binary watch has 4 LEDs on the top to represent the hours (0-11), and
6 LEDs on the bottom to represent the minutes (0-59). Each LED
represents a zero or one, with the least significant bit on the right.

● You would like to spell out the given string target by cutting
individual letters from your collection of stickers and rearranging
them. You can use each sticker more than once if you want, and you have
infinite quantities of each sticker.
Return the minimum number of stickers that you need to spell out target.
If the task is impossible, return -1.

3. Algo. /Approach and output:

class Solution {
public:
vector<string> readBinaryWatch(int turnedOn) {
vector<string> result;
for(int h=0;h<12;h++){
for(int m=0;m<60;m++){
if((__builtin_popcount(h)+__builtin_popcount(m))==turnedOn){
result.push_back(to_string(h)+(m<10 ? ":0" :
":")+to_string(m));
}
}
}
return result;
}
};
class Solution {
public:
int minStickers(vector<string>& stickers, string& target) {
int n = size(stickers);
unordered_set<string> visited;
vector<vector<int>> s_frequencies(n, vector<int>(26, 0));
for (int i = 0; i < n; ++i)
for (auto& c : stickers[i])
++s_frequencies[i][c - 'a'];
vector<int> t_frequency(26, 0);
for (auto& c : target)
++t_frequency[c - 'a'];
queue<vector<int>> q;
q.push(t_frequency);

for (int res = 0; size(q); ++res) {


for (int k = size(q); k > 0; --k) {
auto t_freq = q.front(); q.pop();
string t_str;
for (int i = 0; i < 26; ++i)
if (t_freq[i] > 0)
t_str += string(t_freq[i], i);

if (t_str == "") return res;

if (visited.count(t_str)) continue;
visited.insert(t_str);

char seeking = t_str[0];


for (auto& v : s_frequencies) {
if (v[seeking] > 0) {
q.push(t_freq); // Push first to copy t_freq
for (int i = 0; i < 26; ++i)
q.back()[i] -= v[i];
}
}
}
}

return -1;
}
};
Experiment 3.3

Student Name: Lokesh Raj UID: 21BCS8668


Branch:BE-CSE Section/Group:CC-625
Semester: 6 Date of Performance:29-03-2024
Subject Name: Advance Programming lab
Subject Code:21CSP-251

1. Aim:
● To Solve the Best time to buy and sell the stock
● To Solve the longest Palindromic substring
2. Objective:

● You are given an array prices where prices[i] is the price of a given stock
on the ith day.You want to maximize your profit by choosing a single day to
buy one stock and choosing a different day in the future to sell that
stock.

● Given a string s, return the longest palindromic substring in s.

3. Algo. /Approach and output:

class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.empty()){
return 0;
}
int maxprice=0;
int minprice=prices[0];
for(int i=1;i<prices.size();i++){
if(prices[i]<minprice){
minprice=prices[i];
}
else{
int currprofit=prices[i]-minprice;
maxprice=max(maxprice,currprofit);
}
}
return maxprice;
}
};

class Solution {
public:
std::string longestPalindrome(std::string s) {
if (s.length() <= 1) {
return s;
}

auto expand_from_center = [&](int left, int right) {


while (left >= 0 && right < s.length() && s[left] == s[right]) {
left--;
right++;
}
return s.substr(left + 1, right - left - 1);
};

std::string max_str = s.substr(0, 1);

for (int i = 0; i < s.length() - 1; i++) {


std::string odd = expand_from_center(i, i);
std::string even = expand_from_center(i, i + 1);

if (odd.length() > max_str.length()) {


max_str = odd;
}
if (even.length() > max_str.length()) {
max_str = even;
}
}

return max_str;
}
};

You might also like