There is a task. the function accepts the parameter 'odd' or 'even' - strings and array. And it returns the number of either odd or even elements in the array, depending on the parameter. Tell me where I was wrong?
function () {
$num = 'even';
$arr = [1,2,3,4,5,6,7,8,9];
in_array($num, $arr) {
if($num == 'even') {
return $arr % 2 == 0;
} else {
return $arr % 2 !== 0;
}
}
}
Here is your result. In your program, you are performing a modular operation on an entire array, which is not supported. You need to check each element of an array.
$result = [];
$num = 'even';
$arr = [1,2,3,4,5,6,7,8,9];
function _in_array($num, $arr) {
foreach($arr as $value){
if($num == 'even'){
if($value % 2 == 0){
$result[] = $value;
}
}else{
if($value % 2 != 0){
$result[] = $value;
}
}
}
return $result;
}
Related
I need to find the min and max position into an array where some value exist!
use a loop inside a loop to compare values is not an option ( my array has 100.000 values )
e.g=
$myarray[0]="red";
$myarray[1]="red";
$myarray[2]="blue";
$myarray[3]="blue";
$myarray[4]="blue";
$myarray[5]="red";
how to get the min and max position where blue exist?
Use the second argument for array_keys:
if($blue = array_keys($myarray, 'blue')) {
$min = min($blue);
$max = max($blue);
}
may be this is the answer?
function getMinKey($arr, $search){
if(!in_array($search, $arr)){
return false;
}
foreach($arr as $key => $value){
if($value == $search){
return $key;
}
}
}
function getMaxKey($arr, $search){
if(!in_array($search, $arr)){
return false;
}
$arrCount = count($arr)-1;
for($i = $arrCount; $i >=0; $i--){
if($arr[$i] == $search){
return $i;
}
}
}
All solutions, so far, have searched the whole array, which might be quite inefficient. You only need to search from the start upto the first "blue" and from the end downto the last "blue". Like this:
$find = "blue";
$first = false;
$last = false;
$max = count($myarray);
$key = 0;
while ($key < $max) {
if ($myarray[$key] == $find) {
$first = $key;
break;
}
$key++;
}
if ($first !== false) {
$key = --$max;
while ($key > 0) {
if ($myarray[$key] == $find) {
$last = $key;
break;
}
$key--;
}
}
Note that this code takes into account that nothing will be found. In that case $first and $last will contain false. It also checks to see if the $first was found to prevent searching through the array twice when there's clearly no need for that.
You can use array_keys with the search_value to extract all the matching keys, and then max and min to get the two ones that you want.
$keys = array_keys($myarray,'blue'); //[2,3,4]
$maxKey = max($keys); //4
$minKey = min($keys); //2
I have to advise that performance wise is better to do a for loop:
$length = count($myarray);
$minKey = FALSE;
$maxKey = FALSE;
$search = 'blue';
for($i=0;$i<$length;$i++){
if($myarray[$i] == $search){
if($minKey === FALSE) $minKey = $i;
$maxKey = $i;
}
}
Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1.
My code:
function firstDuplicate($a) {
$unique = array_unique($a);
foreach ($a as $key => $val) {
if ($unique[$key] !== $val){
return $key;
}else{
return -1;
}
}
}
The code above will be OK when the input is [2, 4, 3, 5, 1] but if the input is [2, 1, 3, 5, 3, 2] the output is wrong. The second duplicate occurrence has a smaller index. The expected output should be 3.
How can I fix my code to output the correct result?
$arr = array(2,1,3,5,3,2);
function firstDuplicate($a) {
$res = -1;
for ($i = count($a); $i >= 1; --$i) {
for ($j = 0; $j < $i; ++$j) {
if ($a[$j] === $a[$i]) {
$res = $a[$j];
}
}
}
return $res;
}
var_dump(firstDuplicate($arr));
By traversing the array backwards, you will overwrite any previous duplicates with the new, lower-indexed one.
Note: this returns the value (not index), unless no duplicate is found. In that case, it returns -1.
// Return index of first found duplicate value in array
function firstDuplicate($a) {
$c_array = array_count_values($a);
foreach($c_array as $value=>$times)
{
if($times>1)
{
return array_search($value, $array);
}
}
return -1;
}
array_count_values() will count the duplicate values in the array for you then you just iterate over that until you find the first result with more then 1 and search for the first key in the original array matching that value.
Python3 Solution:
def firstDuplicate(a):
mySet = set()
for i in range(len(a)):
if a[i] in mySet:
return a[i]
else:
mySet.add(a[i])
return -1
function firstDuplicate($a) {
foreach($a as $index => $value) {
$detector[] = $value;
$counter = 0;
foreach($detector as $item) {
if($item == $value) {
$counter++;
if($counter >= 2) {
return $value;
break;
}
}
}
}
return -1;
}
It's easy to just get the first number that will be checked as duplicated, but unfortunately, this function exceeded 4 seconds with a large array of data, so please using it with a small scale of array data.
EDIT
I have new own code fixes execution time for large array data
function firstDuplicate($a) {
$b = [];
$counts = array_count_values($a);
foreach($counts as $num => $duplication) {
if($duplication > 1) {
$b[] = $num;
}
}
foreach($a as $value) {
if(in_array($value, $b)) {
$detector[] = $value;
$counter = 0;
foreach($detector as $item) {
if($item == $value) {
$counter++;
if($counter >= 2) {
return $value;
break;
}
}
}
}
}
return -1;
}
The new code target the current numbers having a reputation only by using array_count_values()
function firstDuplicate($a) {
$indexNumber = -1;
for($i = count($a); $i >= 1 ; --$i){
for($k = 0; $k < $i; $k++){
if(isset($a[$i]) && ($a[$i] === $a[$k]) ){
$indexNumber = $a[$k];
}
}
}
return $indexNumber;
}
Remove error from undefined index array.
I want to combine two arrays into a dictionary.
The keys will be the distinct values of the first array, the values will be all values from the second array, at matching index positions of the key.
<?php
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
?>
array_combine($b,$a);
Expected result as
<?php
/*
Value '1' occurs at index 0, 1 and 4 in $b
Those indices map to values 2, 3 and 6 in $a
*/
$result=[1=>[2,3,6],3=>4,2=>[5,7],6=>8,8=>[9,10]];
?>
There are quite a few PHP array functions. I'm not aware of one that solves your specific problem. you might be able to use some combination of built in php array functions but it might take you a while to weed through your choices and put them together in the correct way. I would just write my own function.
Something like this:
function myCustomArrayFormatter($array1, $array2) {
$result = array();
$num_occurrences = array_count_values($array1);
foreach ($array1 AS $key => $var) {
if ($num_occurrences[$var] > 1) {
$result[$var][] = $array2[$key];
} else {
$result[$var] = $array2[$key];
}
}
return $result;
}
hope that helps.
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
$results = array();
for ($x = 0; $x < count($b); $x++) {
$index = $b[$x];
if(array_key_exists ($index, $results)){
$temp = $results[$index];
}else{
$temp = array();
}
$temp[] = $a[$x];
$results[$index] = $temp;
}
print_r($results);
Here's one way to do this:
$res = [];
foreach ($b as $b_index => $b_val) {
if (!empty($res[$b_val])) {
if (is_array($res[$b_val])) {
$res[$b_val][] = $a[$b_index];
} else {
$res[$b_val] = [$res[$b_val], $a[$b_index]];
}
} else {
$res[$b_val] = $a[$b_index];
}
}
var_dump($res);
UPDATE: another way to do this:
$val_to_index = array_combine($a, $b);
$result = [];
foreach ($val_to_index as $value => $index) {
if(empty($result[$index])){
$result[$index] = $value;
} else if(is_array($result[$index])){
$result[$index][] = $value;
} else {
$result[$index] = [$result[$index], $value];
}
}
var_dump($result);
Return false if the repeated occurrence of 0's or 1's in the string is greater than number($k).
I have written a function which works, but I need to optimize it:
<?php
function satisfied($str, $k){
$stream = $last = $str[0];
for($i = 1; $i <= strlen($str)-1; $i++){
if($str[$i] != $last) $last = $stream = $str[$i];
else $stream .= $str[$i];
if(strlen($stream) > $k) return false;
}
return true;
}
Example:
satisfied("0111", 2) - False
satisfied("0111", 3) - True
satisfied("00111000111", 3) - True
satisfied("00111000111", 4) - True
I wanted to know if I can do this with help of preg_match?
something like:
preg_match('/(0+|1+){'.$k.'}/', "0111");, this is not even close to what i want to achieve.
I want to avoid for loops to optimize the code. Will the preg_match be faster than the function above ? And obviously, you can also suggest me tweaks to my existing function.
Can someone help me out.
You can do it with strpos:
function satisfied($str, $k) {
return strpos($str, str_repeat('0', $k+1)) === false
&& strpos($str, str_repeat('1', $k+1)) === false;
}
or you can use preg_match with a simple alternation:
function satisfied($str, $k) {
$k++;
$pattern = '~0{' . $k . '}|1{' . $k . '}~';
return !preg_match($pattern, $str);
}
Note that preg_match returns an integer (or false if a problem occurs), but since there is a negation operator, the returned value is casted to a boolean.
You can take the input as character array and Here's exactly what your looking for :
<?php
function printCharMostRepeated($str)
{
if (!empty($str))
{
$max = 0;
foreach (count_chars($str, 1) as $key => $val)
if ($max < $val) {
$max = $val;
$i = 0;
unset($letter);
$letter[$i++] = chr($key);
} else if ($max == $val)
$letter[$i++] = chr($key);
if (count($letter) === 1)
echo 'The character the most repeated is "'.$letter[0].'"';
else if (count($letter) > 1) {
echo 'The characters the most repeated are : ';
$count = count($letter);
foreach ($letter as $key => $value) {
echo '"'.$value.'"';
echo ($key === $count - 1) ? '.': ', ';
}
}
} else
echo 'value passed to '.__FUNCTION__.' can\'t be empty';
}
$str = 'ddaabbccccsdfefffffqqqqqqdddaaa';
printCharMostRepeated($str);
How do I keep a certain number of elements in an array?
function test($var)
{
if(is_array($_SESSION['myarray']) {
array_push($_SESSION['myarray'], $var);
}
}
test("hello");
I just want to keep 10 elements in array $a. So when I call test($var) it should push this value to array but keep the number to 10 by removing some elements from top of the array.
while (count($_SESSION['myarray'] > 10)
{
array_shift($_SESSION['myarray']);
}
I would do this:
function test($var) {
if (is_array($_SESSION['myarray']) {
array_push($_SESSION['myarray'], $var);
if (count($_SESSION['myarray']) > 10) {
$_SESSION['myarray'] = array_slice($_SESSION['myarray'], -10);
}
}
}
If there a more than 10 values in the array after adding the new one, take just the last 10 values.
You can use array_shift
if(count($_SESSION['myarray']) == 11))
array_shift($_SESSION['myarray']);
if(count($_SESSION["myarray"]) == 10)
{
$_SESSION["myarray"][9] = $var;
}
else
{
$_SESSION["myarray"][] = $var
}
That should do.
function array_10 (&$data, $value)
{
if (!is_array($data)) {
$data = array();
}
$count = array_push($data, $value);
if ($count > 10) {
array_shift($data);
}
}
Usage:
$data = array();
for ($i = 1; $i <= 15; $i++) {
array_10($data, $i);
print_r($data);
}