[ create a new paste ] login | about

Link: http://codepad.org/sTJSPHtB    [ raw code | output | fork ]

C, pasted on May 24:
#include <stdio.h>

int get_rand(void)
{
        int             t[] = {1,2,3,4,5,6,7,8};                // この配列の中から使う数字を選ぶ
        const int       t_len = 8;                              // 配列の長さ(全部で8個)

        int             cur_last_index = t_len - 1;             // 『現在の、配列の最後の位置』
                                                                // 配列tの範囲は、t[0~7]、なので、tの最後の位置は7。 これをループ毎に1づつ減らしてく。


        int             tmp=0;                                  // 計算時のメモに使う
        int             i=0;
        while (i++ < t_len) {                                   // 8回くりかえす
                int index = rand() % (cur_last_index + 1);      // 0~『現在の、配列の最後の位置』 の範囲内で、乱数を得る。
                                                                // ループ毎に 『現在の、配列の最後の位置』が1づつ短くなっていくので、
                                                                // 最初は0~7のどれか、2回目は0~6のどれか、3回目は0~5のどれか、の数字を得て使う。

                tmp = (tmp*10) + t[index];                      // tmp * 10 して、tmp内の数字の桁を一つずらして、tmpの1の位に 空きスペース を作る。
                                                                // 配列t の index 番目の数字を、tmp の1の位に書く。


                t[index] = t[cur_last_index];                   // いま使った 配列t の index 番目に格納されてる数字は、もう使えないので、
                                                                // この index 番目にある数字は、他の番目に格納されてる数字を持ってきて、その数字に変える。
                                                                // 具体的には、『現在の、配列の最後の位置』に格納されてる数字に変える。

                cur_last_index -= 1;                            // 『現在の、配列の最後の位置』を一つ減らす。
        }


        return (tmp);
}

void main()
{
        int a;
        srand(&a);


        int i=10;
        while (i-->0) {
                printf("%d\n", get_rand());
        }
}


Output:
1
2
3
4
5
6
7
8
9
10
68751342
13458762
14578326
51823674
41853726
76528143
42853167
68247513
76145328
43586712


Create a new paste based on this one


Comments: