There is a two-dimensional array, it is filled in a loop randomly, as a result, when there is only one element not filled, the cycle ends and the coordinates of the element are output.
- Formulate the question more clearly. Not very clear what needs to be done. - IntegralAL
- In short, there is a two-dimensional array, suppose 10 to 10, 99 elements have a value, and one is NULL, or an empty string, you need to output the number of this element. - Niki-Timofe
- depending on how you are filling and looking for .... - Gorets
|
1 answer
works with arbitrary types, for numbers the empty element is 0, for strings - the empty string, for classes - null
public static int[] IndexOfEmptyElement<T>(this T[,] array) { for(int i=array.GetLength(0)-1; i>=0; i--) { for(int j=array.GetLength(1)-1; j>=0; j--) { if(EqualityComparer<T>.Default.Equals(array[i,j], default(T))) return new int[]{i, j}; } } return new int[]{}; } public static int CountOfEmptyElements<T>(this T[,] array) { var count = 0; for(int i=array.GetLength(0)-1; i>=0; i--) { for(int j=array.GetLength(1)-1; j>=0; j--) { if(EqualityComparer<T>.Default.Equals(array[i,j], default(T))) count++; } } return count; }
using:
var a = new int[3,3]{{1,2,3},{0,4,5},{6,7,8}}; if(a.CountOfEmptyElements() == 1) a.IndexOfEmptyElement().Dump(); // [1,0]
UPD: updated answer
- And so, to still define one empty, or not ?? - Niki-Timofe
- "System.Array" does not contain a definition for "CountOfEmptyElements" and the extension method "CountOfEmptyElements" was not found, taking the type "System.Array" as the first argument (possibly using a directive using or a link to the assembly) And the same for IndexOfEmptyElement - Niki-Timofe
- oneread about Extention Methods , learn that extension methods must be contained in a static classroom - Specter
|