Finding position of an element in a two-dimensional array?

前端 未结 2 626
终归单人心
终归单人心 2020-12-07 02:16

Well simple question here (maybe not a simple answer?)

Say I have a two dimensional array

[0] [1] [2]
[3] [4] [5]
[6] [7] [8]

Now s

2条回答
  •  星月不相逢
    2020-12-07 02:44

    Here is a method that should find an index in an array with an arbitrary rank.

    ... Added Upper/Lower bounds range per rank

    public static class Tools
    {
        public static int[] FindIndex(this Array haystack, object needle)
        {
            if (haystack.Rank == 1)
                return new[] { Array.IndexOf(haystack, needle) };
    
            var found = haystack.OfType()
                              .Select((v, i) => new { v, i })
                              .FirstOrDefault(s => s.v.Equals(needle));
            if (found == null)
                throw new Exception("needle not found in set");
    
            var indexes = new int[haystack.Rank];
            var last = found.i;
            var lastLength = Enumerable.Range(0, haystack.Rank)
                                       .Aggregate(1, 
                                           (a, v) => a * haystack.GetLength(v));
            for (var rank =0; rank < haystack.Rank; rank++)
            {
                lastLength = lastLength / haystack.GetLength(rank);
                var value = last / lastLength;
                last -= value * lastLength;
    
                var index = value + haystack.GetLowerBound(rank);
                if (index > haystack.GetUpperBound(rank))
                    throw new IndexOutOfRangeException();
                indexes[rank] = index;
            }
    
            return indexes;
        }
    }
    
        

    提交回复
    热议问题