There are three numbers in set A {3,4,7} and in set B {2,4,7}.
It is not possible to get the result true because the the first numbers in a and b are not same.
But I need to get the result as true by comparing other two number and leaving the first number.
How is it possible to do it in PHP?
try this it will helps you.. it will display the 1 => for more number of combinations as same and 0 => for more of combination as different . in the below code the more number of combination as different so its returns 0.
<?php
$A = array(2,3,7,5,6);
$B = array(4,3,7,8,9);
$flagTrue = 0;
$flagFalse = 0;
for($i=0; $i < count($A); $i++)
{
if($A[$i] == $B[$i])
{
$flagTrue=$flagTrue+1;
}
else
{
$flagFalse=$flagFalse+1;
}
}
$var_is_greater_than_two = ($flagTrue >= $flagFalse) ? 1 : 0;
echo $var_is_greater_than_two;
?>
<?php
$a = array(3,4,7);
$b = array(2,4,7);
echo $a === $b ? 'TRUE' : 'FALSE';
echo PHP_EOL;
array_shift($a);
array_shift($b);
echo $a === $b ? 'TRUE' : 'FALSE';
?>
Shows:
FALSE TRUE
UPD:
If you need to extract values from strings, then:
$strA = '3,4,7';
$strB = '2,4,7';
$a = explode(',', $strA);
$b = explode(',', $strB);
array_shift($a);
array_shift($b);
echo $a === $b ? 'TRUE' : 'FALSE';
Should work.
<?
$A = array(2,3,7);
$B = array(4,3,7);
$isTrue=1;
for($i=1; $i < count($A); $i++) if($A[$i]!=$B[$i]) $isTrue=0;
echo $isTrue;
?>
EDIT:
If you want to return true if exactly two elements are the same, then the code would be:
$common=0;
for($i=0; $i < count($a); $i++) if($a[$i]==$b[$i]) $common++;
if($common==2) $isTrue=1;
function compareSets($a, $b) {
$result = TRUE;
$diffArray = array_diff($a, $b);
foreach ($diffArray as $key => $value) {
if ($key > 0) {
$result = FALSE;
break;
}
}
return $result;
}
<?php
$a = array(3,4,7);
$b = array(2,4,7);
for($i=0;$i<3;$i++)
{
if($a[$i] > $b[$i]
echo true;
}
?>
will give true if a is greater.
Related
I can find if an array of values are in sequence using:
sort($arr);
if ($arr == range($arr[0], $arr[count($arr)-1])) {
return true;
}
So anything like 1,2,3,4,5, 6,7,8 will result in true but how can I find a number in sequence but with one number missing? So the expected output would be:
2,3,5,6 = true
2,5,6,8 = false
3,6,10,16 = false
5,7,8,9,10,11 = true
I just checked this and it matches the outputs you expect from your original question
function skippedValue($arr) {
sort($arr);
return sizeof(array_diff(range($arr[0], $arr[count($arr)-1]), $arr)) == 1;
}
var_dump(skippedValue([2,3,5,6])); // true
var_dump(skippedValue([2,5,6,8])); // false
var_dump(skippedValue([3,6,10,16])); // false
var_dump(skippedValue([5,7,8,9,10,11])); //true
result: bool(true) bool(false) bool(false) bool(true)
Algorithmically rather verbose, but works:
function checkAlmostSequential(array $seq, $maxSkips = 1) {
$skipped = 0;
for ($i = 0, $num = $seq[0]; $i < count($seq); $num++) {
if ($num == $seq[$i]) {
$i++;
} else {
$skipped++;
}
if ($skipped > $maxSkips) {
return false;
}
}
return true;
}
var_dump(checkAlmostSequential([2,3,5,6])); // true
var_dump(checkAlmostSequential([2,5,6,8])); // false
var_dump(checkAlmostSequential([3,6,10,16])); // false
var_dump(checkAlmostSequential([5,7,8,9,10,11])); // true
Small function to verify if is sequence
function verifySequence($arr){
sort($arr);
for($i = 0; $i < sizeof($arr) - 1; $i++){
$j = $i + 1;
if( (($arr[$i] + 1) !== $arr[$j]) && (($arr[$i] + 2) !== $arr[$j])){
return false;
}
}
return true;
}
Having misunderstood the question initially I hope this now does as expected - not the easiest to read perhaps.
$a=[1,2,5,6];
$b=[34,35,36,37,38];
$c=[5,7,8,9,10,15];
$d=[1,3,4,5,6,8];
$e=[3,6,10,16];
$f=[2,3,5,6];
function is_semi_sequential( $a ){
rsort( $a );
$c=[];
for( $i=count( $a )-1; $i >= 0; $i-- ){
if( isset( $a[ $i ] ) && isset( $a[ $i+1 ] ) && $a[ $i ] - $a[ $i + 1 ]!=1 ) $c[]=( $a[ $i ] - $a[ $i + 1 ] );
}
return count( $c ) <= 1 && array_sum( $c ) <= 2 ? true : false;
}
echo is_semi_sequential( $a ) ? 'sequential' : 'non-sequential';
echo '<br />';
echo is_semi_sequential( $b ) ? 'sequential' : 'non-sequential';
echo '<br />';
echo is_semi_sequential( $c ) ? 'sequential' : 'non-sequential';
echo '<br />';
echo is_semi_sequential( $d ) ? 'sequential' : 'non-sequential';
echo '<br />';
echo is_semi_sequential( $e ) ? 'sequential' : 'non-sequential';
echo '<br />';
echo is_semi_sequential( $f ) ? 'sequential' : 'non-sequential';
Outputs:
non-sequential
sequential
non-sequential
non-sequential
non-sequential
sequential
You can check using good old for loop
function missingItemChecker($arr, $max_missing = 1){
sort($arr);
$check_arr = range($arr[0], $arr[count($arr)-1]);
$missing = 0;
$len = count($check_arr);
$j = 0;
for($i = 0; $i < $len; $i++) {
if( $check_arr[$i] !== ($arr[$j] ?? false) ){
$missing++;
} else { $j++; }
}
return $missing == $max_missing;
}
Edit: The Logic here is,
Sort to get the Minimum and Maximum in the range using sort($arr).
Create an array of the actual sequence $check_arr = range().
Maintain a count of the numbers missing with $missing.
Loop through the real sequence to and check against the input array
to get the number of the missing elements.
If the number of missing elements is equal to the max allowed missing elements, the sequence has more than 1 numbers missing, else its either complete or only one element is missing.
If we count items that are one value more than the previous, the total will be two less than the amount of items for sequences with only one missing member.
<?php
// Assuming zero indexed and sequential keys in input array.
function missing_only_one_incremental_value_in_sequence(array $nums)
{
$count = count($nums);
$seq_count = 0;
for($i=1; $i<$count; $i++)
if($nums[$i]==$nums[$i-1]+1)
$seq_count++;
return $seq_count == $count-2;
}
var_dump(missing_only_one_incremental_value_in_sequence([2,3,5,6]));
var_dump(missing_only_one_incremental_value_in_sequence([2,5,6,8]));
Output:
bool(true)
bool(false)
For more sample inputs and outputs see here: https://3v4l.org/PFQ5d
I have 5 variables $a $b $c $d $e . These variables has numerical values. Im trying to compare these variables where each variable will be compared to the rest and if the condition is true it echoes something. Here is my code
if ($a > ($b && $c && $d && $e)) {
$result = '<div>Im A</div>'
} else if ($b > ($a && $c && $d && $e)) {
$result = '<div>Im B</div>'
} else if ($c > ($a && $b && $d && $e)) {
$result = '<div>Im C</div>'
} else if ($d > ($a && $b && $c && $e)) {
$result = '<div>Im D</div>'
} else if ($e > ($a && $b && $c && $d)) {
$result = '<div>Im E</div>'
}
return $result;
The result stops at first condition even though it is false and it should pass it to other conditions.
Some different approach:
$a = 1;
$b = 3;
$c = 4;
$d = 5;
$e = 0;
// Make array [a=>1, b=>3...]
$arr = compact('a','b','c','d','e');
// Sort it in descending order with saving keys
arsort($arr);
// Get the 1st key
echo 'I\'m ' . strtoupper(key($arr)); // I'm D
First of all - you have parentheses around ($b && $c && $d && $e), this means that in $a > ($b && $c && $d && $e) the result of ($b && $c && $d && $e) will be counted first, and then will be compared to $a.
So, $a > ($b && $c && $d && $e) is not
$a is greater than $b and $a is greater than $c and etc.
it is
$a is greater than result of ($b and $c and $d and $e)
And result of $b and $c and $d and $e is either true or false.
So, in the end you compare $a > true or $a > false. According to value of $a you can get different results.
In a simple case, if you want to check if something is greater than anything else you need to write a condition like:
if ($a > $b && $a > $c && $a > $d && $a > $e) {
Other more tricky solutions you will find in other users' anwers.
You can iterate your five variables and keep track of the one with the highest value.
for ($i='a', $x = 0, $max = 'x'; $i <= 'e'; $i++) {
if ($$i > $$max) {
$max = $i;
}
}
$result = "<div>I'm " . strtoupper($max) . "</div>";
I think you should steer clear of if statements ;) Here's a solution without them that can be used with any number of variables. You could use the $key as an index into a list of functions and make the program extensible.
// Make the numbers into an array
$o = [$a, $b, $c, $d, $e];
// Find the highest value
$max = max($o);
// Look up the highest value to get the index
$key = array_search($max, $o);
// Now you know which one it is, you can do anything with it!
switch ($key) {
case 0: $result = '<div>Im A</div>'; break;
case 1: $result = '<div>Im B</div>'; break;
...
}
Try this:
$array = ['A'=>$a,'B'=>$b,' C'=>$c,'D'=>$d,'E'=> $e];
$maxs = array_keys($array, max($array));
foreach ($maxs as $maxi )
echo '<div>Im '.$maxi.'</div>."<br>"';
This way it covers cases were there are multiple max values.
Refer to this answer for more about how it works.
PHP code:
$b = 1;
$ab = 100;
for ($b; $b < $ab; $b++)
{
$len = strlen($b);
$c = 0;
for ($c; $c < $len; $c++)
{
$split = str_split($b);
if ($split[$c] == 5)
{
echo $b . ',';
}
}
}
It's result is :
5,15,25,35,45,50,51,52,53,54,55,55,56,57,58,59,65,75,85,95,
But I want remove the final comma and get the last value.
Changes done.
1. Defined $result=array();;
2. Stored values in an array $result[]= $b;
3. Imploded an array with , $result= implode(",", $result);
PHP code demo
<?php
$b = 1;
$ab = 100;
$result=array();
for ($b; $b < $ab; $b++)
{
$len = strlen($b);
$c = 0;
for ($c; $c < $len; $c++)
{
$split = str_split($b);
if ($split[$c] == 5)
{
$result[]= $b;
}
}
}
$lastElement =end($result);//last element
$result= implode(",", $result);
print_r($result);
There is two way .Either you use all value in a array or explode the string into array
1st way is
$b = 1;
$ab = 100;
$arr=[];
for($b; $b < $ab; $b++){
$len = strlen($b);
$c = 0;
for($c; $c < $len; $c++){
$split = str_split($b);
if($split[$c] == 5){
$arr[]=$b;//push value into the array
}
}
}
echo implode(",",$arr);//create string from array
echo end($arr);// return the last value of a array
2nd way is
$b = 1;
$ab = 100;
$str="";
for($b; $b < $ab; $b++){
$len = strlen($b);
$c = 0;
for($c; $c < $len; $c++){
$split = str_split($b);
if($split[$c] == 5){
$str .=$b .','; //create a string with name str
}
}
}
$str=rtrim($str,','); //remove last comma of this string
echo $str;
$arr=explode(",",$str);//convert string to array
echo end($arr);//return the last value of this array
Every other answer is too inefficient because they are using str_split() in an inner for() loop to build the array.
Echoing your values and concatenating with a comma each time will require you to write a separate condition to handle the commas. This will just make your code messy. Best practice would be to store all of the values in an array, then use implode() to glue them together with commas -- this avoids the unwanted trailing comma. end() is the best way to extract the last value.
Here is a faster way (because it avoids unnecessary loops and function calls) to dynamically build your array, convert it to a csv string, and access the latest element in the array:
Code:
$d="5"; // must be declared as string for strpos()
$x11=$d*11; // set only duplicate occurrence in range
for($x=1; $x<100; ++$x){
if(strpos($x,$d)!==false){ // if at least one $d is found
$array[]=$x;
if($x==$x11){ // if two $d are found in integer
$array[]=$x;
}
}
}
echo implode(',',$array),"<br>Last number: ",end($array); // display
Output:
5,15,25,35,45,50,51,52,53,54,55,55,56,57,58,59,65,75,85,95
Last number: 95
This method makes 99 iterations, and 99 strpos() calls, and 20 comparisons to achieve the desired result.
Compare this to all other codes on this page, which make 99 outer loop iterations, 99 strlen() calls, 189 inner loop iterations, 189 str_split() calls, and 189 comparisons.
*faster still would be to remove the comparison inside of the strpos() block, add the x11 value to the array outside of the loop, then sort the array before displaying. Like this:
Code:
$d="5"; // must be declared as string for strpos()
$array[]=$d*11; // store only duplicate occurrence in range
for($x=1; $x<100; ++$x){
if(strpos($x,$d)!==false){ // if at least one $d is found
$array[]=$x;
}
}
sort($array);
echo implode(',',$array),"<br>Last number: ",end($array); // display
Here is alternative method that uses functional iteration:
Code:
$d=5;
$array=array_filter(range(1,99),function($v)use($d){return strpos($v,(string)$d)!==false;})+[$d*11];
sort($array); // zero-index the keys and position the appended value
echo implode(',',$array),"<br>Last number: ",end($array); // display
Output:
5,15,25,35,45,50,51,52,53,54,55,55,56,57,58,59,65,75,85,95
Last number: 95
Use rtrim then explode to get an array.
$b = 1;
$ab = 100;
for($b; $b < $ab; $b++){
$len = strlen($b);
$c = 0;
for($c; $c < $len; $c++){
$split = str_split($b);
if($split[$c] == 5){
echo $b .',';
}
}
}
$b = rtrim(',',$b);
$b = explode(',',$b);
$b = $b[count($b)-1];
This removes the last coma AND gives you the last value (as a string). You can always change the string back into an integer.
$b = 1;
$ab = 100;
$string = "";
for($b; $b < $ab; $b++){
$len = strlen($b);
$c = 0;
for($c; $c < $len; $c++){
$split = str_split($b);
if($split[$c] == 5){
$string .= $b .',';
}
}
}
$string = trim($string,",");
$pos = strripos($string,",");
echo substr($string,$pos + 1);
simply define a last variable:
$b = 1;
$ab = 100;
$last = 0;
for($b; $b < $ab; $b++){
$len = strlen($b);
$c = 0;
for($c; $c < $len; $c++){
$split = str_split($b);
if($split[$c] == 5){
if($last > 0){
echo ',';
}
echo $b;
$last = $b;
}
}
}
put the last value every time in $last.
and for coma, it checks if $last > 0 put coma before $b
You can also user these codes. Tested it and it worked.
$b = 1;
$ab = 100;
$hasValue = false;
for($b; $b < $ab; $b++){
$hasFive = false;
$len = strlen($b);
$c = 0;
for($c; $c < $len; $c++){
$split = str_split($b);
if($split[$c] == 5){
$hasFive = true;
}
}
if (!$hasValue && $hasFive) {
echo $b;
$hasValue = true;
}else if($hasFive){
echo ','.$b;
}
}
Can a do-while loop have multiple conditions? If so, I can't figure out why the code below is failing on all but the first condition.
Functions used...
function gcf($a,$b) {
$a = abs($a); $b = abs($b);
if( $a < $b) list($b,$a) = Array($a,$b);
if( $b == 0) return $a;
$r = $a % $b;
while($r > 0) {
$a = $b;
$b = $r;
$r = $a % $b;
}
return $b;
}
function factors($n){
$factors_array = array();
for ($x = 1; $x <= sqrt(abs($n)); $x++)
{
if ($n % $x == 0)
{
$z = $n/$x;
array_push($factors_array, $x, $z);
}
}
return $factors_array;
}
Code...
$a = $b;
do{
$a = mt_rand(8, 100);
$a_factors_array = factors($a);
$b = mt_rand(8, 100);
$b_factors_array = factors($b);
} while ($a == $b && count($a_factors_array) < 4 && count($b_factors_array) < 4 && gcf($a, $b) == 1);
echo $a . '<br>';
echo $b . '<br>';
echo count($a_factors_array) . '<br>';
echo count($b_factors_array) . '<br>';
echo gcf($a, $b) . '<br>';
I keep getting numbers for $a and $b that have less than 4 factors and have a GCF of 1. Any ideas?
You'll need || instead of &&. You want to repeat the loop as long as any one of your conditions is met. Currently the loop is only repeated if all of the conditions are met.
I think you have an ANDs where you meant an ORs:
do{
$a = mt_rand(8, 100);
$a_factors_array = factors($a);
$b = mt_rand(8, 100);
$b_factors_array = factors($b);
} while ($a == $b || count($a_factors_array) < 4 || count($b_factors_array) < 4 || gcf($a, $b) == 1);
With your way, the while stops if $a !== $b which is probably not what you want.
The following code is displaying INF as the result. How can I fix it?
<?php
function fibonacci($n)
{
$a = 1;
$b = 1;
$result = 0;
for ($i = 0; $i < $n; $i=$i+1)
{
$sum = $a + $b;
$a = $b;
$b = $sum;
if ($a % 2 == 0)
{
$result = $result + $a;
}
}
echo "<br/>" . $result;
}
echo fibonacci(400000);
?>
The number is too big to display, and INF is a pretty good guess :) (fibonacci(1000) gives you a number with 210 digits).
100: 22 digits, 110: 24 digits, 120: 25 digits, 130: 27 digits
If you extrapolate that, you would end up with about (400000 / 10) * 2 = 80000 digits.
The following implements your logic using bcmath to prevent the INF error.
function fibonacci($n)
{
$a = '1'; $b = '1'; $result = '0';
for ($i = 0; $i < $n; $i++) {
$sum = bcadd($a,$b);
$a = $b;
$b = $sum;
if (bcmod($a,'2') == '0') {
$result = bcadd($result,$a);
}
}
echo "<br />".$result;
}
As your fibonacci function doesn't actually return any value, there's no point in echo fibonacci(400000)
EDIT
However, your logic is completely flawed. The following should give you the correct result for the problem you're trying to solve (again using bcmath):
function fibonacci($n)
{
$a = '0'; $b = '1'; $sum = '0';
$sum = '0';
do {
$fib = bcadd($a,$b);
$a = $b;
$b = $fib;
if (bccomp($fib,$n) == -1) {
if (bcmod($fib,'2') == '0') {
$sum = bcadd($sum,$fib);
}
}
++$i;
} while (bccomp($fib,$n) == -1);
return $sum;
}
echo fibonacci(4000000);
Rather than simply executing it to get the result, look to see how it works and what it's actually doing