Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group list values by KeyValuePair

Tags:

c#

algorithm

list

Say i have a list

[1,2,2,1,3,3,3,2,3,3,1,3,3,2,3]

enter image description here

Any ideas how to group them (List<KeyValuePair<int, int>>) so that the key is the next smallest digit, and Value is next biggest digit, and if it repeats itself, group it with the same smallest key, if that makes sense...

This is the output that I am looking for:

[Key, Value]
[0,1]
[0,2]
[3,4]
[3,5]
[3,6]
[7,8]
[7,9]
[10,11]
[10,12]
[13,14]
like image 753
wtz Avatar asked Aug 02 '26 13:08

wtz


2 Answers

Based on the image and the example input:

       var list = new List<int> { 1, 2, 2, 1, 3, 3, 3, 2, 3, 3, 1, 3, 3, 2, 3}; //example input

        var results = new List<KeyValuePair<int, int>>();
        int key = 0;
        for (int i = 0; i < list.Count; i++)
        {
            if(i==0 || list[i] < list[i - 1])                
                key = i++; //assign key and proceed to next index (NB no index out of range checking)                
            results.Add(new KeyValuePair<int, int>(key, i));
        }

This uses a direct comparison with the previous element and uses the indices as key and values as in the example output. If the key value is always smaller than the previous element as in your description, you could replace the if with: if(i==0 || list[i] < list[i - 1])

edit, made the Tuple a KeyValuePair

like image 57
Me.Name Avatar answered Aug 05 '26 14:08

Me.Name


    private static void foo()
    {
        SortedList<int, List<int>> collection = new SortedList<int, List<int>>();
        Random rnd = new Random();

        // Filling the collection with random keys/values:
        for (int i = 0; i < 100; i++)
        {
            int key = rnd.Next(0, 10);
            if (!collection.ContainsKey(key))
                collection.Add(key, new List<int>());
            for (int j = 0; j < 10; j++)
            {
                int value = rnd.Next(0, 1000);
                collection[key].Add(value);
            }
        }

        // Displaying all pairs:
        foreach (var key in collection.Keys)
        {
            collection[key].Sort();
            for (int j = 0; j < collection[key].Count; j++)
                Console.WriteLine(string.Format("[{0},{1}]", key, collection[key][j]));
        }
    }
like image 25
Nissim Avatar answered Aug 05 '26 15:08

Nissim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!