随机填充数组 [英] Randomly filled Array

查看:69
本文介绍了随机填充数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我需要一个包含9乘9元素的2D数组。问题是每个必须随机填充数字1到9(或0到8)。但每个必须包含一个1,一个2和一个3.


有人可以帮我构建这个阵列吗?


Cindy

Hi,

I need a 2D array with 9 by 9 elements. The problem is that every column must be randomly filled with the numbers 1 To 9 (Or 0 To 8). But every row must contain exactly one 1, one 2 and one 3.

Can somebody please help me with building this array?

Cindy

推荐答案


我需要一个9乘9的二维数组......
I need a 2D array with 9 by 9 ...



我看,像数独的东西,但没有3x3的正方形。


我不知道是否有一个简单的方法,但是对于一些DO和FORs你可以实现它,这样的东西应该适用于第一列,你可以使用类似的东西用于下一个。

I see, something like a Sudoku, but without the 3x3 squares.

I dont know if there is an easy way, but with some DOs and FORs you can achieve it, something like this should work for the first column, you can use something like that for the next ones.

展开 | 选择 | Wrap | 行号



... DO和FOR ...
... with some DOs and FORs ...



我编写的代码生成一个9乘9的数组,其中包含随机的一个1数组。在每一列和每行中:所以永远不会有两个或更多个1。在一排或一列。我的代码如下所示:

I have written a code that produces a 9 by 9 array that contains randomly one "1" in each column and row: So there are never two or more "1" ''s in a row or column. My code looks like this:

展开 | 选择 | Wrap | < span class =codeLinkonclick =LineNumbers(this);>行号



我想要的下一件事要做的是,添加数字2。以相同的方式,当然不覆盖1。 的。你能帮我么?
The next thing I want to do, is to add the numbers "2" in the same way and of course without overwriting the "1" ''s. Can you please help me?



嗨Cindy,我已经制作了添加所有数字的代码,但这里有一个小问题,算法并不保证你'我会做出有效的安排。例如同时分配号码4。这可能发生:


0 0 3 1 2 4 0 0 0

0 4 0 2 0 3 0 1 0

0 0 4 3 0 1 2 0 0

0 0 0 4 1 2 3 0 0

0 3 0 0 4 0 0 2 1

1 0 0 0 3 0 4 0 2

2 0 0 0 0 0 1 3 4

0 1 2 0 0 0 0 4 3

3 2 1 0 0 0 0 0 0


所以你没有机会在最后一行写一个4。我认为正确的方法应该是生成这样的有序数组:


1 2 3 4 5 6 7 8 9

2 3 4 5 6 7 8 9 1

3 4 5 6 7 8 9 1 2

4 5 6 7 8 9 1 2 3

5 6 7 8 9 1 2 3 4

6 7 8 9 1 2 3 4 5

7 8 9 1 2 3 4 5 6

8 9 1 2 3 4 5 6 7

9 1 2 3 4 5 6 7 8


然后随机地随机切换行和列。


HTH

Hi Cindy, I''ve made the code that adds all the numbers but there''s a small problem here, the algorithm doesn''t guarantee that you''ll be making a valid arrangement. e.g. while assigning number "4" this might happen:

0 0 3 1 2 4 0 0 0
0 4 0 2 0 3 0 1 0
0 0 4 3 0 1 2 0 0
0 0 0 4 1 2 3 0 0
0 3 0 0 4 0 0 2 1
1 0 0 0 3 0 4 0 2
2 0 0 0 0 0 1 3 4
0 1 2 0 0 0 0 4 3
3 2 1 0 0 0 0 0 0

So you won''t have a chance to write a 4 in the last line. I think the right way should be generating an ordered array like this:

1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9 1
3 4 5 6 7 8 9 1 2
4 5 6 7 8 9 1 2 3
5 6 7 8 9 1 2 3 4
6 7 8 9 1 2 3 4 5
7 8 9 1 2 3 4 5 6
8 9 1 2 3 4 5 6 7
9 1 2 3 4 5 6 7 8

and then randomly switch rows and columns a random number of times.

HTH


这篇关于随机填充数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