日期:2014-05-18  浏览次数:20846 次

如何从一个数组里 随机取6个数据出来
如何从一个数组里 随机取6个数据出来

------解决方案--------------------
不知道你要的是不是这个意思 
private object[] GetRandomOfIndex(object[] p_DataList, int p_Count)
{
object[] _ReturnList = new object[p_Count];
System.Random _RandonIndex = new Random(System.DateTime.Now.Millisecond);
IList<int> _AddIndex = new List<int>();
while (true)
{
if (_AddIndex.Count == p_Count) return _ReturnList;
int _Index = _RandonIndex.Next(0, p_DataList.Length);
if (_AddIndex.IndexOf(_Index) == -1)
{
_ReturnList[_AddIndex.Count] = p_DataList[_Index];
_AddIndex.Add(_Index);
}
}
}


测试

string[] _Temp =new string[100];
for(int i=0;i!=_Temp.Length;i++)
{
_Temp[i]=i.ToString();
}

object[] _Value= GetRandomOfIndex(_Temp, 10);

string _MessageText = "";
for (int i = 0; i != _Value.Length; i++)
{
_MessageText += _Value[i].ToString()+",";
}
MessageBox.Show(_MessageText);


------解决方案--------------------
int[]GetRandomArray(int[]array)
{
Random ran=new Random();
int[] result=new int[6];
int length=array.Length;
for(int i=0;i<6;i++)
{
int pos=ran.Next(i,length);
int temp=array[i];
array[i]=array[pos];
result[i]=array[pos];
array[pos]=temp;
}
return result;
}
------解决方案--------------------
int[] a=new int[100];
int[] b = new int[6];
Random r = new Random();

b[0] = r.Next(100);
b[1] = r.Next(100);
b[2] = r.Next(100);
b[3] = r.Next(100);
b[4] = r.Next(100);
b[5] = r.Next(100);
Start: for (int i = 0; i < 5; i++)
{
for (int j = i + 1; j < 6; j++)
{
if (b[i] == b[j])
b[j] = r.Next(100);
goto Start;
}

}
for (int k = 0; k < 6; k++)
{
Console.WriteLine(b[k]);

}

------解决方案--------------------
想了个笨方法!!

public int[] GetRandNum(int[] array)
{
Random rand = new Random();
int [] result=new int[6];//选出的数组
bool[] arrayState = new bool[array.Length];//标示是否可选
for (int i = 0; i < array.Length; i++)
{
arrayState[i] = true;
}
//产生随机数
for (int i = 0; i < 6; i++)
{
while (true)
{
int j = rand.Next(array.Length);//产生随机下标

if (arrayState[j])
{
result[i] = array[j];
arrayState[j] = false;
break;
}

}
return result;
}