diff --git a/2160. Minimum Sum of Four Digit Number After Splitting Digits b/2160. Minimum Sum of Four Digit Number After Splitting Digits new file mode 100644 index 0000000..6876265 --- /dev/null +++ b/2160. Minimum Sum of Four Digit Number After Splitting Digits @@ -0,0 +1,61 @@ +/* +Get all digits of num. +Sort them. +To get the minimum sum. We need to choose 1st and 2nd digits as tens digits and 3rd and 4th as ones digits. +As when the tens digits will be minimum, then only we will get minimum sum. +For example: +5643=>3,4,5,6 +30+40+5+6=86(min) + +Other possibilities: +30+50+4+6=90 +30+60+4+5=101 +40+50+4+6=100 and so on. + +Method 1: +Time complexity: O(nlogn) +Use array to store the digits of num. +*/ + +class Solution { + public int minimumSum(int num) { + int[] res=new int[4]; + int i=0; + while(num>0){ + res[i]=num%10; + num/=10; + i++; + } + Arrays.sort(res) + return res[0]*10+res[2]+res[1]*10+res[3]; + } +} + + + + + +//method 2 +/* +Method 2: +Use priorityqueue to store the digits of num. +Time complexity: O(n) +*/ + + +class Solution { + public int minimumSum(int num) { + PriorityQueuepq=new PriorityQueue<>(); + //complexity to insert: O(1) + while(num>0){ + pq.offer(num%10); + num/=10; + } + //complexity to remove: O(n) + int a=10*pq.remove(); + int b=10*pq.remove(); + int c=pq.remove(); + int d=pq.remove(); + return a+b+c+d; + } +} diff --git a/BFS.cpp b/BFS.cpp new file mode 100644 index 0000000..f0e309b --- /dev/null +++ b/BFS.cpp @@ -0,0 +1,88 @@ +// Program to print BFS traversal from a given +// source vertex. BFS(int s) traverses vertices +// reachable from s. +#include +using namespace std; + +// This class represents a directed graph using +// adjacency list representation +class Graph +{ + int V; // No. of vertices + + // Pointer to an array containing adjacency + // lists + vector> adj; +public: + Graph(int V); // Constructor + + // function to add an edge to graph + void addEdge(int v, int w); + + // prints BFS traversal from a given source s + void BFS(int s); +}; + +Graph::Graph(int V) +{ + this->V = V; + adj.resize(V); +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +void Graph::BFS(int s) +{ + // Mark all the vertices as not visited + vector visited; + visited.resize(V,false); + + // Create a queue for BFS + list queue; + + // Mark the current node as visited and enqueue it + visited[s] = true; + queue.push_back(s); + + while(!queue.empty()) + { + // Dequeue a vertex from queue and print it + s = queue.front(); + cout << s << " "; + queue.pop_front(); + + // Get all adjacent vertices of the dequeued + // vertex s. If a adjacent has not been visited, + // then mark it visited and enqueue it + for (auto adjecent: adj[s]) + { + if (!visited[adjecent]) + { + visited[adjecent] = true; + queue.push_back(adjecent); + } + } + } +} + +// Driver program to test methods of graph class +int main() +{ + // Create a graph given in the above diagram + Graph g(4); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + cout << "Following is Breadth First Traversal " + << "(starting from vertex 2) \n"; + g.BFS(2); + + return 0; +} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..30b9f91 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,53 @@ +# Contributing to Programming_HacktoberFest-2023 + +Welcome to Programming_Hactober23 ! We appreciate your interest in contributing. Before you get started, please read and follow these guidelines. + +## Prerequisites + +Prior to beginning your contributions, please ensure the following: + +- Possess a GitHub Account. +- Complete your contributor registration on the [Hacktoberfest 2023 website.](https://hacktoberfest.com/) + +
+ +## How to Contribute + +1. **Look for the issue you wish to solve** on the project's issue tracker. + +2. **Comment on the issue**: Please comment on the issue, indicating your interest in working on it. You can use a comment like: "Please assign me this issue." + + + **Note**: + + - If the assigned contributor takes longer than expected to work on the issue, the maintainer may reassign the issue to the next person in the comment queue. + +
+ +## Commit your changes: + +- Make your changes or additions to the code, documentation, or any other improvements. + +- Test your changes thoroughly. + +## Contribution Guidelines + +- Please ensure your code and contributions align with the project's purpose and goals. + +- Follow the coding style and guidelines of the project. + +- Keep your commits and pull requests concise and clearly describe the changes you've made. + +- Do not submit spammy, trivial, or duplicate pull requests. Quality contributions are highly encouraged. + +
+ +## Questions and Support + +- If you have questions or need support related to your contributions or the project, feel free to tag and ask your doubts to the repository maintainer. + +- Thank you for contributing to Programming_HacktoberFest-2023! Your contributions are greatly appreciated. + +
+ + Happy contributing! 🚀 diff --git a/CheckEvenandOddInArray.cpp b/CheckEvenandOddInArray.cpp new file mode 100644 index 0000000..53f3dd4 --- /dev/null +++ b/CheckEvenandOddInArray.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; + +int main(){ + +int size; +cout<<"Enter Size of Array: "; +cin>>size; + +int arr[size]; + +cout<<" Enter Elements in the array: "; + +for(int i=0; i>arr[i]; +} + +cout<<" Even elements: "; + +for(int i=0; i +#include +#include + +int main() { + int n; + std::cout << "Enter the number of elements: "; + std::cin >> n; + + std::vector arr(n); + + std::cout << "Enter " << n << " elements: "; + for (int i = 0; i < n; ++i) { + std::cin >> arr[i]; + } + + std::set uniqueElements; + for (int i : arr) { + uniqueElements.insert(i); + } + + std::cout << "Unique elements in the array: "; + for (int element : uniqueElements) { + std::cout << element << " "; + } + std::cout << std::endl; + + return 0; +} diff --git a/Gr8stIntInArr.cpp b/Gr8stIntInArr.cpp new file mode 100644 index 0000000..8c0b0d8 --- /dev/null +++ b/Gr8stIntInArr.cpp @@ -0,0 +1,48 @@ +#include +using namespace std; + +int findLargestElement(int arr[], int size) { + if (size <= 0) { + // Ha the case of an empty array or invalid size + return -1; + } + + int largest = arr[0]; // Assuming the first element is the largest + + for (int i = 1; i < size; i++) { + if (arr[i] > largest) { + largest = arr[i]; // Updating largest if current element is greater + } + } + + return largest; +} + +int main() { + int size; + + cout << "Enter the size of the array: "; + cin >> size; + + if (size <= 0) { + cout << "Invalid array size." <> arr[i]; + } + + int largest = findLargestElement(arr, size); + + if (largest != -1) { + cout << "The largest element in the array is: " << largest < +#include + +// Structure to represent an item +struct Item { + int weight; + int value; +}; + +// Function to compare items by their value-to-weight ratio +int compare(const void* a, const void* b) { + double ratioA = ((struct Item*)a)->value / (double)((struct Item*)a)->weight; + double ratioB = ((struct Item*)b)->value / (double)((struct Item*)b)->weight; + return (ratioB > ratioA) - (ratioB < ratioA); +} + +// Greedy Knapsack Algorithm +void knapsack(struct Item items[], int n, int capacity) { + // Sort items by their value-to-weight ratio in descending order + qsort(items, n, sizeof(struct Item), compare); + + int currentWeight = 0; // Current weight in the knapsack + double totalValue = 0.0; // Total value in the knapsack + + // Loop through the sorted items + for (int i = 0; i < n; i++) { + if (currentWeight + items[i].weight <= capacity) { + // Include the whole item as it fits in the knapsack + currentWeight += items[i].weight; + totalValue += items[i].value; + } else { + // Include a fraction of the item to fill the knapsack + int remainingCapacity = capacity - currentWeight; + totalValue += (items[i].value / (double)items[i].weight) * remainingCapacity; + break; // Knapsack is full + } + } + + printf("Maximum value in the knapsack: %.2lf\n", totalValue); +} + +int main() { + int n, capacity; + + printf("Enter the number of items: "); + scanf("%d", &n); + printf("Enter the knapsack capacity: "); + scanf("%d", &capacity); + + struct Item items[n]; + + printf("Enter the weight and value of each item:\n"); + for (int i = 0; i < n; i++) { + scanf("%d %d", &items[i].weight, &items[i].value); + } + + knapsack(items, n, capacity); + + return 0; +} diff --git a/KadansAlgorithm.cpp b/KadansAlgorithm.cpp new file mode 100644 index 0000000..60b1f70 --- /dev/null +++ b/KadansAlgorithm.cpp @@ -0,0 +1,24 @@ +#include +#include + +int kadanesAlgorithm(const std::vector& arr) { + int maxEndingHere = arr[0]; + int maxSoFar = arr[0]; + + for (int i = 1; i < arr.size(); ++i) { + maxEndingHere = std::max(arr[i], maxEndingHere + arr[i]); + maxSoFar = std::max(maxSoFar, maxEndingHere); + } + + return maxSoFar; +} + +int main() { + std::vector arr = {1, -3, 2, 1, -1}; + + int maxSubarraySum = kadanesAlgorithm(arr); + + std::cout << "Maximum subarray sum: " << maxSubarraySum << std::endl; + + return 0; +} diff --git a/LCS.c b/LCS.c new file mode 100644 index 0000000..6939309 --- /dev/null +++ b/LCS.c @@ -0,0 +1,57 @@ +//Script to find the largest common subsequence +#include +#include + +int max(int a, int b) { + return (a > b) ? a : b; +} + +void lcs(char *X, char *Y, int m, int n) { + int L[m + 1][n + 1]; + + // Build the LCS matrix + for (int i = 0; i <= m; i++) { + for (int j = 0; j <= n; j++) { + if (i == 0 || j == 0) + L[i][j] = 0; + else if (X[i - 1] == Y[j - 1]) + L[i][j] = L[i - 1][j - 1] + 1; + else + L[i][j] = max(L[i - 1][j], L[i][j - 1]); + } + } + + // Find the LCS length + int length = L[m][n]; + + // Create an array to store the LCS + char lcs[length + 1]; + lcs[length] = '\0'; + + int i = m, j = n; + while (i > 0 && j > 0) { + if (X[i - 1] == Y[j - 1]) { + lcs[length - 1] = X[i - 1]; + i--; + j--; + length--; + } else if (L[i - 1][j] > L[i][j - 1]) + i--; + else + j--; + } + + printf("Longest Common Subsequence: %s\n", lcs); +} + +int main() { + char X[] = "AGGTAB"; + char Y[] = "GXTXAYB"; + + int m = strlen(X); + int n = strlen(Y); + + lcs(X, Y, m, n); + + return 0; +} diff --git a/MaxSubarray.cpp b/MaxSubarray.cpp new file mode 100644 index 0000000..0280476 --- /dev/null +++ b/MaxSubarray.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; + +// function for kadane's algorithm +static int kadane(int Array[], int n) { + int max_sum = 0; + int current_sum = 0; + + for(int i=0; i 496. Next Greater Element I +import java.util.*; +class Hactober { + public static int[] nextGreaterElement(int[] nums1, int[] nums2) { + HashMap map = new HashMap<>(); + Stack s = new Stack<>(); + for(int i:nums2){ + while(!s.isEmpty()&&s.peek() +using namespace std; + +int main(){ + +int num, result=0; +cout<<"Enter a positive integer: "; +cin>>num; + + +int temporary = num; +while(num>0){ + int dig = num%10; + result = result*10+dig; + num=num/10; +} + +num = temporary; + + + if(result==num){ + cout<<"Number is a palindrome."; +} + else + cout<<"Not a palindrome."; + +return 0; +} diff --git a/Python/F1_RACE_PREDICTION.py b/Python/F1_RACE_PREDICTION.py new file mode 100644 index 0000000..974910f --- /dev/null +++ b/Python/F1_RACE_PREDICTION.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- +"""Untitled19.ipynb + +Automatically generated by Colab. + +Original file is located at + https://colab.research.google.com/drive/1n8tDlXoN3D4JWiWUl-WPjG2wfc9qMR1C + +NEW MODEL +""" + +import pandas as pd +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.ensemble import RandomForestClassifier +from sklearn.metrics import accuracy_score, confusion_matrix + +# Load datasets (update paths if needed) +drivers = pd.read_csv("/content/drivers.csv") +constructor = pd.read_csv("/content/constructors.csv") +driver_standings = pd.read_csv("/content/driver_standings.csv") +constructor_standings = pd.read_csv("/content/constructor_standings.csv") +results = pd.read_csv("/content/results.csv") +constructor_results = pd.read_csv("/content/constructor_results.csv") + +# Merge driver info into results +data = results.merge(drivers, on="driverId", how="left") +# Merge constructor info +data = data.merge(constructor, on="constructorId", how="left") +# Using average points per race for realistic values +driver_points_avg = results.groupby('driverId')['points'].mean().to_dict() +constructor_points_avg = results.groupby('constructorId')['points'].mean().to_dict() + +data['driver_points'] = data['driverId'].map(driver_points_avg) +data['constructor_points'] = data['constructorId'].map(constructor_points_avg) + +data.head() + +# Target = 1 if driver won the race, else 0 +data['target'] = (data['positionOrder'] == 1).astype(int) + +features = ['grid', 'driver_points', 'constructor_points'] +X = data[features] +y = data['target'] + +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + +model = RandomForestClassifier(n_estimators=100, random_state=42) +model.fit(X_train, y_train) + +y_pred = model.predict(X_test) +print("Accuracy:", accuracy_score(y_test, y_pred)) +print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred)) + +# Example future race: use actual driver IDs +future_race = pd.DataFrame({ + 'driverId': [1, 2, 3, 4, 5], + 'grid': [1, 2, 3, 4, 5] # starting positions +}) + +# Maping driver names +driver_names = drivers.set_index('driverId')['surname'].to_dict() +future_race['driver_name'] = future_race['driverId'].map(driver_names) + +# Maping latest constructor for each driver from results +latest_race_per_driver = results.groupby('driverId').apply(lambda x: x.sort_values('raceId', ascending=False).iloc[0]) +driver_constructor_map = latest_race_per_driver.set_index('driverId')['constructorId'].to_dict() +future_race['constructorId'] = future_race['driverId'].map(driver_constructor_map) + +# Mapingg constructor names +constructor_names = constructor.set_index('constructorId')['name'].to_dict() +future_race['constructor_name'] = future_race['constructorId'].map(constructor_names) + +# Maping average points per race for drivers and constructors +driver_points_avg = results.groupby('driverId')['points'].mean().to_dict() +constructor_points_avg = results.groupby('constructorId')['points'].mean().to_dict() +future_race['driver_points'] = future_race['driverId'].map(driver_points_avg) +future_race['constructor_points'] = future_race['constructorId'].map(constructor_points_avg) + +future_race + +features = ['grid', 'driver_points', 'constructor_points'] +X_future = future_race[features] + +# Predict probability of winning +future_race['win_probability'] = model.predict_proba(X_future)[:,1] +future_race + +# Sorting by win probability descending +future_race_sorted = future_race.sort_values('win_probability', ascending=False) + +# final table +future_race_sorted[['driver_name', 'constructor_name', 'grid', 'driver_points', 'constructor_points', 'win_probability']] + +# Select top 3 drivers by win probability +top3 = future_race_sorted.head(3) + +# Display a clean leaderboard +for i, row in top3.iterrows(): + print(f"Position {i+1}: {row['driver_name']} ({row['constructor_name']})") + print(f" Grid: {row['grid']}, Avg Driver Points: {row['driver_points']:.1f}, " + f"Avg Constructor Points: {row['constructor_points']:.1f}, " + f"Win Probability: {row['win_probability']:.2%}\n") + +# Sorting by win_probability descending +future_race_sorted = future_race.sort_values('win_probability', ascending=False) + +# top drivers +future_race_sorted[['driver_name', 'constructor_name', 'grid', 'driver_points', 'constructor_points', 'win_probability']] + +import matplotlib.pyplot as plt + +# Sort by win probability descending +future_race_sorted = future_race.sort_values('win_probability', ascending=False) + +# Bar chart of win probabilities +plt.figure(figsize=(12,6)) +bars = plt.bar(future_race_sorted['driver_name'], future_race_sorted['win_probability'], color='royalblue') + +# Add probability values on top of bars +for bar in bars: + height = bar.get_height() + plt.text(bar.get_x() + bar.get_width()/2.0, height + 0.01, f"{height:.2%}", ha='center', va='bottom') + +plt.ylabel('Win Probability') +plt.xlabel('Driver') +plt.title('Predicted Win Probabilities for Future Race') +plt.ylim(0, 1) # set y-axis between 0 and 1 +plt.show() \ No newline at end of file diff --git a/README.md b/README.md index d279230..dfee3ea 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,3 @@ -# Programming_Hactoberfest23. -#Add issues by your choices.
-#Add codes in specific folders.
-#do not copy the code from anywhere..


-![723s3y5aujdvqn3x7w2h](https://github.com/Nikhil-2002/Programming_Hactoberfest23/assets/76964639/e05bccc4-a735-4322-81f5-6107cc282cf0) +# Programming_Hactoberfest23 +New Contribution Repository +https://github.com/Nikhil-2002/hacktoberfest2025-contributions diff --git a/Rainwater trapping.cpp b/Rainwater trapping.cpp new file mode 100644 index 0000000..c3844a0 --- /dev/null +++ b/Rainwater trapping.cpp @@ -0,0 +1,59 @@ +/* +Problem: Trapping Rain Water +We need to calculate how much water can be trapped between bars of different heights after raining. +Approach (Prefix–Suffix / Auxiliary Arrays Method) + +The main idea is: For each element, the amount of water that can be trapped above it depends on The maximum height to its left and the maximum height to its right + +Water trapped at that position = min(maxLeft, maxRight) - height[i] + +So, we first precompute two arrays: +left[i] → highest bar from the start to index i +right[i] → highest bar from the end to index i +Then, for every index i, we find: water[i] = min(left[i], right[i]) - height[i] +Add up all these values to get the total trapped water. +*/ +#include +using namespace std; + +class Solution { +public: + int trap(vector& height) { + int n = height.size(); + if (n == 0) return 0; + + // Step 1: Precompute the maximum height to the left of each bar + vector leftMax(n); + leftMax[0] = height[0]; + for (int i = 1; i < n; i++) { + leftMax[i] = max(leftMax[i - 1], height[i]); + } + + // Step 2: Precompute the maximum height to the right of each bar + vector rightMax(n); + rightMax[n - 1] = height[n - 1]; + for (int i = n - 2; i >= 0; i--) { + rightMax[i] = max(rightMax[i + 1], height[i]); + } + + // Step 3: Calculate trapped water for each index + int totalWater = 0; + for (int i = 0; i < n; i++) { + int waterLevel = min(leftMax[i], rightMax[i]); + totalWater += (waterLevel - height[i]); + } + + return totalWater; + } +}; + +int main() { + Solution s; + vector height = {4,2,0,3,2,5}; + cout << "Total trapped water: " << s.trap(height) << endl; + return 0; +} + +/*The time complexity of this approach is O(n) since we make three separate passes through the array — one to compute the leftMax array, one to compute the rightMax array, and one final pass to calculate the total trapped water. Each step takes linear time, so the overall complexity remains O(n). + +The space complexity, however, is O(n) because we use two additional arrays, leftMax and rightMax, to store the maximum heights on each side for every index. While this approach is easy to understand and straightforward to implement, it does require extra memory. The main advantage is its clarity and simplicity, but the downside is the use of additional space — which can be optimized using a more efficient two-pointer approach that reduces the space complexity to O(1).*/ \ No newline at end of file diff --git a/Reverse_an_array/ReverseArrayUsingScanner.java b/Reverse_an_array/ReverseArrayUsingScanner.java new file mode 100644 index 0000000..e959bb1 --- /dev/null +++ b/Reverse_an_array/ReverseArrayUsingScanner.java @@ -0,0 +1,47 @@ +import java.util.Scanner; + +public class ArrayReverser { + + public static void reverseArray(int[] arr) { + int start = 0; + int end = arr.length - 1; + + while (start < end) { + // Swap the elements at start and end positions + int temp = arr[start]; + arr[start] = arr[end]; + arr[end] = temp; + + // Move the pointers toward each other + start++; + end--; + } + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.print("Enter the size of the array: "); + int size = scanner.nextInt(); + int[] array = new int[size]; + + System.out.println("Enter elements of the array:"); + for (int i = 0; i < size; i++) { + array[i] = scanner.nextInt(); + } + + scanner.close(); + + System.out.println("Original Array:"); + for (int num : array) { + System.out.print(num + " "); + } + + reverseArray(array); + + System.out.println("\nReversed Array:"); + for (int num : array) { + System.out.print(num + " "); + } + } +} diff --git a/SCS.c b/SCS.c new file mode 100644 index 0000000..c93cc41 --- /dev/null +++ b/SCS.c @@ -0,0 +1,83 @@ +//Script to find the Shortest COmmon Subsequence +#include +#include + +int max(int a, int b) { + return (a > b) ? a : b; +} + +int shortestCommonSupersequenceLength(char X[], char Y[]) { + int m = strlen(X); + int n = strlen(Y); + + int dp[m + 1][n + 1]; + + for (int i = 0; i <= m; i++) { + for (int j = 0; j <= n; j++) { + if (i == 0) + dp[i][j] = j; + else if (j == 0) + dp[i][j] = i; + else if (X[i - 1] == Y[j - 1]) + dp[i][j] = 1 + dp[i - 1][j - 1]; + else + dp[i][j] = 1 + max(dp[i - 1][j], dp[i][j - 1]); + } + } + + return dp[m][n]; +} + +void printSCS(char X[], char Y[]) { + int m = strlen(X); + int n = strlen(Y); + int SCSLength = shortestCommonSupersequenceLength(X, Y); + char SCS[SCSLength + 1]; + + int i = m, j = n, k = SCSLength; + + while (i > 0 && j > 0) { + if (X[i - 1] == Y[j - 1]) { + SCS[k - 1] = X[i - 1]; + i--; + j--; + k--; + } else if (dp[i - 1][j] > dp[i][j - 1]) { + SCS[k - 1] = X[i - 1]; + i--; + k--; + } else { + SCS[k - 1] = Y[j - 1]; + j--; + k--; + } + } + + while (i > 0) { + SCS[k - 1] = X[i - 1]; + i--; + k--; + } + + while (j > 0) { + SCS[k - 1] = Y[j - 1]; + j--; + k--; + } + + SCS[SCSLength] = '\0'; + + printf("Shortest Common Supersequence: %s\n", SCS); +} + +int main() { + char X[] = "ABCBDAB"; + char Y[] = "BDCABA"; + + int SCSLength = shortestCommonSupersequenceLength(X, Y); + printf("Length of Shortest Common Supersequence: %d\n", SCSLength); + + printSCS(X, Y); + + return 0; +} diff --git a/Take input in String form and convert to array format for operation #98 b/Take input in String form and convert to array format for operation #98 new file mode 100644 index 0000000..361bbdc --- /dev/null +++ b/Take input in String form and convert to array format for operation #98 @@ -0,0 +1,38 @@ +/* +Steps: +1. Directly take a string as input. +2. Keep a list and a temporary string str. +3. Traverse in the string add the characters in the temporary string until the white space encountered. +4. If white space encountered, add the temporary string to list after converting to integer. +5. Make temporary string empty string. +6. after coming out of the string again check the temporary string and add. +Note: step 6 is important as in most of the cases white space will not come at the end. + so, after coming to end add the temporary string in end. +7. Now, you have the list of integers, without giving the input number of elements. + +*/ + + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class Solution { + public static void main(String[] args) { + Scanner sc=new Scanner(System.in); + String s=sc.nextLine(); + String str=""; + int n=s.length(); + Listlist=new ArrayList<>(); + for(int i=0;i +#include +#include + +const int V = 6; // Number of vertices in the graph + +// Function to find the vertex with the minimum distance value from the set of vertices not yet included in the shortest path tree +int minDistance(const std::vector& dist, const std::vector& sptSet) { + int minDist = INT_MAX, minIndex = -1; + for (int v = 0; v < V; ++v) { + if (!sptSet[v] && dist[v] < minDist) { + minDist = dist[v]; + minIndex = v; + } + } + return minIndex; +} + +// Function to print the constructed distance array +void printSolution(const std::vector& dist) { + std::cout << "Vertex \t Distance from Source" << std::endl; + for (int i = 0; i < V; ++i) { + std::cout << i << " \t " << dist[i] << std::endl; + } +} + +// Dijkstra's algorithm to find the shortest path from source to all vertices +void dijkstra(const std::vector>& graph, int src) { + std::vector dist(V, INT_MAX); // The output array to store the shortest distance from the source vertex + std::vector sptSet(V, false); // Set to keep track of vertices included in the shortest path tree + + dist[src] = 0; // Distance from the source to itself is 0 + + for (int count = 0; count < V - 1; ++count) { + int u = minDistance(dist, sptSet); + + sptSet[u] = true; + + for (int v = 0; v < V; ++v) { + if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) { + dist[v] = dist[u] + graph[u][v]; + } + } + } + + printSolution(dist); +} + +int main() { + std::vector> graph = { + {0, 2, 4, 0, 0, 0}, + {2, 0, 3, 2, 0, 0}, + {4, 3, 0, 0, 1, 0}, + {0, 2, 0, 0, 3, 2}, + {0, 0, 1, 3, 0, 2}, + {0, 0, 0, 2, 2, 0} + }; + + int src = 0; // Source vertex + + dijkstra(graph, src); + + return 0; +} diff --git a/application of algorithm/shortest_path b/application of algorithm/shortest_path new file mode 100644 index 0000000..1dd7da9 --- /dev/null +++ b/application of algorithm/shortest_path @@ -0,0 +1,64 @@ +#include +#include +#include + +const int V = 6; // Number of vertices in the graph + +// Function to find the vertex with the minimum distance value from the set of vertices not yet included in the shortest path tree +int minDistance(const std::vector& dist, const std::vector& sptSet) { + int minDist = INT_MAX, minIndex = -1; + for (int v = 0; v < V; ++v) { + if (!sptSet[v] && dist[v] < minDist) { + minDist = dist[v]; + minIndex = v; + } + } + return minIndex; +} + +// Function to print the constructed distance array +void printSolution(const std::vector& dist) { + std::cout << "Vertex \t Distance from Source" << std::endl; + for (int i = 0; i < V; ++i) { + std::cout << i << " \t " << dist[i] << std::endl; + } +} + +// Dijkstra's algorithm to find the shortest path from source to all vertices +void dijkstra(const std::vector>& graph, int src) { + std::vector dist(V, INT_MAX); // The output array to store the shortest distance from the source vertex + std::vector sptSet(V, false); // Set to keep track of vertices included in the shortest path tree + + dist[src] = 0; // Distance from the source to itself is 0 + + for (int count = 0; count < V - 1; ++count) { + int u = minDistance(dist, sptSet); + + sptSet[u] = true; + + for (int v = 0; v < V; ++v) { + if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) { + dist[v] = dist[u] + graph[u][v]; + } + } + } + + printSolution(dist); +} + +int main() { + std::vector> graph = { + {0, 2, 4, 0, 0, 0}, + {2, 0, 3, 2, 0, 0}, + {4, 3, 0, 0, 1, 0}, + {0, 2, 0, 0, 3, 2}, + {0, 0, 1, 3, 0, 2}, + {0, 0, 0, 2, 2, 0} + }; + + int src = 0; // Source vertex + + dijkstra(graph, src); + + return 0; +} diff --git a/count-the-number-of-complete-components b/count-the-number-of-complete-components new file mode 100644 index 0000000..111c703 --- /dev/null +++ b/count-the-number-of-complete-components @@ -0,0 +1,79 @@ +/* + Just 3 main steps|| dfs || connected graph || check adjList +a) Intuition + 1. Get the number of connected graphs. + 2. For each connected graph, each element should be present in other's adjacency list. + 3. If the 2nd step becomes correct, increment count by 1. +b) Approach + 1. Make the adjacency list using map. + 2. dfs approach to get the list of connected nodes. + 3. Check whether each node has edges to other in the connected graph. + -->take the adjency list and add itself to its adjency list. + -->If adjency list == connectedNode list (for each node in the connected graph), count it. + +*/ + +class Solution { + List dfs(Listlist,Map>map,int key,int[] vis){ + //visted again means traversal completed for a given connected chunk of nodes + if(vis[key]==1)return list; + //mark node as visted + vis[key]=1; + //store list in new list + Listli=new ArrayList<>(list); + li.add(key); + for(int i=0;ilist,Map>adjList){ + int cnt=0; + for(Integer i:list){ + //if a node can visit to all other node + //means adj list just lack itself + //if we add it to its own adjacency list, + //adj will be equal to list. + Listadj=new ArrayList<>(adjList.get(i)); + adj.add(i); + Collections.sort(adj); + if(list.equals(adj))cnt++; + } + return cnt==list.size()?1:0; + } + public int countCompleteComponents(int n, int[][] edges) { + //make adjacency list using map + Map>map=new HashMap<>(); + for(int i=0;i()); + map.get(edges[i][0]).add(edges[i][1]); + map.putIfAbsent(edges[i][1],new ArrayList<>()); + map.get(edges[i][1]).add(edges[i][0]); + } + + for(int i=0;i()); + } + int[] vis=new int[map.size()]; + int sum=0; + for(Map.Entry>m:map.entrySet()){ + if(vis[m.getKey()]==0){ + Listlist=new ArrayList<>(); + //get the list of connected nodes + list=dfs(list,map,m.getKey(),vis); + + if(list.size()==1)sum++; + else{ + //sort it to match with the adjacency list of particular nodes. + Collections.sort(list); + sum+=conn(list,map); + } + } + } + return sum; + } +} diff --git a/count_number_of_odd_even_elements/soln.cpp b/count_number_of_odd_even_elements/soln.cpp new file mode 100644 index 0000000..2cf452d --- /dev/null +++ b/count_number_of_odd_even_elements/soln.cpp @@ -0,0 +1,21 @@ +//Author: Divya Raj (aka guru_divine) +#include +using namespace std; + +// TC -> O(n) +// SC -> O(1) + +int main() { + cout << "Enter the number of elements to be considered: "; + int n; cin >> n; + int cntEven=0, cntOdd=0; + cout << "Enter " << n << " elements: " << endl; + + for(int i=0; i> x; + if(x&1) cntOdd++; + else cntEven++; + } + cout << "Number of even elements in the list: " << cntEven << endl; + cout << "Number of odd elements in the list: " << cntOdd << endl; +} diff --git a/findDisjoint/ArrayDisjoinOrNot.java b/findDisjoint/ArrayDisjoinOrNot.java new file mode 100644 index 0000000..754cf8d --- /dev/null +++ b/findDisjoint/ArrayDisjoinOrNot.java @@ -0,0 +1,51 @@ +import java.util.HashSet; +import java.util.Scanner; + +public class DisjointArraysChecker { + + public static boolean areDisjoint(int[] arr1, int[] arr2) { + HashSet set = new HashSet<>(); + + for (int num : arr1) { + set.add(num); + } + + for (int num : arr2) { + if (set.contains(num)) { + return false; // Common element found, arrays are not disjoint + } + } + + return true; // No common elements found, arrays are disjoint + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.print("Enter the size of the first array: "); + int size1 = scanner.nextInt(); + int[] array1 = new int[size1]; + + System.out.println("Enter elements of the first array:"); + for (int i = 0; i < size1; i++) { + array1[i] = scanner.nextInt(); + } + + System.out.print("Enter the size of the second array: "); + int size2 = scanner.nextInt(); + int[] array2 = new int[size2]; + + System.out.println("Enter elements of the second array:"); + for (int i = 0; i < size2; i++) { + array2[i] = scanner.nextInt(); + } + + scanner.close(); + + if (areDisjoint(array1, array2)) { + System.out.println("The arrays are disjoint."); + } else { + System.out.println("The arrays are not disjoint."); + } + } +} diff --git a/find_the_smallest_element_in_an_array/smallestelementusingScanner.java b/find_the_smallest_element_in_an_array/smallestelementusingScanner.java new file mode 100644 index 0000000..2bd1377 --- /dev/null +++ b/find_the_smallest_element_in_an_array/smallestelementusingScanner.java @@ -0,0 +1,47 @@ +import java.util.Scanner; + +public class SmallestElementFinder { + + public static int findSmallestElement(int[] arr) { + if (arr.length == 0) { + throw new IllegalArgumentException("Array is empty"); + } + + int smallest = arr[0]; + + for (int num : arr) { + if (num < smallest) { + smallest = num; + } + } + + return smallest; + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.print("Enter the size of the array: "); + int size = scanner.nextInt(); + int[] array = new int[size]; + + if (size <= 0) { + System.out.println("Array size must be greater than 0."); + return; + } + + System.out.println("Enter elements of the array:"); + for (int i = 0; i < size; i++) { + array[i] = scanner.nextInt(); + } + + scanner.close(); + + try { + int smallestElement = findSmallestElement(array); + System.out.println("The smallest element in the array is: " + smallestElement); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } +} diff --git a/maximum-product-of-two-elements-in-an-array b/maximum-product-of-two-elements-in-an-array new file mode 100644 index 0000000..67c1427 --- /dev/null +++ b/maximum-product-of-two-elements-in-an-array @@ -0,0 +1,56 @@ +/* + Approach 1 + Time Complexity: O(nlogn) +*/ + +class Solution { + public int maxProduct(int[] nums) { + Arrays.sort(nums); //O(nlogn) time complexity sorting quick sort + return (nums[nums.length-1]-1)*(nums[nums.length-2]-1); + } +} + +/* + Approach 2 + Time Complexity: O(n) +*/ +class Solution { + public int maxProduct(int[] nums) { + int[] arr=new int[2]; + arr[0]=nums[0];//take array of size 2 store maximum two elements as we traverse through the array. + arr[1]=nums[1]; + //Once traversing the array has O(n) time complexity + for(int i=2;iarr[0] && nums[i]>arr[1]){ + if(arr[0]arr[0]){ + arr[0]=nums[i]; + } + else if(nums[i]>arr[1]){ + arr[1]=nums[i]; + } + } + return (arr[0]-1)*(arr[1]-1); + } +} + +/* + Approach 3 + Time complexity: O(n) using PriorityQueue +*/ +class Solution { + public int maxProduct(int[] nums) { + PriorityQueuepq=new PriorityQueue<>(); + for(int num:nums){ + pq.offer(num); + if(pq.size()>2)pq.poll(); + } + return (pq.poll()-1)*(pq.poll()-1); + } +} diff --git a/mergesort.cpp b/mergesort.cpp new file mode 100644 index 0000000..ab42bd6 --- /dev/null +++ b/mergesort.cpp @@ -0,0 +1,97 @@ +#include +//#include + +// Merges two subarrays of arr[]. +// First subarray is arr[l..m] +// Second subarray is arr[m+1..r] +void merge(int arr[], int l, int m, int r) +{ + int i, j, k; + int n1 = m - l + 1; + int n2 = r - m; + + // Create temp arrays + int L[n1], R[n2]; + + // Copy data to temp arrays L[] and R[] + for (i = 0; i < n1; i++) + L[i] = arr[l + i]; + for (j = 0; j < n2; j++) + R[j] = arr[m + 1 + j]; + + // Merge the temp arrays back into arr[l..r + i = 0; + j = 0; + k = l; + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + arr[k] = L[i]; + i++; + } + else { + arr[k] = R[j]; + j++; + } + k++; + } + + // Copy the remaining elements of L[], + // if there are any + while (i < n1) { + arr[k] = L[i]; + i++; + k++; + } + + // Copy the remaining elements of R[], + // if there are any + while (j < n2) { + arr[k] = R[j]; + j++; + k++; + } +} + +// l is for left index and r is right index of the +// sub-array of arr to be sorted +void mergeSort(int arr[], int l, int r)//mergeSort(arr, 0, arr_size - 1); +{ + if (l < r) {//arr[0]=2, l=0; r=arr_size-1=6-1=5 + int m = l + ( r - l) / 2;//m=0+(5-0)/2 + + // Sort first and second halves + mergeSort(arr, l, m); + mergeSort(arr, m + 1, r); + + merge(arr, l, m, r); + } +} + +// Function to print an array +void printArray(int A[], int size) +{ + int i; + for (i = 0; i < size; i++) + printf("%d ", A[i]); + printf("\n"); +} + +// Driver code +int main() +{ + int n,i, j; + printf("Enter no of elements in the array:"); + scanf("%d",&n); + int arr[n]; + printf("Enter array to be sorted:\n"); + for(i=0;i +#include +#include +using namespace std; + +// Function to check whether the string is palindrome +string isPalindrome(string S) +{ + // Stores the reverse of the string S + string P = S; + + // Reverse the string P + reverse(P.begin(), P.end()); + + if (S == P) { + return "Yes"; + } + + else { + return "No"; + } +} + +//Function to check if string is Palindrome without using extra space +string isPalind(string &s){ + int l=0, r = s.size()-1; + while(l>S; + cout << isPalindrome(S); + cout<=2){ + int csp = 1; + while(csp<=nsp){ + System.out.print(" "); + csp++; + } + } + + //star work + int cst = 1; + while (cst <=nst){ + System.out.print("x"); + cst++; + } + + System.out.println(); + nst--; + nsp+=2; + rows++; + + + } + } +} diff --git a/patterns/starPatterns/Pattern7.java b/patterns/starPatterns/Pattern7.java new file mode 100644 index 0000000..3a5fdf6 --- /dev/null +++ b/patterns/starPatterns/Pattern7.java @@ -0,0 +1,39 @@ +package basics.patterns.starPatterns; + +import java.util.Scanner; + +public class Pattern7 { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + + int nst =n; + //rows + + for(int row=1;row<=n;row++){ + //work done + if(row==1 || row==n){ + for(int cst =1; cst<=nst;cst++ ){ + System.out.print("x "); + } + } + else{ + for(int cst =1;cst<=n;cst++){ + if(cst==1 || cst==n){ + System.out.print("x "); + }else{ + System.out.print(" "); + } + + + } + + } + + + + System.out.println(); + + } + } +} diff --git a/patterns/starPatterns/Pattern8.java b/patterns/starPatterns/Pattern8.java new file mode 100644 index 0000000..8e84da2 --- /dev/null +++ b/patterns/starPatterns/Pattern8.java @@ -0,0 +1,14 @@ +package basics.patterns.starPatterns; + +import java.util.Scanner; + +public class Pattern8 { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + + + + + } +} diff --git a/patterns/starPatterns/Pattern9.java b/patterns/starPatterns/Pattern9.java new file mode 100644 index 0000000..305c6e6 --- /dev/null +++ b/patterns/starPatterns/Pattern9.java @@ -0,0 +1,46 @@ +package basics.patterns.starPatterns; + +import java.util.Scanner; + +/* + x + xxx + xxxxx + xxxxxxx +xxxxxxxxx + + */ + +public class Pattern9 { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + int nst = 1; + int nsp = n-1; + + //rows + int row=1; + while(row<=n){ + // space work + int csp= 1; + while(csp<=nsp){ + System.out.print(" "); + csp++; + } + + //star work + + int cst= 1; + while(cst<=nst){ + System.out.print("x"); + cst++; + } + + //preparation + System.out.println(); + nsp--; + nst+=2; + row++; + } + } +} diff --git a/postfix_eval/eval_postfix.c b/postfix_eval/eval_postfix.c new file mode 100644 index 0000000..e69de29 diff --git a/quickSort.cpp b/quickSort.cpp new file mode 100644 index 0000000..b2f56b5 --- /dev/null +++ b/quickSort.cpp @@ -0,0 +1,75 @@ +#include +using namespace std; + +int partion(int *arr, int s, int e) +{ + // Take pivot + int p = arr[s]; + int cnt = 0; + + // find right posn of pivot + for (int i = s + 1; i <= e; i++) + { + if (arr[i] <= p) + cnt++; + } + + // place pivot at right position + int pIndex = s + cnt; + swap(arr[pIndex], arr[s]); + + // Now, partion kro + int i = s; + int j = e; + + while (i < pIndex && j > pIndex) + { + while (arr[i] < p) // left part + { + i++; + } + + while (arr[j] > p) + { + j--; + } + + if (i < pIndex && j > pIndex) + { + swap(arr[i++], arr[j--]); + } + } + return pIndex; +} + +void quickSort(int *arr, int s, int e) +{ + // base case + if (s >= e) + return; + + // partition + int pivot = partion(arr, s, e); + + // left part sort + quickSort(arr, s, pivot - 1); + + // right part sort + quickSort(arr, pivot + 1, e); +} + +int main() +{ + int arr[] = {3, 1, 4, 5, 2}; + int n = sizeof(arr) / sizeof(int); + + quickSort(arr, 0, n - 1); + + cout << "Quick Sorting" << endl; + for (int i = 0; i < n; i++) + { + cout << arr[i] << " "; + } + + return 0; +} diff --git a/rotate.cpp b/rotate.cpp new file mode 100644 index 0000000..e0fe0b0 --- /dev/null +++ b/rotate.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +using namespace std; + +void rotate(vector& nums, int k) { + k = k % nums.size(); + reverse(nums.begin(), nums.end() - k); + reverse(nums.end() - k, nums.end()); + reverse(nums.begin(), nums.end()); +} + +int main() { + vector nums; + int n, k; + + cout << "Enter the number of elements in the array: "; + cin >> n; + + cout << "Enter " << n << " elements: "; + for (int i = 0; i < n; ++i) { + int num; + cin >> num; + nums.push_back(num); + } + + cout << "Enter the number of positions to rotate to the right: "; + cin >> k; + + cout << "Original Array: "; + for (const auto& num : nums) { + cout << num << " "; + } + cout << endl; + + rotate(nums, k); + + cout << "Array after rotating by " << k << " positions to the right: "; + for (const auto& num : nums) { + cout << num << " "; + } + cout << endl; + + return 0; +}