// main.c
#include
#include //使用srand(int n)和rand()随机函数
typedef unsigned char uchar;
typedef unsigned int uint;
typedef unsigned long ulong;
#define max_random 10
uchar random_buf[max_random];
int rand(void);
void srand(int n);
void initial_timer(void);
uchar random(uchar i);
uchar un_repeat_random(uchar n);
void upset_random_buf(uchar *ranbuf, uchar n);
/***************************************************/
void main(void)
{
uchar i;
initial_timer();
for(i=0;i<max_random;i++) random_buf[i] = i;
i = un_repeat_random(max_random);
i = un_repeat_random(max_random);
i = un_repeat_random(max_random);
i = un_repeat_random(max_random);
i = un_repeat_random(max_random);
i = un_repeat_random(max_random);
i = un_repeat_random(max_random);
i = un_repeat_random(max_random);
i = un_repeat_random(max_random);
i = un_repeat_random(max_random);
while(1);
}
/***************************************************/
/*
* 取得范围内不重复随机数函数
*/
uchar un_repeat_random(uchar n)
{
static uchar ran_count =0;
uchar i;
if(ran_count==n) ran_count = 0;
if(ran_count==0)
upset_random_buf(random_buf, n);
i = random_buf[ran_count++];
return i;
}
/*
* 打乱一个顺序数组,使其成为随机数组
*/
void upset_random_buf(uchar *ranbuf, uchar n)
{
uchar i, j, t;
for(i=n-1;i>0;i--)
{
j = random(i);
t = ranbuf[i];
ranbuf[i] = ranbuf[j];
ranbuf[j] = t;
}
}
/*
* 定时器计数做种子
*/
uchar random(uchar i)
{
uchar k;
int t;
srand((int)(TH0*256 + TL0));
t = rand();
k = (uchar)(t % i);
return k;
}
/***************************************************/
/*
* 初始化定时器
*/
void initial_timer(void)
{
TMOD = 0x01;
TH0 = 0;
TL0 = 0;
TR0 = 1;
}
// main.c ends here
Program Size: data=29.0 xdata=0 code=654
经过单步调试,确实能够实现题目的要求。自我感觉是,程序简单,时间复杂度也为O(n)。缺点是,这个算法的随机度不高,如果范围是100内,那么要用100B。 |