Peter
Peter Campbell Smith

Trees and links

Weekly challenge 129 — 6 September 2021

Week 129: 6 Sep 2021

Task 1

Task — Root distance

You are given a tree and a node of the given tree. Write a script to find out the distance of the given node from the root.

Examples


Example 1:
Tree:
        1
       / \
      2   3
           \
            4
           / \
          5   6
Node: 6
Output: 3 as the distance of given node 6 from the 
   root (1).
Node: 5
Output: 3
Node: 2
Output: 1
Node: 4
Output: 2

Example 2:
Tree:
        1
       / \
      2   3
     /     \
    4       5
     \     /
      6   7
     / \
    8   9
Node: 7
Output: 3 as the distance of given node 6 from the 
   root (1).
Node: 8
Output: 4
Node: 6
Output: 3

Analysis

I did not submit a solution at the time, but have written this later

The first issue is how to represent the tree. I have chosen to input it as a series of $parent, $child arrays, with the notional parent of the root being 0.

It is then just a case of starting with the given node, and counting back to the parent and its parent and so on to the root.

Try it 

Try running the script with any input:



example: 6



example: 0->1, 1->2, 1->3, 3->4, 4->5, 4->6

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2021-09-06
use utf8;     # Week 129 - task 1 - Root distance
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

root_distance([6, 5, 2, 4], [0, 1], [1, 2], [1, 3], [3, 4], [4, 5], [4, 6]);
root_distance([7, 8, 6], [0, 1], [1, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7], [6, 8], [6, 9]);

sub root_distance {
    
    my (@input, $given, $j, $k, %node, $count, $parents, $nodes);
    
    # process input
    @input = @_;
    $nodes = shift @input;
    
    for $k (@input) {
        $node{$k->[1]} = $k->[0];
        $parents .= qq[$k->[0]→$k->[1], ];
    }
    
    # loop back from each supplied node to the root
    for $j (@$nodes) {
        $count = 0;
        $k = $j;
        while (1) {
            last if $node{$k} == 0;
            $k = $node{$k};
            $count ++;
        }
        printf(qq[\nInput:  \$node = %s, \@children = %s\n], $j, substr($parents, 5, -2));
        printf(qq[Output: %s\n], $count);
    }
}

Output


Input:  $node = 6, @children = 1→2, 1→3, 3→4, 4→5, 4→6
Output: 3

Input:  $node = 5, @children = 1→2, 1→3, 3→4, 4→5, 4→6
Output: 3

Input:  $node = 2, @children = 1→2, 1→3, 3→4, 4→5, 4→6
Output: 1

Input:  $node = 4, @children = 1→2, 1→3, 3→4, 4→5, 4→6
Output: 2

Input:  $node = 7, @children = 1→2, 1→3, 2→4, 3→5, 4→6, 
   5→7, 6→8, 6→9
Output: 3

Input:  $node = 8, @children = 1→2, 1→3, 2→4, 3→5, 4→6, 
   5→7, 6→8, 6→9
Output: 4

Input:  $node = 6, @children = 1→2, 1→3, 2→4, 3→5, 4→6, 
   5→7, 6→8, 6→9
Output: 3

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain