Testing returned values for duplicates - php

I've got a method that returns a string with predefined length of random alpha numbers.
I just let it run until it comes across a duplicate and breaks out of the loop and display the amount of generations it took before a duplicate was generated.
The loop numbers will be in the millions, and I am wondering if this really is good and efficient of testing it?

You can use array_search
The function return the string and store it to an array.
Then use array_search to see if it is not FALSE and loop.

Put The generated strings into an array as a key before outputting them.
$array[$alpha_string] = (isset($array[$alpha_string])) ? $array[$alpha_string] + 1 : 1;
Then check which items have a count > 1.

Related

Counting Array Returns One Digit Higher

I'm trying to count a php array.
I have my code successfully counting it, but the value is returning one digit higher than what my array is.
I have tried using -- when echoing my array, but that doesn't work.
Here is my code so far:
$quotes[0] = "Volvo";
$quotes[1] = "BMW";
$quotes[2] = "Toyota";
$quotesCount = count($quotes);
echo ($quotes[rand(0, 2)]);
echo $quotesCount--;
When it count's it returns "3" which makes sense because there are three items, but how do I subtract a number when it echos so that it reflects the the largest digit in the array?
What you tried with the echo $quotesCount--; is almost doing what you want it to. What you missed though is how the -- works. You can place it either infront of the variable or behind it - and that makes a difference.
To get the full version, read this: http://php.net/manual/en/language.operators.increment.php
But the short version is that you could potentially do this:
echo --$quotesCount;
Which will show you the value you want.
However this is still not really true - you are confusing array keys with the count of elements in an array.
If your array had non-sequential keys (1,3,5) for example, that code would return 2 - which is certainly not the highest key.
You can get a nice stepping stone to the key itself by using http://php.net/manual/en/function.array-keys.php - then you can reference the actual key itself by its order in the array.
You can use array_max($quotes) z this will return the highest key in the array.
Hey" you should array_max($array) in this case.
array_max is an array function which returns the highest value of an array.
That's it,
Keep Coding :)

how can a find multiple values at once in an array php

trying to make a tic-tac-toe game actually. So if there's a better way I would like to know too!
So I have a grid [0,8], and the user's positions are stored in an array. Great.
Next I want to see if the columns match up. So let's say first row is (0,1,2).
My question is if the user has an array like array(1,5,6,0,2), so he won. How can I match it efficiently?
I was thinking of doing something like this but doesn't look efficient:
$user= array(1,5,6,0,2);
in_array(0,$user) && in_array(1,$user) && in_array(2,$user)
I also thought about switch case but still face the question how do I find multiple values at once.
I agree that with such a small number of possible combinations to win, the solution can be kept very simple. I would do it using array_diff.
function has_won($user) {
// returns false if the user has not won, otherwise
// returns the first winning combination found.
$wins = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];
foreach ($wins as $win) {
if (!array_diff($win, $user)) return $win;
// array_diff returns the values in the first argument
// not present in any subsequent arguments. So if its
// result is empty, the user has winning combination.
}
return false;
}
I will not make a claim that this is the most efficient method, but it reduces the number of operations considerably compared with && chaining and multiple in_array() calls.
What we'll do is keep a 2-dimensional array of possible win-combinations: rows, columns, diagonals, as sub-arrays. Then in a foreach loop over that 2D array, test the user's current array state against the row combination with array_intersect(). If the entire winning combination is present in the user's array, the result of array_intersect() will be 3, which you can test with count().
Since one match is enough for a win, you can break out of the loop on the first match to declare a win.
$combinations = array(
// Rows
array(0,1,2),
array(3,4,5),
array(6,7,8),
// Columns
array(0,3,6),
array(1,4,7),
array(2,5,8),
// Diagonals
array(0,4,8),
array(2,4,6),
);
// Loop over the array of winners and test array_intersect()
// If 3 values intersect, the full win combination was matched
foreach ($combinations as $combination) {
if (count(array_intersect($combination, $user)) == 3) {
// User wins! Take whatever action necessary...
// Exit the loop
break;
}
}
Here's a demonstration in which 2 of 3 sets for $user are winners: http://codepad.viper-7.com/Mvu0wa
There are algorithmic ways of generating the winning combinations rather than hard-coding them, but there are only eight possible combinations so it isn't that hard, and the point here is the use of array_intersect() to find a subset of the user's current placements.

