【问题标题】:How do I fill an array with unique random numbers in different rows/columns如何在不同的行/列中填充具有唯一随机数的数组
【发布时间】:2015-02-11 18:47:51
【问题描述】:

我已经环顾四周,但似乎找不到令人满意的答案。我想用唯一的数字填充 5x5。在第 1 列中,它只能是 1-5 之间的数字,在第 2 列中只能是 16-30 之间的数字,依此类推,直到第 5 列中的数字在 61-75 之间。它是一个宾果游戏板。我已经尝试了几件事,但都没有奏效,我似乎无法找到一种用我的规范填充数组的方法。在我看来,它只是带有几个数字的预填充数组的示例,或者代码对我来说是高级的方式。

我不久前创建了一个程序,它创建了一个包含数字 1-75 的常规数组,然后使用 Fisher/yates 算法对其进行洗牌。这是我应该继续使用还是应该从头开始?enter code here

 static void Main(string[] args)
{
    string choise = "";
    while (choise != "q" && choise != "Q")
    {

        Console.Clear();
        Console.WriteLine("[1] for a random row of numbers! \n[2] to start the game! 
        \n[Q] to quit! \nPress enter after your selection.");
        choise = Console.ReadLine();
        if (choise == "1")
        {
            RandomNum.randomTal();
        }

  (another class)
  static  Random rnd = new Random();
   public static void Shuffle<T>(T[] array)
    {
        Console.Clear();

        for (int i = 0; i < array.Length; i++)
        {
            int r = i + (int)(rnd.NextDouble() * (array.Length - i));
            T t = array[r];
            array[r] = array[i];
            array[i] = t;
        }
    }

(and another class)

class RandomNum
  {
    public static void randomTal()
    {
        int[] sifferArray = Enumerable.Range(1, 56).ToArray();
        shuffle.Shuffle(sifferArray);
        foreach (var item in sifferArray)
        {
            Console.WriteLine(item);

        }
        Console.WriteLine("Press any key to go back.");
        Console.ReadKey();
    }

【问题讨论】:

  • fisher/yates 算法应该是完美的。假设您想要 5 个 唯一 介于 16 和 30 之间的随机数。请 Enumerable.Range(16,15).ToArray().Shuffle().Take(5);
  • 对不起,我真的不知道该怎么办。如果我尝试放入 RandomNum 类,它会在随机播放下显示“;预期”。我认为可枚举不适用于二维数组。

标签: c# arrays random integer autofill


【解决方案1】:
static void Main(string[] args)
    {
        var bingoCard = getBingoCard();
        int colNum = 1;

        foreach (var col in bingoCard)
        {
            Console.Write("col" + colNum.ToString() + " ");
            foreach (var item in col)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            colNum++;
        }
        Console.WriteLine();

        for (int x = 0; x < 5; x++)
        {
            for (int y = 0; y < 5; y++)
            {
                Console.Write(bingoCard[y][x].ToString() + (bingoCard[y][x] > 9 ?  " " : "  "));
            }
            Console.WriteLine();
        }

        Console.ReadLine();
    }



    public static int[][] getBingoCard()
    {
        var randGen = new Random();
        var bingoCard = new int[][]{
        new int[5],
        new int[5],
        new int[5],
        new int[5],
        new int[5]
    };
        for (int y = 0; y < 5; y++)
        {
            for (int x = 0; x < 5; x++)
            {
                var possibleNumber = randGen.Next((15 * y) + 1, ((y + 1) * 15));
                while (bingoCard[y].Any(num => num == possibleNumber))
                {
                    possibleNumber = randGen.Next((15 * y) + 1, ((y + 1) * 15));
                }
                bingoCard[y][x] = possibleNumber;
            }
        }
        return bingoCard;
    }

【讨论】:

  • 谢谢你们!对此,我真的非常感激!但是在最后一篇文章中,我似乎无法理解 .next() 中的数学是如何工作的。我知道如何在“真实”数学中计算它。但我不明白它在这里是如何工作的以及这些数字的作用。请您向初学者解释一下吗?
  • 而且这段代码不会在数组中生成唯一的数字。
  • 你的意思是它不会生成唯一的数字?你跑了吗?它会生成唯一的数字...
  • next() 中的数学运算是指定要生成的最小和最大数字。因此,它计算的第一列应该得到最小值 1 和最大值 15。在第二个循环(第二列)中,它将每个数字加 15... 最小值为 16,最大值为 30(依此类推通过每个循环/列)。 while(any) 循环强制数字生成器创建一个新数字,直到找到数组的唯一数字。
  • 对不起,我自己编辑了代码,因此有一些重复的数字。但原来的工作正常。我希望数字像一列一样垂直排列?所以尝试在不同的组合中更改 x 和 y,但是代码没有按预期工作。你对我有什么指示吗?感谢您的帮助和解释。
【解决方案2】:

当我需要时,我会使用这样的东西:

   private int[] generatePermutation(int size, int seed) 
   {
        var permutation = new int[size];
        Rnd random = new Rnd(seed);

        List<int> permList = new List<int>(size);
        for (int i = 0; i < size; i++) permList.Add(i);

        for (int i = 0; i < size; i++)
        {
            int index = random.Next(0, permList.Count);
            permutation[i] = permList[index];
            permList.RemoveAt(index);
        }
        return permutation;
    }

【讨论】:

    【解决方案3】:

    如果您有一个类 BingoBoard 具有与单元格对应的嵌入式 2d 整数数组,您可以像这样生成单元格的随机模式:

    public class BingoBoard
    {
        public const int BoardDimension = 5;
    
        readonly int[,] board = new int[BoardDimension, BoardDimension];
    
        public BingoBoard()
        {
            // In column 1 it can only be a number between 1-15 and in column 2 number 16-30 and so on up until column 5 with a number between 61-75.
            for (int iRow = 0; iRow < board.GetLength(0); iRow++)
            {
                var col = Enumerable.Range(iRow * 3 * board.GetLength(1) + 1, 3 * board.GetLength(1)).Shuffle().Take(board.GetLength(1)).ToArray();
                for (int iCol = 0; iCol < board.GetLength(1); iCol++)
                    board[iRow, iCol] = col[iCol];
            }
        }
    
        public int[,] Board
        {
            get
            {
                return board;
            }
        }
    }
    
    public static class RandomProvider
    {
        // Adapted from http://csharpindepth.com/Articles/Chapter12/Random.aspx
        private static int seed = Environment.TickCount;
    
        [ThreadStatic]
        static Random random;
    
        public static Random GetThreadRandom()
        {
            if (random == null)
                random = new Random(Interlocked.Increment(ref seed));
            return random;
        }
    }
    
    public class FisherYatesShuffle 
    {
        public void ShuffleInPlace<T>(T[] array)
        {
            var randomizer = RandomProvider.GetThreadRandom();
    
            // http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm , second version.
            for (int i = 0; i < array.Length; i++)
            {
                // http://msdn.microsoft.com/en-us/library/2dx6wyd4%28v=vs.110%29.aspx
                var j = randomizer.Next(i, array.Length); // i = inclusive lower bound; array.Length = The exclusive upper bound of the random number returned
                array.Swap(i, j);
            }
        }
    }
    
    public static class ListExtensions
    {
        public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list)
        {
            var scrambled = list.ToArray();
            new FisherYatesShuffle().ShuffleInPlace(scrambled);
            return scrambled;
        }
    
        public static void Swap<T>(this T[] list, int i, int j)
        {
            if (list == null)
                throw new ArgumentNullException();
            if (i != j)
            {
                T temp = list[i];
                list[i] = list[j];
                list[j] = temp;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2017-09-03
      相关资源
      最近更新 更多