นี่คือโปรแกรม C++ ที่นำอัลกอริทึม Alexander Bogomolny สำหรับ Permutation แบบไม่เรียงลำดับ (UnOrdered Permutation) ขององค์ประกอบ 1 ถึง N มาใช้งาน
อัลกอริทึม
เริ่มต้น ฟังก์ชัน AlexanderBogomolny() เพื่อนำอัลกอริทึมมาใช้งาน อาร์กิวเมนต์: Val[] = อาร์เรย์ N = จำนวนองค์ประกอบที่รับเป็นอินพุต K = ระดับ (Level) ส่วนตัวของฟังก์ชัน: เริ่มต้น l = -1 l = l+1 Val[k] = l ถ้า (l == N) เรียกฟังก์ชัน display(Val, N) มิฉะนั้น สำหรับ i = 0 ถึง N-1 ถ้า (Val[i] == 0) เรียก AlexanderBogomolny(Val, N, i) l = l - 1 Val[k] = 0 จบ
ตัวอย่างโค้ด
#include<iostream> #include<iomanip> using namespace std; void display(const int *n, const int size) //แสดง Permutation { int i; if (n != 0) { for ( i = 0; i < size; i++) { cout<<setw(4)<<n[i]; } cout<<"\n"; } } void AlexanderBogomolny(int *Val, int N, int k) { static int l = -1; int i; //เริ่มต้น กำหนด Level เป็น 0 l = l+1; Val[k] = l; if (l == N) display(Val, N); else for (i = 0; i < N; i++) //กำหนดค่าให้อาร์เรย์ถ้าเป็นศูนย์ if (Val[i] == 0) AlexanderBogomolny(Val, N, i); //ลด Level หลังจาก Permutation ทั้งหมดในระดับนั้นแล้ว l = l-1; Val[k] = 0; } int main() { int i, N, cnt = 1; cout<<"Enter the value to permute first N natural numbers: "; cin>>N; int Val[N]; for (i = 0; i < N; i++) { Val[i] = 0; cnt *= (i+1); } cout<<"\nThe number of permutations possible is: "<<cnt; cout<<"\n\nPermutation using Alexander Bogomolyn's Algorithms \n"; AlexanderBogomolny(Val, N, 0); return 0; }
ผลลัพธ์
Enter the value to permute first N natural numbers: 5 The number of permutations possible is: 120 Permutation using Alexander Bogomolyn's Algorithms 1 2 3 4 5 1 2 3 5 4 1 2 4 3 5 1 2 5 3 4 1 2 4 5 3 1 2 5 4 3 1 3 2 4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