1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

重複しない数値をランダムで生成する メモ

Posted at

プログラム

test.c
# include <stdio.h>
# include <stdlib.h>
# define MAXDATA 10000

void shuffle(int array[], int size)
{
        int i = size;
        while (i > 1) {
         int j = rand() % i;
         i--;
         int t = array[i];
         array[i] = array[j];
         array[j] = t;
        }
}

int main()
{
        int values[MAXDATA];
        int m;
        int i;
        for (m = 0; m < MAXDATA; m++){
         values[m] = m + 1;
        }

        int size = sizeof(values) / sizeof(int);
        shuffle(values, size);
    
        FILE *fp;
        fp = fopen("test.txt", "a");
        if (fp == NULL){
         perror("ファイルの読み込みに失敗");
         return 1;
        }

        for (i = 0; i < size; i++){
         fprintf(fp, "%d\n", values[i]);
        }

        fclose(fp);

        return 0;
}

説明

  • shuffle関数・・・重複しないように配列要素をシャッフル
  • main関数・・・shuffle関数で扱ったデータをただのテキストファイルに出力しているだけ

その他

  • もっといろいろ改良していく
  • 重複しない数値の生成は難しいと勝手に思っていたが、こんな簡単な方法があったとは(Fisher-Yatesというアルゴリズムらしいです)

参考

C言語で重複しない乱数生成の仕方を教えてください!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?