in reply to RE: Re: All array elements the same?
in thread All array elements the same?

I would argue that this is still brute-force. Since every array element (at least till a mismatch is found) must still be examined. In this case "brute-force" = O(n) (time is proportional to the size of the list). The technique presented above has the performance characteristic that its speed is directly proportional to the list size so IMHO it is still brute-force (or at least performance-equivalent to brute-force).

However, if you were to do something like populate your list elements into a hash as keys at the same time as you added them to a list then determining that they were all the same would be O(1), better than brute-force. However, this would slow-down your "add an element to the list" function.

  • Comment on RE: RE: Re: All array elements the same?

Replies are listed 'Best First'.
RE: RE: RE: Re: All array elements the same?
by eLore (Hermit) on Aug 01, 2000 at 22:37 UTC
    ...proving that brute force is not always a Bad Thing (tm), and that non-brute force methods can be a Bad Thing (tm), depending on your purpose and perspective.

    IMHO: Given all the above descriptions, I would consider the hash method brute force and in this case, the more efficient method.

      I agree, except in your assertion that the hash brute-force method is best.

      Performance wise the hash method will always take O(n) time, even if the first and second elements of the lists are different. An appriach like what I present below can bail-out if it finds a mismatch before examining the entire list. Therefore giving it a better average and best-case performance for lists that don't have homogeneous contents.

      sub is_list_homegeneous{ my @list=@_; my $val=shift @list; foreach(@list){ return 0 if($_ ne $val) } return 1; }
      This is not as short and cool, but does have better algorithmic performance. You could tweak-out the overhead I incurred by copying the list if you wanted the utmost in speed. My technique is probably slightly slower worse-case (a homogeneous list), because it does do slightly more work.
        Should I start stripping RE:'s out of the subject line?

        Anyway, I sit corrected regarding speed. At worst case, your code is ever-so-slightly slower than 0(n).

        Thanks so much, for the discussion. It's proven to be a learning experience! -eLore