How to distribute point from the winner to the loser? - php

Let's explain my problem!
we are coding a website for player of some games we know that the minimum of player is 2 and don't know the maximum of player.
in these games we have a leaderboard (1st,second,...,Last) and we want to distribute for exemple 50 points in an exponential or other way to make graphs.
so here is my question how to give these 50 points to the players with the rules that the first must have the most of points and the last must not have points.
I'm open for suggestions,
and thank all of you who can help me

You can simply remap a priority.
You were asking the last not having any points, try to add one additional player and remove after calculation.
Let's say we want to distribute 50 points over 10 players by descending priority.
$pointsAvailable = 50;
$playerCount = 10;
We set some kind of priority.
$players = range(1, $playerCount);
$players = array_map(function($p) use ($playerCount, $pointsAvailable) {
return ($playerCount / $p);
}, $players);
Now we know we divide the sum of the distribution by the number of points to get the scalar factor.
$pointScalar = $pointsAvailable / array_sum($players);
$players = array_map(function($p) use ($pointScalar) {
return ($pointScalar * $p);
}, $players);
Here you can see the results.
print_r($players);
Array // The points for the players
(
[0] => 17.07085760737
[1] => 8.5354288036851
[2] => 5.6902858691234
[3] => 4.2677144018426
[4] => 3.4141715214741
[5] => 2.8451429345617
[6] => 2.43869394391
[7] => 2.1338572009213
[8] => 1.8967619563745
[9] => 1.707085760737
)
The sum of all points:
print_r(array_sum($players));
50

Related

Random Destribution of arbitrary numbers of items

I need a PHP function that randomly distributes an arbitrary number of darts over an arbitrary number of dartboards. It has to return the number of dartboards that have 0 darts in them, the amount of boards with 1 dart, 2 darts etc.
I have to be able to run this within a few milliseconds with millions of darts and dartboards, but an approximation is good enough. I already have a function that can give me normally distributed random values so a solution that gives the average result can be worked with.
//Example result with 1000 darts and 500 dartboards
Array
(
[0] => 62
[1] => 128
[2] => 152
[3] => 96
[4] => 40
[5] => 14
[6] => 6
[7] => 2
)
I've made a function that generates example values by procedurally distributing each dart randomly. This is for example purposes only. The production version of the function will have to use normal distribution to create results in a scalable way.
Do not tell me how to optimize this example, its for demonstration purposes only:
<?php
function distribute($items, $targets) {
$result = array();
$values = array();
for($i=0; $i<$items; $i++) {
#$values[ mt_rand(0,$targets) ] ++;
}
for($i=0;$i<$targets;$i++) {
#$result[ (int) $values[$i] ] ++;
}
ksort($result);
return $result;
}
$microtime = microtime(true);
echo '<pre>';
print_r( distribute(100000, 50000) );
print_r(microtime(true) - $microtime);

php split integer into smaller parts

i'm working on a project that will need to have everything shown with barcodes, so I've generated 7 numbers for EAN8 algorithm and now have to get these 7 numbers seperately, right now i'm using for the generation
$codeint = mt_rand(1000000, 9999999);
and I need to get this 7 numbers each seperately so I can calculate the checksum for EAN8, how can i split this integer to 7 parts, for example
12345678 to
arr[0]=1
arr[1]=2
arr[2]=3
arr[3]=4
arr[4]=5
arr[5]=6
arr[6]=7
any help would be appreciated..
also I think that I'm becoming crazy :D because I already tried most of the solutions you gave me here before and something is not working like it should work, for example:
$codeint = mt_rand(1000000, 9999999);
echo $codeint."c</br>";
echo $codeint[1];
echo $codeint[2];
echo $codeint[3];
gives me :
9082573c
empty row
empty row
empty row
solved! $codeint = (string)(mt_rand(1000000, 9999999));
Try to use str_split() function:
$var = 1234567;
print_r(str_split($var));
Result:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
)
There are two ways to do this, one of which is reasonably unique to PHP:
1) In PHP, you can treat an integer value as a string and then index into the individual digits:
$digits = "$codeint";
// access a digit using intval($digits[3])
2) However, the much more elegant way is to use actual integer division and a little knowledge about mathematical identities of digits, namely in a number 123, each place value is composed of ascending powers of 10, i.e.: 1 * 10^2 + 2 * 10^1 + 3 * 10^0.
Consequently, dividing by powers of 10 will permit you to access each digit in turn.
it's basic math you can divide them in loop by 10
12345678 is 8*10^1 + 7*10^2 + 6*10^3...
the other option is cast it to char array and then just get it as char
Edit
After #HamZa DzCyberDeV suggestion
$string = '12345678';
echo "<pre>"; print_r (str_split($string));
But in mind it comes like below but your suggestion is better one.
If you're getting string from your function then you can use below one
$string = '12345678';
$arr = explode(",", chunk_split($string, 1, ','));
$len = count($arr);
unset($arr[$len-1]);
echo "<pre>";
print_r($arr);
and output is
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
)
okay what you can do is
Type cast to string with prefill 0
this is how it works
$sinteger = (string)$integer;
$arrsize = 0 ;
for (i=strlen($sinteger), i == 0 ; i--)
{
arr[$arrsize]=$sinteger[i];
$arrsize++;
}
And then what is left you can prefill with zip.
I am sure you can manage the order reverse or previous. but this is simple approach.

PHP - Sort Array Based Off Factor :: usort?

here is a little background on what I'm trying to accomplish. I have an array from a MySQL query that is being displayed. I want to sort the array based on a factor. The factor is calculated inline based on the time the article was posted & the number of votes it's received. Something like this:
// ... MySQL query here
$votes = $row['0']
$seconds = strtotime($record->news_time)+time();
$sum_total = pow($votes,2) / $seconds;
So the array thats coming in looks something like this:
Array (
[0] => stdClass Object (
[id] => 13
[news_title] => Article
[news_url] => http://website.com/article/14
[news_root_domain] => website.com
[news_category] => Business
[news_submitter] => 2
[news_time] => 2013-02-18 12:50:02
[news_points] => 2
)
[1] => stdClass Object (
[id] => 14
[news_title] => Title
[news_url] => http://www.website.com/article/2
[news_root_domain] => www.website.com
[news_category] => Technology
[news_submitter] => 1
[news_time] => 2012-10-02 10:03:22
[news_points] => 8
)
)
I want to sort the aforementioned array using the factor I mentioned above. The idea is to show the highest rated articles first on the list (using the calculated factor), instead of the default sorting method that the array comes in. It seems like usort might be my best bet, but let me know what you all think?
Do it all in the query:
SELECT n.*, ( POW(?, 2) / (UNIX_TIMESTAMP(n.news_time) + UNIX_TIMESTAMP(NOW())) ) as rank
FROM news_table n
ORDER BY rank;
Now in order to get the votes you may have to do a subquery or a join, but i cant advise on that because you dont give enough info on where the votes are coming from. You could however supply the votes to the query as well instead of selecting it all in one shot something like:
$sql = sprintf('SELECT n.*, ( POW(%d, 2) / (UNIX_TIMESTAMP(n.news_time) + UNIX_TIMESTAMP(NOW())) ) as rank FROM news_table n ORDER BY rank', $votes);
Aside from that, yes you could use usort, but that would also require you to have the entire recordset in memory to provide accurate sorting, which could be problematic at some point.

How to make a Round Robin? or Is there an easier way other than Round Robin?

The problem that I face is in what way if there is issue like the example below:
Codes 1000, 2000, 3000, 4000, 5000
ID 1, 2, 3
========================================
This:
ID number 1 has codes 1000, 2000, 3000, 4000
ID number 2 has codes 2000, 4000, 3000
ID number 3 has codes 3000, 4000, 5000
========================================
When all the fields are connected, each ID has found the same codes.
From the example above, I want to produce fair result and adjusted to the code that it had before on each ID as below: (producing fair codes over the set of ID's)
========================================
To be:
ID number 1 has codes 1000, 2000 (1000 must be on number 1 cause only it has than other)
ID number 2 has codes 3000, 4000
ID number 3 has codes 5000 (5000 must be on number 3 cause only it has than other)
========================================
Some say using Round Robin, but I never heard Round Robin before and I don't have idea how to use it, such a blank mind.
Is there another easier way like to use PHP may be? I'm lost.
Thanks.
=============================================================
Explanation:
I'm making an application where each user has a predefined code and does not have the same code. For example user A has a range of codes between 1000-1500, the user B has a range of codes between 1600 to 2000. And user C has a range of codes between 1300-1550. As we see, the distance of a code on the C contained in the codes on the A (A -> 1000-1500, C -> 1300-1550), will certainly get duplicate between the two user.
With this condition, how to separate and divide it to make it more fair. Let C has 1300, A has 1301, C has 1302 et cetera until 1500.
I thought the simple example I gave before could quite understand, but it seemed like a mess, my mistake.
$codes = array(1000, 2000, 3000, 4000, 5000);
// set up the receiving "containers"
$ids = array(
array(),
array(),
array(),
);
$n_ids = count($ids);
$i = 0;
foreach ($codes as $code) {
// use ($i % $n_ids) to distribute over $n_ids containers
$ids[$i % $n_ids][] = $code;
++$i;
}
print_r($ids);
Output:
Array
(
[0] => Array
(
[0] => 1000
[1] => 4000
)
[1] => Array
(
[0] => 2000
[1] => 5000
)
[2] => Array
(
[0] => 3000
)
)
This problem is a simple distribution task: Distribute N items over M containers.
For every i (0 <= i < N) you select a container to put item N[i] in; the selection is done by using this expression: i mod M (i modulo M).
This expression is what you could call the round-robin, because it goes round like this:
i : 0 1 2 3 4
i % M: 0 1 2 0 1
Even faster
The array_chunk function does this task as well, but I figured you would like to understand the problem first. Also, array_chunk produces a somewhat different result.
$ids = array_chunk(array(1000, 2000, 3000, 4000, 5000), round(count($codes) / 3));
Output:
Array
(
[0] => Array
(
[0] => 1000
[1] => 2000
)
[1] => Array
(
[0] => 3000
[1] => 4000
)
[2] => Array
(
[0] => 5000
)
)

Find the best combination from a given set of multiple sets

Say you have a shipment. It needs to go from point A to point B, point B to point C and finally point C to point D. You need it to get there in five days for the least amount of money possible. There are three possible shippers for each leg, each with their own different time and cost for each leg:
Array
(
[leg0] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 5000
)
[FedEx] => Array
(
[days] => 2
[cost] => 3000
)
[Conway] => Array
(
[days] => 5
[cost] => 1000
)
)
[leg1] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 3000
)
[FedEx] => Array
(
[days] => 2
[cost] => 3000
)
[Conway] => Array
(
[days] => 3
[cost] => 1000
)
)
[leg2] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 4000
)
[FedEx] => Array
(
[days] => 1
[cost] => 3000
)
[Conway] => Array
(
[days] => 2
[cost] => 5000
)
)
)
How would you go about finding the best combination programmatically?
My best attempt so far (third or fourth algorithm) is:
Find the longest shipper for each leg
Eliminate the most "expensive" one
Find the cheapest shipper for each leg
Calculate the total cost & days
If days are acceptable, finish, else, goto 1
Quickly mocked-up in PHP (note that the test array below works swimmingly, but if you try it with the test array from above, it does not find the correct combination):
$shippers["leg1"] = array(
"UPS" => array("days" => 1, "cost" => 4000),
"Conway" => array("days" => 3, "cost" => 3200),
"FedEx" => array("days" => 8, "cost" => 1000)
);
$shippers["leg2"] = array(
"UPS" => array("days" => 1, "cost" => 3500),
"Conway" => array("days" => 2, "cost" => 2800),
"FedEx" => array("days" => 4, "cost" => 900)
);
$shippers["leg3"] = array(
"UPS" => array("days" => 1, "cost" => 3500),
"Conway" => array("days" => 2, "cost" => 2800),
"FedEx" => array("days" => 4, "cost" => 900)
);
$times = 0;
$totalDays = 9999999;
print "<h1>Shippers to Choose From:</h1><pre>";
print_r($shippers);
print "</pre><br />";
while($totalDays > $maxDays && $times < 500){
$totalDays = 0;
$times++;
$worstShipper = null;
$longestShippers = null;
$cheapestShippers = null;
foreach($shippers as $legName => $leg){
//find longest shipment for each leg (in terms of days)
unset($longestShippers[$legName]);
$longestDays = null;
if(count($leg) > 1){
foreach($leg as $shipperName => $shipper){
if(empty($longestDays) || $shipper["days"] > $longestDays){
$longestShippers[$legName]["days"] = $shipper["days"];
$longestShippers[$legName]["cost"] = $shipper["cost"];
$longestShippers[$legName]["name"] = $shipperName;
$longestDays = $shipper["days"];
}
}
}
}
foreach($longestShippers as $leg => $shipper){
$shipper["totalCost"] = $shipper["days"] * $shipper["cost"];
//print $shipper["totalCost"] . " <?> " . $worstShipper["totalCost"] . ";";
if(empty($worstShipper) || $shipper["totalCost"] > $worstShipper["totalCost"]){
$worstShipper = $shipper;
$worstShipperLeg = $leg;
}
}
//print "worst shipper is: shippers[$worstShipperLeg][{$worstShipper['name']}]" . $shippers[$worstShipperLeg][$worstShipper["name"]]["days"];
unset($shippers[$worstShipperLeg][$worstShipper["name"]]);
print "<h1>Next:</h1><pre>";
print_r($shippers);
print "</pre><br />";
foreach($shippers as $legName => $leg){
//find cheapest shipment for each leg (in terms of cost)
unset($cheapestShippers[$legName]);
$lowestCost = null;
foreach($leg as $shipperName => $shipper){
if(empty($lowestCost) || $shipper["cost"] < $lowestCost){
$cheapestShippers[$legName]["days"] = $shipper["days"];
$cheapestShippers[$legName]["cost"] = $shipper["cost"];
$cheapestShippers[$legName]["name"] = $shipperName;
$lowestCost = $shipper["cost"];
}
}
//recalculate days and see if we are under max days...
$totalDays += $cheapestShippers[$legName]['days'];
}
//print "<h2>totalDays: $totalDays</h2>";
}
print "<h1>Chosen Shippers:</h1><pre>";
print_r($cheapestShippers);
print "</pre>";
I think I may have to actually do some sort of thing where I literally make each combination one by one (with a series of loops) and add up the total "score" of each, and find the best one....
EDIT:
To clarify, this isn't a "homework" assignment (I'm not in school). It is part of my current project at work.
The requirements (as always) have been constantly changing. If I were given the current constraints at the time I began working on this problem, I would be using some variant of the A* algorithm (or Dijkstra's or shortest path or simplex or something). But everything has been morphing and changing, and that brings me to where I'm at right now.
So I guess that means I need to forget about all the crap I've done to this point and just go with what I know I should go with, which is a path finding algorithm.
Could alter some of the shortest path algorithms, like Dijkstra's, to weight each path by cost but also keep track of time and stop going along a certain path if the time exceeds your threshold. Should find the cheapest that gets you in under your threshold that way
Sounds like what you have is called a "linear programming problem". It also sounds like a homework problem, no offense.
The classical solution to a LP problem is called the "Simplex Method". Google it.
However, to use that method, you must have the problem correctly formulated to describe your requirements.
Still, it may be possible to enumerate all possible paths, since you have such a small set. Such a thing won't scale, though.
Sounds like a job for Dijkstra's algorithm:
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1959, 1 is a graph search algorithm that solves the single-source shortest path problem for a graph with non negative edge path costs, outputting a shortest path tree. This algorithm is often used in routing.
There are also implementation details in the Wikipedia article.
If I knew I only had to deal with 5 cities, in a predetermined order, and that there were only 3 routes between adjacent cities, I'd brute force it. No point in being elegant.
If, on the other hand, this were a homework assignment and I were supposed to produce an algorithm that could actually scale, I'd probably take a different approach.
As Baltimark said, this is basically a Linear programming problem. If only the coefficients for the shippers (1 for included, 0 for not included) were not (binary) integers for each leg, this would be more easily solveable. Now you need to find some (binary) integer linear programming (ILP) heuristics as the problem is NP-hard.
See Wikipedia on integer linear programming for links; on my linear programming course we used at least Branch and bound.
Actually now that I think of it, this special case is solveable without actual ILP as the amount of days does not matter as long as it is <= 5. Now start by choosing the cheapest carrier for first choice (Conway 5:1000). Next you choose yet again the cheapest, resulting 8 days and 4000 currency units which is too much so we abort that. By trying others too we see that they all results days > 5 so we back to first choice and try the second cheapest (FedEx 2:3000) and then ups in the second and fedex in the last. This gives us total of 4 days and 9000 currency units.
We then could use this cost to prune other searches in the tree that would by some subtree-stage result costs larger that the one we've found already and leave that subtree unsearched from that point on.
This only works as long as we can know that searching in the subtree will not produce a better results, as we do here when costs cannot be negative.
Hope this rambling helped a bit :).
This is a knapsack problem. The weights are the days in transit, and the profit should be $5000 - cost of leg. Eliminate all negative costs and go from there!
I think that Dijkstra's algorithm is for finding a shortest path.
cmcculloh is looking for the minimal cost subject to the constraint that he gets it there in 5 days.
So, merely finding the quickest way won't get him there cheapest, and getting there for the cheapest, won't get it there in the required amount of time.

Categories