AP 2.2 Tanmay
AP 2.2 Tanmay
Experiment: 2.2
Task 1
String t is generated by random shuffling string s and then add one more letter at a random
position.
Algorithm:
Code:
class Solution {
public:
char findTheDifference(string s, string t)
{
for(int i=0;i<s.size();i++)
t[i+1]+=t[i]-s[i]; //Passing the diff: (t[i]-s[i]) to t[i+1]
return t[t.size()-1]; //The diff will be carried over to the last element eventually
}
};
Output:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Task 2
Aim: Predict the Winner
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.
Algorithm:
1. Define a recursive function solve that takes nums, start index i, end index j, and chance indicating
player's turn.
2. Base case: If i surpasses j, return 0.
3. If it's player's turn (chance = = 0), return max of choosing either nums[i] or nums[j] and
recursively call for opponent's turn.
4. If it's opponent's turn (chance = =1), return the minimum of recursive calls for both possible
moves.
5. Define predictTheWinner function to calculate the total sum of nums and call solve initially.
6. Calculate the remaining sum after player one's turn.
7. Return true if player one's score is greater or equal to remaining sum.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Code:
class Solution {
public:
vector<vector<int>> dp;
return dp[st][end]=max(a,b);
}
dp.clear();
dp.resize(22,vector<int>(22,-1));
int ans = helper(arr,0,arr.size()-1);
};
Output:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Learning Outcomes: