I'm not sure why, but I've created a function and somehow it never return anything.
It supposed to return a random number generated by using the mt_rand() function.
I modified the code and tried to run it on ideone and the results says runtime error, signal 11 (SIGSEGV)
Can someone tell me what's wrong with this?
<?php
function breedingTree($name, $N, $max)
{
include('config.php');
if ($N < $max AND $name > 0)
{
$sql = 'SELECT sire, dam
FROM '.$prefix.'owned_adoptables
WHERE aid = "'.$name.'"';
$res = mysql_query($sql);
list($s, $d) = mysql_fetch_row($res);
if (mt_rand(0,1) === 1) breedingTree($s, $N+1, $max);
else breedingTree($d, $N+1, $max);
}
elseif ($name <= 0)
{
if ($N === 0) return mt_rand(1,100);
elseif ($N === 1) return mt_rand(5,95);
elseif ($N === 2) return mt_rand(15,85);
elseif ($N === 3) return mt_rand(25,75);
}
}
echo breedingTree(355, 0, 4); // Return nothing
echo breedingTree(0, 0, 4); // Return random number between 1 - 100
?>
What if $N is not 0, 1, 2, or 3, or if ($N < $max AND $name > 0), or if ($N >= max AND $name > 0)? There is no return statement for those code paths.
Related
I had a job interview test and the question I got was about making a function which would return the number of ways a number could be generated by using numbers from a certain set and any number in the set can be used N times.
It is like if I have the number 10 and I want to find out how many ways 10 can be generated using [2,3,5]
2+2+2+2+2 = 10
5+3+2 = 10
2+2+3+3 = 10
5+5 = 10
to solve it I made this function:
function getNumberOfWays($money, $coins) {
static $level = 0;
if (!$level) {
sort($coins);
}
if ($level && !$money) {
return 1;
} elseif (!$level && !$money) {
return 0;
}
if ($money === 1 && array_search(1, $coins) !== false) {
return 1;
} elseif ($money === 1 && array_search(1, $coins) === false) {
return 0;
}
$r = 0;
$tmpCoins = $coins;
foreach ($coins as $index => $coin) {
if (!$coin || $coin > $money) {
continue;
}
$tmpCoins[$index] = 0;
$tmpMoney = $money;
do {
$tmpMoney -= $coin;
if ($tmpMoney >= 0) {
$level++;
$r += getNumberOfWays($tmpMoney, $tmpCoins);
$level--;
} elseif (!$tmpMoney) {
$r++;
}
} while ($tmpMoney >= 0);
}
return $r;
}
This function works ok and returns the right value.
My question is if there is a better way for it.
Thanks
I created this function to converting numbers to words. And how I can convert words to number using this my function:
Simple function code:
$array = array("1"=>"ЯК","2"=>"ДУ","3"=>"СЕ","4"=>"ЧОР","5"=>"ПАНҶ","6"=>"ШАШ","7"=>"ҲАФТ","8"=>"ХАШТ","9"=>"НӮҲ","0"=>"НОЛ","10"=>"ДАҲ","20"=>"БИСТ","30"=>"СИ","40"=>"ЧИЛ","50"=>"ПАНҶОҲ","60"=>"ШАСТ","70"=>"ҲАФТОД","80"=>"ХАШТОД","90"=>"НАВАД","100"=>"САД");
$n = "98"; // Input number to converting
if($n < 10 && $n > -1){
echo $array[$n];
}
if($n == 10 OR $n == 20 OR $n == 30 OR $n == 40 OR $n == 50 OR $n == 60 OR $n == 70 OR $n == 80 OR $n == 90 OR $n == 100){
echo $array[$n];
}
if(mb_strlen($n) == 2 && $n[1] != 0)
{
$d = $n[0]."0";
echo "$array[$d]У ".$array[$n[1]];
}
My function so far converts the number to one hundred. How can I now convert text to a number using the answer of my function?
So, as #WillParky93 assumed, your input has spaces between words.
<?php
mb_internal_encoding("UTF-8");//For testing purposes
$array = array("1"=>"ЯК","2"=>"ДУ","3"=>"СЕ","4"=>"ЧОР","5"=>"ПАНҶ","6"=>"ШАШ","7"=>"ҲАФТ","8"=>"ХАШТ","9"=>"НӮҲ","0"=>"НОЛ","10"=>"ДАҲ","20"=>"БИСТ","30"=>"СИ","40"=>"ЧИЛ","50"=>"ПАНҶОҲ","60"=>"ШАСТ","70"=>"ҲАФТОД","80"=>"ХАШТОД","90"=>"НАВАД","100"=>"САД");
$postfixes = array("3" => "ВУ");
$n = "98"; // Input number to converting
$res = "";
//I also optimized your conversion of numbers to words
if($n > 0 && ($n < 10 || $n%10 == 0))
{
$res = $array[$n];
}
if($n > 10 && $n < 100 && $n%10 != 0)
{
$d = intval(($n/10));
$sd = $n%10;
$ending = isset($postfixes[$d]) ? $postfixes[$d] : "У";
$res = ($array[$d * 10]).$ending." ".$array[$sd];
}
echo $res;
echo "\n<br/>";
$splitted = explode(" ", $res);
//According to your example, you use only numerals that less than 100
//So, to simplify your task(btw, according to Google, the language is tajik
//and I don't know the rules of building numerals in this language)
if(sizeof($splitted) == 1) {
echo array_search($splitted[0], $array);
}
else if(sizeof($splitted) == 2) {
$first = $splitted[0];
$first_length = mb_strlen($first);
if(mb_substr($first, $first_length - 2) == "ВУ")
{
$first = mb_substr($first, 0, $first_length - 2);
}
else
{
$first = mb_substr($splitted[0], 0, $first_length - 1);
}
$second = $splitted[1];
echo (array_search($first, $array) + array_search($second, $array));
}
You didn't specify the input specs but I took the assumption you want it with a space between the words.
//get our input=>"522"
$input = "ПАНҶ САД БИСТ ДУ";
//split it up
$split = explode(" ", $input);
//start out output
$c = 0;
//set history
$history = "";
//loop the words
foreach($split as &$s){
$res = search($s);
//If number is 9 or less, we are going to check if it's with a number
//bigger than or equal to 100, if it is. We multiply them together
//else, we just add them.
if((($res = search($s)) <=9) ){
//get the next number in the array
$next = next($split);
//if the number is >100. set $nextres
if( ($nextres = search($next)) >= 100){
//I.E. $c = 5 * 100 = 500
$c = $nextres * $res;
//set the history so we skip over it next run
$history = $next;
}else{
//Single digit on its own
$c += $res;
}
}elseif($s != $history){
$c += $res;
}
}
//output the result
echo $c;
function search($s){
global $array;
if(!$res = array_search($s, $array)){
//grab the string length
$max = strlen($s);
//remove one character at a time until we find a match
for($i=0;$i<$max; $i++ ){
if($res = array_search(mb_substr($s, 0, -$i),$array)){
//stop the loop
$i = $max;
}
}
}
return $res;
}
Output is 522.
I'm trying to solve a backward prime question.
Following is the question:
Find all Backwards Read Primes between two positive given numbers (both inclusive), the second one being greater than the first one. The resulting array or the resulting string will be ordered following the natural order of the prime numbers.
Example
backwardsPrime(2, 100) => [13, 17, 31, 37, 71, 73, 79, 97]
backwardsPrime(9900, 10000) => [9923, 9931, 9941, 9967]
I tried doing something like this:
public function backwardPrime()
{
$start = 7000;
$stop = 7100;
$ans = [];
while($start <= $stop)
{
if($start > 10)
{
if($start !== $this->reverse($start))
{
if($this->isPrime($start) && $this->isPrime($this->reverse($start)))
{
array_push($ans, $start);
}
}
}
$start++;
}
return $ans;
}
public function reverse($num)
{
$reverse = 0;
while($num > 0)
{
$reverse = $reverse * 10;
$reverse = $reverse + $num%10;
$num = (int)($num/10);
}
return $reverse;
}
public function isPrime($num)
{
if($num == 1 || $num == 2 || $num == 3)
return true;
elseif ($num%2 == 0 || $num%3 == 0)
return false;
else
{
$i=5;
while($i<=$num/2)
{
if($num%$i===0)
{
return false;
}
$i++;
}
}
return true;
}
I'm able to get the appropriate answer but while doing the same in single function I'm not able to get it:
public function backwardPrimes()
{
$start = 7000;
$stop = 7100;
$ans = [];
while($start <= $stop)
{
$isStartPrime = true;
$isReversePrime = true;
if($start > 10)
{
$reverse = 0;
$num = $start;
while($num > 0)
{
$reverse = $reverse * 10;
$reverse = $reverse + $num%10;
$num = (int)($num/10);
}
if($start !== $reverse)
{
if($start%2 != 0 && $start%3 != 0)
{
$i =5;
while($i<=$start/2)
{
if($start%$i === 0)
{
$isStartPrime = false;
break;
}
$i++;
}
}
if($reverse%2 != 0 && $reverse%3 != 0)
{
$i =5;
while($i<=$reverse/2)
{
if($reverse%$i === 0)
{
$isReversePrime = false;
break;
}
$i++;
}
}
if($isStartPrime && $isReversePrime)
{
array_push($ans, $start);
}
}
}
$start++;
}
return $ans;
}
I don't know where I'm having mistake, guide me.
Thanks.
An emirp ("prime" spelled backwards) is a prime whose (base 10) reversal is also prime, but which is not a palindromic prime. in other words
Backwards Read Primes are primes that when read backwards in base 10 (from right to left) are a different prime. (This rules out primes which are palindromes.)
try this short solution in which I use two helper function reverse and isPrime :
isPrime: Thanks to #Jeff Clayton for his method to test prime numbers, for more information click the link below https://stackoverflow.com/a/24769490/4369087
reverse: that use the php function [strrev()][1], this method take a string a reverse it, we'll use this trick to reverse a number by converting it to a string reverse it and converting back to an integer.
backwardsPrime: this last function's job is itterating over a range of numbers from $min value to $max value and test if the number if a prime number and it's reverse is a prime number as well and it's not a palindrome number if all of those conditions are true then we addit to the result array.
implementation
function isPrime($number)
{
return !preg_match('/^1?$|^(11+?)\1+$/x', str_repeat('1', $number));
}
function reverse($n)
{
return (int) strrev((string) $n);
}
function backwardsPrime($min, $max)
{
$result = [];
foreach(range($min, $max) as $number) {
$reverse = reverse($number);
if($reverse !== $number && isPrime($number) && isPrime($reverse)) {
$result[] = $number;
}
}
return $result;
}
echo "<pre>";
print_r(backwardsPrime(2, 100));
print_r(backwardsPrime(9900, 10000));
output :
Array
(
[0] => 13
[1] => 17
[2] => 31
[3] => 37
[4] => 71
[5] => 73
[6] => 79
[7] => 97
)
Array
(
[0] => 9923
[1] => 9931
[2] => 9941
[3] => 9967
)
you can even optimize the backwardsPrime function like this :
function backwardsPrime($min, $max)
{
$result = [];
foreach(range($min, $max) as $number) {
$reverse = reverse($number);
if($reverse !== $number && !in_array($number, $result) && isPrime($number) && isPrime($reverse)) {
$result[] = $number;
}
}
return $result;
}
This question already has answers here:
Shorten long numbers to K/M/B?
(14 answers)
Closed 8 years ago.
I need to show a page views value in the format of 1K of equal to one thousand, or 1.1K, 1.2K, 1.9K etc, if its not an even thousands, otherwise if under a thousand, display normal 500, 100, 250 etc, using PHP to format the number?
I'm using:--
function count_number($n) {
// first strip any formatting;
$n = (0+str_replace(",","",$n));
// is this a number?
if(!is_numeric($n)) return false;
// now filter it;
if($n>1000000000000) return round(($n/1000000000000),1).'T';
else if($n>1000000000) return round(($n/1000000000),1).'G';
else if($n>1000000) return round(($n/1000000),1).'M';
else if($n>1000) return round(($n/1000),1).'K';
return number_format($n);
}
BUT it does not work correctly...
If my page visted 2454 times, it shows 2.5k and if 2990, it shows 3k...
How o fix that problem??
I want to SHOW Like --> if page visited 2454 -> how to display 2.4k and if 2990 -> 2.9k, if 3000 -> 3k etc
Plz help me...
Thanks # MonkeyZeus
Now itz DONE...
function kilo_mega_giga($n) {
if($n >= 1000 && $n < 1000000)
{
if($n%1000 === 0)
{
$formatted = ($n/1000);
}
else
{
$formatted = substr($n, 0, -3).'.'.substr($n, -3, 1);
if(substr($formatted, -1, 1) === '0')
{
$formatted = substr($formatted, 0, -2);
}
}
$formatted.= 'k';
} else
if($n >= 1000000 && $n < 1000000000)
{
if($n%1000000 === 0)
{
$formatted = ($n/1000000);
}
else
{
$formatted = substr($n, 0, -6).'.'.substr($n, -6, 1);
if(substr($formatted, -1, 1) === '0')
{
$formatted = substr($formatted, 0, -2);
}
}
$formatted.= 'M';
} else
if($n >= 1000000000 && $n < 1000000000000)
{
if($n%1000000000 === 0)
{
$formatted = ($n/1000000000);
}
else
{
$formatted = substr($n, 0, -9).'.'.substr($n, -9, 1);
if(substr($formatted, -1, 1) === '0')
{
$formatted = substr($formatted, 0, -2);
}
}
$formatted.= 'G';
} else
if($n >= 0 && $n < 1000)
{
$formatted= $n;
}
return $formatted;
}
You can use this to calculate thousands. You can use this formula to figure out the formula for millions as well.
$n = 2000;
$formatted = '';
if($n >= 1000 && $n < 1000000)
{
if($n%1000 === 0)
{
$formatted = ($n/1000);
}
else
{
$formatted = substr($n, 0, -3).'.'.substr($n, -3, -2);
if(substr($formatted, -1, 1) === '0')
{
$formatted = substr($formatted, 0, -2);
}
}
$formatted.= 'k';
}
echo $formatted;
Also, please use curly braces, ALWAYS. Future you will thank present you.
What about number greater than 10000
function facebookFormattter($digit) {
if ($digit >= 1000000000) {
return round($digit/ 1000000000, 1). 'G';
}
if ($digit >= 1000000) {
return round($digit/ 1000000, 1).'M';
}
if ($digit >= 1000) {
return round($digit/ 1000, 1). 'K';
}
return $digit;
}
I have written a PHP function to add the appropriate stems to each rank. I.E. 1st 2nd 3rd... so on and so forth.
When $num = 0 the displayed result is "0th", is there a way to display this a 'No Data' instead?
function ordinalSuffix($num) {
$suffixes = array("st", "nd", "rd");
$lastDigit = $num % 10;
if(($num < 20 && $num > 9) || $lastDigit == 0 || $lastDigit > 3) return "th";
return $suffixes[$lastDigit - 1];
}
Like this?
function ordinalSuffix($num) {
//Check if $num is equal to 0
if($num == 0){
//return
return 'No Data';
}
$suffixes = array("st", "nd", "rd");
$lastDigit = $num % 10;
if(($num < 20 && $num > 9) || $lastDigit == 0 || $lastDigit > 3) return "th";
return $suffixes[$lastDigit - 1];
}
function ordinalSuffix($num) {
$suffixes = array("st", "nd", "rd");
$lastDigit = $num % 10;
if(($num < 20 && $num > 9) || $lastDigit == 0 || $lastDigit > 3)
{
return "th";
}
elseif($num == "0")
{
return "no data";
}
return $suffixes[$lastDigit - 1];
}
This does not add to your function but I thought it would be fun to post a one-line solution anyways.
function ordinalSuffix($n) {
return ($n==0?'No Data':date('S',mktime(0,0,0,1,($n%10==0?9:($n%100>20?$n%10:$n%100)),2000)));
}