[Solved] Concert - PHP Exam Task

  

2
Topic starter

Mandy was hired to accept the group applications for the upcoming concert. She thought that it would be easy but now she is in trouble. She needs a programmer to make an application that will help her to safe the concert. She needs you.

You will read commands until you receive "start of concert" command.

There are two types of commands:

  • "Add; {bandName}; {member 1}, {member 2}, {member 3}" - applies a band and a list of members to the concert. All members must be unique so don't add duplicates. If you receive the same band twice add only those members that aren't present in the list.
  • "Play; {bandName}; {time}" – the band with the given name plays an amount of time on the stage.  If you receive a band that has already applied in the concert, just increase the band time.

If in both commands the band does not exist, add it.

At the end you have to print the total time and the bands ordered by the time on stage in descending order, then by band name in ascending order.

Also the final input line will be "{bandName}" and you have to print all members for this band in insertion order.

Input / Constraints:

  • The time of the bands – integer in range [0 – 231 - 1] 
  • There will always be at least one member in the group
  • The bands will always have time on stage
  • The final input line will always contain an existing band name
  • Input will always be valid and in the range specified. You don’t need to check it

Output:

Total time: {totalTime}

{firstBandName} -> {firstBandTime}

{secondBandName} -> {secondBandTime}

{thirdBandName} -> {thirdBandTime} …

{bandName}

=> {firstMemberName}

=> {secondMemberName}

=> {thirdMemberName} …

Examples:

concert php exam task

1 Answer
2

Here is my solution:

<?php
 
$input = readline();
$bands = [];
$playTimes = [];
$totalPlayTime = 0;
 
while ($input != "start of concert") {
 
    $args = explode("; ", $input);
 
    $command = $args[0];
    $bandName = $args[1];
 
    if ($command === "Add") {
        $members = explode(", ", $args[2]);//Creating 3rd array
        foreach ($members as $member) {
            $bands[$bandName][$member] = $member;
        }
    } else if ($command === "Play") {
        $currentTime = $args[2];
        $totalPlayTime += $currentTime;
        if (!key_exists($bandName, $playTimes)) {
            $playTimes[$bandName] = $currentTime;
        } else {
            $playTimes[$bandName] += $currentTime;
        }
    }
 
    $input = readline();
}
 
ksort($playTimes);//Sort the bands(keys) in $playTimes in ASCENDING order
arsort($playTimes);//Sort the times(values) in $playTimes in DESCENDING order
 
echo "Total time: " . $totalPlayTime . PHP_EOL;
 
foreach ($playTimes as $band => $time) {
    echo "$band -> $time" . PHP_EOL;
}
 
$bandToPrint = readline();
echo $bandToPrint . PHP_EOL;
 
foreach ($bands[$bandToPrint] as $item) {
    echo "=> " . $item . PHP_EOL;
Share: