9
$\begingroup$

Given a list of sets I want to choose the sets whose elements are in ascending order. I think I need to use: Select[list, crit] for this problem, but I could not set the criteria.

For instance,

I have a list:

list = {{1,4,2,3}, {4,2,3,1}, {1,4,8,9}, {1,3,5,7}, {2,4,6,8}, {2,1,3,5}, {4,8,9,10}, {2,7,9,11,13}, {4,1,7,9}}; 

From this list, I would like to obtain the list

{{1,4,8,9}, {1,3,5,7}, {2,4,6,8}, {4,8,9,10}, {2,7,9,11,13}}
$\endgroup$
1
  • $\begingroup$ As an alternative Pick[list, LessEqual[##] & @@@ list] $\endgroup$ Nov 1, 2019 at 17:46

6 Answers 6

11
$\begingroup$

Use OrderedQ:

Select[OrderedQ] @ list

{{1, 4, 8, 9}, {1, 3, 5, 7}, {2, 4, 6, 8}, {4, 8, 9, 10}, {2, 7, 9, 11, 13}}

$\endgroup$
2
$\begingroup$
list = {{1, 4, 2, 3}, {4, 2, 3, 1}, {1, 4, 8, 9}, {1, 3, 5, 7}, {2, 4, 6, 8}, 
        {2, 1, 3, 5}, {4, 8, 9, 10}, {2, 7, 9, 11, 13}, {4, 1, 7, 9}};

Using Pick and Differences:

Pick[#, AllTrue[Differences@#, # > 0 &] & /@ #] &@list

(*{{1, 4, 8, 9}, {1, 3, 5, 7}, {2, 4, 6, 8}, {4, 8, 9, 10}, {2, 7, 9, 11, 13}}*)
$\endgroup$
2
$\begingroup$

Point-free variations:

list = {{1, 4, 2, 3}, {4, 2, 3, 1}, {1, 4, 8, 9}, {1, 3, 5, 7}, {2, 4,
     6, 8}, {2, 1, 3, 5}, {4, 8, 9, 10}, {2, 7, 9, 11, 13}, {4, 1, 7, 
    9}};

Select[Apply[And]@*Positive@*Differences][list]

Pick[list, Apply[And]@*Positive@*Differences /@ list]

Pick[list, Map[Apply[And]@*Positive@*Differences][list]]

Result:

{{1, 4, 8, 9}, {1, 3, 5, 7}, {2, 4, 6, 8}, {4, 8, 9, 10}, {2, 7, 9,
11, 13}}

$\endgroup$
2
$\begingroup$

Just some variants (I have voted for @CarlWoll):

Pick[list, # == Sort@# & /@ list]
Cases[list, x_?(Sort[#] == # &)]
Select[# == Sort[#] &][list]
Reap[Sow[#, #==Sort[#] ]&/@ list, True][[2,1]]

All yield: {{1, 4, 8, 9}, {1, 3, 5, 7}, {2, 4, 6, 8}, {4, 8, 9, 10}, {2, 7, 9, 11, 13}}

$\endgroup$
1
$\begingroup$
list =
  {{1, 4, 2, 3}, {4, 2, 3, 1}, {1, 4, 8, 9}, {1, 3, 5, 7},
   {2, 4, 6, 8}, {2, 1, 3, 5}, {4, 8, 9, 10}, {2, 7, 9, 11, 13}, {4, 1, 7, 9}};

Using LongestOrderedSequence (new in 10.2)

Intersection[list, LongestOrderedSequence /@ list]

{{1, 3, 5, 7}, {1, 4, 8, 9}, {2, 4, 6, 8}, {4, 8, 9, 10}, {2, 7, 9, 11, 13}}

$\endgroup$
1
$\begingroup$
list =
  {{1, 4, 2, 3}, {4, 2, 3, 1}, {1, 4, 8, 9}, {1, 3, 5, 7}, {2, 4, 6, 8}, 
   {2, 1, 3, 5}, {4, 8, 9, 10}, {2, 7, 9, 11, 13}, {4, 1, 7, 9}};

Using SequenceSplit (new in 11.3) and OrderedQ

Catenate @ SequenceSplit[list, {x_ /; ! OrderedQ[x]}]

{{1, 4, 8, 9}, {1, 3, 5, 7}, {2, 4, 6, 8}, {4, 8, 9, 10}, {2, 7, 9, 11, 13}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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