Marcos Rezende

Posted on

# Repeated String Code Challenge Solved

Lilah has a string, s, of lowercase English letters that she repeated infinitely many times.

Given an integer 'n' find and print the number of letters 'a's in the first letters of Lilah's infinite string.

For example, if the string s = 'abcac' and n = 10, the substring we consider is abcacabcac, the first 10 characters of her infinite string. There are 4 occurrences of 'a' in the substring.

Function Description
Complete the repeatedString function in the editor below. It should return an integer representing the number of occurrences of 'a' in the prefix of length in the infinitely repeating string.

repeatedString has the following parameter(s):

• s: a string to repeat
• n: the number of characters to consider

Input Format
The first line contains a single string, s. The second line contains an integer, n.

Output Format
Print a single integer denoting the number of the letter a's in the first letters of the infinite string created by repeating infinitely many times.

Sample input
aba
10

Sample output
7

Explanation
The first letters of the infinite string are 'abaabaabaa'. Because there are a's, we print on a new line.

## Solution

``````

function repeatedString(\$s, \$n) {
// check the number of occurrences of letter 'a' on given string \$s
\$a_occurrences_in_s = substr_count(\$s, 'a');

// check how many occurrences of string \$s belongs to an repeated string \$s of length of \$n
\$s_occurrences_qty = floor(\$n / strlen(\$s));

// get the \$s occurrences left
\$s_occurrences_left = \$n - (\$s_occurrences_qty * strlen(\$s));

// left string
\$s_left = substr(\$s, 0, \$s_occurrences_left);

// 'a' occurrences in left string
\$a_occurrences_in_s_left = substr_count(\$s_left, 'a');

// occurrencies of 'a' on the entire repeated string of \$s with a length of \$n
return (\$a_occurrences_in_s * \$s_occurrences_qty) + \$a_occurrences_in_s_left;
}
``````