54
\$\begingroup\$

Given an input string S, return truthy if all the letters in S are Lexically Ordered: their ASCII values need to be in either ascending or descending order. Return falsy in other cases.

Input

  • Input will be in the same case (all upper- or all lowercase). Your submission should be able to handle both.
  • Input will consist of ASCII in the range [A-Za-z] only
  • Input length will be at least 1, up to whatever maximum your language supports.
  • Input is a string - not a list of characters, not an array of ASCII-codepoints.

Output

  • Output should be true or false, or 0/1, or any other distinct true / false style output your language can provide.
  • All true cases need to have the same output, as well as all the false cases. No "False is 0, true is 1, 2, or 3".

Additional rules

  • Standard loopholes are forbidden
  • Answer must be a full program or a function, not a snippet or a REPL-entry.
  • , shortest answer in bytes wins.

Test cases

Truthy

"ABCDEF" "ZYX" "no" "tree" --> the multiple 'e's don't break the order "q" 

Falsy

"ABCDC" "yes" "deed" 

Invalid

"Hello" --> invalid input - mixed case-, does not have to be handled "" --> invalid input - length 0-, does not have to be handled "\n " --> invalid input - newline is not in range [A-Za-z]-, does not have to be handled 
\$\endgroup\$
18
  • 1
    \$\begingroup\$ Can you clarify about the output: does the truthy value need be the same regardless of what input is given? \$\endgroup\$ Commented Jan 30, 2017 at 19:12
  • 1
    \$\begingroup\$ @BusinessCat I've added a clarification. \$\endgroup\$ Commented Jan 30, 2017 at 20:01
  • \$\begingroup\$ What if your language's implementation of a string is a list of characters? Many of the answers posted here are using such languages... \$\endgroup\$ Commented Jan 30, 2017 at 20:40
  • 1
    \$\begingroup\$ If you really want distinct values for True and False you shouldn't say truthy or falsy. This implies that any values that evaluate to true or false are allowed. \$\endgroup\$ Commented Jan 30, 2017 at 21:50
  • 3
    \$\begingroup\$ related: Find the Wavy Words! \$\endgroup\$ Commented Jan 30, 2017 at 22:25

70 Answers 70

2
\$\begingroup\$

Pushy, 7 bytes

ogoGo|# 

Try it online!

Explanation:

 \ Implicit: Input on stack as charcodes og \ Check if the stack is sorted ascendingly (Push 0/1) oG \ Check if the stack is sorted descendingly (Push 0/1) \ - Note that this will work regardless of the first check, as input \ is guaranteed to be /[A-Za-z]+/ o| \ Bitwise OR # \ Print the result 
\$\endgroup\$
5
  • \$\begingroup\$ This does not return one distinct true-value. \$\endgroup\$ Commented Jan 30, 2017 at 18:35
  • 1
    \$\begingroup\$ @steenbergh No, but it satisfies our meta consensus on what counts as truthy or falsy - 1 and 2 are True in Pushy, whereas 0 is False. \$\endgroup\$ Commented Jan 30, 2017 at 19:11
  • \$\begingroup\$ If Pushy has a bitwise OR operator, that should work instead. \$\endgroup\$ Commented Jan 30, 2017 at 19:20
  • \$\begingroup\$ @FlipTack I thought it was clear in the challenge, but I've now made it more specific: TRUE must output the same value on all testcases. Same goes for FALSE. \$\endgroup\$ Commented Jan 30, 2017 at 21:38
  • \$\begingroup\$ @steenbergh The meta consensus is there for a reason and makes sense, but if you insist... \$\endgroup\$ Commented Jan 30, 2017 at 21:39
2
\$\begingroup\$

Pyth, 5 bytes

}Q_BS 

A program that takes input of a "quoted string" and prints True or False as appropriate.

Test suite

