Sort disjoint sublist: Difference between revisions
(J) |
(Indices are better described as a set rather than a list, although a list may be used - with caveats.) |
||
Line 1: | Line 1: | ||
{{draft task}} |
{{draft task}} |
||
Given a list of values and a |
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, but preserving the values at indices outside the set of those to be sorted. |
||
Make your example work with the following list of values and |
Make your example work with the following list of values and set of indices: |
||
<code> |
<code> |
||
values: [7, <b>6</b>, 5, 4, 3, 2, <b>1</b>, <b>0</b>] |
values: [7, <b>6</b>, 5, 4, 3, 2, <b>1</b>, <b>0</b>] |
||
indices: |
indices: {6, 1, 7}</code> |
||
Where the correct result would be: |
Where the correct result would be: |
||
<code>[7, <b>0</b>, 5, 4, 3, 2, <b>1</b>, <b>6</b>]</code>. |
<code>[7, <b>0</b>, 5, 4, 3, 2, <b>1</b>, <b>6</b>]</code>. |
||
Note that for one based, rather than the zero-based indexing above, use the <code>indices: |
Note that for one based, rather than the zero-based indexing above, use the <code>indices: {7, 2, 8}</code>. The indices are described as a set rather than a list but any collection-type of those indices may be used as long as the example is insensitive to the order of indices given. |
||
=={{header|J}}== |
=={{header|J}}== |
Revision as of 13:10, 12 February 2011
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, but preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
values: [7, 6, 5, 4, 3, 2, 1, 0]
indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6]
.
Note that for one based, rather than the zero-based indexing above, use the indices: {7, 2, 8}
. The indices are described as a set rather than a list but any collection-type of those indices may be used as long as the example is insensitive to the order of indices given.
J
Note that the task requires us to ignore the order of the indices.
<lang j> 7 6 5 4 3 2 1 0 (/:~@:{`[`]}~ /:~) 6 1 7 7 0 5 4 3 2 1 6 </lang>
Compare this with: <lang j> 6 1 7 /:~@:{`[`]} 7 6 5 4 3 2 1 0 7 1 5 4 3 2 0 6</lang>
Here, the order of the indices specifies the order we want the selected items to be sorted in: 7 1 5 4 3 2 0 6
Python
The function modifies the input data list in-place and follows the Python convention of returning None in such cases.
<lang python>>>> def sort_disjoint_sublist(data, indices): indices = sorted(indices) values = [data[i] for i in indices] values.sort() for index, value in zip(indices, values): data[index] = value
>>> d = [7, 6, 5, 4, 3, 2, 1, 0]
>>> i = [6, 1, 7]
>>> sort_disjoint_sublist(d, i)
>>> d
[7, 0, 5, 4, 3, 2, 1, 6]</lang>