Re-ordering arbitrary an array of integers

前端 未结 4 745
长发绾君心
长发绾君心 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:40

    What about extension method?

    public static class ArrayExtensions
    {
        private static Lazy random = new Lazy(() => new Random());
    
        public static IEnumerable GetReorderedElements(this T[] input)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
    
            var rnd = random.Value;        
            var nums = input.ToList();         
            var repeats = unusedNums.Length;
    
            while (repeats > 0)
            {
                var index_first = rnd.Next(0, nums.Length);
                var index_second = rnd.Next(0, nums.Length);
    
                var temp = nums[index_first];
                nums[index_first] = nums[index_second];
                nums[index_second] = temp;
    
                repeats -= 1;
            }
    
            return new ReadOnlyCollection(nums);
        }
    
    
        public static T[] GetReorderedElementsAsArray(this T[] input)
        {
            return GetRandomElements(input).ToArray();
        }
    }
    

    Usage:

    _current_number = _game_number.GetReorderedElementsAsArray();
    

提交回复
热议问题