Calculating Highly divisible triangular number with PHP - php

I am trying to resolve project euler problem no 12 with PHP but it is taking too much time to process. I came across with similar processing problems of PHP while solving previous problems and I had to solve them in C++ just to test whether my approach is correct or not.
I want to know whether there is something wrong with my approach or somehow I can do something to make processing fast. Here is the code of my solution which works well for the triangle having 360 divisors. The link of problem is http://projecteuler.net/problem=12 and here is my code
<?php
set_time_limit(0);
ini_set('memory_limit', '1G');
$triangles = array(0);
$count = 1;
$numOfDivisiors = 0;
$lastTriangle = 0;
while($numOfDivisiors < 500){
$triangle = (int) $lastTriangle + (int) $count;
$factors = getFactors($triangle);
//$triangles[] = array('triangle' => $triangle, 'factors' => $factors, 'factorsCount' => count($factors));
$triangles[] = array('triangle' => $triangle, 'factorsCount' => count($factors));
$lastTriangle = $triangle;
$numOfDivisiors = count($factors);
$count++;
//echo '<pre>'; print_r(array('triangle' => $triangle, 'factorsCount' => count($factors), 'count' => $count)); echo '</pre>';
}
echo $numOfDivisiors; exit;
/**
for($i = 0 ; $i < 10 ; $i++){
}
**/
//echo '<pre>'; print_r($triangles); exit;
function getFactors($number){
$factors = array();
$break = false;
$count = 1;
while($break != true){
$remainder = $number % $count;
if($remainder == 0){
$factors[] = $count;
}
//echo $count." ".$number; exit;
if($count == $number){
$break = true;
}
$count++;
}
return $factors;
}
?>

use some maths.
triangle numbers can be generated by
n(n+1) /2
and that if you can find the prime factors, Adding 1 to their powers and multiplying together gives the number of divisors.
My PHP solution takes around 4 seconds and i think i can speed that up also

There are several ways to speed up your solution. The first one I'd point you at is the following:
if a * b = c then both a and b are factors of c
One of a and b will be <= to the square root of c
this should help speed up your solution

Related

How to compare 2 numeric strings

I have 2 strings like this
$s1="32.56.86.90.23";
$s2="11.25.32.90.10";
I need to compare $s1 and $s2 and find if there are 2 or more numbers in common.
I am using this way
$s1_ar=explode(".",$s1);
$s2_ar=explode(".",$s2);
$result=array_diff($s1_ar,$s2_ar);
$rt1=5-count($result);
if($result>=2){ echo "YES"; } else {echo "no"; }
Since I need millions values of $s1 and $s2 and the code above seems to be slow, do you know alternative way to execute the work faster ?
I tested it with the following code, one million times, less than 2 seconds on my 3 years old laptop.
Loop 1M times takes no time, most time is used for displaying.
Comment off the display, 1M loops, 0.816432 seconds
Saved the results into a file, ~13.564MB, 0.731708 seconds
ob_start();
$t1 = microtime();
for($i=1; $i<=1000000; $i++) {
$s1="32.56.86.90.23";
$s2="10.25.30.90.10";
$s1_ar=explode(".",$s1);
$s2_ar=explode(".",$s2);
$result=array_diff($s1_ar,$s2_ar);
$rt1=5-count($result);
if($result>=2){ echo $i . " YES<br>"; } else {echo $i . " no<br>"; }
}
$out = ob_get_contents();
ob_end_clean();
var_dump($out);
echo '<p>'.(microtime() - $t1).'</p>';
Try this.
$s1="32.56.86.90.23";
$s2="11.23.32.90.10";
$s1_ar=explode(".",$s1);
$s2_ar=explode(".",$s2);
//assuming $s1_ar and $s2_ar both has unique values if not please make them unique
$result_array = array();
$hasMatch = 0;
for($i = 0; $i < count($s1_ar) && $i < count($s2_ar); $i++){
if(!isset($result_array[$s1_ar[$i]])){
$result_array[$s1_ar[$i]] = 1;
}else{
$result_array[$s1_ar[$i]]++;
}
if(!isset($result_array[$s2_ar[$i]])){
$result_array[$s2_ar[$i]] = 1;
}else{
$result_array[$s2_ar[$i]]++;
}
}
foreach($result_array as $result){
if($result >=2) $hasMatch++;
}
if($hasMatch >= 2)
echo "YES";
else
echo "NO";
I think it will solve your purpose.
Looking at: php array_intersect() efficiency
There's mention that array_intersect_key may be more efficient. But really it would be nice to have data and versions to compare results.
$s1 = "2.3.5.7.9.11.13.17";
$s2 = "2.3.4.5.6";
$s1 = array_flip(explode('.', $s1));
$s2 = array_flip(explode('.', $s2));
echo count(array_intersect_key($s1, $s2))>=2 ? 'yes' : 'no';
Output:
yes
I thought of a way to solve this in a 2*n complexity:
We loop one list and create an associative array from it's elements (LIST c) then we loop the second list and look up if the list c contains such an index/key ( c[element] ).
This shall be very light weighted :
$commons = 0;
$s1_fliped = array_flip($s1_ar)
foreach($s2_ar as $s2_el){
if ( isset($s1_fliped[$s2_el]) ){
$commons ++;
}
if($commons >=2) break;
});

