Help me in solving BLOBBYVOLLEY problem

My issue

When I solve this problem in PHP I get a “Wrong Answer”. When I do the same in Python, I get it correct.

I’m not able to tell the difference between my code in PHP and Python that causes this issue.

My code

<?php

$t = readline();

for($i = 0; $i < $t; $i++) {
    $n = readline();
    $string = readline();
    
    $alice_score = $bob_score = 0;
    
    for($j = 0; $j < $n - 1; $j++) {
        if($j == 0 and $string[$j] == 'A') {
            $alice_score++;
        } 
        
        if($j < $n - 1 and $string[$j] == 'A' and $string[$j + 1] == 'A') {
            $alice_score++;
        } elseif($j < $n - 1 and $string[$j] == 'B' and $string[$j + 1] == 'B') {
            $bob_score++;
        }
    }
    print($alice_score . ' ' . $bob_score . PHP_EOL);
}
t = int(input())

for _ in range(t):
    n = int(input())
    string = input()
    
    alice_score = bob_score = 0
    for index, value in enumerate(string):
        if index == 0 and value == 'A':
            alice_score += 1
        
        if index < len(string) - 1 and value == 'A' and string[index + 1] == 'A':
            alice_score += 1
        elif index < len(string) - 1 and value == 'B' and string[index + 1] == 'B':
            bob_score += 1
        
    print(alice_score, bob_score)

Problem Link: BLOBBYVOLLEY Problem - CodeChef

So, by changing the PHP index from $n - 1 to $n. I get a warning but I’m able to get a “Correct Answer”. I don’t know why. Wish there was debugging available for PHP. I’m a paying member.

@mr_try_hard
This is my first php code i’ll tried to take things in a simpler way hope u will get it and u are receiving warning because to are going till n in loop and in condition u are checking for j+1 which will exceed the strings size for j=n-1.
This in my code i hope u will get it.

<?php // your code goes here $t = readline(); for($i = 0; $i < $t; $i++) { $n = readline(); $string = readline(); $alice_score = $bob_score = 0; $ch='A'; for($j = 0; $j < $n ; $j++) { if($string[$j] == $ch and $ch=='A') { $alice_score++; } elseif($string[$j] == $ch and $ch=='B') { $bob_score++; } else{ $ch=$string[$j]; } } print($alice_score . ' ' . $bob_score . PHP_EOL); }

https://www.codechef.com/viewsolution/100192115

1 Like