You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中生成13位唯一随机数并修改指定代码实现该功能

Generating 13-Digit Unique Random Numbers in C#

Hey there! Let's tackle your two questions about 13-digit unique random numbers in C# one by one.

1. How to Generate a 13-Digit Unique Random Number

First, let's clarify: a valid 13-digit number ranges from 1000000000000 (the smallest 13-digit value) up to 9999999999999 (the largest). To ensure it's unique, you need two core components:

  • A reliable way to generate a random number within that specific range
  • A system to track already generated numbers (since the built-in Random class doesn't guarantee uniqueness, especially if you create multiple instances quickly)

A solid baseline approach would be:

  • Reuse a single Random instance (to avoid duplicate sequences from overlapping system clock seeds)
  • Use a HashSet<string> to store generated numbers—this lets you quickly check if a number has already been used
  • Ensure your number starts with a non-zero digit so it stays exactly 13 digits long

2. Modified Code for 13-Digit Unique Random Numbers

Looking at your original code, it generates a 6-digit number and retries if all digits are identical (like 000000). Let's adapt it to handle 13 digits, add proper uniqueness checks, and fix the range to ensure valid 13-digit values:

We'll add a static HashSet to track generated numbers across calls, reuse a single Random instance, and adjust the number range. Here's the updated code:

// Static storage to track generated numbers (ensures uniqueness across calls)
private static readonly HashSet<string> _usedNumbers = new HashSet<string>();
// Reuse one Random instance to avoid duplicate sequences from quick repeated calls
private static readonly Random _randomGenerator = new Random();

public static string GenerateUniqueRandomNumbers()
{
    // Generate a number between 1000000000000 and 9999999999999 (inclusive)
    long randomNum = _randomGenerator.NextInt64(1000000000000, 10000000000000);
    string result = randomNum.ToString();

    // Retry if all digits are the same (e.g., 7777777777777)
    if (result.Distinct().Count() == 1)
    {
        return GenerateUniqueRandomNumbers();
    }

    // If the number already exists in our tracked set, retry; otherwise, add it and return
    if (!_usedNumbers.Add(result))
    {
        return GenerateUniqueRandomNumbers();
    }

    return result;
}

Key Fixes & Improvements:

  • Reused Random Instance: Creating a new Random every time can lead to duplicate numbers if called rapidly (since it uses the system clock as a seed). A static instance avoids this issue.
  • Valid 13-Digit Range: NextInt64(1000000000000, 10000000000000) ensures we only get numbers that are exactly 13 digits (no leading zeros).
  • Uniqueness Tracking: The HashSet stores every generated number. The Add method returns false if the number is already present, so we retry in that case.
  • Retained All-Same Digit Check: Keeps your original logic to avoid numbers with identical digits.

Bonus: More Robust Loop Version

If you're generating a lot of numbers, recursion could hit stack limits. Here's a do-while loop alternative that's safer for repeated retries:

public static string GenerateUniqueRandomNumbers()
{
    string result;
    do
    {
        long randomNum = _randomGenerator.NextInt64(1000000000000, 10000000000000);
        result = randomNum.ToString();
    }
    // Keep trying until we get a number that's not all-same digits and hasn't been used before
    while (result.Distinct().Count() == 1 || !_usedNumbers.Add(result));

    return result;
}

Quick Note on Persistence

If you need uniqueness to persist even after restarting your app, you'll need to store the _usedNumbers set in a database, file, or other persistent storage—an in-memory HashSet will reset when the app closes.

内容的提问来源于stack exchange,提问作者hornet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:42:47