By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Train - PHP Array Task

+6 votes
  • On the first line you will be given a list of wagons (integers). Each integer represents the number of passengers that are currently in each wagon.
  • On the next line you will get the max capacity of each wagon (single integer).

Until you receive "end" you will be given two types of input:

  • Add {passengers} – add a wagon to the end with the given number of passengers.
  • {passengers} -  find an existing wagon to fit all the passengers (starting from the first wagon) At the end print the final state of the train (all the wagons separated by a space)


train php array task

asked in PHP category by user john7
edited by user golearnweb

1 Answer

+5 votes

Here is my solution:


$train = explode(" ", readline());
$capacity = readline();

$input = readline();

while ($input != "end") {
    $args = explode(" ", $input);
    $command = $args[0];

    if ($command == "Add") {
        $wagon = $args[1];
        array_push($train, $wagon);
    } else {
        for ($i = 0; $i < count($train); $i++) {
            if ($command + $train[$i] <= $capacity) {
                $train[$i] += $command;
                break;//the break; is needed: otherwise it will continue adding to the other wagons of the train as well

    $input = readline();

echo implode(" ", $train);
answered by user andrew