Here is the list of problems with correct answers for Elance PHP5 Code Test:
1. recursive xml traversal:
function ReadXml($xmlstr) { static $res = ''; $xml = new SimpleXMLElement($xmlstr); if(count($xml->children())) { $res .= $xml->getName().PHP_EOL; foreach($xml->children() as $child) { ReadXml($child->asXML()); } } else { $res .= $xml->getName().': '.(string)$xml.PHP_EOL; } return $res; }
2. (sql) select the second highest id from user table:
SELECT id FROM user ORDER BY id DESC LIMIT 1,1
3. get checkbox values from POST:
$res = array(); while(list($checkbox,) = each($_POST)) { $res[] = intval(substr($checkbox,strpos($checkbox,'_') + 1)); } sort($res); echo implode(' ',$res);
4. get unique array elements:
function GetUniqueOnes($arr) { $res = implode(',',array_unique($arr)); return $res; }
5. generate random password:
function GeneratePassword ($length,$chars) { $res = ''; $char_length = strlen($chars); for($i = 0; $i < $length; $i++) { $res .= $chars[rand(0,$char_length)]; } return $res; }
6. split email addresses:
function SplitEmailAddress($address) { list($user, $domain) = explode('@',$address); return array('user' => $user, 'domain' => $domain); }
7. the most challenging task (for me). Phone regexps:
function ReformatPhoneNumber($number) { if (preg_match('/^(\d[ -]?){7,12}$/', $number, $matches)) { return preg_replace('/[ -]/', '', $number); } throw new Exception('Invalid phone number'); }
8. get longest string in arguments:
function GetLongestString() { $length = 0; foreach(func_get_args() as $arg) { $var = strlen($arg); if($var > $length) { $length = $var; } } return $length; }
9. find maximum in nested array:
function MaxArray($arr) { $GLOBALS['max'] = 0; array_walk_recursive($arr,create_function('$item,$key','if($item > $GLOBALS["max"]) $GLOBALS["max"] = $item;')); return $GLOBALS['max']; }
10. output all numbers divisable by 8 from 200 to 600 inclusive:
for($i = 200; $i <= 592; $i+=8) { echo $i.','; } echo $i;
Note, that all answers are correct, but some of them are not optimized, so you may be in top 20% with this, but not higher. If someone would like to post any improvements to the code snippets above – they are welcome:)
function MaxArray($arr) {
$max = 0;
foreach($arr as $a) {
$tmp = (is_array($a) ? MaxArray($a) : $a;
$max = ($tmp > $max) ? $tmp : $max;
}
return $max;
}
Very nice, i suggest webmaster can set up a forum, so that we can talk and communicate.
function GeneratePassword($length, $chars)
{
return substr(str_shuffle($chars), 0, $length);
}
function GetLongestString()
{
return max(array_map(strlen, func_get_args()));
}
$i=200;
while($i%8!=0)
{
$i++;
}
while($i<=600)
{
echo $i;
if($i<600)
{
echo ",";
}
$i+=8;
}
hey thank you very much …….
appreciate all of your efforts π
function GeneratePassword($length, $chars)
{
return substr(str_shuffle($chars), 0, $length);
}
pretty good idea,but what if $length’s value is greater than strlen($chars) οΌ
you won’t get a 10 chars password while $chars=’abc’
nice catch, pride. But then I think Andrew’s solution may be improved by
return substr(str_shuffle(str_repeat($chars,$length)), 0, $length);
right?
Not sure about the GeneratePassword() problem, but I do have a version of the ReadXml(), that I tested to be way more efficient that one in this post. Obviously it is much uglier, and much more rigid, but it runs at least 5 times as fast. Here is the screenshot from KCacheGrind analyzing xDebug profiling output: http://tinypic.com/r/b8k704/5
Here is the code:
function ReadXml($xmlstr)
{
$p = xml_parser_create();
xml_parser_set_option ($p, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($p, $xmlstr, $vals);
xml_parser_free($p);
return
($vals[0][‘tag’].PHP_EOL.
$vals[1][‘tag’].’: ‘.$vals[1][‘value’].PHP_EOL.
$vals[2][‘tag’].’: ‘.$vals[2][‘value’].PHP_EOL.
$vals[3][‘tag’].’: ‘.$vals[3][‘value’].PHP_EOL.
$vals[4][‘tag’].’: ‘.$vals[4][‘value’].PHP_EOL);
}
Hi kievan,
thanks for your solution, hope it helps others!
I hope so too.
And thanx for this great post π
I was able to score 85 for this same test on vWorker.
Used your examples while preparing for the test, saved me a good deal of time for sure π
Hi mate, you may loose your account for posting this to public π
Sorry for that ugly name, also results worked fine, bud kievan reply about XML DONT works. Thanks dudes π
The second response is wrong you need to do a double query there.
SELECT MAX(id) FROM user WHERE id NOT IN (SELECT MAX(id) FROM user )
Something similar i dinΒ΄t tested it but it must work.
I passed this test on elance and I was top 10%
for($i=200;$i<=600;$i++){
if(($i % 8) === 0){
echo $i;
if($i != 600){echo ",";}
}
}
function GetLongestString(){
global $maxlength;
$numofargs = func_num_args();
for($i=0;$i<$numofargs;$i++){
$string = func_get_arg($i);
$length = strlen($string);
if($maxlength < $length){
$maxlength = $length;
}
}
return $maxlength;
}
What is the wrong with this code??
function MaxArray($arr){
$length = count($arr);
global $maxValue;
for($i=0;$i<$length;$i++){
if(is_int($arr[$i])){
//count maximum value
if($maxValue < $arr[$i]){
$maxValue = $arr[$i];
}
//end counting
}
elseif(is_array($arr[$i])){
MaxArray($arr[$i]);
}
}
return $maxValue;
}
Additionally I don’t find any wrong but Elance won’t except my code. Do you tell me why?
Thanks friend really I appreciate your efforts ..
SELECT id, name
FROM user
WHERE id = (SELECT MAX(id) FROM user WHERE id < (SELECT MAX(id) FROM user));
Here is my result to convert the POST values ending with underscore to a sortable array.
Based upon 10000 fields it performs 35% faster
$res = array();
foreach($_POST as $key => $value) {
$res[] = intval(substr($key,strrpos($key,'_') + 1));
}
sort($res);
$result1 = implode(' ',$res);
Sorry!! Please replace $result1 = with echo
thanks Marc
SELECT DISTINCT(id) FROM `user` WHERE `id`=(SELECT MAX(id) FROM user);
Thanks bro you rock π
Write a program that outputs the numbers that are divisible by 8 and are between 200 and 600 (inclusive), separated by commas (without spaces or line breaks).
<?php
$Result = array();
for($i = 200; $i
super , duper, bumper.
Your SQL is not perfect:
Right one is like this:
table name: basic_information
roll name total_marks
45 Faisal 90
46 Rasel 89
47 Adit 91
48 Sajib 91
SELECT * FROM `basic_information` WHERE `total_marks` = (SELECT DISTINCT `total_marks` FROM `basic_information` ORDER BY `total_marks` DESC LIMIT 1,1);
Really aewsome tutorial…..
you are awesome bro
Awesome man….. π
for GeneratePassword ($length,$chars) function
$char_length = strlen($chars); should be char_length =strlen($chars) -1;
Because rand(0, max) including max. but max element of array is chars[char_length -1], right?