Re: Number of Differing Digits & Another Problem (want to see different
- To: mathgroup at smc.vnet.net
- Subject: [mg76334] Re: Number of Differing Digits & Another Problem (want to see different
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Sun, 20 May 2007 02:20:35 -0400 (EDT)
- Organization: The Open University, Milton Keynes, UK
- References: <f2mf5b$mbm$1@smc.vnet.net>
VenDiddy at gmail.com wrote: > I just purchased a copy of Mathematica and I've been learning it for > about a week now. You can expect that I will be posting a lot of > questions. One thing I've noticed is that there are so many different > ways to do the same thing! > > Here is a function I came up with that calculates how many binary > digits two numbers differ in: > > BitDifferences[a_, b_, n_] := > Count[Equal @@@ > Thread[{IntegerDigits[a, 2, n], IntegerDigits[b, 2, n]}], True] ---------------------------------------------------------------^^^^ Here, I believe you want to count the occurrences of False rather than True. > > For example 5 = 101 differs from 6 = 111 by one digit (the middle > digit). The number 6 (decimal) is 110 in binary. (BaseForm[#1, 2] & ) /@ {5, 6} ==> {101, 110} > I want to see how you would do it so I can broaden my Mathematica > perspective. > > Thanks. One possible way is the following: In[1]:= BitDifferences2[a_, b_] := Module[{n}, n = Max[Length /@ (IntegerDigits[#1, 2] & ) /@ {a, b}]; Total[ (Boole[#1[[1]] != #1[[2]]] & ) /@ Transpose[(IntegerDigits[#1, 2, n] & ) /@ {a, b}]]] BitDifferences2[5, 6] BitDifferences2[5, 256] Out[2]= 2 Out[3]= 3 Regards, Jean-Marc