Add element to listnode in PHP - 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);

Related

Error when printing how many levels are visible in tree in PHP

I am receiving the error "Using $this when not in object context". I think I might be using the class node incorrectly. I cannot figure out where I am going wrong at this point.
I am trying to get the answer 4 in the case of a tree like the below. This is because there are 4 visible layers.
$root = new TreeNode(8);
$root->left = new TreeNode(3);
$root->right = new TreeNode(10);
$root->left->left = new TreeNode(1);
$root->left->right = new TreeNode(6);
$root->left->right->left = new TreeNode(4);
$root->left->right->right = new TreeNode(7);
$root->right->right = new TreeNode(14);
$root->right->right->left = new TreeNode(13);
class TreeNode{
public $val;
public $left;
public $right;
public function __construct($val=0) {
$this->val = $val;
$this->left = NULL;
$this->right = NULL;
}
}
function findLeft($root){
$queue = $root;
while(!empty($queue)){
$size = sizeof($queue);
$i = 0;
$answer = 0;
while($i<$size){
$i= $i+1;
//if first node print
if ($i == 1){
$answer += 1;
}
if($this->left){
array_push($queue, $this->left);
}
if($this->right){
array_push($queue, $this->right);
}
array_unshift($queue); //shift first item
}
} return $queue;
}
//calling function
function visibleNodes($root) {
// Write your code here
if(empty($root)){
return 0;
} else {
$answer = findLeft($root);
}
return $answer;
}

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

Pass $sSymbol an input parameter to a Class

I got this class code from https://github.com/ricardotiago/sec-gov-api, which is used to retrieve and parse quarterly and yearly reports from the U.S Securities Exchange website.I do not understand how to print the results and what sort of parameters it's accepts. Is$sSmbol an input parameter, how do I pass this parameter so that it displays the quarterly and yearly report
<?php
require_once "parallelCurl.php";
class SecGovAPI {
const SEARCH_LINK = "http://www.sec.gov/cgi-bin/browse-edgar";
const BASE_LINK = "http://www.sec.gov/";
const QUARTERLY_REPORT = '10-Q';
const YEARLY_REPORT = '10-K';
const MOST_RECENT_REPORT = 0;
const ALL_REPORTS = 1;
public function __construct($sSymbol) {
$this->oParallelCurl = new ParallelCurl();
$this->sSymbol = $sSymbol;
$this->oDoc = new DOMDocument();
$this->report = array();
}
public function getQuaterlyReport($iSearchType = SecGovAPI::MOST_RECENT_REPORT) {
if ($iSearchType !== SecGovAPI::MOST_RECENT_REPORT && $iSearchType !== SecGovAPI::ALL_REPORTS) {
return array();
}
$aReportLinks = $this->search(SecGovAPI::QUARTERLY_REPORT, $iSearchType);
var_dump($aReportLinks);
foreach ($aReportLinks as $link) {
$this->oParallelCurl->addUrl(SecGovAPI::BASE_LINK."/".$link);
}
$aData = $this->oParallelCurl->run();
foreach ($aData as $link => $xml) {
$this->oDoc->loadXML($xml);
$oXPath = new DOMXPath($this->oDoc);
$oXPath->registerNamespace("xbrli", "http://www.xbrl.org/2003/instance");
$this->getReportData($oXPath, $link, "dei:EntityCommonStockSharesOutstanding", "CommonStockSharesOutstanding");
$this->getReportData($oXPath, $link, "us-gaap:NetIncomeLoss", "NetIncomeLoss");
}
var_dump($this->report);
}
public function getYearlyReport($iSearchType = SecGovAPI::MOST_RECENT_REPORT) {
if ($iSearchType !== SecGovAPI::MOST_RECENT_REPORT && $iSearchType !== SecGovAPI::ALL_REPORTS) {
return array();
}
$aReportLinks = $this->search(SecGovAPI::YEARLY_REPORT, $iSearchType);
var_dump($aReportLinks);
foreach ($aReportLinks as $link) {
$this->oParallelCurl->addUrl(SecGovAPI::BASE_LINK."/".$link);
}
$aData = $this->oParallelCurl->run();
foreach ($aData as $link => $xml) {
$this->oDoc->loadXML($xml);
$oXPath = new DOMXPath($this->oDoc);
$oXPath->registerNamespace("xbrli", "http://www.xbrl.org/2003/instance");
$this->getReportData($oXPath, $link, "dei:EntityCommonStockSharesOutstanding", "CommonStockSharesOutstanding");
$this->getReportData($oXPath, $link, "us-gaap:NetIncomeLoss", "NetIncomeLoss");
}
var_dump($this->report);
}
public function getReportData($oXPath, $link, $sEntity, $sSaveAs) {
$oNodelist = $oXPath->query("//xbrli:xbrl/".$sEntity);
for ($i = 0; $i < $oNodelist->length; $i++) {
$this->report[$link][$sSaveAs][$i] = $oNodelist->item($i)->nodeValue;
}
}
protected function search($sType, $iSearchType) {
$aParams = array("company" => "",
"match" => "",
"CIK" => $this->sSymbol,
"filenum" => "",
"State" => "",
"Country" => "",
"SIC" => "",
"count" => "40",
"owner" => "exclude",
"Find" => "Find Companies",
"action" => "getcompany",
"type" => $sType,
"output" => "atom");
$sUrl = SecGovAPI::SEARCH_LINK . "?". http_build_query($aParams);
$this->oDoc->load($sUrl);
$oXPath = new DOMXPath($this->oDoc);
$oXPath->registerNamespace("atom", "http://www.w3.org/2005/Atom");
$aLinks = $this->getReportLinks($oXPath, $iSearchType);
$aReportLinks = array();
foreach ($aLinks as $link) {
$this->oParallelCurl->addUrl($link);
}
$aHtmls = $this->oParallelCurl->run();
foreach ($aHtmls as $html) {
$this->oDoc->loadHTML($html);
$oXPath = new DOMXPath($this->oDoc);
$oNodeList = $oXPath->query('//table[#summary="Data Files"]/tr[2]/td[3]/a');
if ($oNodeList->length === 0) continue;
$aReportLinks[] = $oNodeList->item(0)->getAttribute("href");
}
return $aReportLinks;
}
protected function getReportLinks($oXPath, $iSearchType) {
if ($iSearchType === SecGovAPI::MOST_RECENT_REPORT) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry[1]/atom:link");
if ($aNodeList->length === 1)
return array($aNodeList->item(0)->getAttribute("href"));
else
return null;
}
else if ($iSearchType === SecGovAPI::ALL_REPORTS) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry/atom:link");
for ($i = 0; $i < $aNodeList->length; $i++) {
$aReportLinks[] = $aNodeList->item($i)->getAttribute("href");
}
return $aReportLinks;
}
else return null;
}
protected function getAccessionNumber($oXPath, $iSearchType) {
if ($iSearchType === SecGovAPI::MOST_RECENT_REPORT) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry[1]/atom:id");
if ($aNodeList->length === 1) $sRawAccessNumber = $aNodeList->item(0)->nodeValue;
else return null;
return $this->processAccessionNumber($sRawAccessNumber);
}
else if ($iSearchType === SecGovAPI::ALL_REPORTS) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry/atom:id");
for ($i = 0; $i < $aNodeList->length; $i++) {
$sRawAccessNumber = $aNodeList->item($i)->nodeValue;
$aAccessionNumber[] = $this->processAccessionNumber($sRawAccessNumber);
}
return $aAccessionNumber;
}
else return null;
}
protected function processAccessionNumber($sRawAccessNumber) {
$aSplitData = preg_split('/accession-number=/', $sRawAccessNumber);
if (!isset($aSplitData[1])) return null;
$sAccessionNumber = str_replace('-','', $aSplitData[1]);
return $sAccessionNumber;
}
protected function getReportDate($oXPath, $iSearchType) {
if ($iSearchType === SecGovAPI::MOST_RECENT_REPORT) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry[1]/atom:updated");
if ($aNodeList->length === 1)
return $sUpdated = $aNodeList->item(0)->nodeValue;
else
return null;
}
else if ($iSearchType === SecGovAPI::ALL_REPORTS) {
$aNodeList = $oXPath->query("//atom:feed/atom:entry/atom:updated");
for ($i = 0; $i < $aNodeList->length; $i++) {
$aUpdated[] = $aNodeList->item($i)->nodeValue;
}
return $aUpdated;
}
else return null;
}
}
?>
parallelCurl.php
<?php
class ParallelCurl {
protected $aHandlers;
public function __construct() {
$this->aHandlers = array();
$this->rMultiHandler = curl_multi_init();
}
public function addUrl($sUrl) {
$rHandler = curl_init();
curl_setopt($rHandler, CURLOPT_URL, $sUrl);
curl_setopt($rHandler, CURLOPT_HEADER, 0);
curl_setopt($rHandler, CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($this->rMultiHandler, $rHandler);
$this->aHandlers[$sUrl] = $rHandler;
}
public function run() {
$blsRunning = null;
do {
$rHandler = curl_multi_exec($this->rMultiHandler, $blsRunning);
} while ($rHandler === CURLM_CALL_MULTI_PERFORM);
while ($blsRunning && $rHandler == CURLM_OK) {
if (curl_multi_select($this->rMultiHandler) != -1) {
do {
$rHandler = curl_multi_exec($this->rMultiHandler, $blsRunning);
} while ($rHandler == CURLM_CALL_MULTI_PERFORM);
}
}
foreach ($this->aHandlers as $url => $handler) {
$data[$url] = curl_multi_getcontent($handler);
curl_multi_remove_handle($this->rMultiHandler, $handler);
}
$this->aHandlers = array();
return $data;
}
public function __destruct() {
curl_multi_close($this->rMultiHandler);
}
}
?>
To create an instance of the SecGovAPI class you can use the new keyword:
$class = new SecGovAPI($sSymbol);
then you can call the methods getQuaterlyReport and getYearlyReport with:
echo $class->getQuaterlyReport();
echo $class->getYearlyReport();
Both these methods has an argument, and by default is SecGovAPI::MOST_RECENT_REPORT. You can also use:
SecGovAPI::QUARTERLY_REPORT
SecGovAPI::YEARLY_REPORT
SecGovAPI::ALL_REPORTS
Example:
echo $class->getQuaterlyReport(SecGovAPI::QUARTERLY_REPORT);

apply apriori php to CI

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>

Optimizing Trie implementation

For no reason other than fun I implemented a Trie today. At the moment it supports add() and search(), remove() should also be implemented but I think that's fairly straight forward.
It is fully functional, but filling the Trie with data takes a little too much for my taste. I'm using this list as datasource: http://www.isc.ro/lists/twl06.zip (found somewhere else on SO). It takes ~11s to load. My initial implementation took ~15s so I already gave it a nice performance boost, but I'm still not satisfied :)
My question is: what else could give me a (substantial) performance boost? I'm not bound by this design, a complete overhaul is acceptable.
class Trie
{
private $trie;
public function __construct(TrieNode $trie = null)
{
if($trie !== null) $this->trie = $trie;
else $this->trie = new TrieNode();
$this->counter = 0;
}
public function add($value, $val = null)
{
$str = '';
$trie_ref = $this->trie;
foreach(str_split($value) as $char)
{
$str .= $char;
$trie_ref = $trie_ref->addNode($str);
}
$trie_ref->value = $val;
return true;
}
public function search($value, $only_words = false)
{
if($value === '') return $this->trie;
$trie_ref = $this->trie;
$str = '';
foreach(str_split($value) as $char)
{
$str .= $char;
if($trie_ref = $trie_ref->getNode($str))
{
if($str === $value) return ($only_words ? $this->extractWords($trie_ref) : new self($trie_ref));
continue;
}
return false;
}
return false;
}
public function extractWords(TrieNode $trie)
{
$res = array();
foreach($trie->getChildren() as $child)
{
if($child->value !== null) $res[] = $child->value;
if($child->hasChildren()) $res = array_merge($res, $this->extractWords($child));
}
return $res;
}
}
class TrieNode
{
public $value;
protected $children = array();
public function addNode($index)
{
if(isset($this->children[$index])) return $this->children[$index];
return $this->children[$index] = new self();
}
public function getNode($index)
{
return (isset($this->children[$index]) ? $this->children[$index] : false);
}
public function getChildren()
{
return $this->children;
}
public function hasChildren()
{
return count($this->children)>0;
}
}
Don't know php but,
in the following methods:
public function add($value, $val = null)
{
$str = '';
$trie_ref = $this->trie;
foreach(str_split($value) as $char)
{
$str .= $char;
$trie_ref = $trie_ref->addNode($str);
}
$trie_ref->value = $val;
return true;
}
public function search($value, $only_words = false)
{
if($value === '') return $this->trie;
$trie_ref = $this->trie;
$str = '';
foreach(str_split($value) as $char)
{
$str .= $char;
if($trie_ref = $trie_ref->getNode($str))
{
if($str === $value) return ($only_words ? $this->extractWords($trie_ref) : new self($trie_ref));
continue;
}
return false;
}
return false;
}
Why do you even need the $str .= $char (which I suppose is append)? This itself changes your O(n) time addition/searching to Omega(n^2) (n is length of $value) instead of O(n).
In a trie, you usually walk the trie while walking the string i.e you find the next node based on the current character, rather than the current prefix.
I suppose this implementation is for a Key|value type of insertion and lookup? Here is one that handles [English] words.
class Trie {
static function insert_word(Node $root, $text)
{
$v = $root;
foreach(str_split($text) as $char) {
$next = $v->children[$char];
if ($next === null)
{
$v->children[$char] = $next = new Node();
}
$v = $next;
}
$v->leaf = true;
}
static function get_words_sorted(Node $node, $text)
{
$res = array();
for($ch = 0; $ch < 128; $ch++) {
$child = $node->children[chr($ch)];
if ($child !== null)
{
$res = array_merge($res, Trie::get_words_sorted($child, $text . chr($ch)));
}
}
if ($node->leaf === true)
{
$res[] = $text;
}
return $res;
}
static function search(Node $root, $text)
{
$v = $root;
while($v !== null)
{
foreach(str_split($text) as $char) {
$next = $v->children[$char];
if ($next === null)
{
return false;
}
else
{
$v = $next;
}
}
if($v->leaf === true)
{
return true;
}
else
{
return false;
}
}
return false;
}
}
class Node {
public $children;
public $leaf;
function __construct()
{
$children = Array();
}
}
Example usage
$root = new Node();
$words = Array("an", "ant", "all", "allot", "alloy", "aloe", "are", "ate", "be");
for ($i = 0; $i < sizeof($words); $i++)
{
Trie::insert_word($root, $words[$i]);
}
$search_words = array("alloy", "ant", "bee", "aren't", "allot");
foreach($search_words as $word)
{
if(Trie::search($root, $word) === true)
{
echo $word . " IS in my dictionary<br/>";
}
else
{
echo $word . " is NOT in my dictionary <br/>";
}
}

Categories