How to generate a certain amount of numbers and spread them randomly across a grid?

荒凉一梦 提交于 2020-01-07 09:43:40

问题


I want to generate the number 2 5 times and the number 1 10 times. I'm trying to spread these across a String Grid in Delphi randomly. I also want to fill the rest of the grid that isn't 1 or 2, with 0's. I have no idea how to even start here.

It would look something like this (P stands for player and there would only be 5 2's and 10 1's): https://gyazo.com/aeef05c3a92ce7847c0f42ad40faa733


回答1:


Given a grid with dimensions m×n, create an array of length m * n. Put five 2's and 10 1's in the array, and fill the remainder with 0's. (We'll assume the product of m and n is at least 15.) Shuffle the array. Copy each element of the shuffled array into successive cells in the grid.




回答2:


While the approach represented in Robs answer will do the job I personally think it is way to complicated for it's purpose.

So what would be more simpler approach?

Well your goal is to place these numbers at random positions in grid.

How do you determine position of some object in a grid? You do it by its X (Column) and Y (Row) coordinates.

So how do you get random position in a grid? Simple chose two random values for X and Y coordinates.

As for placing certain numbers of number 1 and number 2 use two simple loops.



来源:https://stackoverflow.com/questions/41857117/how-to-generate-a-certain-amount-of-numbers-and-spread-them-randomly-across-a-gr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!