Aditya Singh
Aditya Singh

Reputation: 2453

Same algorithm runs differently in C and PHP

I was practicing a problem on CodeChef.com.

https://www.codechef.com/problems/CHOPRT --> Link to the question I was solving.

I successfully solved the question using C.

My C code:

#include <stdio.h>

int main() {

    int t;
    int num1;
    int num2;


    scanf("%d", &t);

    while(t--) {

        scanf("%d %d", &num1, &num2);
        if(num1 > num2)
            printf(">");
        else if(num1 < num2)
            printf("<");
        else
            printf("=");
        printf("\n");           
    }

    return 0;
}  

But I am not able to solve it using PHP:

My PHP code:

<?php

    $t = intval(fgets(STDIN));

    while($t--) {

        $line = split(" ", trim(fgets(STDIN)));
        $num1 = intval($line[0]);
        $num2 = intval($line[1]);

        if($num1 < $num2)
            print("<");
        else if($num1 > $num2)
            print(">");
        else
            print("="); 
        print("\n");        
    }
?>  

Though both the programs run perfectly on my MacBook Pro, the PHP code is not run on codechef.com and gives a WA(Wrong Answer). C code is run perfectly though and that to within 0.00 seconds.

Please, enlighten me with the difference between the two respective codes, which I personally believe, should be working the same, and also produce the same output.

Upvotes: 2

Views: 70

Answers (1)

Rahul Jha
Rahul Jha

Reputation: 1141

Often i hear that some testcases are erroneous.I have a corner case for you which would give perfect result for your C code but not for your PHP

Do this :

1
10  10 

Notice there is more than one space between the two digits.

I tested it here. Instead of the expected output which is:

=

your Output is:

>

Though C would pass this test case as scanf searches for the next integer number you type, PHP would fail since there is more than one space. To make it work in PHP i did suggest you to code in such a way that the spaces between the two numbers dont affect your expected output.

That's the only way i believe your PHP Code won't work.If this indeed was the issue it's not your fault!

Upvotes: 3

Related Questions