I'm trying to get used to Mathematica's approach to programming and list manipulation, and am struggling with one thing.
Say that I have a function f
which takes a list of two values and returns a list of two values. I also have a list of doubles, c = {{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}}
.
For each double in c
, I want to return a list of four values: two of them zero, and the ones with corresponding indices in c
should be defined by applying the function f
to the double in c
. Let me show some examples. For the value {1,3}
, I would like to return { f[{1,3}][[1]], 0, f[{1,3}][[2]], 0 }
, and for {2,3}
, I would like { 0, f[{2,3}][[1]], f[{2,3}][[2]], 0 }
.
I am completely stumped by this problem when I try to find a nice solution using Map
and other standard Mathematica list operations. The approach that I've tried was to map over c
trying to assign values to a list of zeroes depending on the values in c
, but I'm lost as to how I would accomplish that. I can basically do what I want with a loop:
result = {};
Do[
list = {0, 0, 0, 0};
list[[x[[1]]]] = f[x][[1]];
list[[x[[2]]]] = f[x][[2]];
AppendTo[result, list],
{x, c}]
but I would like to learn a better approach. Here, I don't even know how to perform the operation inside the Do
loop more elegantly, because something like
Map[(list[[x[[#]]]] = f [x][[#]])&, {1,2}]
does not work. I would appreciate any suggestions and help with this problem.
Riffle[f@#, {0,0}]& /@ c
? $\endgroup$