MathGroup Archive 2006

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

Search the Archive

Re: Word permutations - frustrated by lists.

  • To: mathgroup at smc.vnet.net
  • Subject: [mg71702] Re: Word permutations - frustrated by lists.
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Mon, 27 Nov 2006 04:04:10 -0500 (EST)
  • Organization: The Open University, Milton Keynes, UK
  • References: <ekbrks$jga$1@smc.vnet.net>

wooks wrote:
> Hello. Am relatively new with Mathematica.
> 
> I seem to have a general problem with results that look right but for
> embedded lists. Here is an example of my problem. This is supposed to
> be a algorithm to generate all permutations of a string. T
> 
> Clear[arrangements]
> arrangements[str_String /; StringLength[str] == 1] := {str};
> arrangements[str_String] := (Prepend[arrangements[StringJoin[
>     Rest[#]]]], First[#]) & /@
>        NestList[RotateRight, Characters[str], StringLength[str] - 1];
> arrangements["dear"]
> 
> PS This is not homework. I'm rewriting some examples from another
> programming book as as practice  for Mathematica.
> 

Hi,

I am not sure which one is going to fit your needs (I admit I am a 
little bit confuse by your code and what I think you try to achieve.) 
Both are recursive functions, although the result given by the second 
function might not be what you had in mind.

In[1]:=
Clear[arrangements];
arrangements[str_String /; StringLength[str] == 1] := {str};
arrangements[str_String] := StringJoin /@ NestList[RotateRight,
      Characters[str], StringLength[str] - 1];
arrangements["dear"]

Out[4]=
{dear,rdea,arde,eard}

In[5]:=
Clear[arrangements];
arrangements[str_String /; StringLength[str] == 1] := {str};
arrangements[str_String] := (Prepend[arrangements[StringJoin[Rest[#1]]],
       First[#1]] & ) /@ NestList[RotateRight, Characters[str],
      StringLength[str] - 1];
arrangements["dear"]

Out[8]=
{{d,{e,{a,r},{r,a}},{r,{e,a},{a,e}},{a,{
     r,e},{e,r}}},{r,{d,{e,a},{a,e}},{a,{d,e},{e,d}},{e,{a,d},{d,a}}},{
   a,{r,{d,e},{e,d}},{e,{r,d},{d,r}},{d,{
     e,r},{r,e}}},{e,{a,{r,d},{d,r}},{d,{a,r},{r,a}},{r,{d,a},{a,d}}}}

HTH,
Jean-Marc


  • Prev by Date: Re: SetPrecision vs N
  • Next by Date: Re: Bookmarks in Mathematica????
  • Previous by thread: Re: Word permutations - frustrated by lists.
  • Next by thread: Re: Word permutations - frustrated by lists.