Home > Backend Development > PHP Tutorial > Your favorite puzzle: Use PHP to print the nine-square grid - third-order magic square_PHP tutorial

Your favorite puzzle: Use PHP to print the nine-square grid - third-order magic square_PHP tutorial

WBOY
Release: 2016-07-13 17:53:00
Original
744 people have browsed it

ignore_user_abort(true);
set_time_limit(0);
$tmp = array();
function getArr($arr='')
{
for ($i = 1; $i <= 9; $i++) {
if ( empty($arr) ) {
$arr[] = $i;
} elseif ( in_array($i, $arr) ) {
continue;
} else {
$arr[] = $i;
}
if ( count($arr) < 9 ) {
getArr($arr);
}
if ( count($arr) < 9 && count($arr) > 1 ) {
array_pop($arr);
continue;
} elseif ( count($arr) == 1 ) {
unset($arr);
continue;
} elseif ( checkArr($arr) ) {
$GLOBALS['tmp'][] = $arr;
}
}
}
function checkArr($arr)
{
$m = array();
$m[] = $arr[0] + $arr[1] + $arr[2];
$m[] = $arr[3] + $arr[4] + $arr[5];
$m[] = $arr[6] + $arr[7] + $arr[8];
$m[] = $arr[0] + $arr[3] + $arr[6];
$m[] = $arr[1] + $arr[4] + $arr[7];
$m[] = $arr[2] + $arr[5] + $arr[8];
$m[] = $arr[0] + $arr[4] + $arr[8];
$m[] = $arr[2] + $arr[4] + $arr[6];
$tmp = array_count_values($m);
foreach ($tmp as $v) {
if ( $v == 8 ) {
return true;
} else {
return false;
}
}
}
$startTime = microtime(true);
getArr();
$endTime = microtime(true);
for( $i=0; $i $arr = $tmp[$i];
echo $str=<<

















{$arr[0]} {$arr[1]} {$arr[2]}
{$arr[3]} {$arr[4]} {$arr[5]}
{$arr[6]} {$arr[7]} {$arr[8]}

fs;
}
echo '

共花费时间:';
echo round($endTime - $startTime, 3);
echo '秒

';www.2cto.com
die;
用穷举的方式完成的,8个结果
我的电脑大约要花10.5秒种时间
用递归的方式完成,可以很方便的增加到4阶、5阶……
花了20分种写出来的,如果把不可能条件排除的话应该不用一秒钟就可以完成的
你们最喜欢的智力题
作者:zdrjlamp

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/478057.htmlTechArticleignore_user_abort(true); set_time_limit(0); $tmp = array(); function getArr($arr=) { for ($i = 1; $i = 9; $i++) { if ( empty($arr) ) { $arr[] = $i; } elseif ( in_array($i, $arr) ) {...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template