Keyword: 整数ベクトル, 疑似ランダム置換
概要
本サンプルは整数ベクトルの疑似ランダム置換を行うC言語によるサンプルプログラムです。 本サンプルは1から8までの8個の昇順の整数を含むベクトルを10回置換しその結果を出力します。
※本サンプルはnAG Cライブラリに含まれる関数 nag_rand_permute() のExampleコードです。本サンプル及び関数の詳細情報は nag_rand_permute のマニュアルページをご参照ください。
ご相談やお問い合わせはこちらまで
出力結果
(本関数の詳細はnag_rand_permute のマニュアルページを参照)| この出力例をダウンロード |
nag_rand_permute (g05ncc) Example Program Results 10 Permutations of first 8 integers 6 2 4 8 1 3 5 7 8 6 4 2 7 3 1 5 4 2 8 7 5 6 3 1 1 6 4 5 2 3 7 8 1 7 3 8 4 2 5 6 6 3 4 7 1 2 8 5 6 4 1 8 2 5 3 7 3 2 1 7 5 8 6 4 4 2 1 5 3 6 8 7 1 5 6 4 2 7 8 3
- 3行目に8個の整数について10回の置換が行われたことが示されています。
- 4〜13行目に整数ベクトルの置換が出力されています。
ソースコード
(本関数の詳細はnag_rand_permute のマニュアルページを参照)
※本サンプルソースコードはnAG数値計算ライブラリ(Windows, Linux, MAC等に対応)の関数を呼び出します。
サンプルのコンパイル及び実行方法
| このソースコードをダウンロード |
/* nag_rand_permute (g05ncc) Example Program.
*
* CLL6I261D/CLL6I261DL Version.
*
* Copyright 2017 Numerical Algorithms Group.
*
* Mark 26.1, 2017.
*/
/* Pre-processor includes */
#include <stdio.h>
#include <math.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagg05.h>
int main(void)
{
/* Integer scalar and array declarations */
Integer exit_status = 0;
Integer i, j, lstate;
Integer *index = 0, *state = 0;
/* nAG structures */
NagError fail;
/* Number of permutations */
Integer m = 10;
/* Sample size */
Integer n = 8;
/* Choose the base generator */
Nag_BaseRNG genid = Nag_Basic;
Integer subid = 0;
/* Set the seed */
Integer seed[] = { 1762543 };
Integer lseed = 1;
/* Initialize the error structure */
INIT_FAIL(fail);
printf("nag_rand_permute (g05ncc) Example Program Results\n\n");
/* Get the length of the state array */
lstate = -1;
nag_rand_init_repeatable(genid, subid, seed, lseed, state, &lstate, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_rand_init_repeatable (g05kfc).\n%s\n",
fail.message);
exit_status = 1;
goto END;
}
/* Allocate arrays */
if (!(index = nAG_ALLOC(n, Integer)) ||
!(state = nAG_ALLOC(lstate, Integer)))
{
printf("Allocation failure\n");
exit_status = -1;
goto END;
}
/* Initialize the generator to a repeatable sequence */
nag_rand_init_repeatable(genid, subid, seed, lseed, state, &lstate, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_rand_init_repeatable (g05kfc).\n%s\n",
fail.message);
exit_status = 1;
goto END;
}
printf(" %2ld Permutations of first %1ld integers\n",
m, n);
/* Permutate M times */
for (j = 0; j < m; j++) {
/* Set up the index vector */
for (i = 0; i < n; i++)
index[i] = i + 1;
/* Call the permutation routine */
nag_rand_permute(index, n, state, &fail);
if (fail.code != NE_NOERROR) {
printf("Error from nag_rand_permute (g05ncc).\n%s\n", fail.message);
exit_status = 1;
goto END;
}
/* Display the results */
printf(" ");
for (i = 0; i < n; i++)
printf("%2ld%s", index[i], (i + 1) % 8 ? " " : "\n");
if (n % 8)
printf("\n");
}
END:
nAG_FREE(index);
nAG_FREE(state);
return exit_status;
}
