---> Small Basics Projects and Implement Functions by C++.
---> They are algorithms for some not easy functions, And here they are:
( I ) Codes.
-
checkBinary(string num):int count = 0;: Initializes an integer variable count to zero. This variable will keep track of the number of valid binary digits encountered.for (int i = 0; i < int(num.size()); i++): Iterates through each character in the input stringnum.int(num.size()): calculates the length of the string.if (num[i] == '0' || num[i] == '1'): Checks whether the current character at indexiis either ‘0’ or ‘1’.- Inside the
ifblock, thecountvariable is incremented by 1. - This means that for each valid binary digit encountered (‘0’ or ‘1’), the count increases.
- After processing all characters, the function compares the final value of
countwith the length of the input stringnum. - If they are equal, it means that all characters in
numare valid binary digits. - If the condition is true (i.e., all characters are valid binary digits), the function returns “
Yes”. - Otherwise (if some characters are not valid binary digits), it returns “
No”.
-
binaryToDecimal(string num):int dec = 0;: Initializes an integer variabledecto store the final decimal value.deque<char> bit;: Creates a deque (double-ended queue) called bit to store the reversed binary digits.for (int i = 0; i < int(num.size()); i++): Iterates through each character in the input stringnum.bit.push_front(num[i]);: Adds each character to the front of thebitdeque.- This effectively reverses the order of the binary digits.
for (int i = 0; i < int(bit.size()); i++): Iterates through each index in thebitdeque.static_cast<int>(bit[i]-'0'): Converts the character at indexi(either ‘0’ or ‘1’) to an integer (0 or 1).pow(2, i): Calculates 2 raised to the power ofi.dec += ...: Adds the product of the converted digit and the appropriate power of 2 to thedecvalue.- This step evaluates the value of each binary digit and accumulates the decimal value.
- After processing all binary digits, the function returns the accumulated
decvalue, which represents the decimal equivalent of the binary number.
-
decimalToBinary(int num):string bin = "";: Initializes an empty string called bin to store the binary representation.if (num == 0) {return "0";}: Checks if the inputnumis zero.- If it is, the function immediately returns “0” (since the binary representation of zero is just “0”).
while (num > 0) { ... }: Enters a loop that continues until num becomes zero.- Inside the loop, the following steps are performed for each iteration:
bin = char('0' + num % 2) + bin;: Converts the remainder to a character (‘0’ or ‘1’) and appends it to the front of thebinstring.- The
+ binpart ensures that we build the binary representation from right to left. num /= 2;: Divides num by 2, effectively shifting to the next binary place value.
- After processing all binary places, the function returns the accumulated
binstring, which represents the binary equivalent of the decimal number.
-
addBinary(string A, string B):if (A.length() > B.length()) {return addBinary(B, A);}:- If the length of string
Ais greater than that of stringB, swap the arguments and recursively calladdBinary(B, A). - This ensures that
Ais not shorter thanB.
- If the length of string
int diff = B.length() - A.length();: calculates the difference in lengths betweenBandA.string padding;: initializes an empty string calledpadding.- The loop adds zeros to
paddingto make the lengths ofAandBequal. - The main loop iterates through each index from right to left (from the end of the strings).
- It performs binary addition based on the values of
A[i]andB[i]and the carry (carry). - The result is accumulated in the
resstring. - Depending on the values of
A[i]andB[i], the carry is updated accordingly. - If the carry is ‘1’, it propagates to the next position.
- If there’s a carry after processing all digits, it’s appended to the result.
- The result is reversed to obtain the correct order.
- Leading zeros are removed by finding the first non-zero digit.
- The function returns the final result, which is the sum of the binary numbers represented by
AandB.
-
decimalToAnyBase(int n, int k):string res = "";: Initializes an empty string calledresto store the result.- The
whileloop continues as long asnis greater than zero. - Inside the loop:
to_string(n % k): Converts the remainder to a string and appends it to theresstring.n /= k: Dividesnbyk, effectively shifting to the next place value.
- After processing all place values, the
resstring contains the digits in reverse order. reverse(res.begin(), res.end()): Reverses the order of characters in theresstring.- The function returns the final result, which represents the number in the specified base.
( II ) Count Words & Letters.
-
Function Definitions:
-
void letter_count(string s):- This function counts the occurrences of each letter in a given string and prints them out. Here’s how it works step by step:
sort(all(s));: The string s is sorted alphabetically, so all identical letters are next to each other.for (int i = 0; s[i] != '\0'; i++): A for loop starts, iterating over each character in the string until the null character \0 is reached (end of the string).if (isalpha(s[i])): Inside the loop, it checks if the current character is an alphabetic character.ll count = 1;: A variable count is initialized to 1 to start counting the occurrences of the current letter.while (s[i] == s[i + 1]) {i++, count++;}: A while loop continues as long as the current character is the same as the next one. For each match, i is incremented to move to the next character, and count is incremented to keep track of the number of occurrences.cout << s[i] << " => "<< count << endl;: Once the while loop ends, the character and its count are printed.
- This function counts the occurrences of each letter in a given string and prints them out. Here’s how it works step by step:
-
int word_count(string st, char sep = ' '):- This function counts the number of words in a string, where words are separated by a specified separator (default is a space character ’ ') .Here’s how it works step by step:
int count = 0;: Initializes a word count to 0.bool inWord = false;: A boolean flag to track whether the current position is inside a word.for (int i = 0; i < st.length(); i++): A for loop iterates over each character in the string.if (st[i] == sep): If the current character is the separator, it checks if it’s at the end of a word.else {inWord = true;}: If the current character is not a separator, it’s part of a word, so set the flag to true.if (inWord) {count++;}: After the loop, if it ends inside a word, increment the word count.
- This function counts the number of words in a string, where words are separated by a specified separator (default is a space character ’ ') .Here’s how it works step by step:
-
-
Example.:
Suppose we have the following input string:
"Hello World! Welcome to C++ programming."Here's what the output would look like after running the
mainfunction with this input:The number of letters in the sentence in details: C => 1 H => 1 W => 2 a => 1 c => 1 d => 1 e => 3 g => 2 i => 1 l => 4 m => 3 n => 1 o => 5 p => 1 r => 3 t => 1 The number of words in the sentence = 6 words.
( III ) Distinct Values & Get Index.
-
Function Definitions:
-
int cntDistinct(string str):- This function takes a string
stras input. - It calculates the number of distinct characters (unique characters) in the given string.
- Here's how it works:
- It uses an
unordered_set<char>(a set that automatically removes duplicates) to store unique characters. - The loop traverses the string, and for each character:
- If the character is not already in the set, it inserts it.
- If the character is already in the set, it is ignored (since it's not unique).
- Finally, it returns the size of the set, which represents the count of distinct characters in the string.
- It uses an
- This function takes a string
-
int countDistinct(int arr[], int n):- This function takes an array of integers
arrand its sizenas input. - It calculates the number of distinct elements in the array.
- Here's how it works:
- It uses a
set<int>(a set that automatically removes duplicates) to store unique elements. - The loop traverses the array, and for each element:
- If the element is not already in the set, it inserts it.
- If the element is already in the set, it is ignored (since it's not unique).
- Finally, it returns the size of the set, which represents the count of distinct elements in the array.
- It uses a
- This function takes an array of integers
-
long long getIndex(vector<ll> v, ll K):- This function takes a vector of
ll(long long) integersvand a target valueK. - It searches for
Kin the vector and returns its index if found; otherwise, it returns -1. - Here's how it works:
- It uses the
findfunction from the<algorithm>library to search forKin the vector. - If
Kis found, it calculates the index by subtracting the iterator position from the beginning of the vector. - If
Kis not present in the vector, it returns -1.
- It uses the
- This function takes a vector of
-
-
Main Function:
- Reads a string
eand calculates the number of distinct characters usingcntDistinct(e). - Reads an integer
nand an array of integersarr. Calculates the number of distinct elements usingcountDistinct(arr, n). - Reads a
long longintegerkand finds its index in the array usinggetIndex(arr, k). - Prints the results accordingly.
- Finally, the program returns 0, indicating successful execution.
- Reads a string
-
End of Program.
( IV ) Five in One.
-
Function Definitions:
Max(): This function sorts the array in descending order (largest to smallest) and then prints the first element, which is the largest number in the array.Min(): Similar to the Max function, but it sorts the array in ascending order (smallest to largest) and prints the first element, which is the smallest number.Prime(): This function counts the number of prime numbers in the array. A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.Palindrome(): This function checks how many numbers in the array are palindromes. A palindrome is a number that reads the same backward as forward.divisors(): This function returns the number of divisors of a given number. A divisor is a number that can divide another number without leaving a remainder.
-
Main Function:
-
Read Number of Elements:
- The program prompts the user to enter the number of elements (
num) that will be in the array.
- The program prompts the user to enter the number of elements (
-
Create and Fill the Array:
- An array
arris created with the size specified by the user. The program then reads the elements of the array from the user input.
- An array
-
Find and Display Maximum and Minimum:
- The
MaxandMinfunctions are called to find and display the largest and smallest numbers in the array.
- The
-
Count and Display Prime Numbers:
- The
Primefunction is called to count and display the number of prime numbers in the array.
- The
-
Count and Display Palindrome Numbers:
- The
Palindromefunction is called to count and display the number of palindrome numbers in the array.
- The
-
Find the Number with Maximum Divisors:
- A loop runs through each element in the array, calling the
divisorsfunction to find the number of divisors for each element. It keeps track of the number with the most divisors and, in case of a tie, the larger number.
- A loop runs through each element in the array, calling the
-
Display the Number with Maximum Divisors:
- After the loop, the program prints the number that has the maximum number of divisors.
-
End of Program:
- The program returns 0, which is a signal that the program has ended successfully.
-
( V ) Multiply the matrix by the scalar.
-
Function Definitions:
void read_matrix(ll row, ll column, int** matrix): This function reads the elements of a matrix from the user. It takes the number of rows and columns as well as a pointer to a pointer of integers (which represents the matrix) as arguments.void write_matrix(ll row, ll column, int** matrix): This function prints the matrix to the console. It also takes the number of rows and columns and the matrix as arguments.void multiply_by_scalar(ll row, ll column, int** matrix, ll scalar): This function multiplies each element of the matrix by a scalar value provided by the user.
-
Main Function:
- The
mainfunction begins with a greeting message to the user. - It then prompts the user to enter the number of rows and columns for the matrix.
- Memory is dynamically allocated for the matrix using
newbased on the number of rows and columns entered by the user. - The
read_matrixfunction is called to read the matrix elements from the user. - The
write_matrixfunction is called to print the original matrix. - The user is prompted to enter a scalar value.
- The
multiply_by_scalarfunction is called to multiply the matrix by the scalar. - The
write_matrixfunction is called again to print the modified matrix.
- The
-
Program Flow:
- The user is interactively involved throughout the program, entering the size of the matrix, its elements, and the scalar value for multiplication.
- The program outputs the matrix before and after the scalar multiplication.
-
Memory Management:
- We allocate memory for the matrix dynamically using
new. - After using the matrix, we free the allocated memory using
delete[].
- We allocate memory for the matrix dynamically using
-
End of Program:
- We display a thank-you message and terminate the program.
( VI ) Sequence Arrangement Solver.
-
Input and Initialization:
int n;: We declare an integer variablento store the number of elements (people in line).cin >> n;: We read the value ofnfrom the standard input (keyboard).vector<int> arr(n), position(n, 0);: We create two vectors:arrto store the input sequence of people.positionto keep track of the positions directly behind each person (initialized with zeros).
int x = 0;: We initialize an integer variablexto zero. This variable will later store the starting position.
-
Reading the Input Sequence:
- We use a
forloop to read the input sequence into thearrvector. - If the current element is not
-1, we update thepositionvector to reflect the position of that element in the sequence. - If the current element is
-1, we setxto the current index plus one, indicating the starting position.
- We use a
-
Output the Sequence:
- We print the starting position (stored in
x). - Then, we follow the chain of positions using a
whileloop:- If the next position is not zero (i.e., there's a valid successor), we print the next position and update
xto that position. - We continue this process until we reach the end of the chain (when the next position is zero).
- If the next position is not zero (i.e., there's a valid successor), we print the next position and update
- We print the starting position (stored in
-
End of Program.
( VII ) The Most Repeated Character.
-
Function
mostFrequent:- This function takes a string
textas input. - It initializes variables:
max(to track the maximum count),count(to count occurrences of each character), andmaxCharcter(to store the most frequent character). - The outer loop iterates over characters from space
' 'to tilde'~'. - The inner loop counts how many times the current character appears in the input string
text. - If the count is greater than the current maximum, it updates the maximum count and the most frequent character.
- The function returns the most frequent character.
- This function takes a string
-
Main Function:
- The
mainfunction starts by declaring an integer variabletest. - It reads a string
txtfrom standard input (keyboard). - It calls the
mostFrequentfunction withtxtas the argument and prints the result (the most frequent character).
- The
-
End of Program.:
- The program returns 0 to indicate successful execution.