Search code examples
c#indexingdata-structureskeysortedlist

How to get range key of specific value in sortedList


I want to get range keys from sortedlist or other similar sorted data structure.

for example ;

                SortedList<long, string> testSorted = new SortedList<long, string>();
                testSorted.Add(1, "a");
                testSorted.Add(4, "b");
                testSorted.Add(15, "c");

                testSorted.Add(12, "d");
                testSorted.Add(10, "e");
                testSorted.Add(8, "f");

                int wantspecifickey = 7;

                int index = testSorted.GetClosestIndex(wantspecifickey);
                int range = 1;
                List<long> rangeIndex = testSorted.GetRangeIndexKey(index , range);

The key value closest to 7 is 8.

So the index value is 2.

After that, at index 2 (key: 8), the keys of the index within index range 1 are 4 8 and 10.

Do you guys any good idea to solve my problem?

PS. I don't have to use sortedlist. If there is a more efficient data structure, please let me know too.


Solution

  • Here is my two cents;

    public class Program
    {
        public static Tuple<int, int, int> FindClosestRange(int[] keys, int key)
        {
            if (keys == null)
                throw new ArgumentNullException(nameof(keys));
            if (keys.Length == 0)
                throw new ArgumentException();
            
            Array.Sort(keys);
            var minDiff = int.MaxValue;
            var minIndex = 0;
            for(var index = 0; index < keys.Length;index++)
            {
                var diff = Math.Abs(keys[index] - key);
                if (diff < minDiff)
                {
                    minDiff = diff;
                    minIndex = index;
                }
            }
            var lowerBoundry = Math.Max(minIndex - 1, 0);
            var higherBoundry = Math.Min(minIndex + 1, keys.Length - 1);
            
            return Tuple.Create(keys[lowerBoundry], keys[minIndex], keys[higherBoundry]);
        }
        
        public static void Main()
        {
            var list = new Dictionary<int, string>()
            {
                { 1, "a" },
                { 4, "b" },
                {10, "e"},
                { 15, "c" },
                {8, "f"},
                { 12, "d"},
            };
    
            var range = FindClosestRange(list.Keys.ToArray(), 7);
            Console.WriteLine($"Closest {range}");
        }
    }
    

    It doesn't use sorted list but uses dictionary.