1
$\begingroup$

Input:

Select[Range[10], 2 <= # <= 5 || 8 <= # <= 10 &]

Output:

{2, 3, 4, 5, 8, 9, 10}

In case I have lots of conditions I want to have them defined separately like this:

Input:

cond = {{2, 5}, {8, 10}};
Or @@ (#[[1]] <= q <= #[[2]] & /@ cond)

Output:

2 <= q <= 5 || 8 <= q <= 10

How to combine my first input with my second input to have all the code in my formula?

$\endgroup$
4
  • 3
    $\begingroup$ Just use Between[]: Select[Range[50], Between[{{2, 5}, {11, 19}, {26, 33}, {44, 49}}]] $\endgroup$ Jan 25, 2020 at 1:02
  • $\begingroup$ OK. But I would like to know also how to do it with Map. In case I wanted a more complex conditions not just simple inequalities. $\endgroup$ Jan 25, 2020 at 1:06
  • 2
    $\begingroup$ Would something like With[{sel = ReleaseHold[Hold[Function][Apply[Or, # <= Hold[Slot][1] <= #2 & @@@ {{2, 5}, {11, 19}, {26, 33}, {44, 49}}]]]}, Select[Range[50], sel]] suit your needs? $\endgroup$ Jan 25, 2020 at 1:17
  • 2
    $\begingroup$ Define a helper function cond = {{2, 5}, {8, 10}}; test[x_] = Or @@ (#[[1]] <= x <= #[[2]] & /@ cond); Select[Range[10], test] $\endgroup$
    – Bob Hanlon
    Jan 25, 2020 at 2:02

1 Answer 1

2
$\begingroup$

You could use Cases with a Condition:

Cases[Range[10], q_ /; 2<=q<=5||8<=q<=10]

{2, 3, 4, 5, 8, 9, 10}

or Select with a pure Function:

Select[Range[10], Function[q, 2<=q<=5||8<=q<=10]]

{2, 3, 4, 5, 8, 9, 10}

$\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.