|
[Date Index]
[Thread Index]
[Author Index]
RE: Pattern Matching in Lists
- To: mathgroup at smc.vnet.net
- Subject: [mg35560] RE: [mg35547] Pattern Matching in Lists
- From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
- Date: Fri, 19 Jul 2002 06:08:03 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
> -----Original Message-----
> From: Anthony Mendes [mailto:amendes at zeno.ucsd.edu]
To: mathgroup at smc.vnet.net
> Sent: Thursday, July 18, 2002 9:07 AM
> Subject: [mg35560] [mg35547] Pattern Matching in Lists
>
>
> Hello,
>
> Suppose w={1,1,1,0,0,1,0,1,0,0,1,0,0}.
>
> How can I count the number of occurrences of a 1 in w immediately
> followed by a 0 in w?
>
> I have tried every incarnation of Count[] I can think of; for example,
>
> Count[w,{___,1,0,___}]
>
> does not seem to work. In general, how can I count the number of
> occurrences of a 1 followed by a 0 in a list of 1's and 0's?
> Thank you!
>
>
> --
> Tony
> _____________________
> amendes at math.ucsd.edu
>
>
Tony,
there are certainly many solutions (and many will appear here in this
newsgroup). Just to pass some ideas
Count[w /. {a___, 1, 0} :> {a, {1, 0}}
//. {a___, 1, 0, b__} :> {a, {1, 0}, b}, {1, 0}]
Count[w //. {a___, 1, 0, b___} :> {a, \[HappySmiley], b}, \[HappySmiley]]
Length[ReplaceList[w, {a___, 1, 0, b___} :> {a, {}, b}]]
specialCount[w_] :=
Module[{ww = w //. {a___, x_, x_, b___} :> {a, x, b}},
If[ww[[1]] === 0, Quotient[Length[ww] - 1, 2], Quotient[Length[ww], 2]]]
this will lead to another idea:
specialCount2[w_] := With[{l = Length[Split[w]]},
If[w[[1]] === 1, Quotient[l, 2], Quotient[l - 1, 2]]]
The last two methods wouldn't work if elements other than 0 or 1 were
present, so best use a pattern test for w
w_?VectorQ[#, MatchQ[#, 0 | 1] &] &
w_?VectorQ[#, IntegerQ[#] && 0 <= # <= 1 & ] &
We may also convert the problem to the numeric domain
specialCount3[w_] :=
Block[{t = 1, c = 0},
NestWhile[(If[Mod[#, 2] == 0, t = 0, If[t === 0, ++c; t = 1]];
Quotient[#, 2]) &, FromDigits[w, 2], Positive]; c]
--
Hartmut
Prev by Date:
Fw: Pattern Matching in Lists
Next by Date:
Re: Re: Problems with simulating society ch4 section 4.3
Previous by thread:
Fw: Pattern Matching in Lists
Next by thread:
Re: Pattern Matching in Lists
|