Been racking my brains on how to write this better AND make it loop depending on the $count value:
if($count == 2){
$thenode = $tree[$splitnode[0]][$splitnode[1]];
} elseif($count == 3){
$thenode = $tree[$splitnode[0]][$splitnode[1]][$splitnode[2]];
}
Any ideas? Thanks!
$thenode = $tree;
for ($i = 0; $i < $count; $i++) {
$thenode = $thenode[$splitnode[$i]];
}
var_dump($thenode);
or
$thenode = array_reduce(
range(0, $count - 1),
function ($thenode, $i) use ($splitnode) { return $thenode[$splitnode[$i]]; },
$tree
);
or maybe
$thenode = $tree;
foreach ($splitnode as $i => $sn) {
if ($i >= $count) {
break;
}
$thenode = $thenode[$sn];
}
Related
I would like to make a program which can calculate first 5000 primary numbers whos ends with 9 :
I tried this but it didn't work :
$div9 = [];
$x = 2;
while (count($div9) <= 5000) {
function findPrime($x)
{
for ($i = 2; $i < ($x / 2); $i++) {
$rest = $x % $i;
if ($rest == 0) {
break;
}
}
return $x;
}
$primeList[] = $x;
for ($j = 0; $j < count($primeList); $j++) {
$array = array_map('intval', str_split($primeList[$j]));
if (end($array[$j]) === 9) {
return $primeList[$j];
$div9[] = $primeList[$j];
}
}
$x++;
}
any hints please?
You should not define a function inside your while loop
This should help
function check_prime($num)
{
if ($num == 1)
return false;
for ($i = 2; $i <= $num/2; $i++)
{
if ($num % $i == 0)
return false;
}
return true;
}
$div9 = [];
$i = 0;
while(count($div9) < 5000) {
if($i%10 === 9 && check_prime($i)) {
$div9[] = $i;
}
$i++;
}
Another variation on the theme, the isPrime function was ported from Javascript cryptoJS library.
# Adapted from CryptoJS v3.1.2
function isPrime( $n=0 ){
$r=sqrt( $n );
for( $f=2; $f <= $r; $f++ ){
if( !( $n % $f ) )return false;
}
return true;
}
function isFactor($n,$f){
return $n % 10 == $f;
}
$limit=5000;
$primes=[];
$x=2;
$f=9;
while( count( $primes ) < $limit ){
if( isPrime( $x ) && isFactor( $x, $f ) )$primes[]=$x;
$x++;
}
printf('<pre>%s</pre>',print_r($primes,true));
Problem Find the smallest positive integer that does not occur in a given sequence.
So what is the best implementation in PHP for this problem of codility!
Solution below results 66%, causing performance issue.
function solution($A)
{
sort($A);
$end = count($A);
$flag = false;
for ($k = 0; $flag == false; $k++, $flag = false) {
for ($i = 0; $i < $end; $i++) {
if ($k + 1 == $A[$i]) {
$flag = $A[$i];
break;
}
}
if($flag == false){
return $k +1;
}
}
}
A simple solution using an associative array as a set:
function solution($A) {
$set = array_flip($A);
for ($n = 1; ; ++$n) {
if (!isset($set[$n])) {
return $n;
}
}
}
Here is the Best solution for the codility problem implemented in PHP, scoring 100%
function solution($A)
{
sort($A);
$end = count($A);
$flag = false;
for ($k = 1, $i = 0; $i < $end; $i++) {
if ($A[$i] == $k) {
$k++;
continue;
} elseif ($A[$i] < $k)
continue;
else return $k;
}
return $k;
}
Im trying to solve one challenge where you have to check all string substrings are they anagrams. The condition is basically For S=abba, anagramic pairs are: {S[1,1],S[4,4]}, {S[1,2],S[3,4]}, {S[2,2],S[3,3]} and {S[1,3],S[2,4]}
Problem is that I have string with 100 chars and execution time should be below 9 secs. My time is around 50 secs... Below is my code, I will appreciate any advice - if you give me only directions or pseudo code it is even better.
$time1 = microtime(true);
$string = 'abdcasdabvdvafsgfdsvafdsafewsrgsdcasfsdfgxccafdsgccafsdgsdcascdsfsdfsdgfadasdgsdfawdascsdsasdasgsdfs';
$arr = [];
$len = strlen($string);
for ($i = 0; $i < strlen($string); $i++) {
if ($i === 0) {
for ($j = 1; $j <= $len - 1; $j++) {
$push = substr($string, $i, $j);
array_push($arr, $push);
}
} else {
for ($j = 1; $j <= $len - $i; $j++) {
$push = substr($string, $i, $j);
array_push($arr, $push);
}
}
}
$br = 0;
$arrLength = count($arr);
foreach ($arr as $key => $val) {
if ($key === count($arr) - 1) {
break;
}
for ($k = $key + 1; $k < $arrLength; $k++) {
if (is_anagram($val, $arr[$k]) === true) {
$br++;
}
}
}
echo $br."</br>";
function is_anagram($a, $b)
{
$result = (count_chars($a, 1) == count_chars($b, 1));
return $result;
}
$time2 = microtime(true);
echo "Script execution time: ".($time2-$time1);
Edit:
Hi again, today I had some time so I tried to optimize but couldnt crack this... This is my new code but I think it got worse. Any advanced suggestions ?
<?php
$string = 'abdcasdabvdvafsgfdsvafdsafewsrgsdcasfsdfgxccafdsgccafsdgsdcascdsfsdfsdgfadasdgsdfawdascsdsasdasgsdfs';
$arr = [];
$len = strlen($string);
for ($i = 0; $i < strlen($string); $i++) {
if ($i === 0) {
for ($j = 1; $j <= $len - 1; $j++) {
$push = substr($string, $i, $j);
array_push($arr, $push);
}
} else {
for ($j = 1; $j <= $len - $i; $j++) {
$push = substr($string, $i, $j);
array_push($arr, $push);
}
}
}
$br = 0;
$arrlen = count ($arr);
foreach ($arr as $key => $val) {
if (($key === $arrlen - 1)) {
break;
}
for ($k = $key + 1; $k < $arrlen; $k++) {
$result = stringsCompare($val,$arr[$k]);
if ($result === true)
{
$br++;
}
}
echo $br."\n";
}
function stringsCompare($a,$b)
{
$lenOne = strlen($a);
$lenTwo = strlen ($b);
if ($lenOne !== $lenTwo)
{
return false;
}
else {
$fail = 0;
if ($lenOne === 1) {
if ($a === $b) {
return true;
}
else
{
return false;
}
}
else
{
for ($x = 0; $x < $lenOne; $x++)
{
$position = strpos($b,$a[$x]);
if($position === false)
{
$fail = 1;
break;
}
else
{
$b[$position] = 0;
$fail = 0;
}
}
if ($fail === 1)
{
return false;
}
else
{
return true;
}
}
}
}
?>
You should think of another rule that all anagrams of a certain string can meet. For example, something about the number of occurrences of each character.
Why does this not make two arrays one within 7 numbers and one within 2 numbers in it?
It somehow combines the both into one.
When i echo $arvottuLottoRivi and $lottoLisaNumerot in my HTML page the result is:
$arvottuLottoRivi (1,2,3,4,5,6,7,8,9,10) : $lottoLisaNumerot
all the seven numbers.
I have now tried three different styles but same thing happens in all cases
// VARAIBLES
$lottoNumerot = $_POST["lottoNumerot"];
$mahdollisetNumerot = array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39");
$i = 0;
$l = 0;
$k = 0;
//ARRAYS
$arvottuLottoRivi = array();
$lottoLisaNumerot = array();
$tenNumbersArray = array();
//FUNCTIONS
$numeroidenRandomointi = array_rand($mahdollisetNumerot, 10);
// COUNTS ARRAY LENGHT
$lottoRivinPituus = count($numeroidenRandomointi);;
// LOOPS
foreach($numeroidenRandomointi as $randomNumero){
while($i <= $lottoRivinPituus){
$i++;
}
$randomToArray = array_push($tenNumbersArray, $randomNumero);
}
// LOOPIT
foreach($tenNumbersArray as $randomToSite){
while($l <= $lottoRivinPituus){
$l++;
}
if($l <= 7){
array_push($arvottuLottoRivi, $randomToSite);
}
}
foreach($tenNumbersArray as $randomToSiteLisanuimerot){
while($k <= $lottoRivinPituus){
$k++;
}
if($k >= 7){
array_push($lottoLisaNumerot, $randomToSiteLisanuimerot);
}
}
$arvottuLottoRivi = implode(' ', $arvottuLottoRivi);
$lottoLisaNumerot = implode(' ', $lottoLisaNumerot);
When you write:
foreach($tenNumbersArray as $randomToSiteLisanuimerot){
while($k <= $lottoRivinPituus){
$k++;
}
if($k >= 7){
array_push($lottoLisaNumerot, $randomToSiteLisanuimerot);
}
}
the while loop is equivalent to:
$k = $lottoRivinPituus + 1;
Since $lottoRivinPituus is 10, $k is always 11. Therefore, if($k >= 7) is always true, so all elements of $randomToSiteLisanuumerot are copied to $lottoLisaNumerot. Similarly, in the previous loop, the test if ($l <= 7) is always false, so nothing is copied to $arvottuLottoRivi.
I think you were trying to test the current position in the loop, not the count of all elements in the array. You can do it like this:
foreach($tenNumbersArray as $l => $randomToSite){
if($l < 7){
array_push($arvottuLottoRivi, $randomToSite);
}
}
foreach($tenNumbersArray as $k => $randomToSiteLisanuimerot){
if($k >= 7){
array_push($lottoLisaNumerot, $randomToSiteLisanuimerot);
}
}
But this wastes time iterating over elements it doesn't care about. A better way would be:
$arvotSize = min(7, $lottoRivinPituus);
for ($l = 0; $l < $arvotSize; $l++) {
array_push($arvottuLottoRivi, $tenNumbersArray[$l]);
}
for ($k = $arvotSize; $k < $lottoRivinPituus; $k++) {
array_push($lottoLisaNumerot, $tenNumbersArray[$k]);
}
I really didn't get your code.
Why don't use rand function?
$randomNumbers1 = array();
$randomNumbers2 = array();
$i = 0;
while ($i < 7) {
$aNumber = rand(1, 39);
if (!in_array($aNumber, $randomNumbers1)) {
$randomNumbers1[] = $aNumber;
$i++;
}
}
$i = 0;
while ($i < 2) {
$aNumber = rand(1, 39);
if (!in_array($aNumber, $randomNumbers2)) {
$randomNumbers2[] = $aNumber;
$i++;
}
}
And if the seconds array cannot contains any number within the first one:
$i = 0;
while ($i < 2) {
$aNumber = rand(1, 39);
if (!in_array($aNumber, $randomNumbers2) && !in_array($aNumber, $randomNumbers1)) {
$randomNumbers2[] = $aNumber;
$i++;
}
}
I created this function and it works on small strings, but for longer strings it times-out. I'm looking for a way to make the function work faster and not timeout, or a better way to accomplish what I want.
function find_diffs($string1, $string2)
{
$array1 = preg_split("/\b/", $string1);
$array2 = preg_split("/\b/", $string2);
$array3 = array();
for($i=0, $j=0; $i < count($array1) || $j < count($array2); $i++, $j++)
{
while(badchars($array1, $i))
{
$i++;
}
while(badchars($array2, $j))
{
$j++;
}
if($array1[$i] != $array2[$j])
{
//-------------------------Find Subtractions--------------------//
$k = $i;
while($array1[$i] != $array2[$j])
{
$i++;
if($i == count($array1))
{
$end = true;
break;
}
while(badchars($array1, $i))
{
$i++;
}
}
if($end)
{
//-------------------------Find Additions--------------------//
$end = false;
$i = $k;
$k = $j;
while($array1[$i] != $array2[$j])
{
$j++;
if($j == count($array2))
{
$end = true;
break;
}
while(badchars($array2, $j))
{
$j++;
}
}
if($end)
{
//-------------------------Find Changes--------------------//
$end = false;
$j = $k;
$l = $i;
while($array1[$i] != $array2[$j])
{
$k = $j;
while($array1[$i] != $array2[$j])
{
$j++;
if($j == count($array2))
{
$end = true;
break;
}
while(badchars($array2, $j))
{
$j++;
}
}
if($end)
{
$j = $k;
$i++;
while(badchars($array1, $i))
{
$i++;
}
while(badchars($array2, $j))
{
$j++;
}
}
else
{
$array3[] = array($l,$i,'-');
$array3[] = array($k,$j,'+');
}
if($i == count($array1))
{
$end = true;
break;
}
if($j == count($array2))
{
$end = true;
break;
}
$end=false;
}
if($end)
{
break;
}
else
{
$array3[] = array($l,$i,'-');
$array3[] = array($k,$j,'+');
}
//---------------------End Find Changes--------------------//
}
else
{
$array3[] = array($k,$j,'+');
}
}
else
{
$array3[] = array($k,$i,'-');
}
}
}
$array3[] = array(0,count($array1),'=');
return array($array1,$array2,$array3);
}
Don't reinvent the wheel. This is the sort of thing that is easy to get wrong and hard to get right.
Check out the Text_Diff Pear Package. I have used it for this sort of thing and it is very well done.