How it works

}Q_BS Program. Input: Q }Q_BSQ Implicit variable fill Q Is Q } in SQ Q sorted B or _ Q sorted reversed? Implicitly print 
\$\endgroup\$
1
  • \$\begingroup\$ You can save a byte (and become the shortest answer) by replacing }Q with /, which uses an implicit Q. \$\endgroup\$ Commented Mar 9, 2017 at 18:33
2
\$\begingroup\$

Octave, 24 bytes

@(s)issorted(s,'either') 

Try It Online!

\$\endgroup\$
2
\$\begingroup\$

GNU sed, 97 + 1(r flag) = 98 bytes

If the letters are ordered, the script returns 1, otherwise 0. In sed there are no data types.

s:$: zyxwvutsrqponmlkjihgfedcba: s:(.*(.)(.).* ).*\2.*\3.*:\1abcdefghijklmnopqrstuvwxyz:i //c0 c1 

To check if all letters are arranged in ascending order, I do a table lookup of each pair of consecutive letters in a descending alphabet, that is I try to find a counter example. Note that // actually repeats the last regular expression match! (see lines 2 and 3)

Run example: the script can test multiple input words, one per line

me@LCARS:/PPCG$ echo -e "tree\nABCDC" | sed -rf word_ordered.sed 1 0 
\$\endgroup\$
2
\$\begingroup\$

CJam, 12 11 bytes

q_$_W%+\#)g 

Try it online!

Explanation

q Push the input _$ Duplicate and sort _W% Duplicate and reverse + Concatenate the sorted and the reversed strings \ Bring input to the top # Find the index of the input in the other string; returns -1 if not found ) Increment g Signum (coerces to 0 or 1) 
\$\endgroup\$
2
\$\begingroup\$

Python 3.5+, 37 bytes

lambda a:sorted(a)in([*a],[*a][::-1]) 
\$\endgroup\$
2
\$\begingroup\$

8086 machine code, 68 61 48 46 45 39 bytes

00000000 b2 31 be 82 00 ac 9f 88 c3 ac 3c 0d 74 14 38 c3 |.1........<.t.8.| 00000010 74 f5 e3 03 b1 00 9f 77 05 9e 76 ea eb 03 9e 77 |t......w..v....w| 00000020 e5 4a b4 02 cd 21 c3 |.J...!.| 00000027 

Assembled from:

org 0x100 use16 mov dl, 0x31 mov si, 0x82 lodsb a: lahf b: mov bl, al lodsb cmp al, 0x0d je y cmp bl, al je b jcxz @f mov cl, 0 lahf @@: ja @f sahf jbe a jmp n @@: sahf ja a n: dec dx y: mov ah, 0x02 int '!' ret 
\$\endgroup\$
1
  • \$\begingroup\$ Is comparing [si] longer or shorter? \$\endgroup\$ Commented Jan 7, 2023 at 19:53
2
\$\begingroup\$

Scala, 47 bytes

def f(x:String)=x==x.sorted|x==x.sorted.reverse 
\$\endgroup\$
2
\$\begingroup\$

Swift 4, 70 bytes

var o=Array(readLine()!);var g=o.sorted();print(o==g||o==g.reversed()) 

Try it online!

\$\endgroup\$
0
2
\$\begingroup\$

Add++, 28 18 bytes

L,2]dbRAº= L^,bU# 

Try it online!

\$\endgroup\$
2
\$\begingroup\$

C, 68 bytes

This assumes the use of a character encoding such as ASCII where the letters are in ascending (or descending) order.

f(char*s){for(int a=3;*s&&a;++s)a&=s[1]<=*s|2*(s[1]>=*s);return!*s;} 

We use variable a to store two flags - bit 0 is set if everything we've seen so far is consistent with an ascending sequence, and bit 1 if it's consistent with descending. Before we've seen anything, both are true.

If both these flags become false before the end of string, we exit the loop before s points at the terminating NUL and so return false (0).

If we reach the end of string, then we return true (1).

Test program

