2014-02-26 4 views
-6

다음과 같은 프로그램을 디버깅하고 마무리하는 데 도움이 필요합니다. 각 행에서 동일한 수의 정수 값을 가진 파일을 읽습니다 (이것은 n x n 행렬입니다). 프로그램은 행렬이 마술 사각형인지 결정해야합니다. 마술 사각형의 예 : "ms.txt" 8,1,6; 3,5,7;매직 스퀘어 프로그램 도움말 C#

내 코드 4,9,2은 (진행중인 작업)을, 당신의 도움이

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 

namespace MagicSquare 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     int[,]S; 
     string line; //to hold one line of file 
     string[] token; //to hold each token in line 
     char[] separator = { ',' }; 
     int N; 

     //open file 
     try 
     { 
      using (StreamReader sr = new StreamReader("..\\..\\ms.txt")) 
      { 
       line = sr.ReadLine(); 
       token = line.Split(separator); 
       N = token.Count(); 
       S = new int[N, N]; 
       for (int i = 0; i < N; i++) 
        S[0, i] = Convert.ToInt32(token[i]); 
       for (int r = 1; r < N; r++) 
       { 
        line = sr.ReadLine(); 
        token = line.Split(separator); 
        for (int c = 0; c < N; c++) 
         S[r, c] = Convert.ToInt32(token[c]); 
       } 
       sr.Close(); 
      } 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("The file could not be read:"); 
      Console.WriteLine(e.Message); 
     } 

     //find Magic Number 
     int magic = 0; 
     for (int i = 0; i < N; i++) 
      magic += S[i, i]; 
     int sum = 0; 
     for (int i=0;i<N;i++) 
      sum += S[i,N -1-i]; 
     if (magic!=sum) 
     { 
      Console.Write("Not Magic"); 
      return; 
     } 
     //check each column 
     for (int c=0;c<N;c++) 
     { 
      int sum1 =0; 
      for (int r=0;r<N;r++) 
       sum1 += S[r,c]; 
      if (sum1!=magic) 
      { 
       Console.WriteLine("Not magic"); 
       return; 
      } 
     } 
    } 
} 
} 

을 감상 할 수있다
+0

왜이 프로그램이 원하는대로 할 수 없습니까? (그리고 "마술 광장"은 무엇입니까?) 질문을 더 명확히하면, 우리가 당신을 도울 것이 더 쉬울 것입니다. –

+1

제목을 편집했습니다. "[제목에"태그 "가 포함되어 있어야합니까?] (http://meta.stackexchange.com/questions/19190/)"합의가 "아니오, 그렇지 않아야합니다"로 표시되어야합니다. –

+0

마술 광장은 하나의 행 또는 하나의 열 (두 개의 대각선 포함)을 추가 할 때 똑같은 대답이나 번호를 부여하는 매트릭스 n × n (행과 열의 수가 동일) 예 : [8 , 1,6] [3,5,7] [4,9,2] –

답변

0

솔루션을 편집합니다. 이것은 행과 열에 적용됩니다.

static void Main(string[] args) 
      { 
       int[,] S = null; 
       int N = 0; 
       string line; //to hold one line of file 
       string[] token; //to hold each token in line 
       char[] separator = { ',' }; 


       //open file 
       try 
       { 
        using (StreamReader sr = new StreamReader(@"C:\Users\sb9923\Desktop\ms.txt")) 
        { 
         line = sr.ReadLine(); 
         token = line.Split(separator); 
         N = token.Count(); 
         S = new int[N, N]; 
         for (int i = 0; i < N; i++) 
          S[0, i] = Convert.ToInt32(token[i]); 
         for (int r = 1; r < N; r++) 
         { 
          line = sr.ReadLine(); 
          token = line.Split(separator); 
          for (int c = 0; c < N; c++) 
           S[r, c] = Convert.ToInt32(token[c]); 
         } 
         sr.Close(); 
        } 
       } 
       catch (Exception e) 
       { 
        Console.WriteLine("The file could not be read:"); 
        Console.WriteLine(e.Message); 
       } 

       int magicValue = GetSum(N * N)/N; 

       //Check for magic 
       bool isMagic = true; 
       for (int counterY = 0; counterY < S.GetLength(1); counterY++) 
       { 
        int rowValue = 0; 
        int columnValue = 0; 
        for (int counterX = 0; counterX < S.GetLength(0); counterX++) 
        { 
         rowValue += Convert.ToInt32(S[counterY, counterX]); 
         columnValue += Convert.ToInt32(S[counterX, counterY]); 
        } 

        if (rowValue != magicValue) 
        { 
         isMagic = false; 
         break; 
        } 

        if (columnValue != magicValue) 
        { 
         isMagic = false; 
         break; 
        } 

        rowValue = 0; 
        columnValue = 0; 
       } 

       if (isMagic) 
       { 
        Console.WriteLine("Yeah it is magic! :)"); 
       } 
       else 
       { 
        Console.WriteLine("No magic in the air!"); 
       } 
      } 


private static int GetSum(int maxValue) 
     { 
      if (maxValue < 1) 
      { 
       return 0; 
      } 

      return maxValue + GetSum(maxValue - 1); 
    } 

당신이 질문을 물어 갈이있는 경우)

0

(단위 테스트, 테스트 목적) "사각형 마법의 경우 확인하는 방법?"에 대한 그냥 하나의 간단한 변화 :

using Microsoft.VisualStudio.TestTools.UnitTesting; 
using System; 
using System.Linq; 
using System.IO; 

namespace MSquareTest 
{ 
    [TestClass] 
    public class MSquareTest 
    { 
     /// <summary> 
     /// Checks if array of int's 
     /// is an magick square 
     /// </summary> 
     /// <param name="matrix">Input array</param> 
     /// <returns>True/False</returns> 
     public bool IsMagicSquare(int[] matrix) 
     { 
      if (matrix.Length % 3 != 0) 
       throw new ArgumentException("Invalid 2D cube!"); 

      // 2x2(6 cells) is minimum 
      if (matrix.Length < 6) 
       throw new ArgumentException("Use at least 2x2 cube!"); 

      // Cube face length 
      int length = matrix.Length/3; 

      // calculate first row sum 
      int excepted = 0; 
      for (int y = 0; y < length; y++) 
       excepted += matrix[y]; 

      // calculate and check second and another rows 
      for (int x = 1; x < length; x++) 
      { 
       int actual = 0; 

       for (int y = 0; y < length; y++) 
        actual += matrix[(length * x) + y]; 

       if (actual != excepted) 
        return false; 
      } 

      // calculate and check columns 
      for (int x = 0; x < length; x++) 
      { 
       int actual = 0; 

       for (int y = 0; y < length; y++) 
        actual += matrix[(length * y) + x]; 

       if (actual != excepted) 
        return false; 
      } 

      return true; 
     } 

     [TestMethod] 
     public void TestMS() 
     { 
      var GoodInput = "8,1,6;3,5,7;4,9,2"; // = File.ReadAllText("..\\..\\ms.txt"); 
      var GoodArray = (from x in GoodInput.Split(',', ';') select int.Parse(x)).ToArray(); 

      var BadInput = "6,4,1;3,0,3;1,5,9"; 
      var BadArray = (from x in BadInput.Split(',', ';') select int.Parse(x)).ToArray(); 

      // Good array is magick square, and bad array is not 
      var Result = IsMagicSquare(GoodArray) && !IsMagicSquare(BadArray); 
      Assert.IsTrue(Result); 
     } 
    } 
}