in reply to Array lookup

hotshot,
Please do not take this post too seriously

I was trying to think outside the box and in the spirit of TIMTOWTDI

#!/usr/bin/perl -w use strict; my @FirstArray = qw(one two three); my @SecondArray = qw(four seven one eight two nine three seventeen); unless (index ((join "" , sort map {"@FirstArray" =~ /\b($_)\b/;} @Sec +ondArray) , (join "" , sort @FirstArray)) eq -1) { print "Second array contains all the elements in first array\n"; + } else { print "Second array does not contain all the elements in the first + array\n"; }

This is probably easily broken, but I thought it was neat.

Cheers - L~R

Replies are listed 'Best First'.
Re: Re: Array lookup
by CountZero (Bishop) on Apr 13, 2003 at 20:30 UTC

    It will indeed break if you have duplicate elements in one or each (but not both) of the arrays.

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

      CountZero,
      I am not sure I follow. The node said all elements (to include duplicates). If add a duplicate in @FirstArray, then there has to be a duplicate in @SecondArray to be valid (which works). If I add an duplicate element in the second array, the substring will just shift. Can you give me an example of a data set where it will not work? I am not saying there isn't one (I am fairly certain there is), but your logic doesn't match what my tests have shown.

      Cheers - L~R

      Update: As I was going to bed last night, I figured out when this wouldn't work. If the second array has duplicates that are in the middle of the list (not on either edge).

      I was thinking about an element being duplicated a number of times in one of the arrays but not in the other array but I now see that this will depend on how you define "all" in the original question. I understood it as "all duplicates are alike", but if you understand it as "all duplicates are different" then your program works (but all hash-based solutions are broken unless they keep an explicit tally of the number of each individual element).

      My solution suffers from the same "defect" as yours depending on whether or not you increment the index of the second array after you have found a match. If you don't increment the index, then duplicates are not relevant.

      Update: Fixed some typos.

      Thanks L~R for this insight.

      CountZero

      "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Re: Re: Array lookup
by CountZero (Bishop) on Apr 14, 2003 at 20:02 UTC

    It will also not distinguish between 'fortynine' and 'forty' 'nine' if there are no other elements which fall alphabetically between 'forty' and 'nine' (granted, perhaps a somewhat rare condition).

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law