#include <stdio.h> #include <string.h> int main(int argc, char **argv) { for (int i = 1; i < argc; ++i) printf(" %s -> %d\n", argv[i], f(argv[i])); } 
\$\endgroup\$
2
\$\begingroup\$

Add++, 13 bytes

L,B#b+dbRB]Ae 

Try it online! Based on @caird coinheringaahing's answer.

Explanation

L, [arg] Lambda with no flags B# [sorted(arg)] Sort every item in stack b+ [sorted] Reduce top item by addition (string join) d [sorted sorted] Duplicate bR [sorted reversed] Reverse top item B] [[sorted reversed]] Clear stack and add stack as single stack item (sorted + reversed) A [[sorted reversed] arg] Add arguent e [result] Top item is found in second top item (Python's "x in y") 
\$\endgroup\$
2
\$\begingroup\$

√ å ı ¥ ® Ï Ø ¿ , 3 bytes

Ißo 

This is a stack-based language that uses cp-1252 encoding. Full description at the link in the title.

How it works

I - Take input and convert to characters ß - Is sorted? o - Output 
\$\endgroup\$
2
\$\begingroup\$

PowerShell, 49 bytes

param($a)$a-in(0,1|%{-join($a|% t*y|sort -d:$_)}) 

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Vyxal, 2 bytes

ÞȮ 

Try it Online!

Simple means is ordered?

\$\endgroup\$
2
\$\begingroup\$

Ruby, 39 bytes

Returns false for ordered and true for unordered.

->s{!(s+$/+s.reverse)[s.chars.sort*""]} 

Attempt This Online!

\$\endgroup\$
2
\$\begingroup\$

Google Sheets, 113 bytes

It assumes the input string is in A1.

=OR(MAP({1,0},LAMBDA(o,LEN(REDUCE(A1,SORT(CHAR(ROW(65:90)),1,o),LAMBDA(a,c,REGEXREPLACE(a,"(?i)^"&c&"+",))))=0))) 
\$\endgroup\$
2
\$\begingroup\$

Tcl, 73 bytes

proc L s {expr {[set C [split $s ""]]in[list [lsort $C] [lsort -de $C]]}} 

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Bespoke, 375 bytes

with a word,I check if ordered letters occur in it what criteria clearly prevents a success?if an A-to-B ordering gets reversed I record a Boolean for it,checking each one is going down/going up given elements of alphabet,a pairwise-comparing is needed each time we apply"less than"we check ordering we consider a sequence unordered if result is changing;else,it is in orde-r 

Outputs 0 for true, and 1 for false.

As the input is processed, two stack values are updated - one to keep track of whether the order is increasing, and one to keep track of whether the order is decreasing. Both are initialized to 1 (meaning the word is both increasing and decreasing). Each pair of characters is then compared twice using STACKTOP LT, and the stack values are updated to reflect the results of these comparisons.

The two stack values are then added together, which results in 0 if the input is neither increasing nor decreasing, and a nonzero value otherwise. STACKTOP F is then used to make the truthy result consistent (which has the effect of flipping the condition from what it normally would be).

\$\endgroup\$
1
\$\begingroup\$

TI-Basic, 66 + 78 = 144 bytes

