# Permission
7 read and write and execute (1+2+4)
6 read and write (2+4)
5 read and execute (1+4)
4 read only
3 write and execute (1+2)
2 write only
1 execute only
0 none
I like the pattern that you can store any combination of the options options in one integer number, and add options by doubling the last number (8, 16 ,32 etc).
I'd like to use this method, and I'd like to know if there's a name for it, and what is the fastest simplest method for turning numbers into results similar to this?
array(1=>false,2=>true,4=>true);//6
array(1=>true,2=>true,4=>true,8=>true);//15
Using bitwise operations as recommended. To get the array you are after.
This function will figure out the number of bit required for any value given and return the array in the format you suggested.
I've included a loop for 0 to 20 to verify.
<?php
function getBitArray($value) {
$numberOfBits = ceil(log($value + 1, 2));
$result = array();
$bit = 1;
for($i = 0; $i < $numberOfBits; $i++) {
$result[$bit] = ($value & $bit) == $bit;
$bit <<= 1;
}
return $result;
}
for($i = 0; $i < 20; $i++)
var_dump(getBitArray($i));
That's generally referred to as a bit field, and you can work with it using bitwise operators.
This method is known as bitwise operation, and is used in php like this. Here is a nice tutorial.
Related
<?php
$list = ['a', 'b', 'c'];
$count = [1, 3, 5];
function stringFormatter($c, $i) {
return "Char is $c & Int is $i";
}
for ($i = 0; i < $list; $i++) {
for ($j = 0; $j < $count; $j++) {
$string = stringFormatter($list[$i], $count[$j]);
print $string;
}
}
?>
This is sample code that I have rewritten to demonstrate an issue I'm having with a program where I want to assign a formatted string, with the right combination of char and int, to be able to execute an SQL statement, using said string. Ideal scenario is getting a string that has the combination of both char and int at that position in their respective lists. E.g. "Char is a & Int is 1". This doesn't currently compile and when I plug it into "Online PHP Sandbox" I get the error message: "Internal Server Error [500]." Any advice on how I could get this to work, or even alternative suggestions are welcome! Thanks in advance!
for ($i = 0; i < $list; $i++) {
for ($j = 0; $j < $count; $j++) {
There are a few syntax errors here - watch out for a missing $ (look at the i inside the outer loop). You probably mean something like $i<count($list) using the built in count function. Similarly in the inner loop you are referencing the $count array with $j<$count - do you mean $j<count($count) or are you using the outer array as in index for the inner element i.e. $j < $count[$i].
On a more general note there are a collection of functions built into php to better handle passing of values into mysql (etc) - you should probably be looking at using those - search on "sanitising" with php and mysqli.
I'm making a simple yahtzee script in PHP, I've got up the final point where it checks the 5 dice for a result at the end.
The 5 dice sides are stored in an array, example $dice (2,5,2,7,8)
I'm not that experienced in working with arrays, but is there easier ways to compare each number, to like find instances of 2 the same, 3 the same, all the same etc?
array_search() ?
array_count_values() might be a function that's worth looking at. It will count the number of instances of a value in an array.
Example:
$dice = array(2,5,2,7,7);
$count = array_count_values($dice);
if($n = array_keys($count, 2))
{
// 2 of a kind
// $n = array(2, 7)
}
if(array_keys($count, 4))
{
// 4 of a kind
}
if(array_keys($count, 2) && array_keys($count, 3))
{
// Full House
}
Just count them.
for ($i=0; $i<count($dice); $i++)
$counter[$dice[$i]]++;
Use:
var_dump(array_count_values($array));
I'm attempting to solve Project Euler in PHP and running into a problem with my for loop conditions inside the while loop. Could someone point me towards the right direction? Am I on the right track here?
The problem, btw, is to find the sums of all prime numbers below 2,000,000
Other note: The problem I'm encountering is that it seems to be a memory hog and besides implementing the sieve, I'm not sure how else to approach this. So, I'm wondering if I did something wrong in the implementation.
<?php
// The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
// Additional information:
// Sum below 100: 1060
// 1000: 76127
// (for testing)
// Find the sum of all the primes below 2,000,000.
// First, let's set n = 2 mill or the number we wish to find
// the primes under.
$n = 2000000;
// Then, let's set p = 2, the first prime number.
$p = 2;
// Now, let's create a list of all numbers from p to n.
$list = range($p, $n);
// Now the loop for Sieve of Eratosthenes.
// Also, let $i = 0 for a counter.
$i = 0;
while($p*$p < $n)
{
// Strike off all multiples of p less than or equal to n
for($k=0; $k < $n; $k++)
{
if($list[$k] % $p == 0)
{
unset($list[$k]);
}
}
// Re-initialize array
sort ($list);
// Find first number on list after p. Let that equal p.
$i = $i + 1;
$p = $list[$i];
}
echo array_sum($list);
?>
You can make a major optimization to your middle loop.
for($k=0; $k < $n; $k++)
{
if($list[$k] % $p == 0)
{
unset($list[$k]);
}
}
By beginning with 2*p and incrementing by $p instead of by 1. This eliminates the need for divisibility check as well as reducing the total iterations.
for($k=2*$p; $k < $n; $k += $p)
{
if (isset($list[k])) unset($list[$k]); //thanks matchu!
}
The suggestion above to check only odds to begin with (other than 2) is a good idea as well, although since the inner loop never gets off the ground for those cases I don't think its that critical. I also can't help but thinking the unsets are inefficient, tho I'm not 100% sure about that.
Here's my solution, using a 'boolean' array for the primes rather than actually removing the elements. I like using map,filters,reduce and stuff, but i figured id stick close to what you've done and this might be more efficient (although longer) anyway.
$top = 20000000;
$plist = array_fill(2,$top,1);
for ($a = 2 ; $a <= sqrt($top)+1; $a++)
{
if ($plist[$a] == 1)
for ($b = ($a+$a) ; $b <= $top; $b+=$a)
{
$plist[$b] = 0;
}
}
$sum = 0;
foreach ($plist as $k=>$v)
{
$sum += $k*$v;
}
echo $sum;
When I did this for project euler i used python, as I did for most. but someone who used PHP along the same lines as the one I did claimed it ran it 7 seconds (page 2's SekaiAi, for those who can look). I don't really care for his form (putting the body of a for loop into its increment clause!), or the use of globals and the function he has, but the main points are all there. My convenient means of testing PHP runs thru a server on a VMWareFusion local machine so its well slower, can't really comment from experience.
I've got the code to the point where it runs, and passes on small examples (17, for instance). However, it's been 8 or so minutes, and it's still running on my machine. I suspect that this algorithm, though simple, may not be the most effective, since it has to run through a lot of numbers a lot of times. (2 million tests on your first run, 1 million on your next, and they start removing less and less at a time as you go.) It also uses a lot of memory since you're, ya know, storing a list of millions of integers.
Regardless, here's my final copy of your code, with a list of the changes I made and why. I'm not sure that it works for 2,000,000 yet, but we'll see.
EDIT: It hit the right answer! Yay!
Set memory_limit to -1 to allow PHP to take as much memory as it wants for this very special case (very, very bad idea in production scripts!)
In PHP, use % instead of mod
The inner and outer loops can't use the same variable; PHP considers them to have the same scope. Use, maybe, $j for the inner loop.
To avoid having the prime strike itself off in the inner loop, start $j at $i + 1
On the unset, you used $arr instead of $list ;)
You missed a $ on the unset, so PHP interprets $list[j] as $list['j']. Just a typo.
I think that's all I did. I ran it with some progress output, and the highest prime it's reached by now is 599, so I'll let you know how it goes :)
My strategy in Ruby on this problem was just to check if every number under n was prime, looping through 2 and floor(sqrt(n)). It's also probably not an optimal solution, and takes a while to execute, but only about a minute or two. That could be the algorithm, or that could just be Ruby being better at this sort of job than PHP :/
Final code:
<?php
ini_set('memory_limit', -1);
// The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
// Additional information:
// Sum below 100: 1060
// 1000: 76127
// (for testing)
// Find the sum of all the primes below 2,000,000.
// First, let's set n = 2 mill or the number we wish to find
// the primes under.
$n = 2000000;
// Then, let's set p = 2, the first prime number.
$p = 2;
// Now, let's create a list of all numbers from p to n.
$list = range($p, $n);
// Now the loop for Sieve of Eratosthenes.
// Also, let $i = 0 for a counter.
$i = 0;
while($p*$p < $n)
{
// Strike off all multiples of p less than or equal to n
for($j=$i+1; $j < $n; $j++)
{
if($list[$j] % $p == 0)
{
unset($list[$j]);
}
}
// Re-initialize array
sort ($list);
// Find first number on list after p. Let that equal p.
$i = $i + 1;
$p = $list[$i];
echo "$i: $p\n";
}
echo array_sum($list);
?>
What is the correct way to check if bit field is turn on - (in php) ?
I want to check a bit field that come from db(mysql) if is turn on or not.
is this is the correct way ?
if($bit & 1)
Are there other ways ?
I see somebody code that using ord() function , it is correct ?
like if(ord($bit) == 1)
Use
if( $bit & (1 << $n) ) {
// do something
}
Where $n is the n-th bit to get minus one (for instance, $n=0 to get the least significant bit)
It's a bit late but might be usefull for future visitors to this question. I've made myself a little function that returns all bits that are active in a certain flag.
/**
* Shows all active bits
*
* #param int $flag
* #return array
*/
function bits($flag)
{
$setBits = array();
for ($i = 1; $i <= 32; $i++) {
if ($flag & (1 << $i)) {
$setBits[] = (1 << $i);
}
}
// Sort array to order the bits
sort($setBits);
return $setBits;
}
echo "<pre>";
var_dump(bits(63));
echo "</pre>";
I use
if (($flag & 0b010) == 0b010) {
// here we know that the second bit (dec 2) is set in $flag
}
Yes, if($bit & 1) is the correct way to check, according to the PHP manual.
An alternative could be to do the check in your MySQL query.
To get the correct bit, use this syntax:
$bit & (1 << $n)
Where $n is to get the (n+1)-th least significant bit. So $n=0 will get you the first least significant bit.
for($i=0;$i<$num;$i++) {
if($i==even) $hilite="hilite";
dothing($i,$hilite);
}
This is basically what I want to accomplish.
What is the most efficient way to determine if $i is even?
I know I could check if half == mod 2 ... but that seems a little excessive on the calculations? Is there a simpler way?
if ($i % 2 == 0)
The already mentioned % 2 syntax is most used, and most readable for other programmers. If you really want to avoid an 'overhead' of calculations:
for($i = 0, $even = true; $i < $num; $i++, $even =! $even) {
if($even) $hilite = "hilite";
dothing($i,$hilite);
}
Although the assignment itself is probably more work then the '%2' (which is inherently just a bit-shift).
It doesn't get any simpler than $i % 2 == 0. Period.
Change the i++ in the loop statement to i+=2, so that you only examine even values of i?
Typically, a number is odd if it's LSB (Least Significant Bit) is set. You can check the state of this bit by using the bitwise AND operator:
if($testvar & 1){
// $testvar is odd
}else{
// $testvar is even
}
In your code above, a more efficient way would be to have $i increment by 2 in every loop (assuming you can ignore odd-values):
for($i=0;$i<$num;$i+=2){
// $i will always be even!
}