如何计算数组中相同值之间的最大距离

时间:2017-11-25 12:41:50

标签: c# console-application

我想编写一个程序来计算每个数字与该数组相同数量之间的最长距离 这是我的代码

int max_dist = 0;
for (int j= 0; j < n; j++)
{
   for (int secondelement = 1; secondelement <= n;secondelement++)
   {
      int first = array[j];
      int second = array[secondelement];
      secondelement++;
      if (first == second)
      {
         max_dist = max_dist +1;
         System.Console.WriteLine(first+""+max_dist);
         first = second;
         break;                        
      }
      else
      {
         break;
      }
   }
}

但缺少某些东西,我不知道这是什么,因为我的程序打印错误的值...问题是什么,错误在哪里

for example if my array is 

2 3 5 7 3

out put is 

3  3 

2 7 5 7 3 4 5 6 7

    out put is 

7 4

1 3 5 7 1

  out put is 

    1  3  

它的平均数x最长距离是y再次出现     注意:可能会多次找到号码

2 个答案:

答案 0 :(得分:0)

你的第一个错误是你正在增加循环内的第二个元素。第二个错误是你增加max_dist而不是计算索引之间的差异。在第二个周期的每次迭代中首先计算也是没有意义的,你应该从第一个周期的当前索引的下一个开始内循环。从周期中脱离也毫无意义。

编辑:

让我们修复你的代码:

for (int j= 0; j < n; j++)
{
   int max_dist = 0;
   int first = array[j];
   for (int secondelement = j + 1; secondelement < n;secondelement++)
   {
      int second = array[secondelement];
      if (first == second)
      {
         if (max_dist < secondelement - j)
         {
            max_dist = secondelement - j;
         }
         first = second;
      }
   }
   System.Console.WriteLine(first+" "+max_dist);
}

编辑:

您还需要避免重复输出:

for (int j= 0; j < n; j++)
{
   int max_dist = 0;
   int first = array[j];
   int earlierIndex = -1;
   for (int k = 0; (earlierIndex < 0) && (k < j); k++) {
      if (first == array[k]) {
         earlierIndex = k;
      }
   }
   if (earlierIndex >= 0) continue;
   for (int secondelement = j + 1; secondelement < n;secondelement++)
   {
      int second = array[secondelement];
      if (first == second)
      {
         if (max_dist < secondelement - j)
         {
            max_dist = secondelement - j;
         }
         first = second;
      }
   }
   System.Console.WriteLine(first+" "+max_dist);
}

答案 1 :(得分:0)

如果您有超过1个数字来计算

var myArray = new[] { 1, 2, 3, 4, 5, 6, 4, 8, 9, 0, 4, 3, 8 }; // 4, 3 and 8
var numbers = myArray.GroupBy(x=>x).Where(x => x.Count() > 1).Select(x => x.Key).ToList();  // Selects 4, 3, 8
foreach (var n in numbers)
{
    var first = Array.IndexOf(myArray, n); //get first occurence of each number
    var last = Array.LastIndexOf(myArray, n); //get last occurence of each number
    var dist = last - first; //calculate distance
    Console.WriteLine($"Number: {n}, distance: {dist}"); //print distance
}