0
$\begingroup$
c = Table[RandomVariate[BernoulliDistribution[1/2], 3], 3]
d = Total[c, {2}]
list = {};
For[k = 0, k <= Length[d], k++, 
If[d[[k]] == 2, AppendTo[list, c[[k]]]]]

This is my code. I want to use reap and sow in place of AppendTo. How should I go about it?

$\endgroup$
  • $\begingroup$ Have you tried anything? $\endgroup$ – MarcoB Feb 27 at 3:10
  • 1
    $\begingroup$ Select[c, 2 == Total[#] &] $\endgroup$ – Alan Feb 27 at 3:14
  • $\begingroup$ Alright thanks! $\endgroup$ – Chloe Feb 27 at 15:13
3
$\begingroup$

You can use Pick or Select instead:

SeedRandom[1]
c = Table[RandomVariate[BernoulliDistribution[1/2], 3], 10]

{{1, 0, 1}, {0, 0, 0}, {1, 0, 0}, {1, 0, 1}, {0, 0, 1}, {1, 1, 1}, {0, 0, 1}, {0, 0, 1}, {0, 1, 0}, {1, 1, 0}}

d = Total[c, {2}]

{2, 0, 1, 2, 1, 3, 1, 1, 1, 2}

list = {};
For[k = 0, k <= Length[d], k++, If[d[[k]] == 2, AppendTo[list, c[[k]]]]]; list

{{1, 0, 1}, {1, 0, 1}, {1, 1, 0}}

Pick[c, d, 2]

{{1, 0, 1}, {1, 0, 1}, {1, 1, 0}}

Select[c, Total[#] == 2 &]

{{1, 0, 1}, {1, 0, 1}, {1, 1, 0}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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