5
$\begingroup$

This would seem like a rather common thing to do: I've been trying since yesterday to Append a increasing sequence of numbers to my list of a pair of numbers. Researching possible solutions, I've explored using MapThread, @@@ and Module in various combinations to no effect. Returning to my original approach, it's not behaving as expected. (I understand the result, just not how to get the result I want.)

data = Partition[RandomSample[Range[100]],2,1];
seq = Range[Length[data]];
Append[#,seq] &/@ data

Expected result:

{{23,45,1},{45,67,2},{89,4,3},...}

Update1:

Uh.. In regards to the suggestion this is a duplicate: As a beginner, I can't even comprehend the code in the linked question. (Like what is the Min in the question?) Ultimately, I'd still have followup questions. I'm just running in the possible suggested solutions from this thread now. Thanks to all who offered answers.

$\endgroup$
  • 3
    $\begingroup$ Join[data, List/@seq, 2] or MapThread[Append, {data, seq}] $\endgroup$ – Simon Woods Oct 8 '17 at 16:25
9
$\begingroup$
MapIndexed[Join, data]
MapIndexed[Join]@data (*in versions 10+ *)

{{81, 15, 1}, {15, 1, 2}, {1, 68, 3}, {68, 4, 4}, ... , {63, 58, 98}, {58, 54, 99}}

$\endgroup$
  • $\begingroup$ Amazing. There's a function built right in that does this. I could have been wondering around in the woods for years before discovering this. TY. $\endgroup$ – BBirdsell Oct 8 '17 at 19:32
  • $\begingroup$ @BBirdsell, my pleasure. Thank you for the accept. $\endgroup$ – kglr Oct 8 '17 at 19:38
5
$\begingroup$

I'm sure there are lots of ways. Here's one:

data = Partition[RandomSample[Range[100]],2,1];
Flatten[{data[[#]], #}] & /@ Range[Length[data]]
{{60, 77, 1}, {77, 62, 2}, {62, 37, 3}, {37, 22, 4}, ....
$\endgroup$
  • 1
    $\begingroup$ I never would have thought of this but did test it out. I just want to wake up one day knowing this stuff. Thanks so much for everyone's time. $\endgroup$ – BBirdsell Oct 8 '17 at 19:35
3
$\begingroup$

Another possibility

n=2;
data=Partition[RandomSample[Range[10]],n,1]

Mathematica graphics

seq=Range[Length[data]]

Mathematica graphics

And now Riffle can be used. But need a small adjustment

 Partition[Flatten[Riffle[data,seq]],n+1]

Mathematica graphics

$\endgroup$
2
$\begingroup$

Long winded but fairly straightforward:

data = RandomChoice[Range[9],{10,2}]
end = Length[data]
Table[{First[data[[n]]],Last[data[[n]]],n},{n,1,end}]
$\endgroup$

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