Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ สร้างคู่เซตย่อยทั้งหมดที่ Union แล้วได้เซตต้นฉบับ


นี่คือโปรแกรม C++ สำหรับสร้างคู่เซตย่อย (Subset Pairs) ทั้งหมด ที่ Union ของทั้งสองจะได้เซตต้นฉบับ (Superset)

อัลกอริทึม

เริ่มต้น    ฟังก์ชัน UnionSet():    อาร์กิวเมนต์:       a[] = อาร์เรย์       n = จำนวนองค์ประกอบ       ส่วนตัวของฟังก์ชัน:       1) สร้างรหัสไบนารีจาก 0 ถึง 2^(n-1)-1 สำหรับคู่ทั้งหมด 2^(n-1) คู่       2) พิมพ์องค์ประกอบของอาร์เรย์ที่มี 0 หรือ 1 ในดัชนีที่ตรงกันในสตริงรหัสสำหรับแต่ละรหัส       3) พิมพ์ในเซตที่ต่างกัน ซึ่งเมื่อ Union ทั้งสองเซตจะได้ Superset จบ

ตัวอย่างโค้ด

#include<iostream> #include<math.h> #include<iomanip> using namespace std; void display(char code[], int a[], int n) //แสดงคู่ {    int i;    cout<<"\t{ ";       for(i = 0; i < n; i++) {          if(code[i] == '1')             cout<<a[i]<<" ";       }    cout<<"}";    cout<<" { ";       for(i = 0; i < n; i++) {          if(code[i] == '0')             cout<<a[i]<<" ";       }    cout<<"}\n"; } void UnionSet(int a[], int n) {    int i, r, l;    char binary[n];    r = pow(2, n-1);    for(i = 0; i < n; i++)       binary[i] = '0';    for(i = 0; i < r; i++) {       display(binary, a, n);       l=n-1;       h:       if(binary[l] == '0')          binary[l] = '1';       else {          binary[l] = '0';          l--;          goto h;       }    } } int main() {    int i, n;    cout<<"\nEnter the number of elements: ";    cin>>n;    int a[n];    cout<<"\n";    for(i = 0; i < n; i++) {       cout<<"Enter "<<i+1<<" element: ";       cin>>a[i];    }    cout<<"\nThe possible subset pairs which on union generates the superset, are: \n";    UnionSet(a, n);    return 0; }

ผลลัพธ์

Enter the number of elements: 4 Enter 1 element: 4 Enter 2 element: 3 Enter 3 element: 2 Enter 4 element: 1 The possible subset pairs which on union generates the superset, are: { } { 4 3 2 1 } { 1 } { 4 3 2 } { 2 } { 4 3 1 } { 2 1 } { 4 3 } { 3 } { 4 2 1 } { 3 1 } { 4 2 } { 3 2 } { 4 1 } { 3 2 1 } { 4 }