logo CodeStepByStep logo

has_mirror_twice

Language/Type: PHP arrays nested loops traversals

Write a function named has_mirror_twice that accepts two arrays of integers $a1 and $a2 as parameters and returns true if $a1 contains all the elements of $a2 in reverse order at least twice (and false otherwise).

For example, if $a2 stores the elements [1, 2, 3] and $a1 stores the elements [6, 3, 2, 1, 4, 1, 3, 2, 1, 5], your function should return true.

Assume that both arrays passed to your function will have a length of at least 1. This means that the shortest possible mirror will be of length 1, representing a single element (which is its own mirror). A sequence that is a palindrome (the same forwards as backwards) is considered its own mirror and should be included in your computations.

For example, if $a1 is [6, 1, 2, 1, 4, 1, 2, 1, 5] and $a2 is [1, 2, 1], your function should return true. The two occurrences of the mirror might overlap, as shown in the fourth sample call below.

The following table shows some calls to your function and their expected results:

Arrays Returned Value
$a1 = [6, 1, 2, 1, 3, 1, 3, 2, 1, 5];
$a2 = [1, 2];
has_mirror_twice($a1, $a2) returns true
$a3 = [5, 8, 4, 18, 5, 42, 4, 8, 5, 5];
$a4 = [4, 8, 5];
has_mirror_twice($a3, $a4) returns false
$a5 = [6, 3, 42, 18, 12, 5, 3, 42, 3, 42];
$a6 = [42, 3];
has_mirror_twice($a5, $a6) returns true
$a7 = [6, 1, 2, 4, 2, 1, 2, 4, 2, 1, 5];
$a8 = [1, 2, 4, 2, 1];
has_mirror_twice($a7, $a8) returns true
$a9 = [0, 0];
$aa = [0];
has_mirror_twice($a9, $aa) returns true
$ab = [8, 9, 2, 1];
$ac = [5, 7, 1, 2, 9, 8];
has_mirror_twice($ab, $ac) returns false

Do not modify the contents of either array passed to your function as parameters.

Function: Write a PHP function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.