C#技术问询:如何将数组元素频率存入二维数组及代码异常排查
Fixing the Element Frequency to 2D Array Issue
Hey there! I see you're trying to convert a 1D array into a 2D array where each sub-array holds an element and its occurrence frequency, but you're getting weird concatenated numbers instead of the expected pairs. Let's break down what's going wrong and fix it step by step.
Your Problem Code (Completed for Context)
First, here's your code with the missing section filled in to understand the full picture:
Console.WriteLine("Enter number of elements: "); int n = int.Parse(Console.ReadLine()); int[] array = new int[n]; for (int i = 0; i < array.Length; i++) { Console.Write("Array[{0}]: ", i); array[i] = int.Parse(Console.ReadLine()); } // I'm guessing your original code tried to build the 2D array directly without deduplication int[,] secArray = new int[array.Length, 2]; for (int i = 0; i < array.Length; i++) { int count = 0; for (int j = 0; j < array.Length; j++) { if (array[i] == array[j]) count++; } secArray[i, 0] = array[i]; secArray[i, 1] = count; } // And printed it incorrectly, leading to outputs like "23 11 22 21 52" foreach (var item in secArray) { Console.Write(item + " "); }
What's Causing the Wrong Output?
- Duplicate Entries: You're adding every element from the original array to the 2D array, even duplicates. For input
{2,1,2,2,5}, this creates 5 rows instead of the 3 unique element rows you need. - Messy Printing: When you loop through the 2D array with a simple
foreach, you're printing each value sequentially without grouping them as [element, frequency] pairs—so 2 and 3 end up looking like "23".
The Fix: Use a Dictionary to Track Unique Frequencies
The cleanest way to count element frequencies is using a Dictionary<int, int> to track unique elements and their counts, then convert that to your 2D array. Here's the corrected code:
Console.WriteLine("Enter number of elements: "); int n = int.Parse(Console.ReadLine()); int[] array = new int[n]; // Populate the original array for (int i = 0; i < array.Length; i++) { Console.Write("Array[{0}]: ", i); array[i] = int.Parse(Console.ReadLine()); } // Step 1: Count frequencies with a Dictionary (avoids duplicates) Dictionary<int, int> frequencyTracker = new Dictionary<int, int>(); foreach (int num in array) { if (frequencyTracker.ContainsKey(num)) frequencyTracker[num]++; // Increment count if element exists else frequencyTracker[num] = 1; // Add new element with count 1 } // Step 2: Convert Dictionary to 2D array int[,] secArray = new int[frequencyTracker.Count, 2]; int rowIndex = 0; foreach (var entry in frequencyTracker) { secArray[rowIndex, 0] = entry.Key; // Store the element secArray[rowIndex, 1] = entry.Value; // Store its frequency rowIndex++; } // Step 3: Print the 2D array correctly Console.WriteLine("\nResulting 2D array (element, frequency):"); for (int i = 0; i < secArray.GetLength(0); i++) { Console.WriteLine($"[{secArray[i, 0]}, {secArray[i, 1]}]"); }
How It Works
- Frequency Counting: The dictionary ensures we only track each unique element once, incrementing its count every time we encounter it in the original array.
- 2D Array Conversion: We create a 2D array with exactly as many rows as there are unique elements, then map each dictionary key-value pair to a row.
- Clear Output: We loop through each row of the 2D array and print it as a paired set, so you get the clean, expected format.
Example Output for Input {2,1,2,2,5}
Resulting 2D array (element, frequency): [2, 3] [1, 1] [5, 1]
内容的提问来源于stack exchange,提问作者KamilaW
相关产品推荐
相关产品推荐

