RogerBW's Blog

Perl Weekly Challenge 130: An Odd Tree 17 September 2021

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

TASK #1 › Odd Number

You are given an array of positive integers, such that all the numbers appear even number of times except one number.

Write a script to find that integer.

One could count all the occurrences and check them for evenness, but we have hashes and sets and things, so there's no need. Here's the Raku (the Ruby and Rust are functionally identical):

sub on(@tree) {

SetHash is the mutable sort of set.

  my $k=SetHash.new;

Iterate through the list.

  for @tree -> $n {

If there's a key in the set for this number, it's now shown up an even number of times. Delete the key.

    if ($k.{$n}) {
      $k{$n}:delete;

If there was no key, the number has now shown up an odd number of times. Set the key.

    } else {
      $k{$n}++;
    }
  }

The remaining keys are therefore the numbers that have shown up an odd number of times. We're told there's exactly one of these, so return it.

  return ($k.keys)[0];
}

Perl and PostScript don't have sets, so I use a hash/dictionary. (Getting the hash key out is a little more fiddly in PostScript.)

/on {
    dup length dict /k exch def
    {
        dup
        k exch known {
            k exch undef
        } {
            k exch 1 put
        } ifelse
    } forall
    k {
        pop
        /out exch def
        exit
    } forall
    out
} def

Python does have native sets, but they're only partly mutable; you can add keys to them, but not delete them. I dug around a bit looking for documentation on MutableSet, which appears to do what I want, but ended up just using a dict instead.

TASK #2 › Binary Search Tree

You are given a tree.

Write a script to find out if the given tree is Binary Search Tree (BST).

According to wikipedia, the definition of BST:

A binary search tree is a rooted binary tree, whose internal
nodes each store a key (and optionally, an associated value),
and each has two distinguished sub-trees, commonly denoted left
and right. The tree additionally satisfies the binary search
property: the key in each node is greater than or equal to any
key stored in the left sub-tree, and less than or equal to any
key stored in the right sub-tree. The leaves (final nodes) of
the tree contain no key and have no structure to distinguish
them from one another.

Once more my preferred tree representation is helpful. I define limit, a list of tuples for each node in the tree, initially containing two copies of the value of that node. This will be updated to contain the minimum and maximum values of that node plus all child nodes. Here's the Rust:

fn bst(tree: Vec<u64>) -> i8 {
    let mut limit: Vec<(u64,u64)>=vec![];
    for i in &tree {
        limit.push((*i,*i));
    }

Iterate downwards from the last-but-one row (i.e. over all nodes that have children, branch to root).

    for s in (0..=((tree.len()-1)/2)-1).rev() {
        let child=s*2+1;
        for sb in 0..=1 {
            let ac=child+sb;

If we have a left-subtree that contains anything larger than this node's value, bail out reporting failure.

            if sb==0 && tree[s]!=0 && limit[ac].1 > tree[s] {
                return 0;
            }

Similarly a right-subtree with anything smaller.

            if sb==1 && limit[ac].0!=0 && limit[ac].0 < tree[s] {
                return 0;
            }
        }

Now update the limit values for this node: the lower of our own value and the left-child's minimum, the higher of our own value and the right-child's maximum.

        limit[s]=(tree[s],max(tree[s],limit[child+1].1));
        if limit[child].0 > 0 {
            limit[s].0=min(tree[s],limit[child].0);
        }
    }

If there were no failures, we succeeded.

    return 1;
}

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 aviation 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 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 2022 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