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

โปรแกรม C++ นำวิธี Binary Counting มาใช้สร้างเซตย่อยของเซต


นี่คือโปรแกรม C++ ที่นำวิธี Binary Counting มาใช้สร้างเซตย่อย (Subsets) ของเซตหนึ่ง

อัลกอริทึม

เริ่มต้น    รับองค์ประกอบของอาร์เรย์เป็นอินพุต    ฟังก์ชัน BinaryCounting():       คำนวณจำนวนเซตย่อยโดย r = pow(2, n) // n = จำนวนองค์ประกอบ       สร้างตัวเลขไบนารีจาก 0 ถึง r-1       เรียก solution() สำหรับแต่ละสตริงไบนารีที่มีความยาว n ตัวอักษร จบ

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

#include<iostream> #include<math.h> using namespace std; void solution(char code[], int a[], int n) //พิมพ์คำตอบ {    int i;    cout<<"\t { ";       for(i = 0; i < n; i++) {          if(code[i] == '1')             cout<<a[i]<<" ";       }    cout<<"}\n"; } int BinaryCounting(int a[], int n) {    int r, i, l;    char bin[] = "00000";    r = pow(2, n);    //สร้างตัวเลขไบนารีจาก 0 ถึง r-1    for(i = 0; i < r; i++) {       solution(bin, a, n);       l=n-1;       h:       if(bin[l] == '0')          bin[l] = '1';       else {          bin[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 subset in the binary counting method: \n";    BinaryCounting(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 subset in the binary counting method: { } { 1 } { 2 } { 2 1 } { 3 } { 3 1 } { 3 2 } { 3 2 1 } { 4 } { 4 1 } { 4 2 } { 4 2 1 } { 4 3 } { 4 3 1 } { 4 3 2 } { 4 3 2 1 }