Skip to content

Instantly share code, notes, and snippets.

@hidayat365
Last active January 29, 2019 04:18
Show Gist options
  • Save hidayat365/51b38145a1ed2e59fcd1fbfea1bf2dd3 to your computer and use it in GitHub Desktop.
Save hidayat365/51b38145a1ed2e59fcd1fbfea1bf2dd3 to your computer and use it in GitHub Desktop.
Tantangan PHP Group: Validasi Input Array Mencari data Pairs
<?php
function my_var_dump($prefix, $data) {
echo $prefix . ": ";
array_walk($data, function($val,$key) {
echo json_encode($val) . ' ';
});
echo "\n";
}
function validate_pairs($data, $sum) {
// message: initial data
my_var_dump("data",$data);
// group data into clusters
$proses = [];
array_walk($data, function($val,$key) use(&$proses) {
$proses[$val][] = $val;
});
// proses cluster, filter non pair
$result = array_filter($proses, function($el) {
return count($el)==2;
});
// calculate total
$total = 0;
array_walk($result, function($val,$key) use(&$total) {
$total += $key+$key;
});
// message: process result
my_var_dump("pairs",$result);
my_var_dump("total",[$total]);
return $sum==$total and count($result)>0;
}
// test case 1
$data = [8,9,1,2,3,4,1,2,4,5,6,7,8,3,4];
echo validate_pairs($data,28) ? "true" : "false";
echo "\n\n";
// test case 2
$data = [0,1,2,3,4,5,0];
echo validate_pairs($data,0) ? "true" : "false";
echo "\n\n";
/***
* Output
********************
data: 8 9 1 2 3 4 1 2 4 5 6 7 8 3 4
pairs: [8,8] [1,1] [2,2] [3,3]
total: 28
true
data: 0 1 2 3 4 5 0
pairs: [0,0]
total: 0
true
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment