比如 {3,5,4,4,4,3,6,6,5} 结果是:{2,3,4,6,7}
- using System;
- using System.Text;
- using System.Collections.Generic;
- namespace CSharpProject
- {
- class Program
- {
- static void Main(string[] args)
- {
- List<int> list = new List<int>() { 0, 0, 3, 5, 4, 4, 4, 3, 6, 6, 5, 8, 8 };
- StringBuilder sb = new StringBuilder();
- GetCloseEqualityEvenNumIndexFromList(list, ref sb);
- Console.WriteLine(sb.ToString());
- Console.ReadKey();
- }
- // 计算 List<int > 中相等且连续的偶数的索引 比如 {3,5,4,4,4,3,6,6,5} 结果是:{2,3,4,6,7}
- static void GetCloseEqualityEvenNumIndexFromList(List<int> list, ref StringBuilder sb)
- {
- if (null == sb)
- sb = new StringBuilder();
- if (null != list)
- {
- int i = 0, iMax = 0, index = 0, counter = 0;
- int currVal = 0, nextVal = 0;
- sb.Append("{");
- for (i = 0, iMax = list.Count; i <iMax; i += (counter + 1))
- {
- currVal = list[i];
- counter = 0;
- for (index = i + 1; index < iMax; ++index)
- {
- nextVal = list[index];
- if (currVal == nextVal && currVal % 2 == 0 && nextVal % 2 == 0)
- {
- ++counter;
- if (index - i <= 1)
- sb.Append(i.ToString() + ",");
- sb.Append((i + counter).ToString() + ",");
- }
- else
- {
- break;
- }
- }
- }
- sb.Remove(sb.Length - 1, 1);
- sb.Append("}");
- }
- }
- }
- }
结果:
来源: http://www.bubuko.com/infodetail-3164014.html