2016-07-22 2 views
0

몇 달 동안 외부 텍스트 파일에서 배열을 읽었으며 월을 월과 같은 값을 보유하는 배열로 변환해야합니다. 1 월 = 1, 2 월 = 2 등. 그러면 Quicksort를 통과 할 수 있습니다.개월을 숫자로 변환합니다. Quicksort에서 사용하는 것과 같습니다.

public static void Main(string[] args) 
    { 
     //Read external files into arrays. 
     string[] Month = File.ReadLines(@"Month.txt").ToArray(); 
     string[] Year = File.ReadLines(@"Year.txt").ToArray(); 

     //Convert arrays from string to double to be used in sort. 
     double[] YearSort = Array.ConvertAll(Year, double.Parse); 

     int UserInput1; 

     //Create new array that will hold selected array to be used in sort. 
     double[] data = new double[1022]; 
     //Prompt user to select action. 
    Console.WriteLine("Press 1 to Sort by month or 2 to sort by year."); 
    UserInput1 = Convert.ToInt32(Console.ReadLine()); 

    if(UserInput1 == 1) 
    { 
     Array.Copy(Month,data,1022); 
     QuickSort(data); 
     for (int i = 0; i < 1022; i++) 
    Console.WriteLine(data[i]); 
    Console.WriteLine(); 
    } 
    else if (UserInput1 == 2) 
    { 
     Array.Copy(YearSort,data,1022); 
     QuickSort(data); 
     for (int i = 0; i < 1022; i++) 
    Console.WriteLine(data[i]); 
    Console.WriteLine(); 
    } 
    else 
    { 
     Console.WriteLine("Please try again and select a valid option"); 
    } 
    } 

static int MonthToDouble(string Month) 
     { 
      int NewMonth = 0; 

      switch(Month) 
      { 
       case "January": 
       case "january": 
        NewMonth = 1; 
        break; 
       case "February": 
       case "february": 
        NewMonth = 2; 
        break; 
       case "March": 
       case "march": 
        NewMonth = 3; 
        break; 
       case "April": 
       case "april": 
        NewMonth = 4; 
        break; 
       case "May": 
       case "may": 
        NewMonth = 5; 
        break; 
       case "June": 
       case "june": 
        NewMonth = 6; 
        break; 
       case "July": 
       case "july": 
        NewMonth = 7; 
        break; 
       case "August": 
       case "august": 
        NewMonth = 8; 
        break; 
       case "September": 
       case "september": 
        NewMonth = 9; 
        break; 
       case "October": 
       case "october": 
        NewMonth = 10; 
        break; 
       case "November": 
       case "november": 
        NewMonth = 11; 
        break; 
       case "December": 
       case "december": 
        NewMonth = 12; 
        break; 
      } 

      return NewMonth; 
     } 

     static string DoubleToMonth(double Month) 
     { 
      string NewMonth = ""; 

      switch ((int)Month) 
      { 
       case 1: 
        NewMonth = "January"; 
        break; 
       case 2: 
        NewMonth = "February"; 
        break; 
       case 3: 
        NewMonth = "March"; 
        break; 
       case 4: 
        NewMonth = "April"; 
        break; 
       case 5: 
        NewMonth = "May"; 
        break; 
       case 6: 
        NewMonth = "June"; 
        break; 
       case 7: 
        NewMonth = "July"; 
        break; 
       case 8: 
        NewMonth = "August"; 
        break; 
       case 9: 
        NewMonth = "September"; 
        break; 
       case 10: 
        NewMonth = "October"; 
        break; 
       case 11: 
        NewMonth = "November"; 
        break; 
       case 12: 
        NewMonth = "December"; 
        break; 
      } 

      return NewMonth; 
     } 

//QuickSort for double data values are in ascending order. 
public static void QuickSort(double[] data) 
{ 
Quick_Sort(data, 0, data.Length - 1); 
} 
public static void Quick_Sort(double[] data, int left, int right) 
{ 
int i, j; 
double pivot, temp; 
i = left; 
j = right; 
pivot = data[(left + right)/2]; 
do 
{ 
while ((data[i] < pivot) && (i < right)) i++; 
while ((pivot < data[j]) && (j > left)) j--; 
if (i <= j) 
{ 
temp = data[i]; 
data[i] = data[j]; 
data[j] = temp; 
i++; 
j--; 
} 
} while (i <= j); 
if (left < j) Quick_Sort(data, left, j); 
if (i < right) Quick_Sort(data, i, right); 
}   
} 

답변

1

DateTime 개체의 Month 속성은 여러분에게 필요한처럼 1에서 시작하는 달의 정수 값을 제공합니다. 당신은 전체 DateTime 객체로 문자열을 구문 분석 DateTime.ParseExact()을 사용할 수 있도록 다음 Month 특성 잡아 :

int monthNumber = DateTime.ParseExact("January", "MMMM", CultureInfo.CurrentCulture).Month; 

당신은 당신의 달 문자열 "January"를 교체해야 할, 그리고 "전체 이름에 대한 Custom Format String"MMMM"를 남겨 달의 ". 위의 모든 코드가하는

는 심지어 어떤 이유로 (또한이 double 아닌 int를 반환해야합니다) 사용하지 않는 당신의 MonthToDouble() 방법을 단순화합니다. 당신의 타이틀과는 달리, 당신은 이미 "월을 동등한 숫자로 변환"하는 방법을 가지고 있습니다. 단지 그것을 사용하지 않고있는 것입니다. 이와

Array.Copy(Month,data,1022); 
    QuickSort(data); 

: 그래서

, 당신이 누락 된 유일한 것은이 대체하는 것입니다 가정

 double[] monthsAsDoubles = new double[Month.Length]; 
     for (int i = 0; i < monthsAsDoubles.Length; i++) 
     { 
      monthsAsDoubles[i] = MonthToDouble(Month[i]); 
     } 
     QuickSort(monthsAsDoubles); 

는 또한 doubleint에서 MonthToDouble()의 반환 값을 변경 (있는 경우 캐스팅 당신은)해야합니다.

+0

가 어떻게 내 달 문자열 1 월을 대체 할

1 3 9 
? 그들은 배열에 있고 많은 사람들이 수동으로 작성하는 방법이 있습니다. – ConfusedProgrammer

+0

@ConfusedProgrammer 내 편집을 참조하십시오. 왜 당신은'MonthToDouble()'메서드를 만들고 그것을 사용하지 않았습니까? – Quantic

0

편집 : 두 번째 생각에서 Quantic의 대답은 더 간단합니다. 나는 이것을 대안으로 남겨 두겠다.


코드는 대소 문자를 구분 문자열 비교와 함께 DateTimeFormatInfo.MonthNames 속성을 사용하여 많은 단순화 할 수있다. 또한 월 이름에 다른 언어를 사용하기가 훨씬 쉽습니다. 여기

은 조각이다 :

using System; 
using System.Globalization; 
using System.Linq; 
using System.Collections.Generic; 

public class Test 
{ 
    public static void Main() 
    { 

     var InputMonths = new List<string> { "January","march","sepTEmber","smarch" }; 

     var MonthNames = new DateTimeFormatInfo().MonthNames.ToList(); 

     var InputMonthNumbers = new List<int>(); 

     foreach (var m in InputMonths) 
     { 
      //Find index of the month name, ignoring case 
      //Note if the input month name is invalid, FindIndex will return 0 
      int month_num = 1 + MonthNames.FindIndex(name => name.Equals(m, StringComparison.OrdinalIgnoreCase)); 

      if (month_num > 0) 
      { 
       InputMonthNumbers.Add(month_num); 
      } 
     } 

     foreach (var n in InputMonthNumbers) 
     { 
      Console.WriteLine(n.ToString()); 
     } 

    } 
} 

출력 :

+0

코드가 작동하는 것을 볼 수는 있지만 출력을 Quicksort를 통해 입력 할 수있는 double 또는 int 배열로 작성해야합니다. – ConfusedProgrammer