<?xml version="1.0" encoding="windows-1252"?>
<node id="911973" title="Re: Filling in missing values in an array" created="2011-06-29 09:49:34" updated="2011-06-29 09:49:34">
<type id="11">
note</type>
<author id="611550">
FunkyMonk</author>
<data>
<field name="doctext">
My take (with tests):&lt;P&gt;

&lt;code&gt;
#!/usr/local/bin/perl

use strict;
use warnings FATAL =&gt; 'all';

sub fill_in_the_blanks {
    my @arr = @_;

    die "No values found" if @arr &amp;&amp; 0 == grep $_ ne '_', @arr;

    for (my $left = 0; $left &lt; @arr; $left++) {
        next unless $arr[$left] eq '_';

        my $right = $left;
        $right++ while $right &lt; $#arr &amp;&amp; $arr[$right+1] eq '_';

        if ($left == 0) { # NULLs at the left
            $arr[$_] = $arr[$right+1] for $left..$right;
        }
        elsif ($right == $#arr) { # NULLs at the right
            $arr[$_] = $arr[$left-1] for $left..$right;
        }
        elsif ($left == $right) { # single
            $arr[$left] = ($arr[$left-1] + $arr[$left+1]) / 2;
        }
        else {
            $arr[$left ] = $arr[$left -1];
            $arr[$right] = $arr[$right+1];
        }
    }

    return @arr;
}

use Test::Most;

is_deeply [fill_in_the_blanks(qw&lt; &gt;)], [qw&lt; &gt;], "( )";
is_deeply [fill_in_the_blanks(qw&lt;1&gt;)], [qw&lt;1&gt;], "(1)";

throws_ok { fill_in_the_blanks(qw&lt;  _  &gt;) } qr{No values found}, "(  _  )";
throws_ok { fill_in_the_blanks(qw&lt; _ _ &gt;) } qr{No values found}, "( _ _ )";
throws_ok { fill_in_the_blanks(qw&lt;_ _ _&gt;) } qr{No values found}, "(_ _ _)";

is_deeply [fill_in_the_blanks(qw&lt;1 _ 1&gt;)], [qw&lt;1 1 1&gt;], "(1 _ 1)";
is_deeply [fill_in_the_blanks(qw&lt;1 _ 3&gt;)], [qw&lt;1 2 3&gt;], "(1 _ 3)";

is_deeply [fill_in_the_blanks(qw&lt;1  _ _  3&gt;)], [qw&lt;1 1   3 3&gt;], "(1  _ _  3)";
is_deeply [fill_in_the_blanks(qw&lt;1 _ _ _ 3&gt;)], [qw&lt;1 1 2 3 3&gt;], "(1 _ _ _ 3)";

is_deeply [fill_in_the_blanks(qw&lt;1   _&gt;)], [qw&lt;1   1&gt;], "(1   _)";
is_deeply [fill_in_the_blanks(qw&lt;1 _ _&gt;)], [qw&lt;1 1 1&gt;], "(1 _ _)";
is_deeply [fill_in_the_blanks(qw&lt;_   1&gt;)], [qw&lt;1   1&gt;], "(_   1)";
is_deeply [fill_in_the_blanks(qw&lt;_ _ 1&gt;)], [qw&lt;1 1 1&gt;], "(_ _ 1)";

is_deeply [fill_in_the_blanks(qw&lt;4 _ _ _ 5&gt;)], [qw&lt;4 4 4.5 5 5&gt;], "dhuang90";

done_testing;
&lt;/code&gt;&lt;p&gt;

The results...

&lt;code&gt;
ok 1 - ( )
ok 2 - (1)
ok 3 - (  _  )
ok 4 - ( _ _ )
ok 5 - (_ _ _)
ok 6 - (1 _ 1)
ok 7 - (1 _ 3)
ok 8 - (1  _ _  3)
ok 9 - (1 _ _ _ 3)
ok 10 - (1   _)
ok 11 - (1 _ _)
ok 12 - (_   1)
ok 13 - (_ _ 1)
ok 14 - dhuang90
1..14
&lt;/code&gt;&lt;p&gt;

An interesting little problem. It has lots of edge cases and so makes a nice [http://codekata.pragprog.com/codekata|code kata]. Thank for posting it. </field>
<field name="root_node">
911838</field>
<field name="parent_node">
911838</field>
</data>
</node>
