apply apriori php to CI - php

I downloaded apriori algorithm on php from www.vtwo.org but i want to apply it to my CI framework, but the input value won't be called. so it couldn't display the result. is it something wrong on my CI code changes? please help
this is my apriori controller (apriori.php)
class Apriori {
private $delimiter = ',';
private $minSup = 2;
private $minConf = 50;
private $rules = array();
private $table = array();
private $allthings = array();
private $allsups = array();
private $keys = array();
private $freqItmsts = array();
private $phase = 1;
//maxPhase>=2
private $maxPhase = 20;
private $fiTime = 0;
private $arTime = 0;
public function setDelimiter($char)
{
$this->delimiter = $char;
}
public function setMinSup($int)
{
$this->minSup = $int;
}
public function setMinConf($int)
{
$this->minConf = $int;
}
public function setMaxScan($int)
{
$this->maxPhase = $int;
}
public function getDelimiter()
{
return $this->delimiter;
}
public function getMinSup()
{
return $this->minSup;
}
public function getMinConf()
{
return $this->minConf;
}
public function getMaxScan()
{
return $this->maxPhase;
}
/**
1. جدول آیتمها را می سازد
2. کلید دسترسی به هر آیتم را تولید می کند
3. تمامی آیتمها و تکرار آنها را محاسبه می کند - سطح 1
توجه: حداقل تکرار محاسبه میشود
**/
private function makeTable($db)
{
$table = array();
$array = array();
$counter = 1;
if(!is_array($db))
{
$db = file($db);
}
$num = count($db);
for($i=0; $i<$num; $i++)
{
$tmp = explode($this->delimiter, $db[$i]);
$num1 = count($tmp);
$x = array();
for($j=0; $j<$num1; $j++)
{
$x = trim($tmp[$j]);
if($x==='')
{
continue;
}
if(!isset($this->keys['v->k'][$x]))
{
$this->keys['v->k'][$x] = $counter;
$this->keys['k->v'][$counter] = $x;
$counter++;
}
if(!isset($array[$this->keys['v->k'][$x]]))
{
$array[$this->keys['v->k'][$x]] = 1;
$this->allsups[$this->keys['v->k'][$x]] = 1;
}
else
{
$array[$this->keys['v->k'][$x]]++;
$this->allsups[$this->keys['v->k'][$x]]++;
}
$table[$i][$this->keys['v->k'][$x]] = 1;
}
}
$tmp = array();
foreach($array as $item => $sup)
{
if($sup>=$this->minSup)
{
$tmp[] = array($item);
}
}
$this->allthings[$this->phase] = $tmp;
$this->table = $table;
}
/**
1. مقدار سوپریموم را با توجه به ورودی شناسه آیتمها شمارش می کند
**/
private function scan($arr, $implodeArr = '')
{
$cr = 0;
if($implodeArr)
{
if(isset($this->allsups[$implodeArr]))
{
return $this->allsups[$implodeArr];
}
}
else
{
sort($arr);
$implodeArr = implode($this->delimiter, $arr);
if(isset($this->allsups[$implodeArr]))
{
return $this->allsups[$implodeArr];
}
}
$num = count($this->table);
$num1 = count($arr);
for($i=0; $i<$num; $i++)
{
$bool = true;
for($j=0; $j<$num1; $j++)
{
if(!isset($this->table[$i][$arr[$j]]))
{
$bool = false;
break;
}
}
if($bool)
{
$cr++;
}
}
$this->allsups[$implodeArr] = $cr;
return $cr;
}
/**
1. ترکیب دو آرایه و حذف مقادیر اضافی
**/
private function combine($arr1, $arr2)
{
$result = array();
$num = count($arr1);
$num1 = count($arr2);
for($i=0; $i<$num; $i++)
{
if(!isset($result['k'][$arr1[$i]]))
{
$result['v'][] = $arr1[$i];
$result['k'][$arr1[$i]] = 1;
}
}
for($i=0; $i<$num1; $i++)
{
if(!isset($result['k'][$arr2[$i]]))
{
$result['v'][] = $arr2[$i];
$result['k'][$arr2[$i]] = 1;
}
}
return $result['v'];
}
/**
1. نام آیتم را با توجه به شناسه آیتم یا آیتمها بر می گرداند
{1,2,3,4} => {A,B,C,D}
**/
private function realName($arr)
{
$result = '';
$num = count($arr);
for($j=0; $j<$num; $j++)
{
if($j)
{
$result .= $this->delimiter;
}
$result .= $this->keys['k->v'][$arr[$j]];
}
return $result;
}
//1-2=>2-3 : false
//1-2=>5-6 : true
private function checkRule($a, $b)
{
$a_num = count($a);
$b_num = count($b);
for($i=0; $i<$a_num; $i++)
{
for($j=0; $j<$b_num; $j++)
{
if($a[$i]==$b[$j])
{
return false;
}
}
}
return true;
}
private function confidence($sup_a, $sup_ab)
{
return round(($sup_ab / $sup_a) * 100, 2);
}
private function subsets($items)
{
$result = array();
$num = count($items);
$members = pow(2, $num);
for($i=0; $i<$members; $i++)
{
$b = sprintf("%0".$num."b", $i);
$tmp = array();
for($j=0; $j<$num; $j++)
{
if($b[$j]=='1')
{
$tmp[] = $items[$j];
}
}
if($tmp)
{
sort($tmp);
$result[] = $tmp;
}
}
return $result;
}
/**
1. آیتم ستهای تکراری را بر می گرداند
**/
private function freqItemsets($db)
{
$this->fiTime = $this->startTimer();
$this->makeTable($db);
while(1)
{
if($this->phase>=$this->maxPhase)
{
break;
}
$num = count($this->allthings[$this->phase]);
$cr = 0;
for($i=0; $i<$num; $i++)
{
for($j=$i; $j<$num; $j++)
{
if($i==$j)
{
continue;
}
$item = $this->combine($this->allthings[$this->phase][$i], $this->allthings[$this->phase][$j]);
sort($item);
$implodeArr = implode($this->delimiter, $item);
if(!isset($this->freqItmsts[$implodeArr]))
{
$sup = $this->scan($item, $implodeArr);
if($sup>=$this->minSup)
{
$this->allthings[$this->phase+1][] = $item;
$this->freqItmsts[$implodeArr] = 1;
$cr++;
}
}
}
}
if($cr<=1)
{
break;
}
$this->phase++;
}
//زیر مجموعه های مربوط به مجموعه های بزرگتر را حذف می کند
foreach($this->freqItmsts as $k => $v)
{
$arr = explode($this->delimiter, $k);
$num = count($arr);
if($num>=3)
{
$subsets = $this->subsets($arr);
$num1 = count($subsets);
for($i=0; $i<$num1; $i++)
{
if(count($subsets[$i])<$num)
{
unset($this->freqItmsts[implode($this->delimiter, $subsets[$i])]);
}
else
{
break;
}
}
}
}
$this->fiTime = $this->stopTimer($this->fiTime);
}
/**
1. قوانین نهایی را با توجه به مقدار حداقل کانفیندس محاسبه می کند
**/
public function process($db)
{
$checked = $result = array();
$this->freqItemsets($db);
$this->arTime = $this->startTimer();
foreach($this->freqItmsts as $k => $v)
{
$arr = explode($this->delimiter, $k);
$subsets = $this->subsets($arr);
$num = count($subsets);
for($i=0; $i<$num; $i++)
{
for($j=0; $j<$num; $j++)
{
if($this->checkRule($subsets[$i], $subsets[$j]))
{
$n1 = $this->realName($subsets[$i]);
$n2 = $this->realName($subsets[$j]);
$scan = $this->scan($this->combine($subsets[$i], $subsets[$j]));
$c1 = $this->confidence($this->scan($subsets[$i]), $scan);
$c2 = $this->confidence($this->scan($subsets[$j]), $scan);
if($c1>=$this->minConf)
{
$result[$n1][$n2] = $c1;
}
if($c2>=$this->minConf)
{
$result[$n2][$n1] = $c2;
}
$checked[$n1.$this->delimiter.$n2] = 1;
$checked[$n2.$this->delimiter.$n1] = 1;
}
}
}
}
$this->arTime = $this->stopTimer($this->arTime);
return $this->rules = $result;
}
public function printFreqItemsets()
{
echo 'Time: '.$this->fiTime.' second(s)<br />===============================================================================<br />';
foreach($this->freqItmsts as $k => $v)
{
$tmp = '';
$tmp1 = '';
$k = explode($this->delimiter, $k);
$num = count($k);
for($i=0; $i<$num; $i++)
{
if($i)
{
$tmp .= $this->delimiter.$this->realName($k[$i]);
$tmp1 .= $this->delimiter.$k[$i];
}
else
{
$tmp = $this->realName($k[$i]);
$tmp1 = $k[$i];
}
}
echo '{'.$tmp.'} = '.$this->allsups[$tmp1].'<br />';
}
}
public function saveFreqItemsets($filename)
{
$content = '';
foreach($this->freqItmsts as $k => $v)
{
$tmp = '';
$tmp1 = '';
$k = explode($this->delimiter, $k);
$num = count($k);
for($i=0; $i<$num; $i++)
{
if($i)
{
$tmp .= $this->delimiter.$this->realName($k[$i]);
$tmp1 .= $this->delimiter.$k[$i];
}
else
{
$tmp = $this->realName($k[$i]);
$tmp1 = $k[$i];
}
}
$content .= '{'.$tmp.'} = '.$this->allsups[$tmp1]."\n";
}
file_put_contents($filename, $content);
}
public function getFreqItemsets()
{
$result = array();
foreach($this->freqItmsts as $k => $v)
{
$tmp = array();
$tmp['sup'] = $this->allsups[$k];
$k = explode($this->delimiter, $k);
$num = count($k);
for($i=0; $i<$num; $i++)
{
$tmp[] = $this->realName($k[$i]);
}
$result[] = $tmp;
}
return $result;
}
public function printAssociationRules()
{
echo 'Time: '.$this->arTime.' second(s)<br />===============================================================================<br />';
foreach($this->rules as $a => $arr)
{
foreach($arr as $b => $conf)
{
echo "$a => $b = $conf%<br />";
}
}
}
public function saveAssociationRules($filename)
{
$content = '';
foreach($this->rules as $a => $arr)
{
foreach($arr as $b => $conf)
{
$content .= "$a => $b = $conf%\n";
}
}
file_put_contents($filename, $content);
}
public function getAssociationRules()
{
return $this->rules;
}
private function startTimer()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
private function stopTimer($start, $round=2)
{
$endtime = $this->startTimer()-$start;
$round = pow(10, $round);
return round($endtime*$round)/$round;
}} ?>
my welcome controller (welcome.php)
class Welcome extends CI_Controller {
function __construct() {
parent::__construct();
include 'class.apriori.php';
}
// input page
public function index() {
$this->load->view('welcome_message');
}
// minSup, minConf, maxScan value as input
public function ambilinput() {
$minSup = $this->input->post('minSup', true);
$minConf = $this->input->post('minConf', true);
$maxScan = $this->input->post('maxScan', true);
redirect("welcome/apriori/$minSup/$minConf/$maxScan");
}
//APRIORI on system
public function apriori($minSup, $minConf, $maxScan) {
$Apriori = new Apriori();
$Apriori->setMaxScan($maxScan);
$Apriori->setMinSup($minSup);
$Apriori->setMinConf($minConf);
$Apriori->setDelimiter(',');
$dataset = array();
$dataset[] = array('A', 'B', 'C', 'D');
$dataset[] = array('A', 'D', 'C');
$dataset[] = array('B', 'C');
$dataset[] = array('A', 'E', 'C');
$Apriori->process($dataset);
echo '<h1>Frequent Itemsets</h1>';
$Apriori->printFreqItemsets();
echo '<h3>Frequent Itemsets Array</h3>';
print_r($Apriori->getFreqItemsets());
//Association Rules
echo '<h1>Association Rules</h1>';
$Apriori->printAssociationRules();
echo '<h3>Association Rules Array</h3>';
print_r($Apriori->getAssociationRules());
}
}
my view file to input minsup, minconf, and maxScan value
(welcome_message.php)
<head>
<meta charset="utf-8">
<title>Input 1</title>
</head>
<body>
<div>
<form action="<?php echo base_url(); ?>index.php/welcome/ambilinput" method="post">
<input type="number" name="minSup" placeholder="Minimal Support dalam %"/></br></br>
<input type="number" name="minConf" placeholder="Minimal Coff dalam %"/></br></br>
<input type="number" name="maxScan" placeholder="Jumlah Transaksi"/></br></br>
<button type="submit" name="submit">Hitung Apriori</button>
</form>
</div>
</body>

Related

Add element to listnode in PHP

If i have a listnode with the following defination
class ListNode {
public $val = 0;
public $next = null;
function __construct($val = 0, $next = null) {
$this->val = $val;
$this->next = $next;
}
}
How can i add an element to the end of the listnode and thus add int[i] elements by interation?
class ListNode {
public int $val = 0;
public ?ListNode $next = null;
function __construct(?int $val = 0, ?ListNode $next = null) {
$this->val = $val;
$this->next = $next;
}
function appendToListEnd(int $val) {
if ($this->next == null) {
$this->next = new ListNode($val);
} else {
$temp = $this->next;
while ($temp->next != null) {
$temp = $temp->next;
}
$temp->next = new ListNode($val);
}
}
}
$arr = [ 1, 2, 3, 4 ];
$listHead = new ListNode($arr[0]);
for ($i = 1; $i < count($arr); $i++) {
$listHead->appendToListEnd($arr[$i]);
}
print_r($listHead);
$listHead->appendToListEnd(5);
print_r($listHead);

Printing prime numbers from an user's input php

I'm trying ta make a program that will ask the user for a number and then show all the prime numbers between 0 to this number in an array.
<?php
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
/* YOUR CODE HERE */
function isPrime($n)
{
if ($n <= 1)
return false;
for ($i = 2; $i < $n; $i++)
if ($n % $i == 0)
return false;
return true;
}
function printPrime($n)
{
for ($i = 2; $i <= $n; $i++)
{
if (isPrime($i))
echo $i . " ";
}
}
$n = 7;
printPrime($n);
/*end of your code here */
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}
}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
This code work, but with a $n fixed.
I don't know how to use an input who ask the user a number
It's a code who verify itself and show us when it's ok
The code that i have to complete is this one (we only have this at first):
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
/* YOUR CODE HERE */
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}
}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
This is your script:
<?php
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
function isPrime($n) {
if ($n <= 1) return false;
for ($i = 2; $i < $n; $i++) if ($n % $i == 0) return false;
return true;
}
function printPrime($n) {
for ($i = 2; $i < $n; $i++) if (isPrime($i)) $result[] = $i;
return $result;
}
$result = printPrime($smaller_than);
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
function getSmallerPrimes($smaller_than) {
if ($smaller_than <= 2) {
return [];
}
$result = [2];
$sqrt = sqrt($smaller_than);
for ($n = 3; $n < $smaller_than; $n += 2) {
$isPrime = true;
foreach($result as $prime) {
if ($n % $prime == 0) {
$isPrime = false;
break;
}
if ($prime > $sqrt) {
break;
}
}
if ($isPrime) {
$result[] = $n;
}
}
return $result;
}
$input = 23;
echo implode(' ', getSmallerPrimes($input));
Result: 2 3 5 7 11 13 17 19

