2011-06-27 22 views
1

我有一个8×8矩阵。现在,下面的坐标占据寻找坐标计数所需的帮助

{ 6, 3 }, { 5, 5 }, { 3, 3 }....什么需要做的是,我需要建立直线

通过这些点,需要算他们有多少感动的坐标?

我的计划至今代表为

private static void GetCount(int[,] Positions) 
{ 

    int rcount = 8; 
    int firstRow = Positions[0, 0];    

    for (int i = 1; i < Positions.Length/2; i++) 
    {    
     int currentRow = Positions[i, 0]; 
     if (currentRow != firstRow) 
     { 
      rcount += 8; 
      firstRow = currentRow; 
     }  
    } 

    int cCount = 8; 
    int firstCol = Positions[0, 1]; 

    for (int i = 1; i < Positions.Length/2; i++) 
    { 


     int currentCol = Positions[i, 1]; 
     if (currentCol != firstCol) 
     { 
      cCount += 8; 
      firstCol = currentCol; 
     } 

     } 
    int totalCount = rcount - cCount; 
    Console.WriteLine(totalCount); 

} 

而且我调用它作为

GetCount(new int[,] { { 6, 3 }, { 5, 5 }, { 3, 3 } }); 

的输出将是40在这里。 (对于每3个唯一行,即6,5,3,计数将为24,对于2个唯一列,即3和5,计数将为16 ...因此,总计数为24 + 16 = 40) 但是,输出为48.

也有可能使用一个单一的循环porgram吗?

我使用C#1.0

编辑

这确实工作

List<int> lstRows = new List<int>(); 
      List<int> lstCols = new List<int>(); 
      int count = 0; 

      //Get the unique rows and columns 
      for (int i = 0; i < marinePositions.Length/2; i++) 
      { 
       if (!lstRows.Contains(marinePositions[i, 0])) lstRows.Add(Positions[i, 0]); 
       if (!lstCols.Contains(marinePositions[i, 1])) lstCols.Add(Positions[i, 1]); 
      } 
      //get row count 
      for (int i = 0; i < lstRows.Count; i++) count += 8; 
      //get column count 
      for (int i = 0; i < lstCols.Count; i++) count += 8; 

      Console.WriteLine(count); 

但需要一个更好的..如果可能的话使用LINQ /λ和无环

请帮忙

+0

是不是正确答案应该是38?因为当计算y坐标时,我们必须计数7而不是8,因为有一个计数重叠,同时为x坐标执行 – Ankur

+0

直线如何通过不在同一行发生的三个点? –

回答

0

这里ü去......但是这是LINQ,不C#1.0是太旧..不知道你为什么要使用这种旧的语言版本:

 private static void GetCount(int[,] Positions) 
     { 
      List<int> x = new List<int>(); 
      List<int> y = new List<int>(); 
      for (int i = 0; i < Positions.Length/2; i++) 
      { 
       x.Add(Positions[i, 0]); 
       y.Add(Positions[i, 1]); 
      } 
      int result = (x.Distinct().Count() * 8) + (y.Distinct().Count() * 8); 
      Console.WriteLine(result); 
     } 

没有循环法宝:

private static void GetCount(int[,] Positions) 
    { 
     var range = Enumerable.Range(0, Positions.Length/2); 
     var result = (range.Select(i => Positions[i, 0]).Distinct().Count() * 8) + 
        (range.Select(i => Positions[i, 1]).Distinct().Count() * 8); 
     Console.WriteLine(result); 

    } 
+0

但是,这并没有给出正确的输出。我的编辑失误高于 – aditi

+0

将我的代码更新为参数“您要求的正确答案” – Ankur

+0

请参阅我更新的“无循环魔术”代码,正如您在更新的问题中询问的那样 – Ankur

0

更正:

1-

int cCount = 8; 

到:

int cCount = 0; 

2-

int totalCount = rcount - cCount; 

到:

int totalCount = rcount + cCount; 

方案应现在工作很好。

+0

{5,5},{5,3}失败。输出将为24 – aditi

+0

你能写下整个数组吗? {5,5},{5,3} ... – ApprenticeHacker