Skip to content

Instantly share code, notes, and snippets.

@jasonknight
Last active August 2, 2018 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonknight/ccf702279bccef5726c9679f2cfbec49 to your computer and use it in GitHub Desktop.
Save jasonknight/ccf702279bccef5726c9679f2cfbec49 to your computer and use it in GitHub Desktop.
Technical Interview Question #1
<?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