in reply to All array elements the same?
I think we need to back up for a second. You're asking if using an array (which is a particular sort of data structure), there is a way to check if all elements are the same, without using brute force. The answer would basically be no, as you are using an array. The best you can do is O(N) time (that is the check time is proportional to the list's size), because of the data structure you are using.
For example, davorg's hash example and also a simple loop would exhibit this O(N) time (well actually davorg's is techinically slower, even in big O notation.. but not by much :) ).
Now, if you would like to make this check something you can do in less than O(N) time you will need to use a different data structure, and probably have to pay some cost for that choice.
The first thing that springs to my mind is to use both an array, and a hash. Use the array, but whenever you insert an item also do a: $hash{$item} = 1 . Then you can see how many different items are in the array by: keys %hash.
Unfortunately this particular arrangement pays a large cost to delete items from the array. It also pays a small cost for insertion. However, if you are not deleting items from this array, then this is not a problem! :) (if you are you will pay a O(N) cost per deletion).
There are other arrangements that would not have the cost for deletion, however you will pay the price someplace else. For instance, as was mentioned higher up (lhoward), you could just use a hash. Then you add an item to your array using: $hash{$item}++ . To remove you need slightly longer code, something like: delete $hash{$item} if not --$hash{item};
This scheme pays a slight cost for deletions and inserts, but you get the same keys %hash function to see how many different items are present.
There are other data structures you could use, such as binary trees, but they each have their own unique features. So I as said in the beginning, it all depends on the data structure you use.
Cheers,
Gryn
|
|---|