PHP数组生成挑战 [英] php array generation challenge

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

问题描述

我需要随机生成一个二维的n×n数组.在此示例中,n =10.该数组应具有此结构.一个例子:

I need to randomly generate an two-dimensional n by n array. In this example, n = 10. The array should have this structure. One example:

$igra[]=array(0,1,2,3,4,5,6,7,8,9);
$igra[]=array(6,9,1,5,0,2,7,3,4,8);
$igra[]=array(2,5....................
$igra[]=array(1,7.....................
$igra[]=array(5,4...................
$igra[]=array(4,2...................
$igra[]=array(9,0.....................
$igra[]=array(8,3.....................
$igra[]=array(7,6....................
$igra[]=array(3,8....................

其中

`$igra[x][z]!=$igra[y][z]`   (x={0,9},y={0,9});

如您所见,

就像一个数字矩阵,它的每一行和每一列也由数字0-9组成,并且在每一行或每一列中从来没有一个数字两次. 如何生成这样的数组,并且每次都是随机的.

as you see it's like a matrix of numbers each row of it and column also consist from numbers 0-9, and there is never one number two times in each row or in each column. how to generate such an array, and each time randomly.

推荐答案

好的,这是我的版本:

$n = 10;

$v1 = range(0, $n-1);
$v2 = range(0, $n-1);
shuffle($v1);
shuffle($v2);

foreach ($v1 as $x => $value)
    foreach ($v2 as $y)
        $array[$y][$x] = $value++ % $n;

这应该是一种非常快速的算法,因为它只涉及生成两个随机数组,而根本不涉及任何交换.它也应该是随机的,但我无法证明这一点. (至少我不知道如何证明这样的东西.)

This should be a really fast algorithm, because it involves only generating two random arrays and doesn't involve any swapping at all. It should be random, too, but I cannot prove it. (At least I don't know how to prove something like this.)

这是一个非常简单的算法的优化版本:

This is an optimized version of a very simple algorithm:

首先以这种方式创建一个非随机矩阵(假设我们只需要5 * 5,而不是10 * 10):

First a non-random matrix is created this way (imagine we want only 5*5, not 10*10):

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

在此矩阵中,我们现在随机交换列.由于我们自己不更改列,因此您的规则仍然得到遵守.然后我们随机交换行.

In this matrix we now randomly swap columns. As we don't change the columns themselves your rules still are obeyed. Then we randomly swap rows.

现在,如您所见,上述算法不会交换任何内容,也不会生成上述矩阵.这是因为它会生成cols和行以进行预先交换($v1$v2),然后直接写入结果数组中的正确位置.

Now, as you can see the above algorithm doesn't swap anything and it doesn't generate the above matrix either. That's because it generates the cols and rows to swap in advance ($v1 and $v2) and then directly writes to the correct position in the resulting array.

只是做了一些基准测试:对于$n = 500,它需要0.3秒.

Just did some benchmarking: For $n = 500 it takes 0.3 seconds.

Edit2:用foreach循环替换for循环后,只需0.2秒.

After replacing the for loops with foreach loops it only takes 0.2 seconds.

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

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