PHP数组代challange [英] php array generation challange

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

问题描述

我需要随机生成由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.

推荐答案

好了,这里是我的版本:

Okay, so here's my version:

$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和rows预先交换( $ 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循环回路后,只用0.2秒。

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

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

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