Extracting N elements of the table satisfying the given condition

Consider the following table:

tab = Join[Partition[RandomReal[{0, 1}, 100], 1],
Partition[RandomInteger[{0, 1}, 100], 1], 2];


I would like to obtain the following. If more than 74 elements of the second column are equal to 1, then the list of 74 elements of the first column for which the second column == 1 (the order of elements does not matter). If there are less than 74 elements (say, this number is m), then the joined list made of these m elements + 74-m elements that are equal to $$\pi/2$$.

Could you please tell me how to do this?

2 Answers

Using Position, Extract and PadRight:

n = 74;
SeedRandom[1234];
tab = Transpose[{RandomReal[{0, 1}, 100],
RandomInteger[{0, 1}, 100]}];


Extract the 74 positions with 1s if possible and PadRight to make up for the difference.

pos = Position[tab[[All, 2]], 1, {1}, n]
res1 = PadRight[Extract[tab, pos][[All, 1]], n, π/2]


{0.876608, 0.521964, 0.0862234, 0.377913, 0.543757, 0.245349,
0.884729, 0.91956, 0.423835, 0.98729, 0.751866, 0.824395, 0.471262,
0.216368, 0.211603, 0.879378, 0.651802, 0.323889, 0.766977, 0.606002,
0.616014, 0.938081, 0.376572, 0.900864, 0.120901, 0.226994, 0.121503,
0.620155, 0.821888, 0.350603, 0.709353, 0.56393, 0.971864, 0.57182,
0.505445, 0.388272, 0.469119, 0.436177, 0.473556, 0.129717, 0.353704,
0.696489, 0.478682, 0.0451599, 0.809682, 0.150546, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2,
π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2}

Clear["Global*"]


A more direct and more efficient approach for generating tab is

SeedRandom[1234];
tab = Transpose[{RandomReal[{0, 1}, 100], RandomInteger[{0, 1}, 100]}];

cnt = 74;

out = Take[PadRight[Pick[##, 1] & @@ Transpose[tab], cnt, Pi/2],
cnt]

(* {0.876608, 0.521964, 0.0862234, 0.377913, 0.543757, 0.245349, 0.884729, \
0.91956, 0.423835, 0.98729, 0.751866, 0.824395, 0.471262, 0.216368, 0.211603, \
0.879378, 0.651802, 0.323889, 0.766977, 0.606002, 0.616014, 0.938081, \
0.376572, 0.900864, 0.120901, 0.226994, 0.121503, 0.620155, 0.821888, \
0.350603, 0.709353, 0.56393, 0.971864, 0.57182, 0.505445, 0.388272, 0.469119, \
0.436177, 0.473556, 0.129717, 0.353704, 0.696489, 0.478682, 0.0451599, \
0.809682, 0.150546, π/2, π/2, π/2, π/2, π/2, π/2, \
π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, \
π/2, π/2, π/2, π/2, π/2, π/2, π/2, π/2, \
π/2, π/2, π/2, π/2, π/2, π/2} *)
`