base64 in PHP Otp Library

I trying to make some simple library for encrypting files in PHP with OTP method. My problem is that some chars in decrypted code are different than original. I worked on it almost one week but without result. Is there problem with base64 chars or with encoding/decoding mechanism ?
Many thanks for the answers.
final class Otp
{
private static $charSet = array('+','/','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z');
public static function encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath)
{
if(!self::existsFile($keyFilePath) || !self::existsFile($encryptedFilePath)) {
if($originalFileData = self::existsFile($originalFilePath)) {
$originalFileBase64Data = base64_encode($originalFileData);
$originalFileBase64DataLength = strlen($originalFileBase64Data) - 1;
$originalFileBase64DataArray = str_split($originalFileBase64Data);
$encryptedData = NULL;
$encryptedDataKey = NULL;
for ($i = 0; $i <= $originalFileBase64DataLength; $i++) {
$randKey = rand(0, sizeOf(self::$charSet) - 1);
$arrayKey = array_search($originalFileBase64DataArray[$i], self::$charSet);
if($randKey > $arrayKey) {
$str = '-' . ($randKey - $arrayKey);
} elseif($randKey < $arrayKey) {
$str = ($randKey + $arrayKey);
} else {
$str = $randKey;
}
$encryptedData .= self::$charSet[$randKey];
$encryptedDataKey .= $str. ';';
}
$encryptedDataString = $encryptedData;
$encryptedDataKeyString = $encryptedDataKey;
if(!self::existsFile($keyFilePath)) {
file_put_contents($keyFilePath, $encryptedDataKeyString);
}
if(!self::existsFile($encryptedFilePath)) {
file_put_contents($encryptedFilePath, $encryptedDataString);
}
return 'OK';
} else {
return 'Source file not exists';
}
} else {
return 'Encrypted data already exists';
}
}
public static function decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath)
{
$keyFileData = self::existsFile($keyFilePath);
$encryptedFileData = self::existsFile($encryptedFilePath);
$encryptedFileDataLength = strlen($encryptedFileData) - 1;
if($encryptedFileData && $keyFileData) {
$encryptedFileDataArray = str_split($encryptedFileData);
$keyFileDataArray = explode(';', $keyFileData);
$decryptedData = NULL;
for ($i = 0; $i <= $encryptedFileDataLength; $i++) {
$poziciaaktualneho = array_search($encryptedFileDataArray[$i], self::$charSet);
$poziciasifrovana = $keyFileDataArray[$i];
if($poziciasifrovana < 0) {
$move = $poziciasifrovana + $poziciaaktualneho;
} elseif($poziciasifrovana > 0) {
$move = $poziciasifrovana - $poziciaaktualneho;
} else {
$move = '0';
}
$decryptedData .= self::$charSet[$move];
}
if(!self::existsFile($decryptedFilePath)) {
file_put_contents($decryptedFilePath, base64_decode($decryptedData));
return 'OK';
} else {
return 'Decrypted data already exists';
}
}
}
private static function existsFile($filePath)
{
$fileData = #file_get_contents($filePath);
if($fileData) {
return $fileData;
}
return FALSE;
}
}
$originalFilePath = 'original.jpg';
$keyFilePath = 'Otp_Key_' . $originalFilePath;
$encryptedFilePath = 'Otp_Data_' . $originalFilePath;
$decryptedFilePath = 'Otp_Decrypted_' . $originalFilePath;
echo Otp::encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath);
echo Otp::decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath);
The problem seems to be only happening when $poziciaaktualneho is equal to $poziciasifrovana and so by adding another if statement on line 78 to check for this and instead set $move equal to $poziciasifrovana I was able to fix the problem. The below script should work:
final class Otp
{
private static $charSet = array('+','/','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z');
public static function encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath)
{
if(!self::existsFile($keyFilePath) || !self::existsFile($encryptedFilePath)) {
if($originalFileData = self::existsFile($originalFilePath)) {
$originalFileBase64Data = base64_encode($originalFileData);
$originalFileBase64DataLength = strlen($originalFileBase64Data) - 1;
$originalFileBase64DataArray = str_split($originalFileBase64Data);
$encryptedData = NULL;
$encryptedDataKey = NULL;
for ($i = 0; $i <= $originalFileBase64DataLength; $i++) {
$randKey = rand(0, sizeOf(self::$charSet) - 1);
$arrayKey = array_search($originalFileBase64DataArray[$i], self::$charSet);
if($randKey > $arrayKey) {
$str = '-' . ($randKey - $arrayKey);
} elseif($randKey < $arrayKey) {
$str = ($randKey + $arrayKey);
} else {
$str = $randKey;
}
$encryptedData .= self::$charSet[$randKey];
$encryptedDataKey .= $str. ';';
}
$encryptedDataString = $encryptedData;
$encryptedDataKeyString = $encryptedDataKey;
if(!self::existsFile($keyFilePath)) {
file_put_contents($keyFilePath, $encryptedDataKeyString);
}
if(!self::existsFile($encryptedFilePath)) {
file_put_contents($encryptedFilePath, $encryptedDataString);
}
return 'OK';
} else {
return 'Source file not exists';
}
} else {
return 'Encrypted data already exists';
}
}
public static function decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath)
{
$keyFileData = self::existsFile($keyFilePath);
$encryptedFileData = self::existsFile($encryptedFilePath);
$encryptedFileDataLength = strlen($encryptedFileData) - 1;
if($encryptedFileData && $keyFileData) {
$encryptedFileDataArray = str_split($encryptedFileData);
$keyFileDataArray = explode(';', $keyFileData);
$decryptedData = NULL;
for ($i = 0; $i <= $encryptedFileDataLength; $i++) {
$poziciaaktualneho = array_search($encryptedFileDataArray[$i], self::$charSet);
$poziciasifrovana = $keyFileDataArray[$i];
if ($poziciasifrovana == $poziciaaktualneho) {
$move = $poziciasifrovana;
} elseif($poziciasifrovana < 0) {
$move = $poziciasifrovana + $poziciaaktualneho;
} elseif($poziciasifrovana > 0) {
$move = $poziciasifrovana - $poziciaaktualneho;
} else {
$move = '0';
}
$decryptedData .= self::$charSet[$move];
}
if(!self::existsFile($decryptedFilePath)) {
file_put_contents($decryptedFilePath, base64_decode($decryptedData));
return 'OK';
} else {
return 'Decrypted data already exists';
}
}
}
private static function existsFile($filePath)
{
$fileData = #file_get_contents($filePath);
if($fileData) {
return $fileData;
}
return FALSE;
}
}
$originalFilePath = 'original.jpg';
$keyFilePath = 'Otp_Key_' . $originalFilePath;
$encryptedFilePath = 'Otp_Data_' . $originalFilePath;
$decryptedFilePath = 'Otp_Decrypted_' . $originalFilePath;
echo Otp::encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath);
echo Otp::decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath);
Warning: I would not recommend using my solution in an enterprise setting if at all since I do not know why this fixes your script or what was
originally wrong with it and it is most likely not air tight.

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

Include these methods into my class

These are my two methods, I need to include them in my class but am unsure how to do it since I'm not an OO programmer
function gcd($x,$y)
{
do {
$rest=$x%$y;
$x=$y;
$y=$rest;
} while($rest!==0);
return $x;
}
function testCommonality($a)
{
$keys = array_keys($a[1]);
$common = array();
foreach ($keys as $key) {
$v1 = $a[0][$key];
$v2 = $a[1][$key];
if ((gcd($v1, $v2)) != 1) $a[0]['m'] *= 1.5;
}
return $a;
}
print_r($parser->algorithm->testCommonality());
I need to include those in this class, and have them operate on the output of $parser->algorithm Help is greatly GREATLY appreciated
class CSVParser
{
public $output = NULL;
public $digits = NULL;
public function __construct($file)
{
if (!file_exists($file)) {
throw new Exception("$file does not exist");
}
$this->contents = file_get_contents($file);
$this->output = array();
$this->digits = array();
}
public function parse($separatorChar1 = ',', $separatorChar2 = ';', $enclosureChar = '"', $newlineChar = "\n")
{
$lines = explode($newlineChar, $this->contents);
foreach ($lines as $line) {
if (strlen($line) == 0) continue;
$group = array();
list($part1, $part2) = explode($separatorChar2, $line);
$group[] = array_map(array($this, "trim_value"), explode($separatorChar1, $part1), array("$enclosureChar \t"));
$group[] = array_map(array($this, "trim_value"), explode($separatorChar1, $part2), array("$enclosureChar \t"));
$this->output[] = $group;
}
}
private function trim_value($value, $chars)
{
return preg_replace("#^( |" . $chars . ")+#", '', $value);
}
public function algorithm()
{
$alpha = array(
'c' => str_split('bcdfghjklmnpqrstvwxz'),
'v' => str_split('aeiouy')
);
$i = 0;
$k = 0;
foreach ($this->output as $item) {
$cnt = 0;
$this->digits[$i] = array();
foreach ($item as $part) {
$this->digits[$i][$cnt] = array();
$new = array();
foreach ($part as $str) {
$v = count(array_intersect(str_split($str), $alpha['v']));
$c = count(array_intersect(str_split($str), $alpha['c']));
$t = strlen(str_replace(' ', '', $str));
$new = array('v' => $v, 'c' => $c, 't' => $t);
$this->digits[$i][$cnt][] = $new;
}
$cnt++;
}
$i++;
}
}
}
$parser = new CSVParser("file.txt");
$parser->parse();
print_r($parser->output);
$parser->algorithm();
print_r($parser->digits);
Thanks for the help!
I know very little of PHP, but, if I understand correctly, what you are asking appears to be straight forward enough. I would have thought somebody would have already answered this.
The following may be something like what you are after:
class CSVParser
{
public $output = NULL;
public $digits = NULL;
public function __construct($file)
{
if (!file_exists($file)) {
throw new Exception("$file does not exist");
}
$this->contents = file_get_contents($file);
$this->output = array();
$this->digits = array();
}
public function parse($separatorChar1 = ',', $separatorChar2 = ';', $enclosureChar = '"', $newlineChar = "\n")
{
$lines = explode($newlineChar, $this->contents);
foreach ($lines as $line) {
if (strlen($line) == 0) continue;
$group = array();
list($part1, $part2) = explode($separatorChar2, $line);
$group[] = array_map(array($this, "trim_value"), explode($separatorChar1, $part1), array("$enclosureChar \t"));
$group[] = array_map(array($this, "trim_value"), explode($separatorChar1, $part2), array("$enclosureChar \t"));
$this->output[] = $group;
}
}
private function trim_value($value, $chars)
{
return preg_replace("#^( |" . $chars . ")+#", '', $value);
}
public function algorithm()
{
$alpha = array(
'c' => str_split('bcdfghjklmnpqrstvwxz'),
'v' => str_split('aeiouy')
);
$i = 0;
$k = 0;
foreach ($this->output as $item) {
$cnt = 0;
$this->digits[$i] = array();
foreach ($item as $part) {
$this->digits[$i][$cnt] = array();
$new = array();
foreach ($part as $str) {
$v = count(array_intersect(str_split($str), $alpha['v']));
$c = count(array_intersect(str_split($str), $alpha['c']));
$t = strlen(str_replace(' ', '', $str));
$new = array('v' => $v, 'c' => $c, 't' => $t);
$this->digits[$i][$cnt][] = $new;
}
$cnt++;
}
$i++;
}
return $this->digits;
}
private function gcd($x,$y)
{
do {
$rest=$x%$y;
$x=$y;
$y=$rest;
} while($rest!==0);
return $x;
}
public function testCommonality($a)
{
$keys = array_keys($a[1]);
$common = array();
foreach ($keys as $key) {
$v1 = $a[0][$key];
$v2 = $a[1][$key];
if ((gcd($v1, $v2)) != 1) $a[0]['m'] *= 1.5;
}
return $a;
}
}
$parser = new CSVParser("file.txt");
$parser->parse();
print_r($parser->output);
$parser->algorithm();
print_r($parser->digits);
print_r( $parser->testCommonality( $parser->digits() ) );
`

Categories