Count similar adjacent items in List<string>

北慕城南 提交于 2019-12-05 18:21:11

You can do something like this:

static IEnumerable<Tuple<string, int>> FindAdjacentItems(IEnumerable<string> list)
{
    string previous = null;
    int count = 0;
    foreach (string item in list)
    {
        if (previous == item)
        {
            count++;
        }
        else
        {
            if (count > 1)
            {
                yield return Tuple.Create(previous, count);
            }
            count = 1;
        }
        previous = item;
    }

    if (count > 1)
    {
        yield return Tuple.Create(previous, count);
    }
}
for (int i= 0; i < list.Count; i++)
   {
      for (int j = i + 1; j < list.Count; j++)
        {
           if (list[i] == list[j])
             {
                adjacent_found = true;
                count++;
             }
        }
   }

Check this:

Dictionary<char,int> dic=new Dictionary<char,int>();
for(int i=1;i<list.count;i++)
{
          if(list[i]==list[i-1])
                {
                      if(dic.ContainsKey(list[i]))
                                 {
                                   dic[list[i]]+=1;
                             }
                          else
                                 { 
                                    dic.Add(list[i],2)
                                  }
                  }
}

To avoid ArgumentOutOfRangeException use for (int j = 1; j < list.Count - 1; j++). Desired answer can't be achieved this way. Try this:

IEnumerable<Adjacent> CountAdjacents(List<string> source)
{
    var result = new List<Adjacent>();

    for (var i = 0; i < source.Count() - 1; i++)
    {
        if (source[i] == source[i + 1])
        {
            if (result.Any(x => x.Word == source[i]))
            {
                result.Single(x => x.Word == source[i]).Quantity++;
            }
            else
                result.Add(new Adjacent
                {
                    Word = source[i],
                    Quantity = 2
                });
        }
    }
    return result;
}

class Adjacent
{
    public string Word;
    public int Quantity;
}

Maintain an int array of 256 size, initialized to 1. Run a loop [O(n)] for i=0 to i-2, compare each char with the next char. If same then find the ascii value of the char and increment the corresponding value in array. Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!