Created
October 21, 2014 17:23
-
-
Save ermand/f6c7019d40a53701b3bd to your computer and use it in GitHub Desktop.
Perform minor calculations on large integer lists.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* A class for performing minor calculations on large integer lists. | |
*/ | |
class Main | |
{ | |
private $buffSize; | |
private $list; | |
/** | |
* Initiolize function. | |
* @param json $params | |
* @return boolean | |
*/ | |
public function __construct($params) | |
{ | |
echo "# Process started: " . date("m/d/Y h:i:s a", time()) . "\n"; | |
$result = json_decode($params); | |
$this->buffSize = $result->buff_size; | |
$this->list = explode(",", $this->clean($result->list)); | |
$this->calculate(); | |
echo "# Process finished: " . date("m/d/Y h:i:s a", time()) . "\n"; | |
return true; | |
} | |
/** | |
* Calculations on large integer lists | |
* | |
* @return array | |
*/ | |
private function calculate() | |
{ | |
$buffSize = $this->buffSize; | |
$list = $this->list; | |
$newArray = []; | |
for ($i=0; $i < sizeof($list); $i++) { | |
if ($i < $buffSize - 1) | |
{ | |
$newArray[$i] = intval($list[$i]); | |
} else | |
{ | |
$checkedArray = array_slice($list, $i + 1 - $buffSize, $buffSize); | |
$minMax = $this->minMax($checkedArray); | |
$min = $minMax[0]; | |
$max = $minMax[1]; | |
$newArray[$i] = $min + $max; | |
} | |
} | |
var_dump($newArray); | |
return $newArray; | |
} | |
/** | |
* Get min & max values from array. | |
* | |
* @param array $list | |
* @return array | |
*/ | |
private function minMax(array $list) { | |
if ($list == null || sizeof($list) < 1) | |
{ | |
return; | |
} | |
$min = 0; | |
$max = 0; | |
// if only one element | |
if (sizeof($list) == 1) | |
{ | |
$max = $list[0]; | |
$min = $list[0]; | |
} else | |
{ | |
if ($list[0] > $list[1]) | |
{ | |
$max = $list[0]; | |
$min = $list[1]; | |
} else | |
{ | |
$max = $list[1]; | |
$min = $list[0]; | |
} | |
for ($i = 2; $i <= sizeof($list) - 1; $i++) | |
{ | |
if ($max < $list[$i]) | |
{ | |
$max = $list[$i]; | |
} else if ($min > $list[$i]) | |
{ | |
$min = $list[$i]; | |
} | |
} | |
} | |
$returnArray[0] = $min; | |
$returnArray[1] = $max; | |
return $returnArray; | |
} | |
/** | |
* Clean string from spaces and special characters. | |
* | |
* @param $input | |
* @return mixed | |
*/ | |
private function clean($input) | |
{ | |
return preg_replace('/[^A-Za-z0-9,\-]/', '', str_replace(' ', '', trim($input))); | |
} | |
} | |
$params = '{"buff_size": 3, "list": "[3, 5, 6, 4, 1, 5]"}'; | |
$start = new Main($params); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment