随机抽取不重复的数据
为了实现从一堆文件中随机抽取一定比例,且不重复的文件出来,我尝试了好几种算法,这种比较简单,也能达成我的要求。废话少说,代码如下:
/// <summary>
/// 功能: 随机抽取一定比率,且不重复的文件名
/// 创建人: AppleGreen
/// 创建时间: 2005-11-28
/// </summary>
/// <param name="aryFileName">包含文件名的数组</param>
/// <param name="dblRate">抽取比例</param>
/// <returns>文件名字符串</returns>
public static string GetRandNum(ArrayList aryFileName,double dblRate)
{
int intFileTotal = aryFileName.Count;
double d = intFileTotal*dblRate;
int intCount = Int32.Parse(d.ToString());
if(intCount>intFileTotal) intCount = intFileTotal; //比率超过1,按100%算
Random rdm = new Random();
StringBuilder sb = new StringBuilder();
for(int i=0;i<intCount;i++)
{
string strValue = aryFileName[rdm.Next(1,intFileTotal-i)].ToString();
sb.Append(strValue+";");
aryFileName.Remove(strValue);
}
return sb.ToString();
}
/// 功能: 随机抽取一定比率,且不重复的文件名
/// 创建人: AppleGreen
/// 创建时间: 2005-11-28
/// </summary>
/// <param name="aryFileName">包含文件名的数组</param>
/// <param name="dblRate">抽取比例</param>
/// <returns>文件名字符串</returns>
public static string GetRandNum(ArrayList aryFileName,double dblRate)
{
int intFileTotal = aryFileName.Count;
double d = intFileTotal*dblRate;
int intCount = Int32.Parse(d.ToString());
if(intCount>intFileTotal) intCount = intFileTotal; //比率超过1,按100%算
Random rdm = new Random();
StringBuilder sb = new StringBuilder();
for(int i=0;i<intCount;i++)
{
string strValue = aryFileName[rdm.Next(1,intFileTotal-i)].ToString();
sb.Append(strValue+";");
aryFileName.Remove(strValue);
}
return sb.ToString();
}