If the array has more then 10 elements ... then what?

I have a top 10 list right here. The list contains all the IPs who visited the domain (out of my log files) and my code below gives me the top 10 IPs of them.
But I want it more dynamically. Like if there are more then 10 different IPs, give me just the 10 IPs that appear the most. If the amount of different IPs is less then 10, just give me all the IPs there are.
The code for this:
$all_ips = array_count_values($ip_array);
arsort($all_ips);
$count = count($all_ips);
$keys = array_keys($all_ips);
$topTenIp = array();
$count = $count -1;
for($i=0; $i <= $count; $i++){
if($count < 9){
$topTenIp[] = $keys[$i];
}else{
$topTenIp[] = $keys[$i];
}
}
This works okay but not perfect. If the amount of IPs is below 10, it gives me all the IPs there are. But if there are more then 10, it doesn't give me the 10 most appearing IPs, it just gives me all IPs of the log script.
I hope you understood what I was trying to say. I'm from Germany, so my English isn't that good.
Thanks anyway :)
I don't really see how this is related to Laravel at all, but anyway:
$counted = array_count_values($ipArray);
arsort($counted);
$top = array_keys(array_slice($counted, 0, 10));
Would be a faster, simpler way to get top 10 items, given that your source $ipArray is a simple array of IP addresses.
What you're doing isn't logical. Say $all_ips is 30 then every 30 iterations will execute in the else. Resulting in a array of 30 ip's.
You'll need to change your if and else part.
for($i=0; $i <= $count; $i++){
if($i < 9){
$topTenIp[] = $keys[$i];
} else {
break; //Break out of the loop
}
}
This is because you are doing same code in if and else condition.
You can do like this:
for($i=0; $i <= $count; $i++){
if($i < 9){
$topTenIp[] = $keys[$i];
}
}
please try the following
$all_ips = array_count_values($ip_array);
arsort($all_ips);
$count = count($all_ips);
$keys = array_keys($all_ips);
$topTenIp = array();
$count = $count -1;
for($i=0; $i <= $count; $i++){
if($count < 9){
$topTenIp[] = $keys[$i];
}else{
$topTenIp[] = $keys[$i];
}
if( $i >= 9 )
{
break;
}
}
in your code there is no check given if number count is grater than 10 , so please give a check , i have updated my answer

How to generate random numbers to produce a non-standard distributionin PHP

