Reputation:
If the nested int[]
contains coordinates x, y, how do I compare them using SequenceEqual?
The List are a group of coordinates. I want to check every other List to see if they have the same number of coordinates and also the same coordinate values. If they both match, I want to remove the redundant one. Otherwise, leave it.
private List<List<int[]>> combineList(List<List<int[]>> matches){
Debug.Log (matches.Count());
foreach(List<int[]> tileGroup in matches){
foreach(List<int[]> other in matches){
if(other == tileGroup) continue;
if(sequenceEqual(tileGroup, other)){
matches.Remove(other);
}
}
}
Debug.Log (matches.Count());
return matches;
}
private bool sequenceEqual(List<int[]> groupA, List<int[]> groupB){
if(groupA.Count() == groupB.Count()){
int i = 0, j = 0;
Dictionary<int, int[]> dictA = new Dictionary<int, int[]>(),
dictB = new Dictionary<int, int[]>();
foreach(int[] coordinate in groupA){
dictA.Add (i, coordinate);
i++;
}
foreach(int[] coordinate in groupB){
dictB.Add (j, coordinate);
j++;
}
return dictA.Values.SequenceEqual(dictB.Values);
}
return false;
}
Upvotes: 0
Views: 283
Reputation: 1614
Probably the quickest way would be to implement an IEqualityComparer<int[]>
:
class IntArrayEqualityComparer : IEqualityComparer<int[]>
{
public bool Equals(int[] x, int[] y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(null, x)) return false;
if (ReferenceEquals(null, y)) return false;
if (x.Length != y.Length) return false;
for (var i = 0; i < x.Length; i++)
{
if (x[i] != y[i]) return false;
}
return true;
}
public int GetHashCode(int[] x)
{
if (x == null) return 0;
var hashCode = 0;
for (var i = 0; i < x.Length; i++)
{
hashCode = (32 * hashCode) + x[i];
}
return hashCode;
}
}
And then use the overloaded version of IEnumerable<TSource>.SequenceEqual
:
private bool sequenceEqual(List<int[]> groupA, List<int[]> groupB)
{
if (ReferenceEquals(groupA, groupB)) return true;
if (ReferenceEquals(null, groupA)) return false;
if (ReferenceEquals(null, groupB)) return false;
return groupA.SequenceEqual(groupB, new IntArrayEqualityComparer());
}
In the long run it might be beneficial to create a Coordinates
type that simply implements IEquatable<Coordinates>
, in which case you would simply be comparing two List<Coordinates>
objects.
Upvotes: 1