Re: number of switches
- To: mathgroup at smc.vnet.net
- Subject: [mg47512] Re: number of switches
- From: "Carl K. Woll" <carlw at u.washington.edu>
- Date: Thu, 15 Apr 2004 03:39:14 -0400 (EDT)
- Organization: University of Washington
- References: <c5j6vd$qqo$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Hi, A similar problem came up a couple years ago, and probably the fastest solution is switches[lst_]:=Tr[BitXor[lst,RotateLeft[lst]]]-If[lst[[1]]==lst[[-1]],0,1] There are two reasons this is pretty quick. First, rather than splitting up the list into pairs and comparing them (n-1 pairs for a length n list), we create 2 lists of length n and operate on just these 2 lists. Second, we make sure the output of the operation on the two lists is suitable for Tr, because Tr is one of the fastest Mathematica functions. For example, if we want to add up all the elements of a list lst, we could do Plus@@lst, or Tr[lst], and Tr[lst] is much much faster. In the above code I used RotateLeft to create two lists that were offset by one, but this necessitated the If statement to fix up end point conditions. One could instead do something like Tr[BitXor[Drop[lst,1],Drop[lst,-1]]] and avoid the If statement, creating a perhaps more elegant looking piece of code at the cost of a slight amount of speed. Carl Woll "fake" <fake at fake.it> wrote in message news:c5j6vd$qqo$1 at smc.vnet.net... > Consider the lists {1,1,0,1} and {1,1,0,0},{1,0,1,0,1}. > The first sequence (1101) switches 2 times (#2digit~#3digit, > #3digit~#4digit}, the second (1100) 1 time, the third 10101 4 times. > > I have the following problem. > Consider a list of binary digits. Which is the easiest way to count the > number of switches of the list (using Mathematica commands)? >