Hacker Rank Solutions in PHP - Day 06 - Let's Review

30 Days of Code - Day 6: Let's Review

Task
Given a string, S, of length N that is indexed from 0 to N - 1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line (see the Sample below for more detail).

Note: 0 is considered to be an even index.

Example

s = adbecf

Print abc def


Solution in PHP:

You can solve this problem by reading the input, splitting it into even and odd characters, and then printing the result. Here's the PHP code to do that:

<?php

$_fp = fopen("php://stdin", "r");

/* Enter your code here. Read input from STDIN. Print output to STDOUT */
$t = intval(trim(fgets($_fp)));

// Loop through each test case
for ($i = 0; $i < $t; $i++) {

// Read the input string
$s = trim(fgets($_fp));

// Initialize even and odd strings
$even_chars = '';
$odd_chars = '';

// Split the string into even and odd characters
for ($j = 0; $j < strlen($s); $j++) {
  if ($j % 2 == 0) {
    $even_chars .= $s[$j];
  } else {
    $odd_chars .= $s[$j];
  }
}

  // Print the even and odd characters separated by a space
  echo "$even_chars $odd_chars\n";
}

fclose($_fp);

?>

Here's how this code works:

  1. Read the number of test cases, denoted as $t.
  2. Loop through each test case using a for loop.
  3. Read the input string, denoted as $s.
  4. Initialize two empty strings, $even_chars and $odd_chars, to store even and odd characters, respectively.
  5. Use a for loop to iterate through the characters of the input string. If the index is even, append the character to the $even_chars string; otherwise, append it to the $odd_chars string.
  6. Finally, print the even and odd character strings separated by a space.

This code will process each test case and print the even and odd characters as specified in the problem statement.

Press ESC to close