Ensure no variables are equal (Lottery Code) - php

So I am working on my Final Project for a web application development class I'm taking and I am creating a Powerball lottery generator. For this to work, the White ball numbers cannot be duplicated. Here is how my code is looking so far:
<?php
for($x = 1; $x < 6; $x++){
//set each white ball variable (a through e) to a random number between 1 and 69
$a = floor((lcg_value() * 69 + 1));
$b = floor((lcg_value() * 69 + 1));
$c = floor((lcg_value() * 69 + 1));
$d = floor((lcg_value() * 69 + 1));
$e = floor((lcg_value() * 69 + 1));
//set powerball number variable to a number between 1 and 26
$f = floor((lcg_value() * 26 + 1));
//echo all white ball numbers and powerball number
echo "<b><u>Set #" . $x . "</u></b> - <b>White ball numbers are: </b>" . $a . " , " . $b . " , " . $c . " , " . $d . " , " . $e . ". <b>Powerball Number is </b>" . $f . ".<br />";
};
?>
The issue with this code is that there is a chance that variables 'a' through 'e' have a chance of being duplicate numbers. What code could I use to ensure that none of the variables 'a' through 'e' are the same? I thought of doing something like:
if($a != $b || $a != $c || $a || $d...){
//echo numbers
}else{
//generate new numbers
};
But that is just too much work and I always try to find the most efficient ways to write code. I don't want to have to write more code than I need to. Any assistance would be greatly appreciated. Thank you in advance!

You could generate the numbers this way:
$arr = range(1, 69);
shuffle($arr);
$a = $arr[0];
$b = $arr[1];
$c = $arr[2];
$d = $arr[3];
$e = $arr[4];
Also take a look at Generating random numbers without repeats

Add them in an array and check for uniqueness:
<?php
for($x = 1; $x < 6; $x++){
$unique = false;
while(!$unique) {
//set each white ball variable (a through e) to a random number between 1 and 69
$a = floor((lcg_value() * 69 + 1));
$b = floor((lcg_value() * 69 + 1));
$c = floor((lcg_value() * 69 + 1));
$d = floor((lcg_value() * 69 + 1));
$e = floor((lcg_value() * 69 + 1));
$numbers = array($a, $b, $c, $d, $e);
if(count($numbers) == count(array_unique($numbers)) {
$unique = true;
}
}
//set powerball number variable to a number between 1 and 26
$f = floor((lcg_value() * 26 + 1));
//echo all white ball numbers and powerball number
echo "<b><u>Set #" . $x . "</u></b> - <b>White ball numbers are: </b>" . $a . " , " . $b . " , " . $c . " , " . $d . " , " . $e . ". <b>Powerball Number is </b>" . $f . ".<br />";
}

While loop the random generation of numbers and check for duplicates on the fly.
Test it here:
https://3v4l.org/odOqb
I have changed the random numbers to a smaller size to see if it does create duplicates.
But I have not seen any.
<?php
$arr =array();
for($x = 1; $x < 6; $x++){
//set each white ball variable (a through e) to a random number between 1 and 69
While (count($arr) != 5){
$arr[] = floor((lcg_value() * 6 + 1));
$arr = array_unique($arr);
}
//set powerball number variable to a number between 1 and 26
$f = floor((lcg_value() * 26 + 1));
Var_dump($arr);
//echo all white ball numbers and powerball number
//echo "<b><u>Set #" . $x . "</u></b> - <b>White ball numbers are: </b>" . $a . " , " . $b . " , " . $c . " , " . $d . " , " . $e . ". <b>Powerball Number is </b>" . $f . ".<br />";
};

To make it as efficient as possible you do not want to have to generate a new set of numbers each time therefore if a duplicate appears you would just want to re-pick for that letter right away.
To do this you can add the elements to an array and search through it after each letter to make sure its a unique number. This is done through the utilization of the for loop, while loop, and check variable.
<?php
for($x = 1; $x < 6; $x++) {
//set each white ball variable (a through e) to a random number between 1 and 69
$uniqueNumbers = array();
$check = true;
$a = floor((lcg_value() * 69 + 1));
array_push($uniqueNumbers, $a);
while ($check) {
$check = false;
$b = floor((lcg_value() * 69 + 1));
foreach ($uniqueNumbers as $element) {
if ($b == $element) {
$check = true;
}
}
}
array_push($uniqueNumbers, $b);
$check = true;
while ($check) {
$check = false;
$c = floor((lcg_value() * 69 + 1));
foreach ($uniqueNumbers as $element) {
if ($c == $element) {
$check = true;
}
}
}
array_push($uniqueNumbers, $c);
$check = true;
while ($check) {
$check = false;
$d = floor((lcg_value() * 69 + 1));
foreach ($uniqueNumbers as $element) {
if ($d == $element) {
$check = true;
}
}
}
array_push($uniqueNumbers, $d);
$check = true;
while ($check) {
$check = false;
$e = floor((lcg_value() * 69 + 1));
foreach ($uniqueNumbers as $element) {
if ($e == $element) {
$check = true;
}
}
}
array_push($uniqueNumbers, $e);
//set powerball number variable to a number between 1 and 26
$f = floor((lcg_value() * 26 + 1));
//echo all white ball numbers and powerball number
echo "<b><u>Set #" . $x . "</u></b> - <b>White ball numbers are: </b>" . $a . " , " . $b . " , " . $c . " , " . $d . " , " . $e . ". <b>Powerball Number is </b>" . $f . ".<br />";
}

Below code is for 6/49 Canada lottery
<body bgcolor="gold"><font size="9"></font>
<pre>
<?php
// Code by bhupinder Deol . modify according to needs
for ($i=0;$i<=10;$i++) {
for ($x=0;$x<=5;$x++) {
$rand[$x]=rand(1,49);
}
asort($rand);
$result = array_unique($rand);
$count = count($result);
if ($count == 6) {
print_r($rand);
$x=0;
}
else
{
echo "same numbers in array";
--$x;
}
}
?>
</pre>
</body>

Related

mt_rand math numbers

I want to create an application that shows multiplication, addition, subtraction and division with 2 random numbers. I made a function that shows random numbers:
function Numbers() {
echo(mt_rand() . "<br>");
echo(mt_rand() . "<br>");
echo(mt_rand(1,10));
}
Numbers();
Can someone explain to me how I can make it go +/- and x each other?
I now changed my code to this:
function Numbers() {
$Number1= echo(mt_rand() . "<br>");
$Number2= echo(mt_rand() . "<br>");
$Number1 + $Number2;
$Number1 - $Number2;
$Number1 / $Number2;
}
Numbers();
Here's an example for the addition, you figure out the rest:
$a = mt_rand();
$b = mt_rand();
echo "$a + $b = " . ($a + $b);
function printRnd()
{
$a_ = rand(1,10);
$b_ = rand(1,10);
echo "a={$a_}, b={$b_}<br><br>";
$plus_ = $a_+$b_;
$minus_ = $a_-$b_;
$multi_ = $a_*$b_;
$divid_ = $a_/$b_;
echo "a+b={$plus_}<br>";
echo "a-b={$minus_}<br>";
echo "a*b={$multi_}<br>";
echo "a/b={$divid_}<br>";
}
printRnd();

How do I divide an integer over multiple values in PHP?

I'm trying to make a little PHP script for fun, and I'm a little stuck.
I want to divide an integer (for example 5) over multiple values.
For example:
$total = 5;
$mike = 0;
$ralf = 0;
$ashley = 0;
// Run the magic here
echo "Mike has " . $mike . " apples, Ralf has " . $ralf ." apples and Ashley has " . $ashley . " apples";
The output that I expect would look something like this:
Mike has 2 apples, Ralf has 1 apples and Ashley has 2 apples
Is there a way how to do this? :)
I can't do this hard coded, because I want the values to be randomized.
Cheers
Do it like this:
$total = 5;
$mike = rand(1,$total-2); // so that max value is 3 (everyone should get at least 1) ($total - $numberOfVarsToDistributeTheValueTo + 1)
$ralf = rand(1,$total - $mike - 1); // if 3 goes to mike, only 1 goes to ralf
$ashley = $total - $mike - $ralf; // i hope you understand.
// use it.
Something like this would work:
$people = array('mike','ralf','ashley');
$num = count($people);
$sum = 5; // TOTAL SUM TO DIVIDE
$groups = array();
$group = 0;
while(array_sum($groups) != $sum) {
$groups[$group] = mt_rand(0, $sum/mt_rand(1,5));
if(++$group == $num){
$group = 0;
}
}
// COMBINE ARRAY KEYS WITH VALUES
$total = array_combine($people, $groups);
echo "Mike has " . $total['mike'] . " apples, Ralf has " . $total['ralf'] ." apples and Ashley has " . $total['ashley'] . " apples";
Solution is inspired from this answer: https://stackoverflow.com/a/7289357/1363190
Hope This function will do your work . it can work for variable # of persons also.
divide_items(10,['mike','ralf','ashley']);
function divide_items($total=1,array $persons){
$progressed = 0;
for($i=0;$i<count($persons);$i++){
echo $random_count = rand(1,$total);
if(($i==(count($persons)-1)) && $progressed<$total ){
$random_count1 =$total - $progressed;
echo $persons[$i]." has ".$random_count1 ." Items<br>";
continue;
}
$progressed = $progressed+$random_count;
if($progressed<=$total){
echo $persons[$i]." has ".$random_count ." Items<br>";
}else{
echo $persons[$i]." has 0 Item<br>";
}
$total = $total-$random_count;
$progressed = 0;
}
}

Set color shade based on variable number with PHP

Ok, I don't even know where to start with this one! I'll try and explain what I want to achieve, and we'll go from there....
I have a list of dates each with an associated number, say from 20-100. What I want to do is to output the date in a shade which represents the associated number. So 20 would display in a light blue and 100 in a dark blue. My code so far looks like this...
dateArray = Array('2001-01-01'=>30, '2001-02-01'=>40, '2001-03-01'=>50, '2001-04-01'=>60, '2001-05-01'=>70, '2001-06-01'=>80, '2001-07-01'=>90, '2001-08-01'=>90, '2001-09-01'=>80, '2001-10-01'=>70, '2001-11-01'=>60, '2001-12-01'=>50)
$maxNum = max($dateArray);
$minNum = min($dateArray);
foreach($dateArray AS $date => $num){
$lightest = 'rgb(204,204,255)';
$darkest = 'rgb(0, 0, 179)';
///magic that converts $num into $shade goes here///
echo "<span style='color:$shade'>$date</span><br>"
}
Any ideas? Thanks
I would do something like that :
$dateArray = Array('2001-01-01'=>30, '2001-02-01'=>40, '2001-03-01'=>50, '2001-04-01'=>60, '2001-05-01'=>70, '2001-06-01'=>80, '2001-07-01'=>90, '2001-08-01'=>90, '2001-09-01'=>80, '2001-10-01'=>70, '2001-11-01'=>60, '2001-12-01'=>50)
// get max and min values
$maxNum = max($dateArray);
$minNum = min($dateArray);
// set rgb values for max and min
$lightest = array(204, 204, 255);
$darkest = array(0, 0, 179);
foreach($dateArray AS $date => $num)
{
// get a "delta" where the current num value is
$delta = ($num / $maxNum) - $minNum;
// get a pro-rata values thanks to $delta
$shadesNum = array(
$delta * ($lightest[0] - $darkest[0]) + $darkest[0],
$delta * ($lightest[1] - $darkest[1]) + $darkest[1],
$delta * ($lightest[2] - $darkest[2]) + $darkest[2]
);
echo "<span style='rgb(".implode(',', $shadesNum).")'>$date</span><br>";
}
Some languages have a "lerp" function - linear interpolation. Quite useful.
My suggestion:
for ($x1=20; $x1<=100; $x1+=10)
echo $x1 . ": " . getshade($x1) . "<br />\n";
function getshade($num) {
$rlight = 204;
$glight = 204;
$blight = 255;
$rdark = 0;
$gdark = 0;
$bdark = 179;
$lightnum = 20;
$darknum = 100;
$k01 = ($num-$lightnum)/($darknum-$lightnum); // 0 to 1
$rshade = ilerp($rlight, $rdark, $k01);
$gshade = ilerp($glight, $gdark, $k01);
$bshade = ilerp($blight, $bdark, $k01);
return "rgb($rshade,$gshade,$bshade)"; }
function lerp($start, $end, $k01) { // linear interpolation
return $k01*$end + (1.0-$k01)*$start; }
function ilerp($start, $end, $k01) { // integer lerp
return intval($k01*$end + (1.0-$k01)*$start); }
EDIT: Same thing but better:
$rgblight = [204,204,255];
$rgbdark = [0,0,179];
$numlight = 20;
$numdark = 100;
for ($x1=20; $x1<=100; $x1+=10)
echo $x1 . ": " . getshade2($x1, $numlight, $numdark, $rgblight, $rgbdark) . "<br />\n";
function getshade2($num, $numlight, $numdark, $rgblight, $rgbdark) {
$k01 = ($num-$numlight)/($numdark-$numlight);
for ($i1=0; $i1<3; $i1+=1)
$rgb[$i1] = ilerp($rgblight[$i1], $rgbdark[$i1], $k01);
return "rgb({$rgb[0]},{$rgb[1]},{$rgb[2]})"; }

