tree+graph+comments - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of tree+graph+comments.php

  1. <?php
  2.  
  3. $tree = [
  4.         1 => ['value' => 1, 'children' => [2, 3]],
  5.         2 => ['value' => 2, 'children' => []],
  6.         3 => ['value' => 4, 'children' => [4,6]],
  7.         4 => ['value' => 8, 'children' => [5]],
  8.         5 => ['value' => 16, 'children' => [2]],
  9.         6 => ['value' => 32, 'children' => [6]],
  10.         7 => ['value' => 64, 'children' => [8]],
  11.         8 => ['value' => 100, 'children' => [7]],
  12. ];
  13.  
  14. echo "Graph #1: ", sumGraph($tree, 1), "\n";
  15. echo "Graph #3: ", sumGraph($tree, 3), "\n";
  16. echo "Graph #7: ", sumGraph($tree, 7), "\n";
  17.  
  18. // Another way to do it is to modify the existing tree. Mark element "visited" somehow
  19. // and exit recursion if it is marked. For example, assign value to null. Might be better 
  20. // if we want to minimize memory usage. If it is ok to modify it in the first place.
  21. function sumGraph(array $arr, int $id, array &$visited = []) {
  22.     // This check can be moved to the foreach itself.
  23.     // runs approx 10% faster on my machine, but increases nesting 
  24.     // which generally harms readability
  25.     if (isset($visited[$id])) {
  26.         return 0;
  27.     }
  28.     
  29.         $sum = $arr[$id]['value'];
  30.         $visited[$id] = 1;
  31.        
  32.         foreach ($arr[$id]['children'] as $childId) {
  33.             $sum += sumGraph($arr, $childId, $visited);
  34.         }
  35.        
  36.         return $sum;
  37. }
  38.  
  39. function sumTree(array $arr, int $id) {
  40.         $sum = $arr[$id]['value'];
  41.         foreach ($arr[$id]['children'] as $childId) {
  42.         $sum += sumTree($arr, $childId);
  43.         }
  44.        
  45.         return $sum;
  46. }
  47.  
  48.  
File Description
  • tree+graph+comments
  • PHP Code
  • 03 Oct-2023
  • 1.36 Kb
You can Share it: