JSON Array values to always total up to 100% - php

I have a wheel of fortune that spins, and has probability set for winning each prize that adds up to 100%. Once the quantity of a prize is met, ie, all of that prize is gone from stock, it sets the probability to 0 so you can't win it again. My problem then, is that the other values don't add up to 100. They always have to add up to 100 otherwise the wheel doesn't work.
I've got to the point of dividing all of the values by the total, rounding to two decimals and then adding them together, but i get 99 instead of 100. I've tried a few other ways of doing it and can never get to 100.
edit: My main problem seems to be that there is a 0.01% chance of winning 2 of the prizes. Dividing them by the total drops them to 0.000234234% or something similar, so when i multiply that by 100 then round that up to 2 decimals i'm getting 0.00% - but i can't think of any other way around it...
$jsonString = file_get_contents('wp-content/themes/supertheme/wheel_data.json');
$data = json_decode($jsonString, true);
echo '<pre>';
//print_r($data['segmentValuesArray'][0]['probability']);
echo '</pre>';
if ($prize1 <= 5){
$prize1before = $data['segmentValuesArray'][0]['probability'];
$data['segmentValuesArray'][0]['probability'] = 0;
}
if ($prize2 >= 5){
$data['segmentValuesArray'][1]['probability'] = 0;
}
if ($prize3 >= 300){
$data['segmentValuesArray'][2]['probability'] = 0;
}
if ($prize4 >= 500){
$data['segmentValuesArray'][3]['probability'] = 0;
}
if ($prize5 >= 10){
$data['segmentValuesArray'][4]['probability'] = 0;
}
$prize1total = $data['segmentValuesArray'][0]['probability'];
$prize2total = $data['segmentValuesArray'][1]['probability'];
$prize3total = $data['segmentValuesArray'][2]['probability'];
$prize4total = $data['segmentValuesArray'][3]['probability'];
$prize5total = $data['segmentValuesArray'][4]['probability'];
$total = $prize1total + $prize2total + $prize3total + $prize4total + $prize5total;
echo'<pre>';
print_r($total);
echo'<pre>';
$a = 0;
foreach($data['segmentValuesArray'] as $prize_array){
if($prize_array['probability'] > 0){
$a++;
}
}
$integer = $prize1before / $a;
$divided1 = $prize1total / $total;
$rounded1 = number_format((float)$divided1, 2, '.', '');
$full1 = $rounded1 * 100;
$divided2 = $prize2total / $total;
$rounded2 = number_format((float)$divided2, 2, '.', '');
$full2 = $rounded2 * 100 + $integer;
$divided3 = $prize3total / $total;
$rounded3 = number_format((float)$divided3, 2, '.', '');
$full3 = $rounded3 * 100 + $integer;
$divided4 = $prize4total / $total;
$rounded4 = number_format((float)$divided4, 2, '.', '');
$full4 = $rounded4 * 100 + $integer;
$divided5 = $prize5total / $total;
$rounded5 = number_format((float)$divided5, 2, '.', '');
$full5 = $rounded5 * 100 + $integer;
$newtotal = $full1 + $full2 + $full3 + $full4 + $full5;
echo'<pre>';
print_r($newtotal);
echo'<pre>';
$newJsonString = json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
file_put_contents('wp-content/themes/supertheme/wheel_data.json', $newJsonString);

Related

How to validate decimal stepping from a starting number in PHP

I need to validate that an inputted number is a valid number based on my stepping rules and round up to the nearest valid number if not. These numbers will change but one example would be:
$min = 0.25;
$step = 0.1
$qty = 0.75 // user input
so these would be valid inputs:
0.75
0.85
0.95
But these should round:
0.76 (to 0.85)
0.80 (to 0.85)
I thought I could use modulus somehow but not getting the calculation correct.
if (($qty % min) / $step == 0)) {
echo "good";
}
I've tried some variations of math that are likely very wrong
$step = 0.1;
$min = 0.25;
$qty = .85;
$h = ($qty / $min) / $step;
echo $h;
$j = mround($qty, $min-$step);
echo $j;
function mround($num, $parts) {
if ($parts <= 0) { $parts = 1; }
$res = $num * (1/$parts);
$res = round($res);
return $res /(1/$parts);
}
I think you can use fmod to do this.
$new = $original + ($step - fmod($original - $minimum, $step));
Example on 3v4l.org

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]})"; }

Array counting with different keys

What I need is putting this array in a loop, but I can't get it to work because week is 1 - 9 and the key is 0 - 8. So i getting a error with a undefined offset i know why the does that but I don't know how to do this properly.
Before people ask me why not just change week1 to week0 and start counting from there. I can't because I did a calculating that is based on 1 - 52 and it will mess up my calculating if I start on 0 - 51
$totaal_vruchtzetting_week[10] = $totaal["week1"][0] + // = 0.46
$totaal["week2"][1] + // = 2.87
$totaal["week3"][2] + // = 4.97
$totaal["week4"][3] + // = 4.35
$totaal["week5"][4] + // = 3.02
$totaal["week6"][5] + // = 2.03
$totaal["week7"][6] + // = 1.41
$totaal["week8"][7] + // = 1.12
$totaal["week9"][8]; // = 1.13
// Should be total 21,36
Edit:
This is my loop I got until now but it gives me the wrong answer plus 2 errors
for($week = 1; $week < 9; $week++)
{
for($sw = 0; $sw <= 8; $sw++)
{
$totaal_vruchtzetting_week[10] += $totaal["week".$week][$sw];
}
}
echo $totaal_vruchtzetting_week[10]; // Outputs 170.89
$i=1;
$totaal_vruchtzetting_week[10]=0;
foreach($totaal as $total)
{
$totaal_vruchtzetting_week[10]+=$total["week$i"][$i-1];
$i++;
}
echo $totaal_vruchtzetting_week[10];
You should sum with this this loop
$i = 1;
$result = 0;
for ($i = 1; $i <= 9; $i++) {
if (isset($totaal['week' . $i]) && isset($totaal['week' . $i][$i - 1])) {
$result += floatval($totaal['week' . $i][$i - 1]);
}
}
$totaal_vruchtzetting_week[10] = $result;
$sum = 0;
foreach(array_values($totaal) as $index=>$item)
$sum += reset($item);
echo $sum; // 21.36
$totaal_vruchtzetting_week[10] = $sum;
Demo
Not sure if I got your question, but did you consider foreach? It iterates over every array regardless of the keys.

PHP - Optimization - Levenshtein distance with prioritization

I am trying to implement the levenshtein algorithm with a little addon. I want to prioritize values that have consecutive matching letters. I've tried implementing my own form of it using the code below:
function levenshtein_rating($string1, $string2) {
$GLOBALS['lvn_memo'] = array();
return lev($string1, 0, strlen($string1), $string2, 0, strlen($string2));
}
function lev($s1, $s1x, $s1l, $s2, $s2x, $s2l, $cons = 0) {
$key = $s1x . "," . $s1l . "," . $s2x . "," . $s2l;
if (isset($GLOBALS['lvn_memo'][$key])) return $GLOBALS['lvn_memo'][$key];
if ($s1l == 0) return $s2l;
if ($s2l == 0) return $s1l;
$cost = 0;
if ($s1[$s1x] != $s2[$s2x]) $cost = 1;
else $cons -= 0.1;
$dist = min(
(lev($s1, $s1x + 1, $s1l - 1, $s2, $s2x, $s2l, $cons) + 1),
(lev($s1, $s1x, $s1l, $s2, $s2x + 1, $s2l - 1, $cons) + 1),
(lev($s1, $s1x + 1, $s1l - 1, $s2, $s2x + 1, $s2l - 1, $cons) + $cost)
);
$GLOBALS['lvn_memo'][$key] = $dist + $cons;
return $dist + $cons;
}
You should note the $cons -= 0.1; is the part where I am adding a value to prioritize consecutive values. This formula will be checking against a large database of strings. (As high as 20,000 - 50,000) I've done a benchmark test with PHP's built in levenshtein
Message Time Change Memory
PHP N/A 9300128
End PHP 1ms 9300864
End Mine 20ms 9310736
Array
(
[0] => 3
[1] => 3
[2] => 0
)
Array
(
[0] => 2.5
[1] => 1.9
[2] => -1.5
)
Benchmark Test Code:
$string1 = "kitten";
$string2 = "sitter";
$string3 = "sitting";
$log = new Logger("PHP");
$distances = array();
$distances[] = levenshtein($string1, $string3);
$distances[] = levenshtein($string2, $string3);
$distances[] = levenshtein($string3, $string3);
$log->log("End PHP");
$distances2 = array();
$distances2[] = levenshtein_rating($string1, $string3);
$distances2[] = levenshtein_rating($string2, $string3);
$distances2[] = levenshtein_rating($string3, $string3);
$log->log("End Mine");
echo $log->status();
echo "<pre>" . print_r($distances, true) . "</pre>";
echo "<pre>" . print_r($distances2, true) . "</pre>";
I recognize that PHP's built in function will probably always be faster than mine by nature. But I am wondering if there is a way to speed mine up?
So the question: Is there a way to speed this up? My alternative here is to run levenshtein and then search through the highest X results of that and prioritize them additionally.
Based on Leigh's comment, copying PHP's built in form of Levenhstein lowered the time down to 3ms. (EDIT: Posted the version with consecutive character deductions. This may need tweaked, by appears to work.)
function levenshtein_rating($s1, $s2, $cons = 0, $cost_ins = 1, $cost_rep = 1, $cost_del = 1) {
$s1l = strlen($s1);
$s2l = strlen($s2);
if ($s1l == 0) return $s2l;
if ($s2l == 0) return $s1l;
$p1 = array();
$p2 = array();
for ($i2 = 0; $i2 <= $s2l; ++$i2) {
$p1[$i2] = $i2 * $cost_ins;
}
$cons = 0;
$cons_count = 0;
$cln = 0;
$tbl = $s1;
$lst = false;
for ($i1 = 0; $i1 < $s1l; ++$i1) {
$p2[0] = $p1[0] + $cost_del;
$srch = true;
for($i2 = 0; $i2 < $s2l; ++ $i2) {
$c0 = $p1[$i2] + (($s1[$i1] == $s2[$i2]) ? 0 : $cost_rep);
if ($srch && $s2[$i2] == $tbl[$i1]) {
$tbl[$i1] = "\0";
$srch = false;
$cln += ($cln == 0) ? 1 : $cln * 1;
}
$c1 = $p1[$i2 + 1] + $cost_del;
if ($c1 < $c0) $c0 = $c1;
$c2 = $p2[$i2] + $cost_ins;
if ($c2 < $c0) $c0 = $c2;
$p2[$i2 + 1] = $c0;
}
if (!$srch && $lst) {
$cons_count += $cln;
$cln = 0;
}
$lst = $srch;
$tmp = $p1;
$p1 = $p2;
$p2 = $tmp;
}
$cons_count += $cln;
$cons = -1 * ($cons_count * 0.1);
return $p1[$s2l] + $cons;
}
I think the major slowdown in your function is the fact that it's recursive.
As I've said in my comments, PHP function calls are notoriously heavy work for the engine.
PHP itself implements levenshtein as a loop, keeping a running total of the cost incurred for inserts, replacements and deletes.
I'm sure if you converted your code to a loop as well you'd see some massive performance increases.
I don't know exactly what your code is doing, but I have ported the native C code to PHP to give you a starting point.
define('LEVENSHTEIN_MAX_LENGTH', 12);
function lev2($s1, $s2, $cost_ins = 1, $cost_rep = 1, $cost_del = 1)
{
$l1 = strlen($s1);
$l2 = strlen($s2);
if ($l1 == 0) {
return $l2 * $cost_ins;
}
if ($l2 == 0) {
return $l1 * $cost_del;
}
if (($l1 > LEVENSHTEIN_MAX_LENGTH) || ($l2 > LEVENSHTEIN_MAX_LENGTH)) {
return -1;
}
$p1 = array();
$p2 = array();
for ($i2 = 0; $i2 <= $l2; $i2++) {
$p1[$i2] = $i2 * $cost_ins;
}
for ($i1 = 0; $i1 < $l1; $i1++) {
$p2[0] = $p1[0] + $cost_del;
for ($i2 = 0; $i2 < $l2; $i2++) {
$c0 = $p1[$i2] + (($s1[$i1] == $s2[$i2]) ? 0 : $cost_rep);
$c1 = $p1[$i2 + 1] + $cost_del;
if ($c1 < $c0) {
$c0 = $c1;
}
$c2 = $p2[$i2] + $cost_ins;
if ($c2 < $c0) {
$c0 = $c2;
}
$p2[$i2 + 1] = $c0;
}
$tmp = $p1;
$p1 = $p2;
$p2 = $tmp;
}
return $p1[$l2];
}
I did a quick benchmark comparing yours, mine, and PHPs internal functions, 100,000 iterations each, time is in seconds.
float(12.954766988754)
float(2.4660499095917)
float(0.14857912063599)
Obviously it hasn't got your tweaks in it yet, but I'm sure they wont slow it down that much.
If you really need more of a speed boost, once you have worked out how to change this function, it should be easy enough to port your changes back into C, make a copy of PHPs function definitions, and implement your own native C version of your modified function.
There's lots of tutorials out there on how to make PHP extensions, so you shouldn't have that much difficulty if you decide to go down that route.
Edit:
Was looking at ways to improve it further, I noticed
$c0 = $p1[$i2] + (($s1[$i1] == $s2[$i2]) ? 0 : $cost_rep);
$c1 = $p1[$i2 + 1] + $cost_del;
if ($c1 < $c0) {
$c0 = $c1;
}
$c2 = $p2[$i2] + $cost_ins;
if ($c2 < $c0) {
$c0 = $c2;
}
Is the same as
$c0 = min(
$p1[$i2 + 1] + $cost_del,
$p1[$i2] + (($s1[$i1] == $s2[$i2]) ? 0 : $cost_rep),
$c2 = $p2[$i2] + $cost_ins
);
Which I think directly relates to the min block in your code. However, this slows down the code quite significantly. (I guess its the overhead of the extra function call)
Benchmarks with the min() block as the second timing.
float(2.484846830368)
float(3.6055288314819)
You were right about the second $cost_ins not belonging - copy/paste fail on my part.

Split total into 5 different numbers

Ok what i'm wanting to do is split a number ($row['count']) into 5, this is easy enough if you want equal numbers:
$sum = ($row['count'] / 5);
$fsum = floor($sum);
but I want each number to be different and still add up to total ie $row['count'] how can this be achieved?
Update:
If this helps its to be used to update 5 rows in a database:
$query = "SELECT * FROM foo";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$sum = ($row['count'] / 5);
$fsum = floor($sum);
$id = $row['id'];
$update = "UPDATE foo SET foo1='$fsum', foo2='$fsum', foo3='$fsum', foo4='$fsum', foo5='$fsum' WHERE id='$id'";
mysql_query($update);
}// while
so ideally the $update query would be something like:
$update = "UPDATE foo SET foo1='$fsum1', foo2='$fsum2', foo3='$fsum3', foo4='$fsum4', foo5='$fsum5' WHERE id='$id'";
This is my take:
function randomize($sum, $parts) {
$part_no = count($parts);
$continnue_counter = 0;
while (count(array_unique($parts)) != $part_no) {
$changing = array_rand($parts, 2);
if (($parts[$changing[0]] - 1) == 0 || ($parts[$changing[1]] - 1) == 0) { // don't let them go under 1
++$continnue_counter;
// sometime one element get everything and others even out on 1
// just throw away everything you got so far and start over
if ($continnue_counter > 10) {
$parts = setup($sum, $part_no);
$continnue_counter = 0;
}
continue;
}
$continnue_counter = 0;
$signum = mt_rand(0, 100) % 2 ? 1 : -1;
$delta = $signum * mt_rand(1, min($parts[$changing[0]] - 1, $parts[$changing[1]] - 1)); // -1 to make sure they don't go under 0
$parts[$changing[0]] += $delta;
$parts[$changing[1]] -= $delta;
}
return $parts;
}
function setup($sum, $part_no) {
$parts = array_fill(0, $part_no, (int)($sum / $part_no));
// acount for the reminder of (int) cast
$reminder = $sum - array_sum($parts);
while ($reminder) {
$parts[array_rand($parts)] += 1;
--$reminder;
}
return $parts;
}
$part_no = 5;
$sum = 42;
$parts = randomize($sum, setup($sum, $part_no));
var_export($parts);
print array_sum($parts)
Update:
I've added a version that introduces a little more entropy.
Update2:
The more random one had a tendency to decrement everything to 1 except one part, added an explicit detection to deal with this. Still the algorithm behind it has unknown termination time.

Categories