Here is a way to do it. I believe that I caught every possible type of way for NULL to appear except for an array with all NULLs. This will break my code.
I find a null and use the index before it as the left index and then find the next non null index and use that as the right index. Then I fill in the blanks using your logic. I have some logic in there to recognize it starting or ending with a chain of NULLs.
Hope this helps.
@array = ("NULL","NULL",1,3,70,"NULL","NULL","NULL","NULL",
"NULL",50,1,"NULL",4,"NULL","NULL",5,"NULL","NULL","NULL");
$max_element = @array - 1;
for $i (0 .. @array-1)
{
if($array[$i] eq "NULL")
{
$left_i = $i-1;
$right_i = $i;
#find the index of the next non null (but the array might end on a
+ null)
while($array[$right_i] eq "NULL" && $right_i<=$max_element)
{
$right_i++;
}
if($right_i > $max_element)
{
#if the array ends with nulls then just replace them all w/ $a
+rray[$left_i]
for $null_index ($i .. $max_element)
{
$array[$null_index] = $array[$left_i];
}
$i = $max_element;
}
elsif($left_i < 0)
{
#if the array starts with nulls then just replace all with $ar
+ray[$right_i]
for $null_index ($i .. $right_i - 1)
{
$array[$null_index] = $array[$right_i];
}
$i=$right_i;
}
else
{
for $null_index ($i .. $right_i-1)
{
if($null_index - $left_i == $right_i - $null_index)
{
$array[$null_index] = ($array[$left_i] + $array[$right_i])
+/2;
}
if($null_index - $left_i > $right_i - $null_index)
{
$array[$null_index] = $array[$right_i];
}
if($null_index - $left_i < $right_i - $null_index)
{
$array[$null_index] = $array[$left_i];
}
}
$i=$right_i;
}
}
}
for $ar (@array)
{
print $ar . " ";
}
print "\n";
#OUTPUT
#1 1 1 3 70 70 70 60 50 50 50 1 2.5 4 4 5 5 5 5 5