Problem:
Input is a list containing N numbers from 1 to N in random order.
Rearrange the list in such a way that "position of ith element is the value of ith element of list.
ie for 4 1 2 3:
new position of 4 should be value of 4th element ie 3rd
new position of 1 should be value of 1st element ie 4th
new position of 2 should be value of 2nd element ie 1st.
new position of 3 should be value of 3rd element ie 2nd.
So new arrangement would be 2 3 4 1
Rearrange the list in such a way that "position of ith element is the value of ith element of list.
ie for 4 1 2 3:
new position of 4 should be value of 4th element ie 3rd
new position of 1 should be value of 1st element ie 4th
new position of 2 should be value of 2nd element ie 1st.
new position of 3 should be value of 3rd element ie 2nd.
So new arrangement would be 2 3 4 1
Input Format:
list containing N numbers from 1 to N in random order
Output Format:
list after rearrangementConstraints:
NoneSample Input
5 6 1 8 3 7 2 4
Sample Output:
3 7 5 8 1 2 6 4
Explanations:
Explained in problem statement
Solution:
@arr=split(" ",$input);
foreach(@arr)
{
$arr1[$arr[$_-1]-1]=$_;
}
foreach(@arr1)
{
print "$_ ";
}
Tips:
Remember that in perl , array index starts with 0
No comments:
Post a Comment