Deleting A Specified Element In An Array Using Random Class

后端 未结 4 1043
余生分开走
余生分开走 2021-01-29 12:37
class Check
{
     public static void Main()
     {         
              int[] arr1 = new int[] { 1, 2, 3 };
              Console.WriteLine(\"The Number That Left Us          


        
4条回答
  •  南笙
    南笙 (楼主)
    2021-01-29 13:10

    Arrays can not be re-sized, one you set them they are that size forever.

    The "best" option is use a List instead of an int[]

    class Check
    {
         public static void Main()
         {         
                  List arr1 = Listint[] { 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 arr1 = Listint[] { 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());
          }
     }
    

提交回复
热议问题