1
$\begingroup$

How can I tell Mathematica to add a certain value ---not necessarily the same for all elements --- to the two, three, four... greater or smaller elements of a list without sorting it.

$\endgroup$
3
  • 4
    $\begingroup$ Use Ordering[] to fetch their positions in the list, and then you can do an assignment like list[[pos]] += value. $\endgroup$ Aug 13, 2017 at 17:17
  • 1
    $\begingroup$ it will help if you make a MWE, giving small input and what is the output you want. $\endgroup$
    – Nasser
    Aug 13, 2017 at 17:49
  • $\begingroup$ Probably simplest to thread over J.-M. 's suggestion, i.e.list = {1, 4, 23, 49, 27, 18, 3}; valueDelta ={12,5,7,3}; list[[Ordering[list, -Length[valueDelta]]]] += valueDelta; to increment 4 max values; otherwise list[[Ordering[list, +Length[valueDelta]]]] += valueDelta; to increment 4 min values. See Ordering documentation here for reference. $\endgroup$ Aug 13, 2017 at 21:36

2 Answers 2

1
$\begingroup$
b = RandomInteger[{0, 10}, {10}]

example b= {3, 4, 3, 5, 9, 2, 6, 5, 2, 2}

value = {1, 2, 3, 4};
funcMax[x_List, y_Integer, z_List] := 
 ReplacePart[x, 
  Rule @@@ Partition[Riffle[ Ordering[x][[-y ;; -1]], z], 2]]
funcMax[b, 4, value]

output

{3, 4, 3, 1, 4, 2, 3, 2, 2, 2}

to do the same for the minimun just replace Ordering[x][[-y ;; -1]] with Ordering[x][[1 ;; y]]

$\endgroup$
1
$\begingroup$
ClearAll[f1, f2]
f1 = MapAt[#, #2, List /@ Ordering[##2]] &;
f2 = Module[{ord = Ordering[##2]}, ReplacePart[#2, Thread[ord -> (# /@ #2[[ord]])]]] &;

Examples:

list = {1, 4, 3, 7, 2, 7, 6, 4, 8, 2, 3, 4, 1, 9};
f1[foo, list, 3]

{foo[1], 4, 3, 7, foo[2], 7, 6, 4, 8, 2, 3, 4, foo[1], 9}

f2[foo, list, 3]

{foo[1], 4, 3, 7, foo[2], 7, 6, 4, 8, 2, 3, 4, foo[1], 9}

f1[foo, list, -3]

{1, 4, 3, 7, 2, foo[7], 6, 4, foo[8], 2, 3, 4, 1, foo[9]}

f2[foo, list, -3]

{1, 4, 3, 7, 2, foo[7], 6, 4, foo[8], 2, 3, 4, 1, foo[9]}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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