Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Challenge: Hidden Message

by Unanimous Monk (Sexton)
on May 11, 2006 at 01:50 UTC ( #548598=note: print w/replies, xml ) Need Help??

in reply to Challenge: Hidden Message

Well, here's my first crack at it.

use strict; use Data::Dumper; my %result; { ### Populate initial tree my @prev; my $temp=<DATA>; chomp $temp; foreach my $char (split '', $temp) { foreach my $pchar (@prev) { $result{$pchar}{$char}{valid} = 1; }; push @prev, $char; }; }; { ### Prune invalid data while (<DATA>) { chomp; my @invalid; foreach my $char (split '') { foreach my $ichar (@invalid) { $result{$char}{$ichar}{valid} = 0; }; push @invalid, $char; }; }; } my $maxdepthchar; { ### Determine depth of each tree my $maxdepth; foreach my $char (keys %result) { getdepth(\%result, $char); if ($result{$char}{depth} > $maxdepth) { $maxdepth = $result{$char +}{depth}; $maxdepthchar = $char }; }; } { ### Output longest string while ($maxdepthchar ne '') { print substr($maxdepthchar,0,1); $maxdepthchar = $result{$maxdepthchar}{maxdepthchar}; }; } sub getdepth{ my ($ref, $char) = @_; my %result = %{$ref}; my $maxdepth; my $maxdepthchar; if ($result{$char}{depth} eq undef) { foreach my $key (keys %{$result{$char}}) { if ($result{$char}{$key}{valid}) { my $depth = getdepth(\%result, $key); if ($depth > $maxdepth) { $maxdepth = $depth; $maxdepthchar = + $key } }; }; $result{$char}{depth} = $maxdepth+1; $result{$char}{maxdepthchar} = $maxdepthchar; return $result{$char}{depth}; } else { return $result{$char}{depth}; }; }; __DATA__ CPD6Z98SB2KQNWV0F7Y1IX4GLRA5MTOJHE3U CXZOL6SUI2WTJ30HF519YPGBRNAK48MQVD7E T8COSQU6I2FJN40DKL157WVGPYXARZ3MBHE9 KNCWVZDSR5420LP91FIQGB7Y3A6J8MOUXTEH XF9C4PSDY62TWJ0QBN17IKG3OH8ALVRM5UEZ D9QCHUSN7TW2YZL0O831FGXIR6JA4P5MVBKE ZC7ISQUPK6N20OLV4T31G9FRXBAWM5YJHED8 Z3C7SJVODL25TRQ01HPWGNKXB4UA68YMI9EF BC9OXDHS2FI5Z6U0TYL1VPGQK7ANR38MEWJ4 K4TCQBHS2ZV7FXU0P8R1YGDON3A6JILM9EW5

and a few modifications to allow for multiple longest strings, and repeated chars (although, the output still only outputs one of the longest string, but the hash contains the info for each longest string).

It ain't pritty, but it works (I think?).

Update:Oops! Fixed general soultion. Needed to trim roots as well as branches. Thanks LR.

Replies are listed 'Best First'.
Re^2: Challenge: Hidden Message
by Limbic~Region (Chancellor) on May 11, 2006 at 17:43 UTC
    Unanimous Monk,
    I am still working on my general purpose solution, but yours does not appear to work with the following:

    Cheers - L~R

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://548598]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2021-02-28 15:35 GMT
Find Nodes?
    Voting Booth?

    No recent polls found