1
<?php
class FileOwners
{
    public static function groupByOwners($files)
    {
        return NULL;
    }
}

$files = array
(
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
);

var_dump(FileOwners::groupByOwners($files));

Implement a groupByOwners function :

  • Accepts an associative array containing the file owner name for each file name.

  • Returns an associative array containing an array of file names for each owner name, in any order.

    For example

Given the input:

["Input.txt" => "Randy", "Code.py" => "Stan", "Output.txt" => "Randy"]

groupByOwners returns:

["Randy" => ["Input.txt", "Output.txt"], "Stan" => ["Code.py"]]
Neil
  • 14,063
  • 3
  • 30
  • 51
Suraneti
  • 81
  • 2
  • 10

3 Answers3

5
<?php
class FileOwners
{
    public static function groupByOwners($files)
    {
        $result=array();
        foreach($files as $key=>$value)
        {
            $result[$value][]=$key;
        }
        return $result;
    }
}

$files = array
(
    "Input.txt" => "Randy",
    "Code.py" => "Stan",
    "Output.txt" => "Randy"
);
print_r(FileOwners::groupByOwners($files));

Output:

Array
(
    [Randy] => Array
        (
            [0] => Input.txt
            [1] => Output.txt
        )

    [Stan] => Array
        (
            [0] => Code.py
        )

)
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
  • print_r() WILL NOT RETURN THE INTENDED RESULTS for the test. Printr() is human readable which is why the test uses var_dump https://stackoverflow.com/questions/3406171/php-var-dump-vs-print-r – INSITE MOBILE Jul 12 '22 at 00:00
1

Here is the one witch gonna work for sure:

 function groupByOwners(array $files) : array
 {
$result =array();
foreach($files as $key =>$elem){
  $result[$elem][]=$key;
 }
return $result;
    }
$files = array
(
"Input.txt" => "Randy",
"Code.py" => "Stan",
"Output.txt" => "Randy"
 );
  var_dump(groupByOwners($files));
albatros
  • 11
  • 3
  • THIS IS THE CORRECT ANSWER WITH THE CORRECT RETURN: array(2) { ["Randy"]=> array(2) { [0]=> string(9) "Input.txt" [1]=> string(10) "Output.txt" } ["Stan"]=> array(1) { [0]=> string(7) "Code.py" } } – INSITE MOBILE Jul 11 '22 at 23:57
-1
$files = array("Input.txt" => "Randy", "Code.py" => "Stan","Output.txt" => "Randy");
$narr = array_fill_keys(array_keys(array_flip($files)), []);

foreach($files as $key => $value) array_push($narr[$value], $key);
return $narr;
Syscall
  • 19,327
  • 10
  • 37
  • 52
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 23 '22 at 02:17
  • The result is the same and I like the method but it is incorrect because it does not use a groupByOwners function. How will another developer find this class? – INSITE MOBILE Jul 12 '22 at 00:10