Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Filling in missing values in an array

by zek152 (Pilgrim)
on Jun 28, 2011 at 19:43 UTC ( [id://911845]=note: print w/replies, xml ) Need Help??


in reply to Filling in missing values in an array

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2024-04-18 06:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found