Last active
August 2, 2018 06:18
-
-
Save jasonknight/ccf702279bccef5726c9679f2cfbec49 to your computer and use it in GitHub Desktop.
Technical Interview Question #1
This file contains 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 | |
function sum_csv($str,$sep,$col) { | |
return floatval(array_reduce(array_slice(explode("\n",$str),1), | |
function ($a,$l) use ($col,$sep) { | |
return $a + explode($sep,$l)[$col]; | |
})); | |
} | |
$table = [ | |
'0.0' => "", | |
'1.5' => "col1,col2\n0.0,0.5\n,1,1", | |
'3.8' => "col1,col2,\n0.1,0.2\n0,0.6\n0,1\n0,2.0", | |
]; | |
foreach ( $table as $t=>$str ) { | |
if ( floatval($t) != sum_csv($str,",",1)) { | |
die("Failed\n"); | |
} else { | |
echo "$t passed with " . sum_csv($str,",",1) . "\n"; | |
} | |
} | |
echo "All functional tests passed\n"; | |
function sum_csv_iter($str,$sep,$col) { | |
$sum = 0; | |
foreach ( array_slice( explode("\n",$str), 1) as $line ) { | |
$cols = explode($sep,$line); | |
$sum += $cols[$col]; | |
} | |
return $sum; | |
} | |
foreach ( $table as $t=>$str ) { | |
if ( floatval($t) != sum_csv_iter($str,",",1)) { | |
die("Failed\n"); | |
} else { | |
echo "$t passed with " . sum_csv_iter($str,",",1) . "\n"; | |
} | |
} | |
echo "All iterative tests passed\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment