2017-03-23 1 views
1

작성해야하는 프로그램에 어려움을 겪고 있습니다. 요구 사항은 사용자가 배열 크기로 입력하는 것입니다. 그런 다음 프로그램은 입력 된 값을 표시 한 다음 각 값이 몇 번 발생하는지 배열의 요소를 입력합니다. 모든 것이 제대로 발생하는 부분을 표시하지 않는 한 모든 것이 작동하는 것처럼 보입니다. (배열 크기가 5 임) 또한 이것이하지 못하기 때문에 발생하였습니다 1 2 배, 4는 1 회이다배열 시간 계산 값이

1 occurs 1 time. 
1 occurs 1 time. 
2 occurs 1 time. 
3 occurs 1 time. 
4 occurs 2 times. 

를 출력 입력 "1 1 2 3 4"라고하자.

static void Main(string[] args) 
    { 
     int[] arr = new int[30]; 
     int size, 
      count=0, 
      count1=0, 
      count2=0; 

     Console.Write("Enter Size of the Array: "); 
     size = Convert.ToInt32(Console.ReadLine()); 

     Console.Write("Enter the elements of an Array: "); 
     for (int i=0; i < size; i++) 
     { 
      arr[i] = Convert.ToInt32(Console.ReadLine()); 
     } 

     Console.Write("Values Entered: \n"); 
     for (int i = 0; i < size; i++) 
     { 
      Console.WriteLine(arr[i]); 
      if (arr[i] <= 10) 
       count++; 
      else 
       count1++; 
     } 

     for(int i = 0; i < size; i++) 
     { 
      for (int j = 0; j < size; j++) 
      { 
       if (arr[i] == arr[j]) 
        count2++; 
       else 
        count2 = 1; 
      } 

      Console.WriteLine(arr[i] + " Occurs " + count2 + " Times."); 
     } 
     Console.WriteLine("The number of valid entries are: " + count + "\nThe number of invalid entries are: " + count1); 
     Console.ReadKey(); 
    } 
+0

이됩니다 Linq를 사용하도록 허용 했습니까? – hatchet

+4

그냥 생각했는데 크기를 말하면 배열을 초기화하는 것이 더 좋지 않겠습니까? 'int [] arr = new arr [size]' – vipersassassin

+0

Linq를 사용할 수 없다면, 사용할 수있는 다른 제약 조건은 무엇입니까? – hatchet

답변

1

당신이 Linq에 사용할 수있는 경우, 이것은 쉬운 일입니다 ... 제발 도와주세요 :

Console.Write("Values Entered: \n"); 

추가

var grouped = arr.GroupBy(x => x); 
foreach (var group in grouped) 
{ 
    Console.WriteLine("number {0} occurs {1} times", group.Key, group.Count()); 
} 

편집

OP에서 Linq를 사용할 수 없으므로 여기에 배열 전용 솔루션이 있습니다. 사전 접근법보다 훨씬 많은 코드가 있지만 배열 만 사용합니다.

static void Main(string[] args) 
    { 
     var dic = new Dictionary<int, int>(); 

     Console.Write("Enter Size of the Array: "); 
     int size = Convert.ToInt32(Console.ReadLine()); 

     Console.Write("Enter the elements of an Array: "); 
     for (int i = 0; i < size; i++) 
     { 
      int val = Convert.ToInt32(Console.ReadLine()); 

      int current; 
      if (dic.TryGetValue(i, out current)) 
      { 
       dic[val] = current + 1; 
      } 
      else 
      { 
       dic.Add(val, 1); 
      } 
     } 

     foreach (int key in dic.Keys) 
     { 
      Console.WriteLine(key + " Occurs " + dic[key] + " Times."); 
     } 

     Console.Read(); 
    } 
+0

나는 이것에 google 수색을 가진 몇몇 재료를 보았다. 그래서 나는 Linq를 사용할 수 없다. 이것은 매우 적은 haha ​​ –

+0

그냥 말하기 위해 실망하고있다 ... 나는 Linq없이 대답을 쓸거야 ... – Nino

+0

왜 downvotes? OP가 해결책을 물었을 때, 나는 (Linq이 "허용"되었다) 작업 중 하나를 제공했다 .... 그래서 나는 왜이 대답이 downvoted인지 이해할 수 없다. – Nino

0

당신은 단순히 사전을 사용할 수 있습니다.

대신해야한다 (이것은 기본적으로 각 항목에 대해 한 번 리셋 있도록) 외부 루프에 0count2를 설정 한 다음 내부 루프 해당 번호의 모든 인스턴스 알아서 무엇 :

// For each item 'i' in the array, count how many other items 'j' are the same 
for (int i = 0; i < size; i++) 
{ 
    count2 = 0; // processing a new item, so reset count2 to 0 

    for (int j = 0; j < size; j++) 
    { 
     if (arr[i] == arr[j]) count2++; 
    } 

    Console.WriteLine(arr[i] + " occurs " + count2 + " times."); 
} 
0

문제는 당신이 불일치를 찾을 count2 언제든지 1에 재설정하고 있다는 것입니다 :

Console.Write("Values Entered: \n"); 
//an array to hold numbers that are already processed/counted. Inital length is as same as original array's 
int[] doneNumbers = new int[arr.Length]; 
//counter for processed numbers 
int doneCount = 0; 
//first loop 
foreach (var element in arr) 
{ 
    //flag to skip already processed number 
    bool skip = false; 
    //check if current number is already in "done" array 
    foreach (int i in doneNumbers) 
    { 
     //it is! 
     if (i == element) 
     { 
      //set skip flag 
      skip = true; 
      break; 
     } 
    } 

    //this number is already processed, exit loop to go to next one 
    if (skip) 
     continue; 

    //it hasn't been processed yes, so go through another loop to count occurrences 
    int occursCounter = 0; 
    foreach (var element2 in arr) 
    { 
     if (element2 == element) 
      occursCounter++; 
    } 

    //number is processed, add it to "done" list and increase "done" counter 
    doneNumbers[doneCount] = element; 
    doneCount++; 

    Console.WriteLine("number {0} occurs {1} times", element, occursCounter); 
} 
+0

그건 의미가 있습니다. 고맙습니다! –

+0

지금 알아 내야 할 것은 배열 크기가 4이고 4 회에 4를 입력한다고 가정 해 보겠습니다. 그것을 인쇄하지 못하게하는 방법 4 번 4 번 연속으로 4 번 발생했습니다. –

+0

그것은 실제로 표시하지 않을 수 없다는 말을 반복하므로 내가 가진 것과 함께 굴러 가고 있습니다. –