平均概率

2 views
Skip to first unread message

小刀客

unread,
Nov 9, 2009, 10:46:58 PM11/9/09
to programming with GNU software
有一个函数int getNum(),每运行一次可以从一个数组V[N]里面取出一个数,N未知,当数取完的时候,函数返回NULL。现在要求写一个函
数int get(),这个函数运行一次可以从V[N]里随机取出一个数,而这个数必须是符合1/N平均分布的,也就是说V[N]里面任意一个数都有
1/N的机会被取出,要求空间复杂度为O(1)

int get()
{
int count = 0;
int value=getNum();
int result = NULL;
while(value != NULL){
result = rand()%++count?result:value;
value = getNum();
}
return result;
}

Reply all
Reply to author
Forward
0 new messages