So I am looking to alternate between 5 different variables but want the 'load' to be equal on each variable. I have seen it done with just two variables and alternating based on random number generated withe limits being set. But trying to expand that idea on to five variables. Thanks in advance.
Just for example purposes say I had 5 images and wanted each image to be shown equally after 100 tests. This is the easiest way I can think of explaining it.
This is how I did it with only 2 variables but trying to think about how to do it with more.
$ad1 = '<img src... >';
$ad2 = '<img src...2 >';
echo mt_rand(0, 1) ? $ad1 : $ad2;
Source:PHP Switching between two variables equally without using database
So this is what I have going just want to know what the ideas on equally being between the different variables.
$input = array("a", "b", "c", "d");
$rand_keys = array_rand($input);
echo 'var key ="'.$input[$rand_keys].'"';
Two options below, because your question is titled "swithcing between 5 variables equally" - There is an equal distribution solution and a randomized solution.
Notice you need apc installed for the equal rotation solution to work. It is a fairly common php module and can be installed quite easily if you have permission to do so:
Redhat/centos : yum install php-apc
Ubuntu: sudo apt-get php-apc
If you are using shared hosting and they don't have apc installed then this won't work for you :(
<?php
//If you want perfectly equal distribution.
$variables = array('a', 'b', 'c', 'd', 'e');
if (!($this_var = apc_fetch('last'))) $this_var = 0;
echo $variables[$this_var];
$this_var++;
$this_var = $this_var % 5;
apc_store('last', $this_var);
//If you want random distribution
$variables = array('a', 'b', 'c', 'd', 'e');
$index = mt_rand(0, 4);
echo $variables[$index];
If you want a random pick out of a set you can use array_rand().
$images = array( '<img src="img1.png">', '<img src="img2.png">', '<img src="img3.png">', '<img src="img4.png">', '<img src="img5.png">' );
$pick = array_rand( $images );
$pick will be a random key from the $images array.
This is easily extensible as you can keep adding elements to the array. Here I am of course following your example of adding the <img> tag to the array but you could just as easily add only some identifier to the array.
I would suggest using a Class to handle each "object":
<?php
...
...
class RandObjClass
{
var $myCounter = 1;
var $mySeed = time();
var $myReference = "...path-to-image-file..."; # Image for example
function getWeight() {
srand($mySeed);
$myWeight = $this->myCounter * rand();
return($myWeight);
}
setSeed($xSeed) {
$this->mySeed = $xSeed;
}
}
...
...
Fill an array of x "RandObjClass" objects and use the "getWeight" to select the next one of "highest" weight.
You can play with affecting the weight via various methods, like counting. This can influence which is chosen next.
Related
static $l1 = array(1,"_" , "_", "_");
static $l2 = array("_", 2, "_", "_");
static $l3 = array("_", "_", 2, "_");
static $l4 = array("_", "_", "_", "_");
static $c1 = array(1, 4, 3, 2);
static $c2 = array(3, 2, 4, 1);
static $c3 = array(4, 1, 2, 3);
static $c4 = array(2, 3, 1, 4);
I am basically trying to make a 2x2 sudoku Game. I have one list of arrays from l1 and l4 which is for guessing and another set c1 to c4 as the answer. User will input the value, row number and column number and if the all the parameters are correct (after comparing with the answer set, c1 to c4), it should change the value in either l1, l2, l3 or l4 depending on the input. The problem is that PHP doesn't stores array information like that, is there a way out? I want to make this program as simple as possible.
if ($_POST['n2'] == 1) {
if ($_POST['n1'] == $c1[$_POST['n3']-1]) {
$l1[$_POST['n3']-1] = $_POST['n1'];
} else {
echo "Try again";
}
}
You could either save player's actions in a session or database. It depends on what you want.
Requesting the way you are trying won't make it dynamic.
Take a look at
PHP Sessions and PHP MySQL API.
If you do not want to use some sort of persistence storage, you will need to keep track of all the data in each request. This means sending the solution so far as well as the final solution to the browser and back to the script each time.
using POST
<?php
$rowNumber = $_POST['rowNubmer'];
$columnNumber = $_POST['columnNumer'];
$guessedValue = $_POST['guessedValue'];
$codedSolutionSoFar = $_POST['solutionSoFar'];
$solutionSoFar = myDecodeFunction($codedSolitionSoFar);
$codedFinalSolution = $_POST['finalSolution'];
$finalSolution = myDecodeFunction($codedSolitionSoFar);
function myDecodeFunction($codedString) {
$decoded = explode(',', $codedString);
return $decoded;
}
function myEncodeFunction(array $sudokuGameValues) {
$encoded = implode(',', $sodukoGameValues);
return $encoded;
}
function checkGuessedValue($row, $column, $value, $solution) {
// this is hardcoded for a 2x2 sudoku where the values are stored in
// a flat array as [(0,0), (0,1), (1,0), (1,1)]
$indexInSolition = $row * 2 + $column;
$correctValue = $solution[$indexInSolution];
return $value === $correctValue;
}
...
sprintf(
'<input type="hidden" name="finalSolution" value="%s">',
myEncodeFunction($finalSolution)
);
sprintf(
'<input type="hidden" name="solitionSoFar" value="%s">',
myEncodeFunction($solutionSoFar)
);
Please note that the above is not complete, complete and utterly ignores input filtering, is bad practice and serves solemnly as a solution to build upon. But since it is for a class it might be usable. From there you can explain all the mistakes and problems that come with code like this. But everyone will love the idea of being able to look up the solution in the HTML source code and this gives the argument you need to introduce server side storage e.g. as already suggested in a session.
I doubt if it is possible but I'm looking for the following:
E.g. $number's value is 1, can I get the next number, in this case 2, to be the value of another variable, e.g. $newnumber?
I prefer to do this in SQLite, so the numbers are stored in a database.
Try: $newnumber = ((int) ($number)) + 1, if this is for a primary key though just set the column to auto increment
$newnumber=$number+1;
I think it can't get more simpler than that.
Without knowing the larger scope of what you're trying to accomplish, my suggestion would be to use the increment operator in PHP.
Original answer:
Something like:
$number = 1;
$newNumber = $number++;
Correct answer (above gives wrong result):
$number = 1;
$number++;
$newNumber = $number;
From there you can do whatever you want with the second variable.
i have a directory with 1000+ images and piece of code (by codaddict) which selects only first 10 and display it:
<?php
foreach (array_slice(glob("/directory/*.jpg"),0,10) as $path)
?>
ok this works, but i need to select 10 RANDOM images, not the first 10
yes, i can use shuffle first, then slice, but with 1000+ (or 10k+) images, it's not smart to shuffle long arrays just for 10 images, or maybe it is?
also, 2nd problem is that this is not just for one folder with 1000+ images, i need to use this script in other folders too, and some of them will only have 1 image, so i don't want to see errors if there is less than 10 images in a folder
i saw in php manual code for 2 random items, but i won't know how many images will be in folders - 1, 10, 10k... you see the problem
<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>
thanks!
function imageGlobber($myDir, $imgCount) {
$globVar = glob($myDir."/*.jpg");
$imgCount = ($imgCount > count($globVar)) ? $imgCount : count($globVar);
$randKeys = array_rand($globVar, $imgCount);
$retArray = array();
foreach($randKeys as $key)
array_push($retArray, $globVar[$key]);
return $retArray;
}
I think this is what you are looking for.
Edit : Added duplicate handling as well.
Edit : Improved performance.
Is there is any way to avoid duplication in random number generation .
I want to create a random number for a special purpose. But it's should be a unique value. I don't know how to avoid duplicate random number
ie, First i got the random number like 1892990070. i have created a folder named that random number(1892990070). My purpose is I will never get that number in future. I it so i have duplicate random number in my folder.
A random series of number can always have repeated numbers. You have to keep a record of which numbers are already used so you can regenerate the number if it's already used. Like this:
$used = array(); //Initialize the record array. This should only be done once.
//Do like this to draw a number:
do {
$random = rand(0, 2000);
}while(in_array($random, $used));
$used[] = $random; //Save $random into to $used array
My example above will of course only work across a single page load. If it should be static across page loads you'll have to use either sessions (for a single user) or some sort of database (if it should be unique to all users), but the logic is the same.
You can write a wrapper for mt_rand which remembers all the random number generated before.
function my_rand() {
static $seen = array();
do{
$rand = mt_rand();
}while(isset($seen[$rand]));
$seen[$rand] = 1;
return $rand;
}
The ideas to remember previously generated numbers and create new ones is a useful general solution when duplicates are a problem.
But are you sure an eventual duplicate is really a problem? Consider rolling dice. Sometimes they repeat the same value, even in two sequential throws. No one considers that a problem.
If you have a controlled need for a choosing random number—say like shuffling a deck of cards—there are several approaches. (I see there are several recently posted answer to that.)
Another approach is to use the numbers 0, 1, 2, ..., n and modify them in some way, like a Gray Code encoding or exclusive ORing by a constant bit pattern.
For what purpose are you generating the random number? If you are doing something that generates random "picks" of a finite set, like shuffling a deck of cards using a random-number function, then it's easiest to put the set into an array:
$set = array('one', 'two', 'three');
$random_set = array();
while (count($set)) {
# generate a random index into $set
$picked_idx = random(0, count($set) - 1);
# copy the value out
$random_set []= $set[$picked_idx];
# remove the value from the original set
array_splice($set, $picked_idx, 1);
}
If you are generating unique keys for things, you may need to hash them:
# hold onto the random values we've picked
$already_picked = array();
do {
$new_pick = rand();
# loop until we know we don't have a value that's been picked before
} while (array_key_exists($new_pick, $already_picked));
$already_picked[$new_pick] = 1;
This will generate a string with one occurence of each digit:
$randomcharacters = '0123456789';
$length = 5;
$newcharacters = str_shuffle($randomcharacters);
$randomstring = substr($newcharacters, 0, $length);
i need to print out numbers 1-100 in a random order. the print statement should be:
echo 'h{'.$num.'}';
what is the shortest code to do this?
The easiest way is to use shuffle with an array containing the 100 numbers
e.g.
$sequence = range(1, 100);
shuffle($sequence);
foreach ($sequence as $num) {
echo 'h{'.$num.'}';
}
Also see the range function
EDIT
I thought I might add a little on what shuffle does. Although php.net doesn't explicitly say so, it is likely based on the modern version of the Fisher-Yates shuffle algorithm. For a video demonstration of how it works, see http://www.youtube.com/watch?v=Ckh2DJrP7F4. Also see this excellent flash demonstration
The shuffle algorithm essentially works like this:
For a given set of elements A1 to AN, and n = N;
Randomly select an element Ak between A1 and An inclusive
Swap Ak and An
Set n = n - 1
Repeat from step 2
Hope that helps.
See the example for shuffle():
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}