[SOLVED] Coding Challenge: Fill in two method bodies to achieve the expected result

Issue

Hi anyone help me to solve this, thanks in advance

class CategoryTree
{
    public function addCategory(string $category, string $parent=null) : void
    {

    }

    public function getChildren(string $parent) : array
    {
        return [];
    }
}

$c = new CategoryTree;
$c->addCategory('A', null);
$c->addCategory('B', 'A');
$c->addCategory('C', 'A');
echo implode(',', $c->getChildren('A'));

Result should be "B,C" or "C,B".

Solution

You could use something like following (not tested):

Store categories with addCategory() in array $categories so you can retrieve them with getChildren().

<?php

class CategoryTree
{
    private $categories = [];

    public function addCategory(string $category, string $parent = null): void
    {
        $this->categories[$parent][] = $category;
    }

    public function getChildren(string $parent): array
    {

        return $this->categories[$parent];
    }
}

$c = new CategoryTree;
$c->addCategory('A', null);
$c->addCategory('B', 'A');
$c->addCategory('C', 'A');
echo implode(',', $c->getChildren('A'));
//Result should be "B,C" or "C,B"

see it in action

Answered By – berend

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *