MathGroup Archive 1996

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

Search the Archive

Re: Inverse of IntegerDigits? and "Index" function?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg3956] Re: Inverse of IntegerDigits? and "Index" function?
  • From: Paul Abbott <paul at earwax.pd.uwa.edu.au>
  • Date: Sat, 11 May 1996 23:53:09 -0400
  • Organization: University of Western Australia
  • Sender: owner-wri-mathgroup at wolfram.com

pehowland at taz.dra.hmg.gb wrote:

> Inverse of IntegerDigits
> ========================
> I'm playing around with some binary numbers, and am using 
> IntegerDigits
> to convert from a decimal integer to the binary notation.  eg.
>         In[1]:= IntegerDigits[10,2]
>         Out[1]= {1,0,1,0}
> 
> What is the function to convert back? eg. I want to do
>         In[2]:= DigitsToInteger[{1,0,1,0},2]
> and get
>         Out[2]= 10

Have a look at the Mathematica Journal 2(2):35:

	Horner[u_List, base_] := Fold[base #1 + #2 &, 0, u]

	Horner[{1,0,1,0},2]

	10

> "Index" Function
> ================
> Writing a function to convert back is easy in principle, eg.
> 
>  DigitsToInteger[x_,n_] := Apply[Plus[Map[(#*n^(Index[#]-1))&, Reverse[x]]]]
> 
> would do the trick, but I seem to require a function, that I've called
> Index[] here, that when Map[]'d across a list returns the position of
> each element.  Thus I want a function that works as follows:
> 
>         In[3]:= Map[Index[#]&, {2,6,3,9,10,2,4}]
>         Out[3]= {1,2,3,4,5,6,7}

Try MapIndexed:

	?MapIndexed

	MapIndexed[f, expr] applies f to the elements of expr, giving
   the part specification of each element as a second
   argument to f. MapIndexed[f, expr, levspec] applies f to
   all parts of expr on levels specified by levspec.

	MapIndexed[f, {2,6,3,9,10,2,4}]

	{f[2, {1}], f[6, {2}], f[3, {3}], f[9, {4}], f[10, {5}], 
	 f[2, {6}], f[4, {7}]}

	MapIndexed[#2 &, {2,6,3,9,10,2,4}]

	{{1}, {2}, {3}, {4}, {5}, {6}, {7}}

Cheers,
	Paul 
_________________________________________________________________ 
Paul Abbott
Department of Physics                       Phone: +61-9-380-2734 
The University of Western Australia           Fax: +61-9-380-1014
Nedlands WA  6907                         paul at physics.uwa.edu.au 
AUSTRALIA                           http://www.pd.uwa.edu.au/Paul
_________________________________________________________________

==== [MESSAGE SEPARATOR] ====


  • Prev by Date: Re: Inverse of IntegerDigits? and "Index" function?
  • Next by Date: Mathematica Training
  • Previous by thread: Re: Inverse of IntegerDigits? and "Index" function?
  • Next by thread: Re: Inverse of IntegerDigits? and "Index" function?