C#生成指定规则4位随机数:循环300次并升序输出需求问询
Hey there! Since you're new to C# coming from VB.NET, let's break down how to adjust your code to meet those requirements step by step.
Generate 300 Unique Valid 4-Digit Numbers & Output in Ascending Order (C#)
First, let's recap our goals clearly:
- Generate 300 unique 4-digit numbers
- Each number can only use digits 1, 2, 3, 4, 5
- Each number must fall between 1123 and 5543 (inclusive)
- Finally, output all numbers in ascending order (we'll make this super simple, no need to worry about complex sorting!)
Your existing code generates one valid number, but we need to scale this up while avoiding duplicates and filtering by the required range. Here's a complete, commented solution tailored for someone new to C#:
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // Define the allowed digits as a string for easy random selection string allowedDigits = "12345"; // Use a HashSet to store valid numbers - it automatically blocks duplicates! HashSet<int> validNumbers = new HashSet<int>(); Random randomGenerator = new Random(); // Keep generating numbers until we have 300 unique valid ones while (validNumbers.Count < 300) { // Generate a 4-digit string using only allowed digits (similar to your original code) char[] numberChars = new char[4]; for (int i = 0; i < 4; i++) { numberChars[i] = allowedDigits[randomGenerator.Next(allowedDigits.Length)]; } string numberString = new string(numberChars); // Convert the string to an integer to check our range requirement if (int.TryParse(numberString, out int number)) { // Check if the number is within our target range if (number >= 1123 && number <= 5543) { // HashSet.Add() returns false if the number already exists, so no duplicates sneak in! validNumbers.Add(number); } } } // Sort the numbers in ascending order (LINQ makes this trivial) var sortedNumbers = validNumbers.OrderBy(num => num).ToList(); // Print all sorted results Console.WriteLine("300 valid numbers in ascending order:"); foreach (int num in sortedNumbers) { Console.WriteLine(num); } } }
Key Details for Your Understanding:
- HashSet
: This collection is ideal here because it rejects duplicate values automatically. You don't have to write extra code to check if a number was already generated — the Add()method handles it for you. - Range Validation: After converting the generated string to an integer, we double-check it falls within 1123 to 5543 before adding it to our set.
- Sorting: Using LINQ's
OrderBy(num => num)is the simplest way to get ascending order in C#. If you really want to skip sorting (though it's very easy!), you can just loop through the HashSet directly — just note that HashSets don't preserve order, so the output will be random. - Loop Until We Hit 300: The
whileloop runs until our set has exactly 300 unique, valid numbers.
Hope this helps you get up and running with C# smoothly!
内容的提问来源于stack exchange,提问作者USERNNNNN
相关产品推荐
相关产品推荐

