Last active
March 16, 2020 23:59
-
-
Save didagu/4dd8e75ddeb0aaedb789f813c9d5a0c1 to your computer and use it in GitHub Desktop.
function that gets the item that occurred an odd number of times in an array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// first solution | |
function getOddOccurrenceFromArray1($arr) | |
{ | |
$result = 0; | |
for ($i = 0; $i < sizeof($arr); $i++) | |
/* | |
* Using xor bitwise operator, the final value of $result will | |
* be the array item that occurred an odd number of time | |
*/ | |
$result = $result ^ $arr[$i]; | |
return $result; | |
} | |
//second solution | |
function getOddOccurrenceFromArray2($arr) { | |
$countedArray = array_count_values($arr); | |
$filteredArray = array_filter($countedArray, function ($value, $key) { | |
return $value % 2 != 0 ; | |
}, ARRAY_FILTER_USE_BOTH); | |
$arrayKeys = array_keys($filteredArray); | |
return $arrayKeys[0]; | |
} | |
/* | |
* input array: [1,1,1,3,4] | |
*/ | |
/* | |
* output: 1 | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment