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

Week - 7th, Assignment Sol - 1st

Uploaded by

someoneuknow64
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)
14 views

Week - 7th, Assignment Sol - 1st

Uploaded by

someoneuknow64
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/ 13

DSA With Coding Army

Assignment Sol-1st Week – 7th Date : 09/07/2024


1. Write a program to calculate the sum of odd numbers between a and b (both inclusive) using
recursion.
#include <bits/stdc++.h>

using namespace std;

int findSum(int curr, int lastNumber) {

if(curr > lastNumber) return 0;

if(curr % 2 == 0) return findSum(curr+1, lastNumber);

return curr + findSum(curr+2, lastNumber);

int main() {

int a, b;

cin >> a >> b;

cout << findSum(a, b) << endl;

return 0;

}
2. Calculate the number of ways in which a person can climb n stairs if he can take
exactly 1, 2 or 3 steps at each level.
#include <bits/stdc++.h>
using namespace std;
int findNumberOfWays(int n) {
if(n < 0) return 0;
if(n == 0)return 1;
return findNumberOfWays(n-1) + findNumberOfWays(n-2) + findNumberOfWays(n-3);
}
int main() {
int n;
cin >> n;
cout << findNumberOfWays(n) << endl;
return 0;
}
3. Given a positive integer, return true if it is a power of 2.
#include <bits/stdc++.h>
using namespace std;
bool isPowerOfTwo(int n) {
if(n == 1) {
return true;
}
if(n % 2 == 0) {
return isPowerOfTwo(n / 2);
}
return false;
}
int main() {

int n;
cin >> n;

if(isPowerOfTwo(n)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
4. Print all the elements of an array in reverse order.
#include <bits/stdc++.h>
using namespace std;
void printElementsInReverse(vector<int> &arr, int currIndex, int n) {
if(currIndex == n) {
return;
}
printElementsInReverse(arr, currIndex+1, n);
cout << arr[currIndex] << " ";
}
int main() {

int n;
cin >> n;

vector<int> arr(n);
for(int i = 0; i < n; ++i) {
cin >> arr[i];
}

printElementsInReverse(arr, 0, n);

return 0;
}
5. Print index of a given element in an array.
#include <bits/stdc++.h>
using namespace std;
int indexOfKey(vector<int> &arr, int currIndex, int n, int key) {
if(currIndex == n) {
return -1;
}
if(arr[currIndex] == key) {
return currIndex;
}
return indexOfKey(arr, currIndex+1, n, key);
}
int main() {

int n, key;
cin >> n;

vector<int> arr(n);
for(int i = 0; i < n; ++i) {
cin >> arr[i];
}
6. If not present, print -1. A function countAndSay is defined as
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.
So, if sample input is n = 4,
countAndSay(1) = 1
countAndSay(2) = “one 1” => 11
countAndSay(3) = “two 1” => 21
countAndSay(4) = “one 2 one 1” => 1211
#include <bits/stdc++.h>
using namespace std;

string countAndSay(int n) {
if(n == 1) {
return "1";
}
string ans = "";
string smallAns = countAndSay(n-1);
for(int i = 0; i < smallAns.size();) {
int count = 1;
int j = i+1;
while(j < smallAns.size() && smallAns[i] == smallAns[j]) {
j++;
count++;
}
ans = ans + to_string(count) + smallAns[i];
i = j;
}
return ans;
}

int main() {
int n;
cout << "Enter the value of n: ";
cin >> n;

string result = countAndSay(n);


cout << "The " << n << "th term of the count-and-say sequence is: " << result << endl;

return 0;
}
7. Given an array of integers, print a sum triangle using recursion from it such that the
first level has all array elements. After that, at each level the number of elements is
one less than the previous level and elements at the level will be the sum of
consecutive two elements in the previous level. So, if sample input is [5, 4, 3, 2, 1],
sample output will be:
[5, 4, 3, 2, 1]
[9, 7, 5, 3]
[16, 12, 8]
[28, 20]
[48]
#include <bits/stdc++.h>
using namespace std;

void sumTriangle(vector<int> &arr, int n) {


if(n == 0) return;

vector<int> temp(n-1);
for(int i = 0; i < n; ++i) {
cout << arr[i] << " ";
if(i != 0) {
temp[i-1] = arr[i-1] + arr[i];
}
}
cout << endl;

sumTriangle(temp, n-1);
}

int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;

vector<int> arr(n);
cout << "Enter the array elements: ";
for(int i = 0; i < n; ++i) {
cin >> arr[i];
}

cout << "Sum Triangle:\n";


sumTriangle(arr, n);

return 0;
}
8. Write a recursive function to reverse a number.
#include <bits/stdc++.h>
using namespace std;
void reverseNum(int n, int &ans) {
if(n == 0) {
return;
}
int digit = n % 10;
ans = ans * 10 + digit;
reverseNum(n / 10, ans);
}
int main() {

int n;
cin >> n;

int ans = 0;
reverseNum(n, ans);
cout << ans << endl;

return 0;
}
9. Avoid preceding 0s in the reversed number. Print all the increasing sequences of
length k from first n natural numbers.

#include <iostream>
#include <vector>
using namespace std;

// Recursive function to generate and print increasing sequences


void generateSequences(vector<int> &seq, int start, int n, int k) {
// Base case: if the sequence length is k, print the sequence
if (seq.size() == k) {
for (int num : seq) {
cout << num << " ";
}
cout << endl;
return;
}

// Try adding numbers starting from 'start' to 'n'


for (int i = start; i <= n; ++i) {
// Add current number to the sequence
seq.push_back(i);

// Recursively generate further sequences


generateSequences(seq, i + 1, n, k);

// Backtrack and remove the current number


seq.pop_back();
}
}

// Function to print all increasing sequences of length k from first n natural numbers
void printIncreasingSequences(int n, int k) {
vector<int> seq;
generateSequences(seq, 1, n, k);
}

int main() {
int n, k;
cout << "Enter the value of n: ";
cin >> n;
cout << "Enter the value of k: ";
cin >> k;

cout << "Increasing sequences of length " << k << " from first " << n << " natural numbers are:\n";
printIncreasingSequences(n, k);

return 0

}
10. Given an integer array containing unique numbers, return power set, containing all
the subsets of the set. [Leetcode 78]
#include <iostream>
#include <vector>

using namespace std;

// Function to generate all subsets (power set)


void generateSubsets(vector<int>& nums, int index, vector<int>& current, vector<vector<int>>& result)
{
// Add the current subset to the result
result.push_back(current);

// Generate further subsets by including each element starting from the current index
for (int i = index; i < nums.size(); ++i) {
// Include the element nums[i] in the current subset
current.push_back(nums[i]);

// Recursively generate subsets with the current element included


generateSubsets(nums, i + 1, current, result);

// Backtrack: remove the last included element to try next possibilities


current.pop_back();
}
}

// Function to return the power set of the given array


vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> result; // To store all subsets
vector<int> current; // To store the current subset
generateSubsets(nums, 0, current, result);
return result;
}

int main() {
int n;
cout << "Enter the number of elements in the array: ";
cin >> n;

vector<int> nums(n);
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; ++i) {
cin >> nums[i];
}

vector<vector<int>> result = subsets(nums);

cout << "Power set: " << endl;


for (const auto& subset : result) {
cout << "{ ";
for (int num : subset) {
cout << num << " ";
}
cout << "}" << endl;
}

return 0;
}
11. Given an integer array which may contain duplicate numbers, return power set,
containing all the subsets of the set. [Leetcode 90]
#include <iostream>
#include <vector>

using namespace std;

// Function to generate all subsets (power set)


void generateSubsets(vector<int>& nums, int index, vector<int>& current, vector<vector<int>>& result)
{
// Add the current subset to the result
result.push_back(current);

// Generate further subsets by including each element starting from the current index
for (int i = index; i < nums.size(); ++i) {
// Include the element nums[i] in the current subset
current.push_back(nums[i]);

// Recursively generate subsets with the current element included


generateSubsets(nums, i + 1, current, result);

// Backtrack: remove the last included element to try next possibilities


current.pop_back();
}
}

// Function to return the power set of the given array


vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> result; // To store all subsets
vector<int> current; // To store the current subset
generateSubsets(nums, 0, current, result);
return result;
}

int main() {
int n;
cout << "Enter the number of elements in the array: ";
cin >> n;

vector<int> nums(n);
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; ++i) {
cin >> nums[i];
}

vector<vector<int>> result = subsets(nums);

cout << "Power set: " << endl;


for (const auto& subset : result) {
cout << "{ ";
for (int num : subset) {
cout << num << " ";
}
cout << "}" << endl;
}
return 0;
}
12. Given a string, find the length of the longest common substring from two given
strings.
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// Function to find the length of the longest common substring between two strings
int longestCommonSubstring(string s1, string s2) {
int n = s1.size();
int m = s2.size();
int result = 0; // To store the length of the longest common substring

// Create a 2D vector to store lengths of longest common suffixes of substrings


vector<vector<int>> dp(n+1, vector<int>(m+1, 0));

// Build the dp array from the bottom up


for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (s1[i-1] == s2[j-1]) {
dp[i][j] = dp[i-1][j-1] + 1;
result = max(result, dp[i][j]);
} else {
dp[i][j] = 0;
}
}
}

return result;
}

int main() {
string s1, s2;
cout << "Enter the first string: ";
cin >> s1;
cout << "Enter the second string: ";
cin >> s2;
int length = longestCommonSubstring(s1, s2);
cout << "The length of the longest common substring is: " << length << endl;

return 0;
}
13. Program to find the factorial of a given number.
#include <iostream>
using namespace std;

// Function to calculate factorial iteratively


unsigned long long factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0 || n == 1) {
return 1;
}
// Initialize result to 1
unsigned long long result = 1;
// Multiply numbers from 2 to n
for (int i = 2; i <= n; ++i) {
result *= i;
}
return result;
}

int main() {
int number;
cout << "Enter a non-negative integer: ";
cin >> number;

if (number < 0) {
cout << "Factorial is not defined for negative numbers." << endl;
} else {
unsigned long long fact = factorial(number);
cout << "Factorial of " << number << " is: " << fact << endl;
}

return 0;
}
14. Program to convert a decimal number to binary
#include <iostream>
using namespace std;

// Function to convert decimal to binary recursively


void decimalToBinary(int n) {
if (n == 0)
return;
decimalToBinary(n / 2);
cout << n % 2;
}

int main() {
int decimalNumber;
cout << "Enter a decimal number: ";
cin >> decimalNumber;

cout << "Binary equivalent: ";


decimalToBinary(decimalNumber);

return 0;
}

Note:- Please try to invest time doing the assignments which are necessary to build a
strongfoundation. Do not directly Copy Paste using Google or ChatGPT. Please use
your brain 😃.

You might also like