Input Str1 For(I,1,length(Str1 inString(Str2,sub(Str1,I,1->L1(I End L1->L2 Ans->L3 SortA(L2 SortD(L3 L1=L2 or L1=L3 

And in Str2 you must have this (+78 bytes):

`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 
\$\endgroup\$
1
\$\begingroup\$

Retina, 36 bytes

Byte count assumes ISO 8859-1 encoding.

$ ¶$_¶$_ O^#`\G. Or`.\G (.+)\D*\b\1$ 

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Pyke, 5 bytes

SD_]{ 

Try it here!

S - sorted(input) ] - [^, v] D - ^ _ - reverse(^) { - input in ^ 
\$\endgroup\$
1
\$\begingroup\$

Haskell, 46 bytes

import Data.List f s=sort s`elem`[s,reverse s] 

Try it online! Usage: f "somestring", returns True or False.

Not as interesting as nimi's approach, but some bytes shorter.

Given a string s, we check whether s sorted is euqal to the original or reversed string.

\$\endgroup\$
1
\$\begingroup\$

Pyth, 5 bytes

}SQ,_ 

Explanation:

}SQ,_ }SQ Check if the sorted input is a member ... ,_QQ ... of [reversed input, input] 
\$\endgroup\$
1
\$\begingroup\$

Scala, 52 bytes

def p(s:String)=List(s,s.reverse).contains(s.sorted) 
\$\endgroup\$
1
\$\begingroup\$

C++, 138 bytes

#import<algorithm> using namespace std;f(string s){string u,t=s;sort(t.begin(),t.end());u=t;reverse(u.begin(),u.end());return s==t||s==u;} 
\$\endgroup\$
1
\$\begingroup\$

Clojure, 69 66 bytes

#(let[s(apply str(sort %))](or(= % s)(= %(apply str(reverse s))))) 

-3 by inlining reversed.

My original try ended up being a longer version of the other Clojure answer, so I went the "sorted" route. Checks if the original string is equal to a sorted version of itself, or a reversed sorted string. Amazingly, (apply str (reverse s) ended up being shorter than using the built-in reverse string method.

(defn lex? [s] ; (apply str ...) basically just turns a list into a string (let [sorted (apply str (sort s)) reversed (apply str (reverse sorted))] (or (= s sorted) (= s reversed)))) 
\$\endgroup\$
2
  • \$\begingroup\$ Wouldn't it be shorter if you remove r altogether and put the definition of r in the second equality check? \$\endgroup\$ Commented Feb 1, 2017 at 10:47
  • \$\begingroup\$ @Qwerp-Derp Thanks, I forgot to inline that in my golfed version. \$\endgroup\$ Commented Feb 1, 2017 at 21:27
1
\$\begingroup\$

PHP 7, 63 bytes

for($s=$argv[1];$s[++$i]&a;)${$s[$i-1]<=>$s[$i]}=1;echo!$${-1}; 
\$\endgroup\$
1
\$\begingroup\$

Röda, 75 bytes

f s{x=[split(s,sep="")];[s=[sort(x)]&""or s=[sort(x,cmp={|a,b|[a>b]})]&""]} 

Try it online!

Alternative solution:

f s{x=[split(s,sep="")];[s in[[sort(x)]&"",[sort(x,cmp={|a,b|[a>b]})]&""]]} 

Try it online!

It is possible that shorter solutions exist, but I couldn't find them now.

\$\endgroup\$
2
  • \$\begingroup\$ Why not s/"" instead of split? \$\endgroup\$ Commented Mar 12, 2017 at 15:41
  • \$\begingroup\$ @KritixiLithos The / operator was implemented after this challenge. \$\endgroup\$ Commented Mar 12, 2017 at 15:46
1
\$\begingroup\$

Alice, 15 bytes, non-competing

/o.zz./ @inssR\ 

Try it online!

Prints nothing (or rather an empty string) as the falsy value and Jabberwocky as the truthy value.

Explanation

/.../ @...\ 

This is a template for linear string-processing programs that operate entirely in Ordinal mode. However, the code in between is executed in a zig-zag pattern first from left to right and then right to left. Unfolding this part, the actual program we get looks like this:

i.szR.szno 

And here is what that does:

i Read all input as a string. .s Duplicate and sort it. z "Drop to substring". If the original contains the sorted version (which means they're equal) this results in the empty string, otherwise we get the original back. R Reverse the string. .sz Do the same thing again. If either the original or the reversed original was sorted, we end up with an empty string (falsy), otherwise we get the reverse of the original (truthy, because it's non-empty). n Logical NOT. Turns non-empty strings into empty (falsy) strings and empty strings into "Jabberwocky". o Print the result. 
\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.