I've searched through a number of similar questions, but unfortunately I haven't been able to find an answer to this problem. I hope someone can point me in the right direction.
I need to come up with a PHP function which will produce a random number within a set range and mean. The range, in my case, will always be 1 to 100. The mean could be anything within the range.
For example...
r = f(x)
where...
r = the resulting random number
x = the mean
...running this function in a loop should produce random values where the average of the resulting values should be very close to x. (The more times we loop the closer we get to x)
Running the function in a loop, assuming x = 10, should produce a curve similar to this:
+
+ +
+ +
+ +
+ +
Where the curve starts at 1, peeks at 10, and ends at 100.
Unfortunately, I'm not well versed in statistics. Perhaps someone can help me word this problem correctly to find a solution?
interesting question. I'll sum it up:
We need a funcion f(x)
f returns an integer
if we run f a million times the average of the integer is x(or very close at least)
I am sure there are several approaches, but this uses the binomial distribution: http://en.wikipedia.org/wiki/Binomial_distribution
Here is the code:
function f($x){
$min = 0;
$max = 100;
$curve = 1.1;
$mean = $x;
$precision = 5; //higher is more precise but slower
$dist = array();
$lastval = $precision;
$belowsize = $mean-$min;
$abovesize = $max-$mean;
$belowfactor = pow(pow($curve,50),1/$belowsize);
$left = 0;
for($i = $min; $i< $mean; $i++){
$dist[$i] = round($lastval*$belowfactor);
$lastval = $lastval*$belowfactor;
$left += $dist[$i];
}
$dist[$mean] = round($lastval*$belowfactor);
$abovefactor = pow($left,1/$abovesize);
for($i = $mean+1; $i <= $max; $i++){
$dist[$i] = round($left-$left/$abovefactor);
$left = $left/$abovefactor;
}
$map = array();
foreach ($dist as $int => $quantity) {
for ($x = 0; $x < $quantity; $x++) {
$map[] = $int;
}
}
shuffle($map);
return current($map);
}
You can test it out like this(worked for me):
$results = array();
for($i = 0;$i<100;$i++){
$results[] = f(20);
}
$average = array_sum($results) / count($results);
echo $average;
It gives a distribution curve that looks like this:
I'm not sure if I got what you mean, even if I didn't this is still a pretty neat snippet:
<?php
function array_avg($array) { // Returns the average (mean) of the numbers in an array
return array_sum($array)/count($array);
}
function randomFromMean($x, $min = 1, $max = 100, $leniency = 3) {
/*
$x The number that you want to get close to
$min The minimum number in the range
$max Self-explanatory
$leniency How far off of $x can the result be
*/
$res = [mt_rand($min,$max)];
while (true) {
$res_avg = array_avg($res);
if ($res_avg >= ($x - $leniency) && $res_avg <= ($x + $leniency)) {
return $res;
break;
}
else if ($res_avg > $x && $res_avg < $max) {
array_push($res,mt_rand($min, $x));
}
else if ($res_avg > $min && $res_avg < $x) {
array_push($res, mt_rand($x,$max));
}
}
}
$res = randomFromMean(22); // This function returns an array of random numbers that have a mean close to the first param.
?>
If you then var_dump($res), You get something like this:
array (size=4)
0 => int 18
1 => int 54
2 => int 22
3 => int 4
EDIT: Using a low value for $leniency (like 1 or 2) will result in huge arrays, since testing, I recommend a leniency of around 3.

Defining percentage for random number

My rand(0,1) php function returns me the 0 and 1 randomly when I call it.
Can I define something in php, so that it makes 30% numbers will be 0 and 70% numbers will be 1 for the random calls? Does php have any built in function for this?
Sure.
$rand = (float)rand()/(float)getrandmax();
if ($rand < 0.3)
$result = 0;
else
$result = 1;
You can deal with arbitrary results and weights, too.
$weights = array(0 => 0.3, 1 => 0.2, 2 => 0.5);
$rand = (float)rand()/(float)getrandmax();
foreach ($weights as $value => $weight) {
if ($rand < $weight) {
$result = $value;
break;
}
$rand -= $weight;
}
You can do something like this:
$rand = (rand(0,9) > 6 ? 1 : 0)
rand(0,9) will produce a random number between 0 and 9, and whenever that randomly generated number is greater than 6 (which should be nearly 70% time), it will give you 1 otherwise 0...
Obviously, it seems to be the easiest solution to me, but definitely, it wont give you 1 exactly 70% times, but should be quite near to do that, if done correctly.
But, I doubt that any solution based on rand will give you 1 exactly 70% times...
Generate a new random value between 1 and 100. If the value falls below 30, then use 0, and 1 otherwise:
$probability = rand(1, 100);
if ($probability < 30) {
echo 0;
} else {
echo 1;
}
To test this theory, consider the following loop:
$arr = array();
for ($i=0; $i < 10000; $i++) {
$rand = rand(0, 1);
$probability = rand(1, 100);
if ($probability < 30) {
$arr[] = 0;
} else {
$arr[] = 1;
}
}
$c = array_count_values($arr);
echo "0 = " . $c['0'] / 10000 * 100;
echo "1 = " . $c['1'] / 10000 * 100;
Output:
0 = 29.33
1 = 70.67
Create an array with 70% 1 and 30% 0s. Then random sort it. Then start picking numbers from the beginning of the array to the end :)
$num_array = array();
for($i = 0; $i < 3; $i++) $num_array[$i] = 0;
for($i = 0; $i < 7; $i++) $num_array[$i] = 1;
shuffle($num_array);
Pros:
You'll get exactly 30% 0 and 70% 1 for any such array.
Cons: Might take longer computation time than a rand() only solution to create the initial array.
I searched for an answer to my question and this was the topic I found.
But it didn't answered my question, so I had to figure it out myself, and I did :).
I figured out that maybe this will help someone else as well.
It's regarding what you asked, but for more usage.
Basically, I use it as a "power" calculator for a random generated item (let's say a weapon). The item has a "min power" and a "max power" value in the db. And I wanted to have 80% chances to have the "power" value closer to the lower 80% of the max possible power for the item, and 20% for the highest 20% possible max power (that are stored in the db).
So, to do this I did the following:
$min = 1; // this value is normally taken from the db
$max = 30; // this value is normally taken from the db
$total_possibilities = ($max - $min) + 1;
$rand = random_int(1, 100);
if ($rand <= 80) { // 80% chances
$new_max = $max - ($total_possibilities * 0.20); // remove 20% from the max value, so you can get a number only from the lowest 80%
$new_rand = random_int($min, $new_max);
} elseif ($rand <= 100) { // 20% chances
$new_min = $min + ($total_possibilities * 0.80); // add 80% for the min value, so you can get a number only from the highest 20%
$new_rand = random_int($new_min, $max);
}
echo $new_rand; // this will be the final item power
The only problem you can have, is if the initial $min and $max variables are the same (or obviously, if the $max is bigger than the $min). This will throw an error since the random works like this ($min, $max), not the other way around.
This code can be very easily changed to have more percentages for different purposes, instead of 80% and 20% to put 40%, 40% and 20% (or whatever you need). I think the code is pretty much easy to read and understand.
Sorry if this is not helpful, but I hope it is :).
It can't do any harm either way ;).

