in reply to merging two arrays with OR operation

use bitwise OR ( | ) or logical OR ( || ) on each element. It doesn't have to be a long program, if you use map or other such perl idioms

# [id://1230926] use warnings; use strict; my @array1 = (0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1); my @array2 = (0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1); my @arrayResult = map { $array1[$_] | $array2[$_] } 0 .. $#array1; print "arrayResult = (@arrayResult)\n"; use Test::More tests => 1; is_deeply( \@arrayResult , [0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1] )

Replies are listed 'Best First'.
Re^2: merging two arrays with OR operation
by Anonymous Monk on Mar 05, 2019 at 21:16 UTC

    Much nicer than mine!! (see below, I forgot to put mine)

    use Data::Dumper; my @array1 = (0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1); my @array2 = (0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1); my @result; if (@array1 != @array2) { $equals = 0; } else { $equals = 1; foreach (my $i = 0; $i < @array1; $i++) { if (($array1[$i] eq 0)&&($array2[$i] eq 0)) { push (@result, 0); } else{ push (@result, 1); } } } print Dumper \@result;

      There is nothing wrong with your code except that the if (($array1[$i] eq 0)&&($array2[$i] eq 0)) {... code could be replaced by:

      $result[$i] = $array1[$i] | $array2[$i];

      and your for loop is better written:

      for my $i (0 .. $#array1)

      Note that for and foreach are identical aside from the spelling so personally I never use foreach just because that way I type less.

      Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
Re^2: merging two arrays with OR operation
by stevieb (Canon) on Mar 06, 2019 at 01:20 UTC

    I should add a "bit_cmp" to Bit::Manip that takes lists, and a bitwise op. Thoughts?

      I think having a conversion from an array of bits into your bitwise integer (and vice versa) would be a good idea.

      I'm not sure that bit_cmp(), which sounds like "bit compare" in my mental reading, quite fits with the OR or AND operations. It would make sense to me for the XOR (which is bits-not-equal) and XNOR (which is bits-are-equal, the same as ~($a ^ $b)), since those do a bitwise "compare". I guess the argument could be made that AND and OR are bitwise compares as well, but I don't think of them that way.) Since you're working with integers internally anyway, it seems easy enough just to use | & ^ ~(^) on the vars, rather than having a wrapper function to do the same thing. Then again, it wouldn't hurt...

      As you can tell, I'm ambivalent whether bit_cmp() should be added. But I definitely vote to implement a conversion to/from a bit-array.