Count values left in Array

I need to figure out how to get the remaining values left in an Array.
Example: I have an array that randomly get two values. I want to get how many are left in that array after removing it.
If i remove 5 values from the array, and have a total of 20 return value 15.
Edit: If i have 52 cards in a deck, I draw 2 cards I have 50. If I draw two more cards i have 48.
I need to track how many "cards" are in the dealers array.
This should work:
$deck = array(1,2,3,4,5,6,7,8,9,10);
unset($deck[0]);
unset($deck[1]);
echo count($deck);
unset removes the elements from the array count should be 8 afterwards.
See it work: https://eval.in/163527
Edit:
...and remember arrays are 0 based so your first key unless otherwise defined will be 0. But the count() function will tell you the actual number of elements in the array. So $deck[count($deck)]; would be undefined.
This will echo size of array yourarray
<?php
echo(sizeof($yourarray));
?>
Store your array size using a count method such as count or sizeof store it in a variable and perform logical checks on it? i.e if().. etc . Your question is a tad bit broad.
I would recommend that you make use of the PHP count function.
echo count($yourArray);
Should do the trick.

PHP - elegant (fast) way to access elements counting from end of array?

I've got an array where I want to grab the "negative three" element regardless of array length. (If that doesn't make sense throw out a comment and I'll clarify).
The obvious way to do it is $arr[count($arr)-4] but this feels clunky.
Is there a quick, elegant way to do this?
UPDATE
Still fiddling, any thoughts regarding this?
array_slice($arr,-4,-3);
The obvious way returns the single value you want in constant time, assuming you have numeric indexes. The array size is known to PHP already, it just jumps to the offset you want and gives you the result.
array_slice does many times as much work, comparing the array size to your offset, computing the loop conditions, creating a new array to store the slice, looping over the portion of the existing array, copying the values into the new array, then returning that array to you.
http://lxr.php.net/opengrok/xref/PHP_TRUNK/ext/standard/array.c
Yes there is:
Try something like this:
$newArray = array_slice($array, -3);
you could use $last = end($arr); then use prev($arr); twice to get 2 other elements.
Oh, and check if these return FALSE, in case you don't have at least 3 elements.
array_slice()?
array_slice($a, -3)
Try array_slice() function, giving negative offset as a second parameter.

PHP - why doesn't count() work like strlen() on a string?

A string is an array of characters, correct? If so, then why does count() not produce the same result as strlen() on a string?
Unless it is an object, count casts its argument to an array, and
count((array) "example")
= count(array("example"))
= 1
A string is an array of characters in C, C++ and Java. In PHP, it is not.
Remember that PHP is a very loose language, you can probobly get a character from a PHP string with the []-selector, but it still dosn't make it an array.
count() counts the number of entries in an Array.
$test = array(1,2,3);
echo count($test);
Output: 3
Why would you want to use count() on a string when strlen() can do that? Are you not sure if your input is a string or an array? Then use is_array() to check that.
How exactly a string is being handled internally by a specific programming language, must not necessarily mean you can handle it equally to therefore "related" data types. What you describe may be possible in plain C. However PHP is not C and so is not following the same characteristics.
Strings are just a series of charactes, and count only counts number of elements in an array.
using $string[$index]; its just a shortcut kinda of thing to help you find Nth character,
you could use count(explode('',$string)); which presumably is what strlen does
so lesson for today is
count == array length
strlen == string length
count gets the number of elements in an array, srtlen gets the length of a string. This is in the docs:
http://php.net/manual/en/function.strlen.php
count is more preferabaly user for array value count
strlen its count only the no of char in str.....

Categories