Simple PHP program requires less time to execute

i had applied for a job recently and the requirement was to complete a test and then interview
2 questions were given for test which was very simple and i did it successfully but still i was told that i have failed the test because the script took more than 18 seconds to complete execution. here is the program i dont understand what else i could do to make it fast. although i have failed the test but still wants to know else i could do?
Program language is PHP and i had to do it using command line input
here is the question:
K Difference
Given N numbers , [N<=10^5] we need to count the total pairs of numbers that have a difference of K. [K>0 and K<1e9]
Input Format:
1st line contains N & K (integers).
2nd line contains N numbers of the set. All the N numbers are assured to be distinct.
Output Format:
One integer saying the no of pairs of numbers that have a diff K.
Sample Input #00:
5 2
1 5 3 4 2
Sample Output #00:3
Sample Input #01:
10 1
363374326 364147530 61825163 1073065718 1281246024 1399469912 428047635 491595254 879792181 1069262793
Sample Output #01:
0
Note: Java/C# code should be in a class named "Solution"
Read input from STDIN and write output to STDOUT.
and this is the solution
$fr = fopen("php://stdin", "r");
$fw = fopen("php://stdout", "w");
fscanf($fr, "%d", $total_nums);
fscanf($fr, "%d", $diff);
$ary_nums = array();
for ($i = 0; $i < $total_nums; $i++) {
fscanf($fr, "%d", $ary_nums[$i]);
}
$count = 0;
sort($ary_nums);
for ($i = $total_nums - 1; $i > 0; $i--) {
for ($j = $i - 1; $j >= 0; $j--) {
if ($ary_nums[$i] - $ary_nums[$j] == $diff) {
$count++;
$j = 0;
}
}
}
fprintf($fw, "%d", $count);
Your algorithm's runtime is O(N^2) that is approximately 10^5 * 10^5 = 10^10. With some basic observation it can be reduced to O(NlgN) which is approximately 10^5*16 = 1.6*10^6 only.
Algorithm:
Sort the array ary_nums.
for every i'th integer of the array, make a binary search to find if ary_nums[i]-K, is present in the array or not. If present increase result, skip i'th integer otherwise.
sort($ary_nums);
for ($i = $total_nums - 1; $i > 0; $i--) {
$hi = $i-1;
$low = 0;
while($hi>=$low){
$mid = ($hi+$low)/2;
if($ary_nums[$mid]==$ary_nums[$i]-$diff){
$count++;
break;
}
if($ary_nums[$mid]<$ary_nums[$i]-$diff){
$low = $mid+1;
}
else{
$hi = $mid-1;
}
}
}
}
I got the same question for my technical interview. I wonder if we are interviewing for the same company. :)
Anyway, here is my answer I came up with (after the interview):
// Insert code to get the input here
$count = 0;
sort ($arr);
for ($i = 0, $max = $N - 1; $i < $max; $i++)
{
$lower_limit = $i + 1;
$upper_limit = $max;
while ($lower_limit <= $upper_limit)
{
$midpoint = ceil (($lower_limit + $upper_limit) / 2);
$diff = $arr[$midpoint] - $arr[$i];
if ($diff == $K)
{
// Found it. Increment the count and break the inner loop.
$count++;
$lower_limit = $upper_limit + 1;
}
elseif ($diff < $K)
{
// Search to the right of midpoint
$lower_limit = $midpoint + 1;
}
else
{
// Search to the left of midpoint
$upper_limit = $midpoint - 1;
}
}
}
#Fallen: Your code failed for the following inputs:
Enter the numbers N and K: 10 3
Enter numbers for the set: 1 2 3 4 5 6 7 8 9 10
Result: 6
I think it has to do with your calculation of $mid (not accounting for odd number)

Categories