<?php
print_r(meanMedianAndMode([8, 7, 2, 4, 2]))."\n";
print_r(meanMedianAndMode([8, 7, 2, 4, 2, 7]))."\n";
function meanMedianAndMode($nums) {
$count = count($nums);
sort($nums);
//Calculates Median
if ($count%2 == 0) {
$median = ($nums[$count/2]+$nums[$count/2-1])/2;
} else {
$median = $nums[floor($count/2)];
}
// Calculates Mode
$counted = array_count_values($nums);
$max = max($counted);
// Checks if there is more than one Mode
$counted_max = array_count_values($counted);
if ($counted_max[$max] == 1) {
$mode = array_search($max, $counted);
} else {
foreach ($counted as $key => $value) {
if ($value == $max) {
$mode[] = $key;
}
}
}
return [
'mean' => array_sum($nums) / $count,
// average number
'median' => $median,
'mode' => $mode
];
}
<?php
print_r(average([4, 1, 5, 3, 7]));
function average($array){
$count = 0;
$sum = 0;
foreach ($array as $item) {
// Calculates the number of array members
$count++;
// Calculates sum of the array
$sum += $item;
}
return $sum/$count;
}
// Using built-in functions
function calculateDetails_builtin($array){
return array_sum($array)/count($array);
}
<?php
echo ohmsLaw_1(12, 220, "")."\n";
echo ohmsLaw_1(230, "", 2) ."\n";
echo ohmsLaw_1("", 220, 0.02) ."\n";
echo ohmsLaw_1("", "", 10)."\n";
echo ohmsLaw_1(500, 50, 10)."\n";
function ohmsLaw_1($voltage, $resistance, $current) {
if ($voltage == "" && $resistance == "" ||
$voltage == "" && $current == "" ||
$resistance == "" && $current == "" ||
$voltage != "" && $resistance != "" && $current != "") {
return "Invalid";
}
if ($voltage == "") {
$res = $resistance*$current;
}
if ($resistance == "") {
$res = $voltage/$current;
}
if ($current == "") {
$res = $voltage/$resistance;
}
return $res;
}
//using empty function
function ohmsLaw_2($voltage, $resistance, $current) {
if (empty($voltage) && empty($resistance) ||
empty($voltage) && empty($current) ||
empty($resistance) && empty($current) ||
!empty($voltage) && !empty($resistance) && !empty($current)
) {
return "Invalid";
}
if (empty($voltage)) {
$res = $resistance*$current;
}
if (empty($resistance)) {
$res = $voltage/$current;
}
if (empty($current)) {
$res = $voltage/$resistance;
}
return round($res, 2);
}
<?php
print_r(twoSum([4,4], 8));
print_r(twoSum([3,2,4], 6));
print_r(twoSum([1,3,4,2], 6));
print_r(twoSum([2,11,7,15], 9));
print_r(twoSum([-1,-2,-3,-4,-5], -8));
function twoSum($nums, $target){
$cnt=count($nums);
for ($i=0; $i<$cnt-1; $i++){
for ($j=$i+1; $j<$cnt; $j++){
if ($nums[$i]+$nums[$j]==$target){
return [$i, $j];
}
}
}
}
time limit
for file_get_contents
is 60 seconds which we can increase using timeout
property of http
object $opts = [
"http" => [
"method" => "GET",
"timeout"=> 1200,
"header" =>
"Channel-Name: ".CHANNEL."\r\n" .
"Authorization: ".AUTHORIZATION."\r\n"
]
];
// DOCS: https://www.php.net/manual/en/function.stream-context-create.php
$context = stream_context_create($opts); //, false, $context
$startTime = microtime(1);
$res = file_get_contents($url . $query, false, $context);