Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting index from unqiue (stand-alone) elements in C#

Tags:

c#

I'd like to get the index of elements that stand alone. It is possible that the elements themselves appear more often in the list (one after the other or mixed). The indication for a single element is that the predecessor and successor are not equal to the current element. Is there an elegant way to do this?

Example:

1.  A
2.  A
3.  A
4.  B
5.  B
6.  A
7.  B
8.  B
9.  C
10. B

Result:

6,9,10
like image 278
br0ken.pipe Avatar asked Dec 23 '22 21:12

br0ken.pipe


2 Answers

simple iterate over the items and check for that condition

char[] items = { 'A', 'A', 'A', 'B', 'B', 'A', 'B', 'B', 'C', 'B' };
for (int i = 0; i < items.Length; i++)
{
    if (i == 0)
    {
        // in case of the first element you only have to validate against the next
        if (items[i] != items[i + 1])
            Console.WriteLine(i + 1);
    }
    else if (i == items.Length - 1)
    {
        // in case of the last element you only have to validate against the previous       
        if (items[i] != items[i - 1])
            Console.WriteLine(i + 1);
    }
    else
    {
        // validate against previous and next element
        if (items[i] != items[i - 1] && items[i] != items[i + 1])
            Console.WriteLine(i + 1);
    }
}

https://dotnetfiddle.net/kWmqu7

like image 85
fubo Avatar answered Jan 12 '23 20:01

fubo


Here is one solution I came up with:

So you have your example list like that:

var list = new List<string>
{
    "A", // 1
    "A", // 2
    "A", // 3
    "B", // 4
    "B", // 5
    "A", // 6
    "B", // 7
    "B", // 8
    "C", // 9
    "B"  // 10
};

and then you call a method called GetSingleListPositions and receive List<int> representing your desired positions.

private static List<int> GetSingleListPositions(IList<string> list)
{
    var uniquePositions = new List<int>();
    var occurence = new List<string>();

    for (int i = list.Count - 1; i >= 0; i--)
    {
        if (!occurence.Contains(list[i]))
        {
            occurence.Add(list[i]);
            uniquePositions.Add(++i);
        }
    }

    uniquePositions.Reverse();
    return uniquePositions;
}

You call it like this:

var result = GetSingleListPositions(list);
Console.WriteLine(string.Join(' ', result));

As a result, I receive this:

6 9 10

Hope this helps, Cheers

like image 38
G.Dimov Avatar answered Jan 12 '23 19:01

G.Dimov