class Check
{
public static void Main()
{
int[] arr1 = new int[] { 1, 2, 3 };
Console.WriteLine(\"The Number That Left Us
Arrays can't be dynamically resized in .NET, so you can't really 'remove' an item from an array (you could set it to 0, but I don't think that's what you want).
Try using a List<int>
instead:
List<int> list = new List<int>() { 1, 2, 3 };
Console.WriteLine("The Number That Left Us Is");
Random rnd = new Random();
int r = rnd.Next(list.Count);
int Left = (list[r]);
list.Remove(Left);
Console.WriteLine(Left);
Arrays can not be re-sized, one you set them they are that size forever.
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());
}
}
Arrays cannot be resized, if you want to remove items use a List<T>
.
However, you can create a new one. If you want to keep all items but one at the random index:
arr1 = arr1.Where((i, index) => index != r).ToArray();
With a list you can use RemoveAt which is more efficient than creating arrays:
var list = new List<int> { 1, 2, 3 };
list.RemoveAt(r);
Try to following it removes the item from the list and creates a new array without the specific item.
static void Main(string[] args)
{
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);
// Create a new array except the item in the specific location
arr1 = arr1.Except(new int[]{arr1[r]}).ToArray();
int Left = (arr1[r]);
Console.WriteLine(Left);
}