【問】
配列の要素の並びをシャッフルする(要素の並びがランダムになるようにかき混ぜる)プログラムを作成せよ。
【shuffle.cppのソースコード】
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
const int n = 10;
int a[n];
srand(time(NULL));
for (int i = 0; i < n; i++)
a[i] = i + 1;
// シャッフル前
cout << "【シャッフル前】\n";
for (int i = 0; i < n; i++) {
if (i != 0)
cout << ' ';
cout << a[i];
}
// シャッフル
int i = n - 1, j, tmp;
while (i > 0) {
j = rand() % (i + 1);
tmp = a[j];
a[j] = a[i];
a[i] = tmp;
i--;
}
// シャッフル後
cout << "\n【シャッフル後】\n";
for (int i = 0; i < n; i++) {
if (i != 0)
cout << ' ';
cout << a[i];
}
}
C:\Users\skonishi\Documents>shuffle
【シャッフル前】
1 2 3 4 5 6 7 8 9 10
【シャッフル後】
6 3 1 10 4 9 5 7 8 2
C:\Users\skonishi\Documents>shuffle
【シャッフル前】
1 2 3 4 5 6 7 8 9 10
【シャッフル後】
10 3 5 6 1 9 4 8 7 2
C:\Users\skonishi\Documents>shuffle
【シャッフル前】
1 2 3 4 5 6 7 8 9 10
【シャッフル後】
4 3 8 2 6 7 10 1 9 5