删除指定数组中的元素使用Random类 [英] Deleting A Specified Element In An Array Using Random Class
本文介绍了删除指定数组中的元素使用Random类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Check
{
public static void Main()
{
int[] arr1 = new int[] { 1, 2, 3 };
Console.WriteLine("The Number That Left Us Is");
Random rnd = new Random();
int r = rnd.Next(arr1.Length);
int Left = (arr1[r]);
Console.WriteLine(Left);
}
}
如果2生成我想要2被删除而剩下的我必须留下应该是1和3
谁能帮助。可它在阵列来完成。
If 2 is generated i want the 2 to be removed and the remaining i have to be left with should be 1 and 3. Can anyone help. Can it be done in array.
推荐答案
数组不能调整大小,一个你设置他们,他们是大小永远。
Arrays can not be re-sized, one you set them they are that size forever.
最佳的选择是使用列表< INT>将
代替 INT []
The "best" option is use a List<int>
instead of an int[]
class Check
{
public static void Main()
{
List<int> arr1 = List<int>int[] { 1, 2, 3 };
Console.WriteLine("The Number That Left Us Is");
Random rnd = new Random();
int r = rnd.Next(arr1.Length);
int Left = (arr1[r]);
arr1.RemoveAt(r);
Console.WriteLine(Left);
}
}
要真正建立一个规模更小的新数组需要更多的代码。
To actually create a new array of one size smaller will take more code.
class Check
{
public static void Main()
{
int[] arr1 = int[] { 1, 2, 3 };
Console.WriteLine("The Number That Left Us Is");
Random rnd = new Random();
int r = rnd.Next(arr1.Length);
int Left = (arr1[r]);
int oldLength = arr1.Length;
arrTmp = arr1;
arr1 = new int[oldLength - 1];
Array.Copy(arrTmp, arr1, r);
Array.Copy(arrTmp, r+1, arr1, r, oldLength - r - 1);
Console.WriteLine(Left);
}
}
你提到你必须坚持使用数组,这是很容易打开列表中的数组
You mention "You gotta stick with the arrays", it is VERY easy to turn the list in to an array
class Check
{
public static void Main()
{
List<int> arr1 = List<int>int[] { 1, 2, 3 };
Console.WriteLine("The Number That Left Us Is");
Random rnd = new Random();
int r = rnd.Next(arr1.Length);
int Left = (arr1[r]);
arr1.RemoveAt(r);
Console.WriteLine(Left);
SomeFunctionThatTakesAnArrayAsAnArgument(arr1.ToArray());
}
}
这篇关于删除指定数组中的元素使用Random类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文