2
$\begingroup$

I have a list of the form list1 = {1, 3, 4, 2, 5, 6} and I would like to replace each of the elements in the position of represented by the previous number in the list, for instance replace 1 in position 6, 3 in position 1, 4 in position 3, 2 in position 4 and so on. In the end I should get a list of the form {3, 5, 4, 2, 6, 1}. I am trying to do the following:

A = ConstantArray[0, Length[list1]]
NewList = 
  Table[
    ReplacePart[
      A, 
      (If[Position[list1, i] - 1 != 0, 
         Position[list1, i] - 1, 
         Position[List1, Last[List1]]) -> i], 
    {i, Range[Length[List1]]}]

I am using If inside ReplacePart to consider the case when an element is in position 1 and send it to the position of the last element of the permutation. However, this methos is not working. Could anyone tell me why? Is there is a more efficient method to solve this problem?

$\endgroup$
1
  • $\begingroup$ The If expression in your code seems to be missing a ] at its end. $\endgroup$ – m_goldberg Jun 19 '16 at 14:13
5
$\begingroup$
newList = list1 = {1, 3, 4, 2, 5, 6};
newList[[RotateRight[list1]]] = list1;
newList

==> {3, 5, 4, 2, 6, 1}

$\endgroup$
2
  • $\begingroup$ Thanks! This solves my problem completely, but would you mind explaining the second line of the code? I don't really see what it is doing. $\endgroup$ – user41116 Jun 19 '16 at 15:47
  • $\begingroup$ @user41116 The second line exposes a very useful purpose of Part by being able to Set arbitrary parts of a list at one time. By rotating the list right, you get {6, 1, 3, 4, 2, 5} and are essentially setting newlist[[6]] = 1, newlist[[1]] = 3 etc... $\endgroup$ – kale Jun 19 '16 at 17:58
3
$\begingroup$

Ordering[] is another opportunity:

list1 = {1, 3, 4, 2, 5, 6};
newList = list1[[Ordering[RotateRight[list1]]]]
(*{3, 5, 4, 2, 6, 1}*)
$\endgroup$
1
  • $\begingroup$ Could you explain whi the expression list1[[Ordering[RotateRight[list1]]]] actually changes list1? I don't see how it is working. THanks! $\endgroup$ – user41116 Jun 19 '16 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.