A 500 error has occurred - Executing long loop within PHP

A 500 error has occurred - executing long loop with PHP.
I am currently working on a scheduling system to schedule nurses on a hospital ward, I am using a genetic algorithm to carry this out.
so I randomly allocate each nurses to a shift.
and then work out how fit they are for the shift.
I then kill off any allocation which do not meet my fitness level.
I then randomly allocate a new timetable.
Assess that for fitness
kill off any allocation which do not meet my fitness level.
Merge the two timetables, keeping the fitness allocations
I loop through generating random timetable, accessing its fitness and merging the timetables
This works fine while looping through 30 - 100 times
Once I go past the 100 mark it sometimes fails - a 500 error has occurred
This always occurs when it takes over 2:30mins to complete the script
So I'm making the assumption at some point my server times out for taking too long?
I have added <?php set_time_limit(3600);
This is at the top of my file, not inside the constructor, or the class. Is it in the right place?
it still times out at 2 and a half minute,
Here is my code, the loop is the 200 loop
Still need to refractor my code so don't be too judgmental
<?php
set_time_limit(3600);
* Description of scheduler
*
* #author Dela
*/
include ("randomTtAllocation.php");
include ("fittness.php");
class scheduler {
private $randomTimetable;
private $timetable;
private $weight;
private $newTimetable ;
private $newWeight;
function __construct($labs,$students) {
echo "helloworld";
// create random timetable and print it
$r = new randomTtAllocation();
$this->randomTimetable = $r->__randomAllocation($labs, $students);
//echo "<br>" . " ............initial Time Table............." . "<br>" ;
echo "<br>";
echo "<br>";
echo "<br>";
$this->__printTt($this->randomTimetable, $this->randomTimetable);
// work out fittness for the timetable, return fit results and print
$fit = new fittness( $this->randomTimetable, $labs, $students , $r->__getNumOfSessions());
$this->newWeight = $fit->__getnewWeight();
$this->newTimetable = $fit->__getnewTimetable();;
//echo "<br>" . " ............newTimetable.........newWeight...." . "<br>" ;
//$this->__printTt($this->newTimetable, $this->newWeight );
// sort
$this->__sortTtByWeight();
$this->timetable = $this->newTimetable;
$this->weight = $this->newWeight;
for ($i = 0; $i < 200; $i++) {
// create second time table
$this->randomTimetable = $r->__randomAllocation($labs, $students);
// echo "<br>" . " ............initial Time Table............." . "<br>" ;
// $this->__printTt($this->randomTimetable, $this->randomTimetable);
// work out fittness for the timetable, return fit results and print
$fit = new fittness( $this->randomTimetable, $labs, $students , $r->__getNumOfSessions());
$this->newWeight = $fit->__getnewWeight();
$this->newTimetable = $fit->__getnewTimetable();
//echo "<br>" . " ............tempTimetable.........tempWeight...." . "<br>" ;
//$this->__printTt($this->newTimetable, $this->timetable );
$this->__sortTtByWeight();
// merge timetables
echo "<br>" . " ......old...........new." . "<br>" ;
$this->__printTt($this->timetable,$this->newTimetable );
$this->__mergeTimetables($this->newTimetable, $this->newWeight );
//echo "<br>" . " ........... mergedTimetable.........newWeight...." . "<br>" ;
//$this->__printTt($this->timetable,$this->weight );
// fittness of new timetable
$fit = new fittness( $this->timetable, $labs, $students , $r->__getNumOfSessions());
echo "<br>" . " ......merged.......kulled" . "<br>" ;
$this->__printTt($this->timetable,$fit->__getnewTimetable() );
$this->weight = $fit->__getnewWeight();
$this->timetable = $fit->__getnewTimetable();
$c[$i] = $this->__countSlotsAllocated();
echo "<br> ". $i;
}
print_r($c);
}
// sorts the re allocated time table by weight
function __sortTtByWeight() {
// for each slot
foreach($this->newTimetable as $l => $i_value) {
$size = 0;
// see how many sessions they are taking
while ($this->newTimetable[$l][$size] != "null") {
if ($this->newTimetable[$l][$size] == "0") {
break;
}
$size++;
}
for ($i = 1; $i < $size; $i++) {
$key = $this->newWeight[$l][$i];
$key1 = $this->newTimetable[$l][$i];
$k = $i - 1;
while ($k >= 0 && $this->newWeight[$l][$k] < $key) {
$this->newWeight[$l][$k + 1] = $this->newWeight[$l][$k];
$this->newTimetable[$l][$k + 1] = $this->newTimetable[$l][$k];
$k--;
}
$this->newTimetable[$l][$k + 1] = $key1;
$this->newWeight[$l][$k + 1] = $key;
}
}
}
function __countSlotsAllocated() {
$count = 0;
foreach($this->timetable as $i => $x_value) {
$j = 0;
while (($this->timetable[$i][$j] != "null") && ($this->timetable[$i][$j] != "0")){
$count++;
$j++;
}
}
echo "count " . $count;
return $count;
}
function __mergeTimetables($tempTimeTable,$tempWeight) {
// for each session
foreach($this->newTimetable as $i => $i_value) {
$j = 0;
$k = 0;
// while there are still students
while (($tempTimeTable[$i][$j] != "null") && ($tempTimeTable[$i][$j] != "0")) {
//echo $tempTimeTable[$i][$j];
// System.out.println(timeTable[i][k]);
// see if there is a free gap
while ($this->timetable[$i][$k] != "null") {
// if student is already taking that session
if ($tempTimeTable[$i][$j] == $this->timetable[$i][$k]) {
break;
}
if ($this->timetable[$i][$k] == "0") {
$this->timetable[$i][$k] = $tempTimeTable[$i][$j];
$this->weight[$i][$k] = $tempWeight[$i][$j];
break;
}
$k++;
}
if ($this->timetable[$i][$k] == "null") {
if ($tempWeight[$i][$j] < $this->weight[$i][0]) {
$this->timetable[$i][0] = $tempTimeTable[$i][$j];
$this->weight[$i][0] = $tempWeight[$i][$j];
}
}
$j++;
}
}
}
function __returnTimetable() {
return $this->timetable;
}
function __printTt($timetable, $weight) {
foreach($timetable as $x => $x_value) {
for ($i = 0; $i < 5; $i++) {
echo $timetable[$x][$i] . " ";
}
echo " . . . . .";
for ($i = 0; $i < 5; $i++) {
echo $weight[$x][$i] . " ";
}
echo "<br>";
}
}
}
Normally you shouldn't do all this work within the http request. Instead you should start a background task and have the web page show progress on the job.
The php configuration has a time limit per request which you can adjust, but it's not expected by users to take so long.

PHP equation from JavaScript

I have this JavaScript equation which I'm now trying to transform to PHP.
JavaScript:
LVL=new Array();
LVL[1]=128;
LVL[0]=128;
m=.05;
for (i=1;i<101;i++) {
if (i>1) {
LVL[i]=Math.floor(LVL[i-1]+(LVL[i-1]*m));
m=m+.0015;
}
}
then it's a bunch of document.writes of a table and a for loop.
Here's what I have so far (which is NOT working):
<?php
$n = 1; // level
$m = .05; // exp modifier
$exp = floor($n*1+($n-1)*$m);
echo "Level " . $n . ", exp needed: " . $exp; // 128 exp
?>
The PHP output is: Level 1, exp needed: 1 and that's WRONG.
It SHOULD say: Level 1, exp needed: 128
What am I doing wrong?
A direct transcription:
$LVL = array();
$LVL[1] = 128;
$LVL[0] = 128;
$m = .05;
for ($i = 1; $i < 101; $i++)
{
if ($i > 1)
{
$LVL[$i] = floor($LVL[$i-1] + $LVL[$i-1]*$m);
$m = $m + .0015
}
}
You need to build the array as its built bottom-up
You do a couple of errors:
you use the index (the level) as it is the amount of the experience points needed to
reach the level.
you forgot the for (if you are testing the formula it is ok)
the code so far:
$lvl = array(128,128);
$modifier=.05;
for ($i=1;$i<101;i++) {
$lvl[$i]=floor($lvl[$i-1]*(1+$modifier));
$modifier+=0.0015;
}
foreach ($lvl as $level=>$points) {
echo "Level " . $level . ", exp needed: " . $points ."\n<br />"; // 128 exp
}

Categories