Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
1995
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 1995

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

Search the Archive

Re: interchanging elements in a list

  • To: mathgroup at christensen.cybernetics.net
  • Subject: [mg2005] Re: [mg1993] interchanging elements in a list
  • From: Richard Mercer <richard at seuss.math.wright.edu>
  • Date: Thu, 14 Sep 1995 23:27:04 -0400

>  Hi Group;
>  

>  Am I the only Mma user to wonder why the obvious list
>  command  Interchange  is missing from Mma?  It is easy
>  enough to programm but why should we have to?  Interchange
>  is not a name used anywhere else in Mma (?), it is a
>  natural list operation, it is important in Gaussian
>  Elimination...
>  

>  Presumably,
>  

>  	Interchange[list_List,n,m]
>  

>  should yield  list  with the nth and mth entries
>  interchanged.  Of course, Interchange might well be
>  designed to handle other heads besides List and perhaps
>  even have some level specs as options.
>  

>  Jack Goldberg Univ. of Michigan

I agree entirely.

Here are four possible implementations.
The first is fastest; the third is shortest and is a condensation of the more  
natural second one; the fourth is intermediate in both length and speed.

Interchange[list_List,n_,m_]:= 

ReplacePart[ReplacePart[list,list[[n]],m],list[[m]],n];

Interchange[list_List,n_,m_]:= 

list /. {list[[m]]->list[[n]],list[[n]]->list[[m]]};

Interchange[list_List,n_,m_]:= 

list /. {#1->#2,#2->#1}& @@ Part[list,{m,n}];

Interchange[list_List,n_,m_]:= 

Part[list,Range[1,Length[list]] /. {m->n,n->m}];

Richard Mercer


  • Prev by Date: Is there a way of declaring a variable REAL?
  • Next by Date: Log[E[n]]
  • Previous by thread: interchanging elements in a list
  • Next by thread: Re: Re: interchanging elements in a list