随机生成不重复的几个数(Unity)

 

using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 随机数管理类
/// </summary>
public class RandomHelper
{
    /// <summary>
    /// 生成指定位数的随机码(数字)
    /// </summary>
    /// <param name="length">生成数字的长度</param>
    /// <param name="min"></param>
    /// <param name="max"></param>
    /// <returns></returns>
    public static string GenerateRandomCode(int length, int min, int max)
    {
        var result = new System.Text.StringBuilder();
        for (var i = 0; i < length; i++)
        {
            var random = new System.Random(System.Guid.NewGuid().GetHashCode());
            result.Append(random.Next(min, max));
        }
        return result.ToString();
    }


    /// <summary>
    /// 生成指定个数的不重复随机数列表
    /// </summary>
    /// <param name="length">列表的长度[不得大于min和max之间随机数的总个数]</param>
    /// <param name="min"></param>
    /// <param name="max"></param>
    /// <returns></returns>
    public static List<int> GenerateRandomList(int length, int min, int max)
    {
        List<int> randomList = new List<int>();
        if (length <= (max - min)) 
        {
            for (var i = 0; i < length; i++)
            {
                int random = Random.Range(min, max);
                if (randomList.Contains(random))
                {
                    i--;
                    continue;
                }
                else
                {
                    randomList.Add(random);
                }
            }
        }
        return randomList;
    }

    /// <summary>
    /// 索引法随机
    /// </summary>
    /// <param name="minValue"></param>
    /// <param name="maxValue"></param>
    /// <returns></returns>
    public static int[] GetIndexRandomNum(int minValue, int maxValue)
    {
        System.Random random = new System.Random();
        int sum = Mathf.Abs(maxValue - minValue);//计算数组范围
        int site = sum;//设置索引范围
        int[] index = new int[sum];
        int[] result = new int[sum];
        int temp = 0;

        for (int i = minValue; i < maxValue; i++)
        {
            index[temp] = i;
            temp++;
        }

        for (int i = 0; i < sum; i++)
        {
            int id = random.Next(0, site - 1);
            result[i] = index[id];
            index[id] = index[site - 1];//因id随机到的数已经获取到了,用最后的一个数来替换它
            site--;//缩小索引范围
        }
        return result;
    }
}
View Code

 

posted @ 2022-03-08 09:18  U3DEngineer  阅读(363)  评论(0编辑  收藏  举报