如何在数组中随机删除和添加单元?例如,如果有长度为10的6个单位和4个零的数组1011100101,如何获得长度为10的3个单位和7个零的数组?或者,如果有长度为10的数组100100000,有2个单位和8个零,如何获得长度为10的5个单位和5个零的数组?我尝试了这样的东西:
int units = array.getUnits();
if (units > P)
{
while (units != P)
{
int p = rnd.Next(units), pos = 0;
for (int i = 0; i < array.Length; i++)
{
if (array[i] == 1)
pos++;
if (pos == p)
{
array[p]=0;
break;
}
}
units--;
}
}
else if (units < P)
{
while (units != P)
{
int p = rnd.Next(array.Length-units),
pos = 0;
for (int i = 0; i < array.Length; i++)
{
if (array[i] == 0)
pos++;
if (pos == p)
{
array[p]=1;
break;
}
}
units++;
}
}它只添加一个单元(而不是2个或更多)或删除一个单元。
发布于 2016-04-11 22:23:14
就像评论中提到的Jdweng。对于这类事情,使用列表更容易。您不能自由地将项插入数组中。在列表中,您可以这样做。
int[] source = {0, 1, 0, 1, 1};
List<int> tempList = new List<int>(source);
int totalChanges = 20;
Random random = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < totalChanges; i++)
{
int index = tempList.Count == 0 ? 0 : random.Next(0, tempList.Count); //return either 0 if empty or a random position
tempList.Insert(index, random.Next(0,1));
}
int[] result = tempList.ToArray();上面的例子将源int数组转换为一个列表,然后它将在列表中的任意位置添加20个项目,并将结果转换回一个数组。如果您从一个空数组开始,它将通过在索引0处插入1或0开始。
发布于 2016-04-12 00:07:18
https://stackoverflow.com/questions/36548404
复制相似问题