How to store and reset a PHP array pointer? - php

I have an associative array, ie
$primes = array(
2=>2,
3=>3,
5=>5,
7=>7,
11=>11,
13=>13,
17=>17,
// ...etc
);
then I do
// seek to first prime greater than 10000
reset($primes);
while(next($primes) < 10000) {}
prev($primes);
// iterate until target found
while($p = next($primes)) {
$res = doSomeCalculationsOn($p);
if( IsPrime($res) )
return $p;
}
The problem is that IsPrime also loops through the $primes array,
function IsPrime($num) {
global $primesto, $primes, $lastprime;
if ($primesto >= $num)
// using the assoc array lets me do this as a lookup
return isset($primes[$num]);
$root = (int) sqrt($num);
if ($primesto < $root)
CalcPrimesTo($root);
foreach($primes as $p) { // <- Danger, Will Robinson!
if( $num % $p == 0 )
return false;
if ($p >= $root)
break;
}
return true;
}
which trashes the array pointer I am iterating on.
I would like to be able to save and restore the array's internal pointer in the IsPrime() function so it doesn't have this side effect. Is there any way to do this?

You can "save" the state of the array:
$state = key($array);
And "restore" (not sure if there's a better method):
reset($array);
while(key($array) != $state)
next($array);

Don't rely on array pointers. Use iterators instead.
You can replace your outer code with:
foreach ($primes as $p) {
if ($p > 10000 && IsPrime(doSomeCalculationsOn($p))) {
return $p;
}
}

If speed is not an issue and you aren't pushing php memory limits the quickest solution is just to duplicate your primes array and iterate 2 different ones.
$awesomePrimes=$primes;
Then change globals and foreach in your function to $awesomePrimes

How about doing one more array of int -> int, where the the index is a running number from 0 to n and the value is the index of the associative array? So, you would have:
$pointer = array(
0 => 2,
1 => 3,
2 => 5,
// ...
);
and instead of referring directly to $prime you would use $prime[$pointer[$i]], or something similar?

use a "for" loop for one of your iterations. for example use this loop in your IsPrime method:
$primesLength = count($primes); // this is to avoid calling of count() so many times.
for ($counter=0 ; $counter < $primesLength ; $counter++) {
$p = $primesLength[$counter];
if( $num % $p == 0 )
return false;
if ($p >= $root)
break;
}
this way the internal array pointer will not be used in the method.

Related

Right rotation on array in php

I have an array for example
$a = [1,2,3,4,5];
From this $a, how to take last one and set it first like [5,1,2,3,4]
And how do I take last two arrays to make it like [4,5,1,2,3]
You can combine using array_pop(), which pops the last element of the array out, and array_unshift() to push it to the front of the array. You can create a simple function for this,
function array_pop_unshift($array) {
array_unshift($array, array_pop($array));
return $array;
}
Then use it as
$a = [1,2,3,4,5];
$new = array_pop_unshift($a);
print_r($new); // [5,1,2,3,4]
To continue shifting it, just call the function again until you're done, for instance through a for loop,
$a = [1,2,3,4,5];
for ($i = 0; $i < 2; $i++) {
$new = array_pop_unshift($a);
}
print_r($new); // [4,5,1,2,3]
Live demo at https://3v4l.org/CoJZZ
If you want to avoid the cost of several array_unshift and array_pop, you can build a generator that plays with the array internal pointer.
If you really need a result array, use iterator_to_array() to create it:
$a = range(1,5);
function rotate(&$array, $step = 1) {
$length = count($array);
end($array);
while ($step--)
prev($array);
while ($length--) {
next($array);
if (key($array) === null)
reset($array);
yield current($array);
}
}
print_r(iterator_to_array(rotate($a, 2))); // [4,5,1,2,3]
demo
Note that the rotate() generator uses a reference to avoid the array copy but doesn't modify the orginal array: it only moves the array pointer n times (where n is the array length) from the choosen position. When the array pointer is out of the array (key() returns null) the array pointer is reseted. In other words it stays efficient even with a large array and many rotations (what I have called "step" in the code).
You are actually doing right rotation, not left. Anyway, here are functions for doing both of them. They are probably not the most efficient but they are short in code and pretty self-explanatory:
<?php
function rotateLeft($array, $times) {
for($i=0; $i<$times; $i++){
$array[] = array_shift($array);
}
return $array;
}
function rotateRight($array, $times) {
for($i=0; $i<$times; $i++){
array_unshift($array, array_pop($array));
}
return $array;
}
$a = [1,2,3,4,5];
$a = rotateRight($a, 1);
print_r($a);
?>
to take last one and set it first This is known as right rotation.
And
$k is the number of units the shifting should be. $a is the array.
for($x=0; $x < $k; $x++){
//remove last element
$last = array_pop($a);
//push last element to the beginning
array_unshift($a, $last);
}
array_pop() pops and returns the value of the last element of array, shortening the array by one element.
https://www.php.net/manual/en/function.array-pop.php
array_unshift() prepends passed elements to the front of the array
https://www.php.net/manual/en/function.array-unshift.php
You could create a function that takes two arguments $k(number of rotations), $a (the array) and returns the array after performing right rotation $k times.
function rotateRight($a, $k){
for($x=0; $x < $k; $x++){
//remove last element
$last = array_pop($a);
//push last element to the beginning
array_unshift($a, $last);
}
return $a;
}
And then call it accordingly.
Example:
$a = [1,2,3,4,5];
$a_one_shift = rotateRight($a, 1);
// [5,1,2,3,4];
$a_two_shift = rotateRight($a_one_shift, 1);
// [4,5,1,2,3];
Or you could pass 2 to directly get the array after two right rotations.
$a_new = rotateRight($a, 2);
// [4,5,1,2,3];
Rather than making iterated calls of array_pop() and array_unshift(), use an efficient, elegant approach that makes fewer function calls and has the lowest possible time complexity. Using early returns prevents making needless function calls for the same result.
Code: (Demo)
function popUnshift(array $indexedArray, int $popShiftsCount): array
{
$count = count($indexedArray);
if ($count < 2) {
return $indexedArray; // array cannot be rotated
}
$remainder = $popShiftsCount % $count;
if (!$remainder) {
return $indexedArray; // sought rotation is the original order
}
return array_merge(
array_splice($indexedArray, -$remainder),
$indexedArray
);
}
Disclosure: This answer was built on the CodeReview page (Codility cyclic rotation solution in PHP) where I offered this snippet in my review.
//$A input array, $K rotation times
function solution($A, $K) {
$new = array();
for($j=1;$j<=$K;$j++)
{
if(count($new)>0)
$A = $new;
for($i=0;$i<count($A);$i++)
{
if($i==0)
$new[$i] = $A[count($A)-1];
else
$new[$i] = $A[$i-1];
}
}
return $new;}

Listing an array of data ordered by how often they appear [duplicate]

Say I have an array like this:
$array = array('', '', 'other', '', 'other');
How can I count the number with a given value (in the example blank)?
And do it efficiently? (for about a dozen arrays with hundreds of elements each)
This example times out (over 30 sec):
function without($array) {
$counter = 0;
for($i = 0, $e = count($array); $i < $e; $i++) {
if(empty($array[$i])) {
$counter += 1;
}
}
return $counter;
}
In this case the number of blank elements is 3.
How about using array_count _values to get an array with everything counted for you?
Just an idea, you could use array_keys( $myArray, "" ) using the optional second parameter which specifies a search-value. Then count the result.
$myArray = array( "","","other","","other" );
$length = count( array_keys( $myArray, "" ));
I dont know if this would be faster but it's something to try:
$counter = 0;
foreach($array as $value)
{
if($value === '')
$counter++;
}
echo $counter;
You could also try array_reduce, with a function which would just count the value you are interested in. eg
function is_empty( $v, $w )
{ return empty( $w ) ? ($v + 1) : $v; }
array_reduce( $array, 'is_empty', 0 );
Some benchmarking might tell you if this is faster than array_count_values()
We use array_filter function to find out number of values in array
$array=array('','','other','','other');
$filled_array=array_filter($array);// will return only filled values
$count=count($filled_array);
echo $count;// returns array count
Generally for counting blanks only.
Really depends on use case and speed needed. Personally I like doing things one one line.
Like the chosen response though But you still need a line to extract the data needed though to another variable.
$r = count($x) - count(array_filter($x));
function arrayvaluecount($array) {
$counter = 0;
foreach($array as $val){
list($v)=$val;
if($v){
$counter =$counter+1;
}
}
return $counter;
}
function countarray($array)
{ $count=count($array);
return $count;
}
$test=$array = array('', '', 'other', '', 'other');
echo countarray($test);

Reorder elements in array evenly

Say i have:
$array = (1,1,1,1,2,2,2,2,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
What I'm trying to achive is to reorder elements evenly in it.
PHP's function shuffle() don't fits here, because i want some distance between same digits. So 1's has to be somewhere in the beginning of array, in the middle and in the end too.
I google about Fisher-Yates_shuffle algorithm, but it seems to work exactly like shuffle().
Thanks in advance!
I think this is close to what you ask: A constant, reasonably even distribution of the items in an array.
// The input array. 0s are regarded as blanks.
$array = array(1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
// Count the times each item occurs. PHP will probably have a function for that, but I don't know.
$counter = array();
foreach ($array as $item)
{
// Zeros are infill. Don't process them now, only process the other numbers and
// the zeros will occupy the remaining space.
if ($item === 0)
continue;
if (!array_key_exists($item, $counter))
$counter[$item] = 0;
$counter[$item]++;
}
// Reverse sort by quantity. This results in the best distribution.
arsort($counter);
// Pre-fill a new array with zeros.
$resultCount = count($array);
$result = array_fill(0, $resultCount, 0);
// Distribute the items in the array, depending on the number of times they occur.
foreach ($counter as $item => $count)
{
// Determine the division for this item, based on its count.
$step = $resultCount / $count;
// Add the item the right number of times.
for ($i = 0; $i < $count; $i++)
{
// Start with the index closest to the preferred one (based on the calculated step).
$index = 0;
$startIndex = (int)($step * $i);
// Count up until a right index is found.
for ($index = $startIndex; $index < $resultCount; $index++)
{
if ($result[$index] === 0)
{
$result[$index] = $item;
break;
}
}
// If no proper index was found, count fown from the starting index.
if ($index === $resultCount)
{
for ($index = $startIndex; $index >= 0; $index--)
{
if ($result[$index] === 0)
{
$result[$index] = $item;
break;
}
}
}
// Still no proper index found, that shouldn't be possible. There's always room.
if ($index === -1)
{
throw new Exception('This cannot not happen');
}
}
}
var_dump($result);
For array:
1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
It returns:
3,2,1,0,3,0,0,0,3,0,2,1,3,0,0,0,3,0,0,0,0,3,2,1,0,3,0,0,0,3,0,2,1,3,0,0,0,3,0,0,0,0
For array:
1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,0,0
It returns:
4,4,3,4,3,4,2,4,3,4,2,4,3,4,1,4,3,4,1,4,0,4,4,3,4,3,4,2,4,3,4,2,4,3,4,1,4,3,4,1,4,0
Which I think is a neat distribution. Thanks to datdo for the idea of sorting the intermediate array.

PHP Array shuffle, keeping unique

this is my first php script and problem, I've searched hours with no conclusion other than looping a function" too many laterations". but it doesn't solve my problem I've never studied programming or what ever so I'm hoping that there is an educated person to fill me in on this:
I have an array that contains 120 elements; consists of duplicates eg:
myArray = [0]= item_1, [1] = item _1, [2] = item_2, [3] = item_3 ect..
Briefly I'm trying to make a flash php pokermachine but I need these items in the array to be shuffled BUT I do not want the duplicates to be next to each other after the shuffle but I need the duplicates to be still in the array
I can't do a loop function to check this because it will change the shuffle too many times which will effect the odds of the game: below is what I currently have:
/ * Removed the link here that is no longer available */
you may notice at times it will double up with 2 items in the same reel
Basically I created the virtual reel dynamically with php.ini file
these values are repeatedly pushed into an array($virtualreel) so the value may appear 10 times in the reel and another value will appear 5 times variating the odds. Then after I take a random slice() from the $virtualreel to display 3 vars from this reel and repeat the loop 4 more times for the other reels, also I only can shuffle once as I want the slice() to be from the same reels array order
I only shuffle every new spin not running loop functions to shuffle if I double up on a slice(array,3 items).
hope I've explained what I'm after well enough to give you guys an idea.
You can use this function:
<?php
function shuffleArray($myArray) {
$value_count = array_count_values($myArray);
foreach($value_count as $key=>$value) {
if ($value > count($myArray)/2) {
return false;
}
}
$last_value = $myArray[count($myArray) - 1];
unset($myArray[count($myArray) - 1]);
$shuffle = array();
$last = false;
while (count($myArray) > 0) {
$keys = array_keys($myArray);
$i = round(rand(0, count($keys) - 1));
while ($last === $myArray[$keys[$i]]) {
$i = round(rand(0, count($keys) - 1));
}
$shuffle[] = $myArray[$keys[$i]];
$last = $myArray[$keys[$i]];
unset($myArray[$keys[$i]]);
}
if ($last_value === $last) {
$i = 0;
foreach($shuffle as $key=>$value) {
if ($value !== $last_value) {
$i = $key;
break;
}
}
array_splice($shuffle, $i + 1, 0, $last_value);
} else {
$shuffle[] = $last_value;
}
return $shuffle;
}
print_r(shuffleArray(array(1,5,5,3,7,7)));
Why not just:
Edit :
$shuffled = array();
while(count($to_shuffle) > 0):
$i = rand(0, count($to_shuffle)-1);
$shuffled[] = $to_shuffle[$i];
array_splice($to_shuffle, $i, 1,null);
endwhile;
I think this is what you were expecting, if you don't mind not preserving the association between keys and values.

Count number of values in array with a given value

Say I have an array like this:
$array = array('', '', 'other', '', 'other');
How can I count the number with a given value (in the example blank)?
And do it efficiently? (for about a dozen arrays with hundreds of elements each)
This example times out (over 30 sec):
function without($array) {
$counter = 0;
for($i = 0, $e = count($array); $i < $e; $i++) {
if(empty($array[$i])) {
$counter += 1;
}
}
return $counter;
}
In this case the number of blank elements is 3.
How about using array_count _values to get an array with everything counted for you?
Just an idea, you could use array_keys( $myArray, "" ) using the optional second parameter which specifies a search-value. Then count the result.
$myArray = array( "","","other","","other" );
$length = count( array_keys( $myArray, "" ));
I dont know if this would be faster but it's something to try:
$counter = 0;
foreach($array as $value)
{
if($value === '')
$counter++;
}
echo $counter;
You could also try array_reduce, with a function which would just count the value you are interested in. eg
function is_empty( $v, $w )
{ return empty( $w ) ? ($v + 1) : $v; }
array_reduce( $array, 'is_empty', 0 );
Some benchmarking might tell you if this is faster than array_count_values()
We use array_filter function to find out number of values in array
$array=array('','','other','','other');
$filled_array=array_filter($array);// will return only filled values
$count=count($filled_array);
echo $count;// returns array count
Generally for counting blanks only.
Really depends on use case and speed needed. Personally I like doing things one one line.
Like the chosen response though But you still need a line to extract the data needed though to another variable.
$r = count($x) - count(array_filter($x));
function arrayvaluecount($array) {
$counter = 0;
foreach($array as $val){
list($v)=$val;
if($v){
$counter =$counter+1;
}
}
return $counter;
}
function countarray($array)
{ $count=count($array);
return $count;
}
$test=$array = array('', '', 'other', '', 'other');
echo countarray($test);

Categories