Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Identical elements

  • To: mathgroup at smc.vnet.net
  • Subject: [mg88429] Re: Identical elements
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Mon, 5 May 2008 06:13:10 -0400 (EDT)
  • Organization: The Open University, Milton Keynes, UK
  • References: <fvhe2h$3th$1@smc.vnet.net> <481C861E.8020808@gmail.com>

Jean-Marc Gulliet wrote:

> KFUPM wrote:
> 
>> I have a list  and i need to test whether all the elements in the list
>> are identical or no. What is the efficient way to do that? The output
>> should be true if all elements are the same and False otherwise. One
>> line command is preferred if possible.
>>
>> Your help is highly appreciated.
> 
> A possible approach, thought you did precise neither the type of the 
> elements of the list (numeric, symbolic, mixed,...) nor whether the list 
> could contains some other lists, is the following. We test each 
> remaining element of the list against the first element and return False 
> as soon as an element differs from the first one.
> 
> 
> myCheck[lst_List] :=
>  Module[{fe = First@lst, status = True},
>   Scan[If[# != fe, Return[status = False]] &, Rest@lst]; status]
> 
> myCheck[{1, 1, 1, 1}]
> myCheck[{1, 1, -1, 1}]
> myCheck[{{1, 2}, {1, 2}, {1, 2}, {1, 2}}]
> myCheck[{{1, 2}, {1, 2}, {-1, 2}, {1, 2}}]
> 
> True
> 
> False
> 
> True
> 
> False

A simpler and faster solution is to use *Equal* to test equality of the 
list against itself slightly rotated. For instance,

In[1]:= lst = Join[{0.}, ConstantArray[1., {10^7}]];
Timing[lst == RotateLeft@lst]

Out[2]= {0.137857, False}

In[3]:= lst = Join[{1.}, ConstantArray[1., {10^7}]];
Timing[lst == RotateLeft@lst]

Out[4]= {0.191334, True}

Best regards,
-- Jean-Marc


  • Prev by Date: Re: MenuView inside Manipulate
  • Next by Date: Re: Wolfram Workbench user experiences
  • Previous by thread: Re: Identical elements
  • Next by thread: Re: Identical elements