What I need is to create five random integer (say rand(1,5)). Then, I generate a score based on these numbers. For instance, if I get a result of 1,2,3,4,5 then that would equal a zero score, but if I got 1,1,3,4,5 that would be 1 as we have a pair. Similar to a poker kind of scoring, so five of the same number would be a "full house" thus resulting in the highest score.
How would I go about the scoring system, even if it is just the mathematical equation?
More detail:
1-5 will hold separate images and then will be fought against "The House" which will have identical code to the user to determine the winner. Here's some example draws and the score they would receive:
1,2,3,4,5 = score 0
1,1,2,3,4 = score 1 (1 pair)
1,1,2,2,4 = score 2 (2 pair)
1,1,1,3,4 = score 3 (3 of a kind)
1,1,1,1,5 = score 4 (4 of a kind)
1,1,1,3,3 = score 5 (full house)
1,1,1,1,1 = score 6 (5 of a kind)
The combination of numbers is irreverent if they score 6 and the house scores 6, it's a tie.
if (isset($_POST['play'])) {
$rand1 = rand(1, 5);
$rand2 = rand(1, 5);
$rand3 = rand(1, 5);
$rand4 = rand(1, 5);
$rand5 = rand(1, 5);
if ($_POST['bet'] <= $user_data['coins']) {
if ($_POST['bet'] < 999999999) {
if ($_POST['bet'] > 0.99) {
if ($user_data['coins'] >= 1) {
$array = array($rand1,$rand2,$rand3,$rand4,$rand5);
print_r(array_count_values($array));
echo $rand1.', '.$rand2.', '.$rand3.', '.$rand4.', '.$rand5;
Array( // Here I don't understand
1 => 3,//
2 => 1,//
3 => 1 //
);
}
}
}
}
}
This outputs ; Array ( [5] => 2 [4] => 2 [1] => 1 ) 5, 5, 4, 4, 1
Use array_count_value function for this.
$array = array(1,1,1,2,5);
print_r(array_count_values($array));
Array(
1 => 3,
2 => 1,
3 => 1
);
Here's the approach I would consider, building on #Lele's answer. Warning: this is a bit confusing, so sit down with a cup of tea for this one.
Build a set of five buckets, [1] to [5], and scan a player's numbers, so that the count for each number is stored in the corresponding bucket
Then count the numbers you are left with into a new bucket system, with each position representing the number of counts you have for something.
So, if your score is this:
1 1 2 2 4
Then your first buckets are:
2 2 0 1 0
That's because you have two ones, two twos, and one four. And your second buckets are:
1 2 0 0 0
That's because you have two two-counts, and one one-count. Here, you disregard the first position (since a one-count for something does not score anything) and score for the others. So, test for two twos, and score that two.
If you score is this:
5 5 5 5 1
Then your first buckets are:
1 0 0 0 4
That's one one and four fives. So your second buckets are:
1 0 0 1 0
Your lookup table for this could be:
x 1 0 0 0 -> one pair
x 2 0 0 0 -> two pairs
x 0 1 0 0 -> three of a kind
x 1 1 0 0 -> full house
x 0 0 1 0 -> four of a kind
x 0 0 0 1 -> five of a kind
The 'x' means that you don't match on this. So, your lookup table matches four numbers to a score.
I was rather interested in this problem, so I have written some code to do the above. You'll still need to do the lookup table, but that is relatively trivial, and will be good practice for you. Here is a demo, with comments (run code here):
<?php
function counting(array $array) {
// Input figures
print_r($array);
// Run the figures twice through the bucket-counter
$firstBuckets = bucketCounter($array);
$secondBuckets = bucketCounter($firstBuckets);
// Ignore counts of 1
array_shift($secondBuckets);
// Output, just need to do the lookup now
echo ' converts to ';
print_r($secondBuckets);
echo "<br />";
}
/**
* Bucket counter
*/
function bucketCounter(array $array) {
$result = array(0, 0, 0, 0, 0, );
foreach($array as $value) {
if ($value > 0) {
$result[$value - 1]++;
}
}
return $result;
}
// Try some demos here!
counting(array(1, 2, 3, 4, 5));
counting(array(1, 1, 2, 4, 2));
counting(array(1, 1, 1, 1, 1));
?>
The demos I've included seem to work, but do hunt for bugs!
If the range is quite small, you can use counting sort approach. For each number, provide a "bucket" to count how many times a number appear. Scan once to fill in the buckets. Then another scan, but this time against the bucket to get the highest value. That's your score.
Related
I've got this task, which I honestly don't understand what exactly to do.
It my be because of my English level, or mathmatics level, but this is really something I can not make sense of. Could you help be at least to understand the task ?
My php knowledge is very well, at least I thought so...
The task is this :
"Carry" is a term of an elementary arithmetic. It's a digit that you transfer to column with higher significant digits when adding numbers.
This task is about getting the sum of all carried digits.
You will receive an array of two numbers, like in the example. The function should return the sum of all carried digits.
function carry($arr) {
// ...
}
carry([123, 456]); // 0
carry([555, 555]); // 3 (carry 1 from ones column, carry 1 from tens column, carry 1 from hundreds column)
carry([123, 594]); // 1 (carry 1 from tens column)
Support of arbitrary number of operands will be a plus:
carry([123, 123, 804]); // 2 (carry 1 from ones column, carry 1, carry 1 from hundreds column)
Background information on "carry": https://en.m.wikipedia.org/wiki/Carry_(arithmetic)
For this task, we don't actually need the numbers written under the equals line, just the numbers which are carried. Importantly, the carried numbers need to be used when calculating subsequent columns.
Before looping each column of integers, reverse the order of the columns so that looping from left-to-right also iterates the lowest unit column and progresses to higher unit columns (ones, then tens, then hundreds, etc).
For flexibility, my snippet is designed to handle numbers of dynamic length. If processing potential float numbers, you could merely multiply all number by a power of 10 to convert all values to integers. My snippet is not designed to handled signed integers.
Code: (Demo)
function sumCarries(array $array) {
$columns = ['carries' => []];
// prepare matrix of 1-digit integers in columns -- ones, tens, hundreds, etc
foreach ($array as $integer) {
$columns[] = str_split(strrev($integer));
}
// sum column values in ascending order and populate carry values
// subsequent column sums need to include carried value
for ($i = 0, $len = strlen(max($array)); $i < $len; ++$i) {
$columns['carries'][$i + 1] = (int)(array_sum(array_column($columns, $i)) / 10);
}
// sum all populated carry values
return array_sum($columns['carries']);
}
$tests = [
[123, 456], // no carries in any column
[555, 555], // 1 ones, 1 tens, 1 hundreds
[123, 594], // 1 tens
[123, 123, 804], // 1 ones, 1 hundreds
[99, 9, 99, 99, 99], // 4 ones, 4 hundreds
[9,9,9,9,9,9,9,9,9,9,9,9], // 10 ones
];
var_export(array_map('sumCarries', $tests));
Output:
array (
0 => 0,
1 => 3,
2 => 1,
3 => 2,
4 => 8,
5 => 10,
)
Since it's homework, I'm not going to fully answer the question, but explain the pieces you seem confused about so that you can put them together.
1 11 111 111 <- these are the carry digits
555 555 555 555 555
+ 555 -> + 555 -> + 555 -> + 555 -> + 555
----- ----- ----- ----- -----
0 10 110 1110
For a better example of two digits, let's use 6+6. To get the carry digit you can use the modulus operator where 12 % 10 == 2. So, (12 - (12 % 10)) / 10 == 1.
Thank you again. #Sammitch
I got it to make it work. Actually the problem was my English Math Level. The term "Carry digits" had no meaning at all for me. I was completely focusing on something else.
Here is my code : It may be far from perfect, but it does the job :)
function carry($arr) {
$sum_ones = 0;
$sum_tens = 0;
$sum_hunds = 0;
$arrCount = count($arr);
foreach($arr as $key){
$stri = (string)$key;
$foo[] = array(
"hunds" => $stri[0],
"tens" => $stri[1],
"ones" => $stri[2]
);
}
$fooCount = count($foo);
for($i=0; $i<$fooCount; $i++) {
$sum_ones+= $foo[$i]["ones"];
$sum_tens+= $foo[$i]["tens"];
$sum_hunds+= $foo[$i]["hunds"];
}
$sum1 = ($sum_ones - ($sum_ones % 10)) / 10;
$sum10 = ($sum_tens - ($sum_tens % 10)) / 10;
$sum100 = ($sum_hunds - ($sum_hunds % 10)) / 10;
return ($sum1 + $sum10 + $sum100);
}
$arr = array(555, 515, 111);
echo carry($arr);
$array = array(1, 2, 3, 4, 5, ..., N);
Also there is a number D = 10%. What is the fastest way to sort the array in such way that:
$sorted_array = {a[i]}
contains exactly the elements of $array in a mixed order, but also:
abs(a[i + 1] - a[i]) >= N * 10%
for any [i] and look randomized as much as possible.
For example,
// assume D = 25%
$array = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// so the difference between any neighbors is >= 4 = 10 * 25%.
$sorted_array = array(4, 8, 3, 7, 1, 5, 9, 2, 6, 10);
Of course if D is large, it is impossible to sort the array I want. I don't need the 100% perfect result, but I want the numbers to look "randomized" and most of them to be different at least for 10%.
I have a strange task but it has a practical area to use. I want to extract randomized lines from the image and they should be different as much as possible. Of course, the neighbor lines on the digital images (photos etc) look very similar.
Did I explain it properly?
I know it's not a good idea just to provide code, but I was intrigued by this question. Here's how I would do it:
$d = 0.3;
$random = array();
// Populate the original array
for ($n=1; $n <= 10; $n++) {
$arr[] = $n;
}
$count = count($arr);
// Loop through array
foreach (array_keys($arr) as $key) {
if (!isset($prev_key)) {
$prev_key = array_rand($arr);
}
$possibles = array(); // This stores the possible values
echo "Trying: $prev_key";
echo ":\n";
// Loop through the array again and populate $possibles with all possible
// values based on the previous values
foreach (array_keys($arr) as $n) {
if ($arr[$n] < $prev_key - $count * $d || $arr[$n] > $prev_key + $count * $d) {
$possibles[] = $n;
echo $arr[$n]." is valid\n";
}
else {
echo $arr[$n];
echo " outside range\n";
}
}
// If there is nothing outside that range, just return the remaining values
if (count($possibles) == 0) {
$possibles = array_keys($arr);
echo "Nothing within range so just returning whole array\n";
}
echo "\n";
// Choose random value from the possible values array
$rand_key = $possibles[array_rand($possibles)];
$random[] = $arr[$rand_key];
$prev_key = $arr[$rand_key];
// Unset this value from the original array since we can only use the
// values once
unset($arr[$rand_key]);
}
print_r($random);
This will produce output like this:
Trying: 8:
1 is valid
2 is valid
3 is valid
4 is valid
5 outside range
6 outside range
7 outside range
8 outside range
9 outside range
10 outside range
Trying: 2:
1 outside range
3 outside range
4 outside range
5 outside range
6 is valid
7 is valid
8 is valid
9 is valid
10 is valid
Trying: 9:
1 is valid
3 is valid
4 is valid
5 is valid
6 outside range
7 outside range
8 outside range
10 outside range
Trying: 5:
1 is valid
3 outside range
4 outside range
6 outside range
7 outside range
8 outside range
10 is valid
Trying: 10:
1 is valid
3 is valid
4 is valid
6 is valid
7 outside range
8 outside range
Trying: 4:
1 outside range
3 outside range
6 outside range
7 outside range
8 is valid
Trying: 8:
1 is valid
3 is valid
6 outside range
7 outside range
Trying: 3:
1 outside range
6 outside range
7 is valid
Trying: 7:
1 is valid
6 outside range
Trying: 1:
6 is valid
Array
(
[0] => 2
[1] => 9
[2] => 5
[3] => 10
[4] => 4
[5] => 8
[6] => 3
[7] => 7
[8] => 1
[9] => 6
)
The only drawback is that since it randomly gets rows, there is a chance that the values near the end may not be outside the defined range. By my tests, this happens to about 4% using the above $d = 0.25 and 1000 values. One way to get around this is just to insert these values back in at random places instead of appending them like I have done.
Also note, this method is not that efficient. It has to loop through the array count($arr) ^ 2 times. So for 1000 values, you're looking at 1,000,000 iterations. Fortunately the array gets progressively smaller.
Given an array of any size (from 1 to 4 rounds) with ranks numbering from 1 to 8 (or more), how can I take that array and sort it bracket style, so rank 1 is first, rank 2 is last, then rank 8 is next, then rank 7 is second to last... like
Then the next round ..
1, 4, 3, 2
I am trying to sort tournament brackets but not having much luck when it comes to sorting the ranking, and also in a way that scales well so the display does not break.
Edit:
Some clarification, each bracket size needs to break down like so:
If the bracket has 8 games, the game numbers are 1 through 8, so that round needs to arrange itself like:
Game 1
Game 8
Game 5
Game 4
Game 6
Game 3
Game 7
Game 2
So then, on the next round, it has 4 games, which would come out as:
Game 1
Game 4
Game 3
Game 2
And so on:
Game 1
Game 2
Finally,
Game 1
It also needs to work if the starting bracket had 16 games instead of 8, or 32, or more. The idea is that the winner of Game 1 and Game 8 play each other in Game 1 on the next round. The first game and second game are always the first and last on each bracket. Then it works it's way inward.
This isn't sorting the list. Unless you really need to sort the list, indices may be faster and more efficient.
The match ups will be set up like (current_rank), (total ranks) - (current_rank) + 1
Since there are 8 ranks,
1, 8 -1 +1 = 8
2, 8 -2 +1 = 7
3, 8 -3 +1 = 6
4, 8 -4 +1 = 5
So the code would look something like
<?php
$rankscount = count($ranks);
for ($i = 1; $i <= $rankscount / 2; $i++) {
echo "matchup will be: rank " . $i . " , rank " . $rankscount - $i + 1;
}
?>
After each round, reseed the function with the new sorted list, and you'll get 1vs4. 2vs3.
I'm not a professional at PHP, but hopefully this helps.
The following function sorts an array of ['r1', 'r2', 'r3', 'r4', 'r5', 'r6', 'r7', 'r8'] into an order of ['r1', 'r8', 'r2', 'r7', 'r3', 'r6', 'r4', 'r5'].
An array of ['r1', 'r2', 'r3', 'r4'] will be rearranged into ['r1', 'r4', 'r2', 'r3']
function rearranged($array) {
sort($array);
$result = array();
$length = count($array);
$offset = 0;
// Handling two elements at once, therefore just do $lenght/2 iterations
for ($i = 0; $i < $length/2; $i++) {
// $i + $offset: The current element in the original array
// + the offset of fields already filled in the results array
$result[$i + $offset] = $array[$i];
// $i + 1 + $offset: The next element in the results array
$result[$i + 1 + $offset] = $array[$length - $i -1];
// Increment offset
$offset++;
}
return $result;
}
I am not using any inbuilt sort function since they compare all keys to each others, assuming that your array already is in order just iterating and swapping positions should be much faster. If the keys are not ordered you can call a inbuilt sort function such as sort(sorts by value) or ksort (sorts by key).
To note is as well, that this function only works properly for arrays with an even amount of elements. If the number of elements is uneven the last element will be dropped from the results array.
i am trying to make a very simple game where i have 7 positions which are all hidden and within those there a 3 winning positions. I can pick randomly 3 times. I need to display whether the pick is a winning or not after every pick and store the result in a base.
Currently my thought where to generate an array of winning numbers on the first pick and then pick random number and check if it is in the winning array.
But i have a feeling that there is much more efficient way to do so.
Would appreciate if you would use PHP for coding examples, but pseudo code will do as-well.
EDIT
i am looking for the way to solve this without populating array with winning positions. maybe there is a way to do this with weights or probability percents.
Something like on first pick i have 3/7*100 percent chance to win. save result to base.
on second pick i have either 3/6*100 or 2/6*100 percent chance to win based weather i won in previous pick which i get from base.
Revised answer: this example does not require you to store the complete state of the game in a variable; instead, you just need to store the try count and won count:
$won = 0;
for($try = 0; $try < 3; $try++) {
$slots = array_fill(0, 7 - $try, 0); // blank slots
$lucky = array_fill(0, 3 - $won, 1); // lucky slots
$pot = array_replace($slots, $lucky); // make some of the slots lucky
$win = $pot[array_rand($pot)]; // randomly pick a slot
$won += $win == 1; // update won count
echo sprintf("Try %d: win=%d, total wins=%d\n", $try + 1, $win, $won);
}
Original answer:
$pot = array( // pot is (an associative) array; 0 = blank, 1 = win
"pos_1" => 0,
"pos_2" => 0,
"pos_3" => 0,
"pos_4" => 0,
"pos_5" => 0,
"pos_6" => 0,
"pos_7" => 0
);
$win = array_rand($pot, 3); // picks three indexes from the pot randomly
foreach($win as $w) {
$pot[$w] = 1; // set winning indicator
}
print_r($pot);
Output: array containing state of the pots.
Array
(
[pos_1] => 0
[pos_2] => 1
[pos_3] => 0
[pos_4] => 1
[pos_5] => 1
[pos_6] => 0
[pos_7] => 0
)
You can just save the positions of the winning numbers. This way you can always check their values using the [] operator for arrays. After all, you just pick the positions and not the numbers.
Update:
This way you even don't need to hide numbers. It's quite possible to have some more abstract "winning things" - characters, words, structures. However, it is important that you do not alter your array of hidden "things" in any way or at least update the stored winning positions accordingly if they stay the same. If that's not the case you'd naturally need to update the saved winning positions.
<?php
$arr = array(true, true, false, false, false, false, false);
shuffle($arr);
function pick($arr, $index) {
return isset($arr[$index]) && $arr[$index] === true;
}
var_dump($arr);
var_dump(pick($arr, 3));
var_dump(pick($arr, 5));
var_dump(pick($arr, 1));
I am doing this programming challenge which can be found at www.interviewstreet.com (its the first challenge worth 30 points).
When I submitted the solution, I was returned a result which said that the answer was wrong because it only passed 1/11 test cases. However, I feel have tested various cases and do not understand what I am doing wrong. It would be helpful to know what those test cases could be so that I can test my program.
Here is the question (in between the grey lines below):
Quadrant Queries (30 points)
There are N points in the plane. The ith point has coordinates (xi, yi). Perform the following queries:
1) Reflect all points between point i and j both including along the X axis. This query is represented as "X i j"
2) Reflect all points between point i and j both including along the Y axis. This query is represented as "Y i j"
3) Count how many points between point i and j both including lie in each of the 4 quadrants. This query is represented as "C i j"
Input:
The first line contains N, the number of points. N lines follow.
The ith line contains xi and yi separated by a space.
The next line contains Q the number of queries. The next Q lines contain one query each, of one of the above forms.
All indices are 1 indexed.
Output:
Output one line for each query of the type "C i j". The corresponding line contains 4 integers; the number of points having indices in the range [i..j] in the 1st,2nd,3rd and 4th quadrants respectively.
Constraints:
1 <= N <= 100000
1 <= Q <= 100000
You may assume that no point lies on the X or the Y axis.
All (xi,yi) will fit in a 32-bit signed integer
In all queries, 1 <=i <=j <=N
Sample Input:
4
1 1
-1 1
-1 -1
1 -1
5
C 1 4
X 2 4
C 3 4
Y 1 2
C 1 3
Sample Output:
1 1 1 1
1 1 0 0
0 2 0 1
Explanation:
When a query says "X i j", it means that take all the points between indices i and j both including and reflect those points along the X axis. The i and j here have nothing to do with the co-ordinates of the points. They are the indices. i refers to point i and j refers to point j
'C 1 4' asks you to 'Consider the set of points having index in {1,2,3,4}. Amongst those points, how many of them lie in the 1st,2nd,3rd and 4th quads respectively?'
The answer to this is clearly 1 1 1 1.
Next we reflect the points between indices '2 4' along the X axis. So the new coordinates are :
1 1
-1 -1
-1 1
1 1
Now 'C 3 4' is 'Consider the set of points having index in {3,4}. Amongst those points, how many of them lie in the 1st,2nd,3rd and 4th quads respectively?' Point 3 lies in quadrant 2 and point 4 lies in quadrant 1.
So the answer is 1 1 0 0
I'm coding in PHP and the method for testing is with STDIN and STDOUT.
Any ideas on difficult test cases to test my code with? I don't understand why I am failing 10 / 11 test cases.
Also, here is my code if you're interested:
// The global variable that will be changed
$points = array();
/******** Functions ********/
// This function returns the number of points in each quadrant.
function C($beg, $end) {
// $quad_count is a local array and not global as this gets reset for every C operation
$quad_count = array("I" => 0, "II" => 0, "III" => 0, "IV" => 0);
for($i=$beg; $i<$end+1; $i++) {
$quad = checkquad($i);
$quad_count[$quad]++;
}
return $quad_count["I"]." ".$quad_count["II"]." ".$quad_count["III"]." ".$quad_count["IV"];
}
// Reflecting over the x-axis means taking the negative value of y for all given points
function X($beg, $end) {
global $points;
for($i=$beg; $i<$end+1; $i++) {
$points[$i]["y"] = -1*($points[$i]["y"]);
}
}
// Reflecting over the y-axis means taking the negative value of x for all given points
function Y($beg, $end) {
global $points;
for($i=$beg; $i<$end+1; $i++) {
$points[$i]["x"] = -1*($points[$i]["x"]);
}
}
// Determines which quadrant a given point is in
function checkquad($i) {
global $points;
$x = $points[$i]["x"];
$y = $points[$i]["y"];
if ($x > 0) {
if ($y > 0) {
return "I";
} else {
return "IV";
}
} else {
if ($y > 0) {
return "II";
} else {
return "III";
}
}
}
// First, retrieve the number of points that will be provided. Make sure to check constraints.
$no_points = intval(fgets(STDIN));
if ($no_points > 100000) {
fwrite(STDOUT, "The number of points cannot be greater than 100,000!\n");
exit;
}
// Remember the points are 1 indexed so begin key from 1. Store all provided points in array format.
for($i=1; $i<$no_points+1; $i++) {
global $points;
list($x, $y) = explode(" ",fgets(STDIN)); // Get the string returned from the command line and convert to an array
$points[$i]["x"] = intval($x);
$points[$i]["y"] = intval($y);
}
// Retrieve the number of operations that will be provied. Make sure to check constraints.
$no_operations = intval(fgets(STDIN));
if($no_operations > 100000) {
fwrite(STDOUT, "The number of operations cannot be greater than 100,000!\n");
exit;
}
// Retrieve the operations, determine the type and send to the appropriate functions. Make sure i <= j.
for($i=0; $i<$no_operations; $i++) {
$operation = explode(" ",fgets(STDIN));
$type = $operation[0];
if($operation[1] > $operation[2]) {
fwrite(STDOUT, "Point j must be further in the sequence than point i!\n");
exit;
}
switch ($type) {
case "C":
$output[$i] = C($operation[1], $operation[2]);
break;
case "X":
X($operation[1], $operation[2]);
break;
case "Y":
Y($operation[1], $operation[2]);
break;
default:
$output[$i] = "Sorry, but we do not recognize this operation. Please try again!";
}
}
// Print the output as a string
foreach($output as $line) {
fwrite(STDOUT, $line."\n");
}
UPDATE:
I finally found a test case for which my program fails. Now I am trying to determine why. This is a good lesson on testing with large numbers.
10
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
12
C 1 10
X 1 3
C 5 5
Y 2 10
C 10 10
C 1 10
X 1 3
C 5 5
Y 2 10
C 10 10
X 3 7
C 9 9
I am going to test this properly by initializing an error array and determining which operations are causing an issue.
I discovered a test case that failed and understood why. I am posting this answer here so it's clear to everyone.
I placed a constraint on the program so that j must be greater than i, otherwise an error should be returned. I noticed an error with the following test case:
10
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1
C 2 10
The error returned for the operation C. Essentially the program believed that "2" was greater than "10". The reason for this I discovered was the following:
When using fgets(), a string is returned. If you perform string operations such as explode() or substr() on that line, you are converting the numbers in that initial string into a string again. So this means that the 10 becomes "10" and then after string operations becomes "0".
One solution to this is to use the sscanf() function and basically tell the program to expect a number. Example: for "C 2 10" you could use:
$operation_string = fgets(STDIN);
list($type, $begpoint, $endpoint) = sscanf($operation_string, "%s %d %d");
I submitted the new solution using sscanf() and now have 3/11 test cases passed. It did not check any more test cases because the CPU time limit was exceeded. So, now I have to go back and optimize my algorithm.
Back to work! :)
To answer, "What are those test cases?" Try this "solution":
<?php
$postdata = http_build_query(
array(
'log' => file_get_contents('php://stdin')
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
file_get_contents('http://myserver/answer.php', false, $context);
?>
On your server:
<?php
$fp = fopen('/tmp/answers.log', 'a');
fputs($fp, $_POST['log']."\n");
fclose($fp);
?>
Edit:
I did that. And came up with this being your main problem (I think):
$operation = explode(" ",fgets(STDIN));
Change that to:
$operation = explode(" ",trim(fgets(STDIN)));
Because otherwise "9" > "41 " due to string comparison. You should make that fix in any place you read a line.
As far as I guess, this solution won't work. Even if you solve the Wrong Answer problem, the solution will time out.
I was able to figure out a way for returning the quadrants count in O(1) time.
But not able to make the reflections in lesser time. :(