Closest Numbers

  • + 0 comments

    Here is my PHP solution:

    function closestNumbers($arr) {
        // Write your code here
        sort($arr);
        $count_arr = count($arr);
        $temp_angka1 = [];
        $temp_angka2 = [];
        $abs =[];
        $min = 999999999;
        $hasil = [];
        
        for ($i=0; $i <= $count_arr - 2; $i++) {
            if (($arr[$i+1] - $arr[$i] < $min)) {
                $min   = $arr[$i+1] - $arr[$i];
                unset($abs);
                unset($temp_angka1);
                unset($temp_angka2);
                $abs[$i] = $min;
                $temp_angka1[$i]   = $arr[$i];
                $temp_angka2[$i+1] = $arr[$i+1];
            }
            else if ($arr[$i+1] - $arr[$i] == $min) {
                $min   = $arr[$i+1] - $arr[$i];
                $abs[$i] = $min;
                $temp_angka1[$i]   = $arr[$i];
                $temp_angka2[$i+1] = $arr[$i+1];
            }
        }
        
        $count_abs = count($abs);
        
        foreach ($abs as $key=>$val) {
            $hasil[] = $temp_angka1[$key];
            $hasil[] = $temp_angka2[$key+1];
        }
        
        return $hasil;
        
    }