Home > Software engineering >  Trying to solve Split Strings 6kyu challenge on codewars with PHP
Trying to solve Split Strings 6kyu challenge on codewars with PHP

Time:01-15

I have been really stuck on this codewars challenge: https://www.codewars.com/kata/515de9ae9dcfc28eb6000001/train/php. I feel like I am very close, but I am not sure what I am doing wrong at this point. Here is my code so far:

function solution($str) {
  $newStr = "";
  
  strlen($str) % 2 === 0 ? $newStr = $str : $newStr = $str.'_';
  $arr = str_split($newStr, 2);
  $finalArr = [];
  for ($i = 0; $i < count($arr); $i  ) {
    if ($i % 2 !== 0) {
      array_push($finalArr, $arr[$i-1], $arr[$i], $arr[$i 1]);
    }
  }
  return $finalArr;
}

And here is the error that I am getting in the output:

Failed asserting that two arrays are equal.
Expected: Array (
    0 => 'ab'
    1 => 'cd'
    2 => 'ef'
    3 => 'g_'
)
Actual  : Array (
    0 => 'ab'
    1 => 'cd'
    2 => 'ef'
    3 => 'ef'
    4 => 'g_'
    5 => null
)

UPDATE: so I made another edit that got me a little bit closer to solving this. I also added a link to the challenge itself and I apologize for not doing that initially. Here is the code:

function solution($str) {
  $newStr = "";
  
  strlen($str) % 2 === 0 ? $newStr = $str : $newStr = $str.'_';
  $arr = str_split($newStr, 2);
  $finalArr = [];
  for ($i = 0; $i <= count($arr); $i  ) {
    if ($i % 2 !== 0) {
      array_push($finalArr, $arr[$i-1], $arr[$i]);
    }
  }
  return $finalArr;
}

And here is the output I am getting now:

Failed asserting that two arrays are equal.
Expected: Array (
    0 => 'ab'
    1 => 'cd'
    2 => 'ef'
)
Actual  : Array (
    0 => 'ab'
    1 => 'cd'
    2 => 'ef'
    3 => null
)

CodePudding user response:

You might update your function to:

function solution($str) {
    return $str === "" ? [] : str_split(
        strlen($str) % 2 === 0 ? $str : $str . '_', 2
    );
}

The function will return an empty array if there is an empty string.

Else it will check if the string has an even amount of characters.

If it is even, then return the $str. If it is odd, append _ to make it even for str_split to return 2 chars for all the values.

  •  Tags:  
  • Related