Ordered words: Difference between revisions

Content added Content deleted
m (→‎{{header|jq}}: map(select(_)))
(→‎{{header|jq}}: is_sorted via until)
Line 1,756: Line 1,756:
});</lang>
});</lang>
=={{header|jq}}==
=={{header|jq}}==
# {{works with|jq|1.4}}
<lang jq># input should be an array
<lang jq># If your jq already defines until/2 then the following definition can be omitted:
# The recursive inner function, sorted, has 0 arity for efficiency
def until(cond; next):
def _until: if cond then . else (next|_until) end;
_until;

# input should be an array
def is_sorted:
def is_sorted:
if length == 0 then true
def _is_sorted(ary):
else . as $in
def sorted: # state: i
| (length - 1) as $lm1
if . == (ary|length) then true
elif ary[. - 1] <= ary[.] then (.+1) | sorted
| $lm1 == (0 | until( . == $lm1 or $in[.] > $in[.+1] ; .+1))
end ;
else false
end;
if ary|length <= 1 then true else 1|sorted end;
. as $in | _is_sorted($in);


def longest_ordered_words:
def longest_ordered_words:
# avoid string manipulation:
# avoid string manipulation:
def is_ordered:
def is_ordered: explode | is_sorted;
explode | is_sorted;
map(select(is_ordered))
map(select(is_ordered))
| (map(length)|max) as $max
| (map(length)|max) as $max