Unity C# basic review 19 - HashSet (P384) obtains unique random numbers

Hashtable

A collection consisting of a pair of elements of type (key, value)

The keys of all elements must be unique

key→value is a one-to-one mapping , that is, you can immediately find the required element in the collection based on the key

Hashtable method

Add(key,value)

Search based on key instead of index , so it is very fast

using UnityEngine;
using System.Threading;

public class Test : MonoBehaviour
{
    private void Start()
    {
        TestHashSet();
    }
    public static void TestHashSet()
    {
        HashSet<int> nums = new HashSet<int>();

        nums.Add(1);
        nums.Add(1);
        nums.Add(1);
        Debug.Log(nums.Count);
    }
}

Logically speaking, nums.Add(1) 3 times, nums.Count should be 3, but because HashSet refuses duplicates, it is 1.

We can borrow this feature to obtain n random non-repeating numbers

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;

public class Test : MonoBehaviour
{
    private void Start()
    {
        TestHashSet();
    }
    public static void TestHashSet()
    {
        HashSet<int> nums = new HashSet<int>();
        System.Random r = new System.Random();
        while (nums.Count != 5)
        {
            nums.Add(r.Next(0, 5));

        }

        foreach (var item in nums)
        {
            Debug.Log("01组 = "+item);
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_46711336/article/details/124512755