Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: replacing order element in array

by kwaping (Priest)
on Apr 18, 2007 at 16:15 UTC ( #610792=note: print w/replies, xml ) Need Help??

in reply to replacing order element in array

Here's my shot at it:
#!/usr/bin/perl use strict; use warnings; # set up srand; my @one = (1,2,3,4,5,6); my @two = (2,4,6,8,9,12); # the value that needs replacing my $bad = 4; # figure out where that value is in list one ### my $index = index(join('',@one),$bad); # <- bad code my $index = 0; my $found = 0; foreach my $item (@one) { if ($item == $bad) { $found++; last; } $index++; } die "The value '$bad' was not found in the list\n" unless ($found); # find elements of list two that aren't already in list one my $re = join('|',@one); my @candidates = grep(! /^(?:$re)$/, @two); # replace unwanted list one value with random selection from list two $one[$index] = $candidates[rand @candidates]; use Data::Dumper::Simple; print Dumper(@one); __END__ @one = ( 1, 2, 3, 8, 5, 6 );

Update: I realize that the line that generates $index is a potential point of failure via false positives (matching "10" when $bad = 1, for example). However, I've discussed this with the OP and he says it's not an issue, due to the fact that the values are all 4-digit numbers.

Update 2: The above statement no longer applies post-patch.

It's all fine and dandy until someone has to look at the code.

Replies are listed 'Best First'.
Re^2: replacing order element in array
by Not_a_Number (Parson) on Apr 18, 2007 at 18:41 UTC
    ...he says it's not an issue, due to the fact that the values are all 4-digit numbers.

    But it is. Try it with these values to see:

    my @one = ( 1234, 5678, 9012 ); my @two = ( 1234, 7891, 9001, 9002 ); my $bad = 5678;


    Use of uninitialized value in join or string at line 21. 1234 5678 9012 9002

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://610792]
[Corion]: Discipulus: I think Module::Corelist ( or corelist ) can tell you that
[Corion]: Meh - Module::CoreList
[choroba]: Just use List::Util 1.29
[choroba]: Be kind to people using old Perl with newer version of the module
[Corion]: But why not simply specify 'List::Util' => 1.29 in your prerequisites? People might install a more recent version of the module into their Perl
[Corion]: (what choroba said)
[Discipulus]: ah! simpler and cleaner
[Discipulus]: thanks! use List::Util 1.29 qw(pairmap ... just works!

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (12)
As of 2017-05-25 09:23 GMT
Find Nodes?
    Voting Booth?