当前位置: 动力学知识库 > 问答 > 编程问答 >

where is mistake ? php letter matrix boggle

问题描述:

I find theese php codes here, but codes aren't working correctly. it seems that the if(isset($words[$word])) doesn't go through as I always get an empty results array

 $boggle = "fxie

amlo

ewbx

astu";

$alphabet = str_split(str_replace(array("\n", " ", "\r"), "", strtolower($boggle)));

$rows = array_map('trim', explode("\n", $boggle));

$dictionary = file("C:/dict.txt");

$prefixes = array(''=>'');

$words = array();

$regex = '/[' . implode('', $alphabet) . ']{3,}$/S';

foreach($dictionary as $k=>$value) {

$value = trim(strtolower($value));

$length = strlen($value);

if(preg_match($regex, $value)) {

for($x = 0; $x < $length; $x++) {

$letter = substr($value, 0, $x+1);

if($letter == $value) {

$words[$value] = 1;

} else {

$prefixes[$letter] = 1;

}

}

}

}

$graph = array();

$chardict = array();

$positions = array();

$c = count($rows);

for($i = 0; $i < $c; $i++) {

$l = strlen($rows[$i]);

for($j = 0; $j < $l; $j++) {

$chardict[$i.','.$j] = $rows[$i][$j];

$children = array();

$pos = array(-1,0,1);

foreach($pos as $z) {

$xCoord = $z + $i;

if($xCoord < 0 || $xCoord >= count($rows)) {

continue;

}

$len = strlen($rows[0]);

foreach($pos as $w) {

$yCoord = $j + $w;

if(($yCoord < 0 || $yCoord >= $len) || ($z == 0 && $w == 0)) {

continue;

}

$children[] = array($xCoord, $yCoord);

}

}

$graph['None'][] = array($i, $j);

$graph[$i.','.$j] = $children;

}

}

function to_word($chardict, $prefix) {

$word = array();

foreach($prefix as $v) {

$word[] = $chardict[$v[0].','.$v[1]];

}

return implode("", $word);

}

function find_words($graph, $chardict, $position, $prefix, $prefixes, &$results, $words) {

$word = to_word($chardict, $prefix);

if(!isset($prefixes[$word])) return false;

**if(isset($words[$word])) {

$results[] = $word;

}**

foreach($graph[$position] as $child) {

if(!in_array($child, $prefix)) {

$newprefix = $prefix;

$newprefix[] = $child;

find_words($graph, $chardict, $child[0].','.$child[1], $newprefix, $prefixes, $results, $words);

}

}

}

$solution = array();

find_words($graph, $chardict, 'None', array(), $prefixes, $solution);

print_r($solution);

网友答案:

When you call find_words() at the end, you are only passing 6 parameters

find_words($graph, $chardict, 'None', array(), $prefixes, $solution);

The variable $words, is the 7th parameter in your definition of find_words()

function find_words($graph, $chardict, $position, $prefix, $prefixes, &$results, $words) {

Hence, $words will always be empty, and isset($words[$word]) will always be false

分享给朋友:
您可能感兴趣的文章:
随机阅读: