Re-ordering arbitrary an array of integers

前端 未结 4 784
长发绾君心
长发绾君心 2021-01-16 22:04

I have a method that accepts as argument an array of integers and I\'d just change arbitrary the order of its values

public static int[] _game_number = new         


        
4条回答
  •  误落风尘
    2021-01-16 22:41

    If you want to reorder them randomly, simply use OrderBy with a random thing as the selector.

    Usually you can use Random.Next()

    public static int[] _game_number = new int[4];
    public static int[] _current_number = new int[4];
    private static Random random = new Random();
    
    public static void GetRandomTwentyFour()
    {
        _current_number = _game_number.OrderBy(r => random.Next()).ToArray();
    }
    

    But a new Guid would work here too², and save you a private field :

    public static int[] _game_number = new int[4];
    public static int[] _current_number = new int[4];
    
    public static void GetRandomTwentyFour()
    {
        _current_number = _game_number.OrderBy(g => new Guid()).ToArray();
    }
    

    ²Please note that Guids are not made to be "random", but to be "unique". However, as you're probably not making an extremely official application (banking, online poker, etc.) it's fair to use it IMO. For an application where the randomness is very important, the RandomNumberGenerator from Cryptography namespace would be a better bet.

提交回复
热议问题