Re: Фільтрація номерів за маскою (задача на 5+)
Трохи величенький у мене код получився на швидку руку
▼Прихований текст
<?
include 'list.php';
$maxLenght = 8;
$support_symbols = array(' ','+','-');
$list = explode("\n",str_replace($support_symbols,'',$list));
echo '<form method="post">';
echo 'Please enter mask (will be cat to '.$maxLenght.' symbols):<input type="text" name="mask" value="'.(isset($_POST['mask'])?$_POST['mask']:'').'">';
echo '</form>';
if(isset($_POST['mask']) && $_POST['mask']){
$_POST['mask']=substr($_POST['mask'],0,$maxLenght);
//check time
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
//end check time
$masks=getMasks($_POST['mask']);
//check time
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "Mask generation time =".$totaltime." seconds<br />";
//end check time
$numbers = array();
foreach($list as $number)
foreach($masks as $mask)
if (strstr($number,$mask)) $numbers[] = $number;
//check time
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime2 = $mtime;
$totaltime = ($endtime2 - $endtime);
echo "Mask comparation time =".$totaltime." seconds<br />";
//end check time
echo "Total selected ".count($numbers)." numbers<br />";
echo "Mask: ".$_POST['mask'];
echo '<pre>'.print_r($numbers,true);
}
function getMasks($string) {
$charMask=str_split($string);
$listMasks= array();
$uniqueChars = array_values(array_unique($charMask));
return setMasks(array(), $uniqueChars, $string, array());
}
function setMasks($inputMasks, $uniqueChars, $string, $excludedNumbers) {
if(!count($inputMasks)) {
$inputMasks = array($string);
}
if(count($uniqueChars)){
$charNumber = count($uniqueChars)-1;
if(is_numeric($uniqueChars[$charNumber])) {
unset($uniqueChars[$charNumber]);
return setMasks($inputMasks, $uniqueChars, $string, $excludedNumbers);
}
else {
$outputMasks = array();
$letter = $uniqueChars[$charNumber];
unset($uniqueChars[$charNumber]);
for($i=0;$i<=9;$i++) {
if(!in_array($i, $excludedNumbers)) {
$outputMasks = array_merge($outputMasks,
setMasks(
replaceChar($inputMasks, $letter, $i)
, $uniqueChars, $string, array_merge($excludedNumbers, array($i))));
}
}
return $outputMasks;
}
}
else {
return $inputMasks;
}
}
function replaceChar($inputMasks, $letter, $i) {
foreach($inputMasks as $key=>$value)
$inputMasks[$key] = str_replace($letter, $i, $value);
return $inputMasks;
}
?>
Ось результати на локальному сервері:
Mask generation time =0.0101351737976 seconds
Mask comparation time =0.113929033279 seconds
Total selected 440 numbers
Mask: abb
Код дуже сильно не оптимізований, так що прошу не бити.