Jump to content

rwhite35

Members
  • Posts

    159
  • Joined

  • Last visited

Everything posted by rwhite35

  1. Yes that could be the case. I don't think there is a right or wrong answer per se' and I'm really doing this for my own "enjoyment" and education. But yes, some sort of search mechanism could potentially be another solution. The book is the Wrox Programmer to Programmer series and titled Programming Interviews Exposed. It doesn't really give any hard solution to the problems it poses, just boundaries and general direction.
  2. Thanks for the feedback. I'll work in the direction of your second pseudocode ( O(log m) ). That seems more intuitive then what I was proposing. Appreciate the feedback, that's a big help.
  3. Reading a CompSci book and it gives problems requiring algorithms WITHOUT the use of (lang.) build in function. In the following problem, the process should remove characters in a string using a set of target characters. It should be able to do this in one pass - or O(n). According to the book, there is a solution - though I'm skeptical and the book is using Java. The following function employs PHP built in functions and works as required, in one pass. function removeWithBuiltin($string,$chr,$replacement) { foreach($chr as $v) { // O(1) $part = $v."|"; $pattern = $pattern . $part; // example a|k|e|x } $pattern = rtrim( $pattern, "|" ); //trim off last vertical bar $pattern = "/".$pattern."/"; $string = preg_filter($pattern, $replacement, $string); // O(1) var_dump($string); } The following class is functionally the same as the above. It returns the same string as removeWithBuiltin(). class stringEditor { public $inputStr; // string to edit public $newStr; // string to return public $rmSet; // array, unknown set of characters to remove public function __construct($str,$rArr) { $this->inputStr = $str; $this->rmSet = $rArr; } /* * removeChar loops through input array and compares each remove target character to its value, * if value and target are equal, assign null to buffer; else assign value to buffer * return array $buffer, processed input characters minus this removed character target (if any) */ protected function removeChar($strArr,$chr) { $buffer = array(); $cnt = count($strArr); for( $i=0; $i<$cnt; $i++ ) { // eval each character, highest term O($i) $buffer[$i] = ( $strArr[$i] == $chr ) ? null : $strArr[$i]; } if(!empty($buffer)) { return $buffer; } else { return $strArr; } } /* * converts input string to indexed array and calls an instance of * removeChar with string array and each character to search and replace with null value * return string $editString, input string without removed characters */ public function processString() { $strArray = str_split($this->inputStr); // convert string to array of chars foreach ($this->rmSet as $char) { // eval each character in the remove set $e=0; if (empty($this->newStr)) { // initial condition, $this->newStr doesnt exist $this->newStr[] = $this->removeChar($strArray, $char); } else { // now use previous and call removeChar, overloading 0 with each loop $this->newStr[0]= $this->removeChar($this->newStr[$e], $char); $e++; } } /* * flatten $this->newStr array object in to a string * prototype: array([0]=>array([0]=>char, [1]=>char, ... )) */ $array = $this->newStr[0]; // overloaded all previous edits for($i=0; $i<count($array); $i++) { $editString = $editString . $array[$i]; } if(isset($editString) && !empty($editString)) {return $editString;} else {return false;} } } // close class This class takes "n" number of characters to remove characters from a given string "t" characters long. So its notation should be O(log n^t); or possible O(n * t), but not O(n). And finally, here is the questions: Any thoughts on how this class could be modified to only loop over the input string - once - removing an unspecified set of characters? Here is the test parameters: $randomString = "bucked the science from popular"; $chars = [ "a", "k", "e", "x" ]; $removeObj = new stringEditor( $randomString, $chars ); $results = $removeObj->processString(); echo $results; // outputs bucd th scinc from populr Some direction on how to improve the performance of the class would be appreciated.
  4. Thanks for the reply. Been busy. I do use Composer for some projects, mainly ZendFramework projects. But wanted something light weight and simple to configure for my own projects. Appreciate the feedback, thanks.
  5. Some general comments. M-V-C is ideal in team situations where you have multiple developers working on a similar problem. Also, when building a framework or API where you plan to give other scripts or users access to certain features/functions. In either instance, its very helpful when the code has strict adherence to the M-V-C paradigm. If this is your own application and you don't expect to have other interact with your code, then having lax adherence (ie Service Layer) to M-V-C is personal preference. As for the script block above, it's hard (for me at least as an "outsider") to tell what's going on without see the implementation and/or application structure. But if I were trying to explain M-V-C to someone, I would use the following scenario. It helps to think about such abstractions in real world terms. SCENARIO: Web user rents linens for her restaurant through a website. She logs into the ordering system and is presented with a catalog of linens. The system defines a default behavior which is to present a catalog of linens (including her previous order). The model first checked to determine if she was authorized to view the catalog. Once satisfied, the model pulls all the relevant linen data; and her last purchase order. The model returns raw data objects to the controller. The controller takes the raw data and processes the information in to formatted data objects. The controller applies filtering rules based on her ordering preferences and other routine functions. The data is stored in transport objects passed to the viewer for output. The viewer creates an instance of the data objects through an interface method (typically defined in the controller) and outputs the result into document objects (DOM) ie product info with an images in some container element. ./catalog.php |_ catalog/src/cat_viewer.php |_ catalog/src/cat_controller.php (includes catalog/lib/cat_model.php) |_ database As both a PHP and Java developer, I find this structure to be the most common. I doubt this answers your question, but hopefully it give some feedback.
  6. Would like some thoughts about this autoloader for namespaces. Its loosely based on Zend Framework 2 using Composer. I wanted a simple loader for including my custom classes(ie DB connection, list and forms generations etc) in application modules. Autoloader works as expected so no error to debug, but looking more for improvements or gotcha's I'm not aware of. This is pseudo code, but the machinery is what's important. ./controller_script.php /* initializes Autoload with an array of namespace strings */ include 'init_autoloader.php'; /* from testspaces.php */ echo Testspaces\Autoload\Tsclass::printSomething(); // outputs This is a simple string. /* from globalspaces.php */ echo Globalspaces\Autoload\Omnipresent::imEverywhere(); //outputs This is a good hand. ./init_autoloader.php /** * initialize the autoloader for namespaces under the lib directory. * this script would be placed in each module where global classes * were required, ie DB connections, UI output(lists and forms) */ /* namespaces array, namespace file name matches first part before first backslash */ $nsarray = array( 'Globalspaces\Autoload\Omnipresent', 'Testspaces\Autoload\Tsclass', ); /* initialize the AutoloaderInit class */ $apath = __DIR__ . "/lib/autoload.php"; if (file_exists($apath)) { include $apath; $loaderObj = new AutoloaderInit($nsarray); $loaderObj->getLoader(); } else { echo "Missing autoload.php script, check file path: ".$apath."<br>"; } lib/autoload.php class AutoloaderInit { private static $loader; private static $nsnames; // indexed array of namespace strings defined in init_autoloader public function __construct($nsarray) { self::$nsnames = $nsarray; } /* * callback function called by spl_autoload_register * $class passed by reference */ public static function loadClassLoader($class) { if ($class) { $nameparts = explode('\\', $class); $filename = strtolower($nameparts[0]).".php"; require __DIR__ . DIRECTORY_SEPARATOR . $filename; } else { throw new Exception("loadClassLoader failed to include ".$filename); } } /* * interface method called from initializer * $params array $nsnames, array of namespace strings * $return void */ public static function getLoader() { //error_log("getLoader nsnames: ".var_dump(self::$nsnames)); if (self::$nsnames) { $cnt = count(self::$nsnames); for($i=0;$i<=$cnt;$i++) { if (null !== self::$loader) return self::$loader; spl_autoload_register(array('AutoloaderInit', 'loadClassLoader'), true, true); self::$loader = $loader = new self::$nsnames[$i]; // new instance of class } // close for loop spl_autoload_unregister(array('AutoloaderInit', 'loadClassLoader')); return $loader; } else { error_log("No namespaces provided to getLoader"); } } } lib/testspace.php namespace Testspaces\Autoload; /* a class defined in namespace */ class Tsclass { static function printSomething() { echo "This is a simple string.<br>"; } } lib/globalspaces.php namespace Globalspaces\Autoload; /* another class defined in namespace */ class Omnipresent { static function imEverywhere() { echo "This is a good hand.<br>"; } }
  7. Okay, you could shorten the process with this modification. It only evaluates one element of the associative array. for ($i=0;$i>=count($Array);$i++) { // loop through indexed array $Url = ($Array[$i]['Purpose'] == $string) ? $Array[$i]['Uri'] : null; // assign url to variable if $string is thumbnail }
  8. First you have a multi-dimensional array, an array or arrays. In your case the first array is indexed. So you can deal with that array using a for loop. The array inside the indexed array is associative, so you can deal with that array using the foreach. Using for outer/inner looping construct: for ($i=0;$i>=count($Array);$i++) { // loop through each indexed array foreach ($Array[$i] as $key=>$value) { // loop through each associative array $Url = ($value == $string) ? $Array[$i]['Uri'] : null; // assign url to variable if $string is thumbnail } }
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.