+ 1

List of unique points

I want to create a list of unique, randomly generated points (x, y), but I get duplicate points in the output and I can't figure out why. Here's my code: class Program { static void Main() { List<int[]> UniquePoints = new List<int[]>(); int MaxPoints = 20; generateUniquePoints(UniquePoints, MaxPoints); displayPoints(UniquePoints); } static void generateUniquePoints(List<int[]> lstUniquePoints, int MaxPoints) { Random rnd = new Random(); while (lstUniquePoints.Count < MaxPoints) { int x = rnd.Next(1, 6); int y = rnd.Next(1, 6); int[] Point = { x, y }; while (lstUniquePoints.Contains(Point)) { x = rnd.Next(1, 6); y = rnd.Next(1, 6); Point[0] = x; Point[1] = y; } lstUniquePoints.Add(Point); } } static void displayPoints(List<int[]> lstUniquePoints) { for (int i = 0; i < lstUniquePoints.Count; i++) { Console.WriteLine(lstUniquePoints[i][0] + " " + lstUniquePoints[i][1]); } } }

10th Apr 2023, 7:23 AM
H2727
H2727 - avatar
2 ответов
+ 4
You represent a point with an int array. You cannot use the Contains method to check if an array already exists in your list, because it uses an object's Equals method to compare things. And two arrays are only equal when they point to the same memory reference. You have two choices here. Either you write your own Point class that encapsulates the two numbers and implements the Equals method, so that two points become comparable. Or you compare the new point with each element of the existing List, where you check the equality of the corresponding coordinates, something like newpoint[0]==oldpoint[0] && newpoint[1]==oldpoint[1] Or you can also use the SequenceEqual method of yout int[] https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.contains?source=recommendations&view=net-7.0 https://interviewsansar.com/how-to-compare-two-arrays-in-c-if-they-are-equal-or-not/
10th Apr 2023, 7:47 AM
Tibor Santa
Tibor Santa - avatar