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

โปรแกรม C++ หาสับเซต (Subsets) ที่แตกต่างกันทั้งหมดของเซตที่กำหนด

ที่นี่เราจะดูวิธีแสดงสับเซตที่แตกต่างกันทั้งหมดของเซตที่กำหนด ถ้าเซตคือ {1, 2, 3} สับเซตจะเป็น {}, {1}, {2}, {3}, {1, 2}, {2, 3}, {1, 3}, {1, 2, 3} เซตของสับเซตทั้งหมดเรียกว่า Power Set Power Set มี 2n สมาชิก

เราจะวนลูปจาก 0 ถึง 2n (ไม่รวม) ในแต่ละรอบ เราจะตรวจสอบว่า บิตที่ i ในตัวนับปัจจุบันถูกตั้งค่าหรือไม่ ถ้าตั้งค่า ให้พิมพ์สมาชิกที่ i

ตัวอย่าง

#include <iostream> 
#include <cmath> 
using namespace std; 

void showPowerSet(char *set, int set_length) { 
    unsigned int size = pow(2, set_length); 
    for(int counter = 0; counter < size; counter++) { 
        cout << "{"; 
        for(int j = 0; j < size; j++) { 
            if(counter & (1 << j)) 
                cout << set[j] << " "; 
        } 
        cout << "}" << endl; 
    } 
} 

int main() { 
    char set[] = {'a','b','c'}; 
    showPowerSet(set, 3); 
}

ผลลัพธ์

{} {a } {b } {a b } {c } {a c } {b c } {a b c }