php please
numberOfPairs
// Return the number of times a pair occurs in array. A pair is any two String values that are equal (case
// sensitive) in consecutive array elements. The array may be empty or have only one element. In both of
// these cases, return 0.
//
// numberOfPairs( array('a', 'b', 'c') ) returns 0
// numberOfPairs( array('a', 'a', 'a') ) returns 2
// assert(2 == numberOfPairs( array('a', 'a', 'b', 'b' ) ) );
// numberOfPairs( array ( ) ) returns 0
// numberOfPairs( array ('a') ) returns 0
// Precondition: $arr has all the same type of elements
function numberOfPairs($arr) {
}
echo PHP_EOL . 'numberOfPairs( array(a, a, a) ) 2: ' . numberOfPairs ( array (
'a',
'a',
'a' ) ) . "\n";
echo ' numberOfPairs( array() ) 0: ' . numberOfPairs ( array () ) . "\n";
PHP CODE:
<?php
// Your code here!
function numberOfPairs($arr)
{
$arrlength = count($arr); #arrlength to find the size of
array
$k= 0;
if ($arrlength !=0) #condition to check if array is non empty or
not
{
if($arrlength==1) #print 0 if array is having only one
element
{echo"0";}
else
{
for ($x = 0; $x < $arrlength; $x++)
{
if ($arr[$x] == $arr[$x+1]){ $k=$k+1;} #if some pair come then k
value increase
}
if($k>0)
{echo $k;} #print the number of pair matches
else
{echo"0";}
}
}
else
{
echo"0";
}
}
echo PHP_EOL . 'numberOfPairs( array(a, a, a) ) 2: ' .
numberOfPairs ( array (
'a',
'a',
'a' ) ) . "\n";
echo ' numberOfPairs( array() ) 0: ' . numberOfPairs ( array () ) . "\n";
#numberOfPairs(array('a','b','c')); //if run this will get 0
#numberOfPairs(array('a','a','a')); //after running will get 2
?>
Get Answers For Free
Most questions answered within 1 hours.