Fisher-Yates 알고리즘은 배열 요소의 무작위 순열을 생성합니다. 즉, 배열의 모든 요소를 무작위로 섞습니다. Fisher-Yates 알고리즘이 편향되지 않기 때문에 어레이의 모든 순열은 동일할 가능성이 있습니다.
C++에서 배열 셔플링을 위한 Fisher-Yates 알고리즘을 구현하는 프로그램은 다음과 같습니다. -
예시
#include <iostream>
#include <t;stdlib.h>
using namespace std;
int main() {
int n;
cout << "Enter the array size: "<<endl;
cin >> n;
int arr[n], arr1[n], index_arr[n];
int index;
cout << "Enter the array elements: "<<endl;
for (int i = 0; i < n; i++)
cin >> arr[i];
for (int i = 0; i < n; i++)
index_arr[i] = 0;
for (int i = 0; i < n; i++) {
do {
index = rand() % n;
}
while (index_arr[index] != 0);
index_arr[index] = 1;
arr1[i] = arr[index];
}
cout<<"The shuffled array is: ";
for (int i = 0; i < n; i++)
cout << arr1[i] << " ";
return 0;
} 출력
위 프로그램의 출력은 다음과 같습니다.
Enter the array size: 10 Enter the array elements: 1 2 3 4 5 6 7 8 9 10 The shuffled array is: 4 7 8 6 3 10 2 1 9 5
위의 프로그램에서는 배열의 크기와 배열의 크기를 사용자에게 요청합니다. 이것은 다음과 같습니다 -
cout << "Enter the array size: "<<endl; cin >> n; int arr[n], arr1[n], index_arr[n]; int index; cout << "Enter the array elements: "<<endl; for (int i = 0; i < n; i++) cin >> arr[i];
배열을 얻은 후 index_arr[]은 0으로 초기화됩니다. 그런 다음 rand() 함수를 사용하여 arr[]의 값을 arr1[]에 무작위로 저장합니다. 이것은 다음 코드 스니펫에 의해 설명됩니다 -
for (int i = 0; i < n; i++) {
do {
index = rand() % n;
}
while (index_arr[index] != 0);
index_arr[index] = 1;
arr1[i] = arr[index];
} 마지막으로 섞인 배열이 표시됩니다. 이것은 아래에서 볼 수 있습니다 -
cout<<"The shuffled array is: "; for (int i = 0; i < n; i++) cout << arr1[i] << " ";