(919) 964-9842
(919) 964-9842

# Hackerrank in PHP: Repeated String

I saw this solution with several for loops and just, way too complicated. I think it just comes down to looping through the last bit because you need to determine how many of the remaining letters are letter As. Anyways, this is my solution in PHP for the Repeated String problem on Hackerrank.

You are given a random string of letters as well as the number of total letters will be assumed to be in the final string made of the random string of letters. So essentially you have a pattern that repeats and ends on a random point in the substring, and you need to determine how many letter As are in that longer pattern.

Let's figure it out!

 12345678910111213141516171819202122 // Complete the repeatedString function below. function repeatedString(\$s, \$n) {     \$repeats = 0;     \$length = strlen(\$s);     \$stringArray = str_split(\$s);     \$numberOfRepeats = floor(\$n / \$length);     \$numberOfRepeats = \$numberOfRepeats * substr_count(\$s, 'a');     for(\$i = 0; \$i < \$n % \$length; \$i++) {         if(\$stringArray[\$i] == 'a') {             \$repeats++;         }     }     \$repeats = \$numberOfRepeats + \$repeats;     return \$repeats; }

First, obviously, we need the length of the substring. Afterwards, we're going to make that substring into an array so we can parse through it later. Now for some math! (Oh no!)

We need to determine how many times the substring can appear based on the total number given. We use floor because we don't want to include any remainder (we will deal with that later). Next, we take the number we found in the last line and multiply that by the number of As found in the substring (now we know how many As are in the repeated pattern, minus the remainder).

We should care about the remainder though, so we need to get the remainder (our favorite friend modulo shows up here), and then go through the substring as many times as there is a remainder. If the letter in the substring is an A, add it to the repeats.

Put those two together and you get the total amount of letters in the new, longer pattern using this substring pattern. Hooray!

Categories: Development