RogerBW's Blog

Perl Weekly Challenge 129: Eats Roots and Lists 10 September 2021

I’ve been doing the Weekly Challenges. The latest involved more binary trees and linked lists. (Note that this is open until 12 September 2021.)

TASK #1 › 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.

Well, once more, this is made vastly easier by using a simple tree representation rather than some complex cross-linked structure. (If there were a bog-standard way of representing a binary tree I'd write code to convert between that format and this.) Here's a test case in Rust:

#[test]
fn test_ex1a() {
    assert_eq!(rd(vec![
               1,
           2,      3,
         0,  0,  0,  4,
        0,0,0,0,0,0,5,6
    ],6),3);
}

and here's how to do the work:

fn rd(tree: Vec<u64>,content: u64) -> i64 {

Initial variable setup. First node is at depth 0; the number of nodes at this level is 1.

    let mut depth: i64=0;
    let mut dl: u64=1;
    let mut db: u64=1;

Run down each member of the tree. If we find what we want, return the answer.

    for i in 0..tree.len() {
        if tree[i]==content {
            return depth;
        }

We didn't find it. Update the row length counter.

        dl -= 1;

If we've got to the end of the row:

  • the next row will be twice as long as this one
  • reset the row length counter
  • the depth will be one greater than before

(This whole bit could also have been done by returning int(log2(i+1)) above, or successive right-shifts for the same effect without floating point.)

        if dl==0 {
            db *= 2;
            dl = db;
            depth += 1;
        }
    }
    return -1;
}

The same approach works in PostScript, though returning directly doesn't work as one might wish, so I introduce an extra variable for the case where the node value is not found. (The problem doesn't specify behaviour in that case, or if node values are not unique, which there's no need for them to be.)

/rd {
    /content exch def
    /tree exch def
    /ret -1 def
    /depth 0 def
    /dl 1 def
    /db 1 def
    tree {
        content eq { /ret depth def exit } if
        /dl dl 1 sub def
        dl 0 eq {
            /db db 2 mul def
            /dl db def
            /depth depth 1 add def
        } if
    } forall
    ret
} def

TASK #2 › Add Linked Lists

You are given two linked list having single digit positive numbers.

Write a script to add the two linked list and create a new linked [list] representing the sum of the two linked list numbers. The two linked lists may or may not have the same number of elements.

OK, perhaps I was feeling a bit peevish, but I really don't have any use for singly-linked lists like this; I'm not writing that kind of low-level code, and the data structures I already have in various languages are entirely suitable for the things I do. (Nothing here requires insertion anywhere other than at the end of the list, or deletion at all. Even if they did, Perl's native lists are reasonably good at that, enough that a custom data structure may mean more overhead than letting the language do the work until the data sets get fairly massive, and the double-ended queues in Python and especially Rust are great; and if ordering isn't needed much or at all, hashes are just fine too.) So I only answered this one in Perl, and it's a bit of a cheat.

Basic initialisation. My object substrate is itself a Perl list. But I'm not cheating yet: each node has a pointer to the next node, which I use.

package Local::LinkedList;

sub new {
  my $class=shift;
  my $self=[];
  bless $self,$class;
}

Return the index in the substrate of the last entry in the list (because that's the one I'm going to update when I append). (Or -1 if there aren't any entries.)

sub lastused {
  my $self=shift;
  if ($#{$self}==-1) {
    return -1;
  }
  my $i=0;
  while ($self->[$i]{next} != -1) {
    $i=$self->[$i]{next};
  }
  return $i;
}

Append a value (or, if given an arrayref, several values in order). Find the last-used node; push on a new node with an end-of-list marker; update the last-used node to point to the new node. (Yes, index 0 will always get a "next" pointer of 1, etc.; the question didn't require me to justify using a linked list, just to implement it.)

sub append {
  my $self=shift;
  my $elem=shift;
  if (ref $elem eq 'ARRAY') {
    map {$self->append($_)} @{$elem};
  } else {
    my $i=$self->lastused;
    push @{$self},{value => $elem,next => -1};
    if ($i > -1) {
      $self->[$i]{next}=$#{$self};
    }
  }
}

Dump the content of the list as an arrayref. (You can tell where this is going, right?)

sub as_arrayref {
  my $self=shift;
  my @a;
  my $i=0;
  while (defined $self->[$i]) {
    push @a,$self->[$i]{value};
    $i=$self->[$i]{next};
    if ($i == -1) {
      last;
    }
  }
  return \@a;
}

And finally, the piecewise addition (expanded somewhat from the definition in the question by the examples). I would obviously not choose a singly-linked list for this case which involves walking the list in reverse – and therefore I don't!

sub piecewise_add {
  my $self=shift;
  my $other=shift;

Grab the data from each list, and reverse them into proper Perl lists.

  my @a=reverse @{$self->as_arrayref};
  my @b=reverse @{$other->as_arrayref};

Even up the lengths. (Could get clever with references, but why?)

  while (scalar @a < scalar @b) {
    push @a,0;
  }
  while (scalar @b < scalar @a) {
    push @b,0;
  }

Do a piecewise addition with carry, into a new list.

  my @c;
  my $carry=0;
  foreach my $i (0..$#a) {
    my $d=$a[$i]+$b[$i]+$carry;
    push @c,$d % 10;
    $carry=int($d/10);
  }
  if ($carry) {
    push @c,1;
  }

And finally reverse the new list into the required linked-list structure.

  my $out=Local::LinkedList->new;
  $out->append([reverse @c]);
  return $out;
}

Full code on github.

Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.

Search
Archive
Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 3d printing action advent of code aeronautics aikakirja anecdote animation anime army astronomy audio audio tech base commerce battletech beer boardgaming book of the week bookmonth chain of command children chris chronicle church of no redeeming virtues cold war comedy computing contemporary cornish smuggler cosmic encounter coup covid-19 crime crystal cthulhu eternal cycling dead of winter doctor who documentary drama driving drone ecchi economics en garde espionage essen 2015 essen 2016 essen 2017 essen 2018 essen 2019 essen 2022 essen 2023 existential risk falklands war fandom fanfic fantasy feminism film firefly first world war flash point flight simulation food garmin drive gazebo genesys geocaching geodata gin gkp gurps gurps 101 gus harpoon historical history horror hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2021 hugo 2022 hugo 2023 hugo 2024 hugo-nebula reread in brief avoid instrumented life javascript julian simpson julie enfield kickstarter kotlin learn to play leaving earth linux liquor lovecraftiana lua mecha men with beards mpd museum music mystery naval noir non-fiction one for the brow opera parody paul temple perl perl weekly challenge photography podcast politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant reviews romance rpg a day rpgs ruby rust scala science fiction scythe second world war security shipwreck simutrans smartphone south atlantic war squaddies stationery steampunk stuarts suburbia superheroes suspense television the resistance the weekly challenge thirsty meeples thriller tin soldier torg toys trailers travel type 26 type 31 type 45 vietnam war war wargaming weather wives and sweethearts writing about writing x-wing young adult
Special All book reviews, All film reviews
Produced by aikakirja v0.1