यह C++ प्रोग्राम दिए गए नंबर्स या कैरेक्टर्स के सेट से रैंडम पार्टीशन (यादृच्छिक विभाजन) उत्पन्न करता है। प्रोग्राम दो मोड में काम करता है: इंटीजर ऐरे के लिए और कैरेक्टर स्ट्रिंग के लिए।
एल्गोरिदम
शुरुआत
1. इंटीजर या कैरेक्टर इनपुट लें।
2. विकल्प 1 (इंटीजर) के लिए:
- n इंटीजर ऐरे का इनपुट लें
- l = 0 असाइन करें ऐरे ट्रैवर्स करने के लिए
- rand() का उपयोग करके n का रैंडम इंटीजर पार्टीशन जनरेट करें
- प्रत्येक पार्टीशन i के लिए, इंडेक्स l से अगले i इंटीजर प्रिंट करें
3. विकल्प 2 (कैरेक्टर) के लिए:
- चरित्र स्ट्रिंग ch[] में इनपुट लें
- स्ट्रिंग की लंबाई कैलकुलेट करें और l = 0 असाइन करें
- स्ट्रिंग की लंबाई का रैंडम इंटीजर पार्टीशन जनरेट करें
- प्रत्येक पार्टीशन i के लिए, इंडेक्स l से अगले i कैरेक्टर प्रिंट करें
समाप्ति
उदाहरण कोड
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main() {
int n, i, j, l, choice;
cout << "Enter 1 for integer and 2 for character array: ";
cin >> choice;
// विकल्प 1: इंटीजर ऐरे
if (choice == 1) {
cout << "\nEnter the number of elements in the integer array: ";
cin >> n;
int a[n];
cout << "\nEnter the elements of the array:\n";
for (i = 0; i < n; i++) {
cout << "Enter " << i+1 << " element: ";
cin >> a[i];
}
cout << "\nThe random partition of the given array is:\n";
l = 0;
while (n > 0) {
cout << "\t[";
i = rand() % n + 1; // 1 से n के बीच रैंडम पार्टीशन साइज
n = n - i;
for (j = 0; j < i; j++) {
cout << a[l] << " ";
l++;
}
cout << "]";
}
}
// विकल्प 2: कैरेक्टर स्ट्रिंग
else {
char ch[100];
cout << "Enter the characters: ";
cin >> ch;
n = strlen(ch);
cout << "\nThe random partition of the given string is:\n";
l = 0;
while (n > 0) {
cout << "\t[ ";
i = rand() % n + 1;
n = n - i;
for (j = 0; j < i; j++) {
cout << ch[l] << " ";
l++;
}
cout << "]";
}
}
return 0;
}
आउटपुट (इंटीजर ऐरे)
Enter 1 for integer and 2 for character array: 1 Enter the number of elements in the integer array: 10 Enter the elements of the array: Enter 1 element: 10 Enter 2 element: 9 Enter 3 element: 8 Enter 4 element: 7 Enter 5 element: 6 Enter 6 element: 5 Enter 7 element: 4 Enter 8 element: 3 Enter 9 element: 2 Enter 10 element: 1 The random partition of the given array is: [10 9 ] [8 7 6 5 ] [4 3 2 ] [1 ]
आउटपुट (कैरेक्टर स्ट्रिंग)
Enter 1 for integer and 2 for character array: 2 Enter the characters: ABCDEFGHIJKLMNOPQRSTUVWXYZ The random partition of the given string is: [ A B C D E F G H I J K L M N O P ] [ Q R S T U V W X ] [ Y ] [ Z ]
नोट: प्रत्येक रन पर अलग-अलग पार्टीशन मिलेंगे क्योंकि rand() का उपयोग किया गया है। वास्तविक अनुप्रयोगों के लिए srand(time(0)) से सीड सेट करना चाहिए।