53
\$\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\$ Jan 30, 2017 at 19:12
  • 1
    \$\begingroup\$ @BusinessCat I've added a clarification. \$\endgroup\$
    – steenbergh
    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\$
    – minseong
    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\$
    – FlipTack
    Jan 30, 2017 at 21:50
  • 3
    \$\begingroup\$ related: Find the Wavy Words! \$\endgroup\$
    – Titus
    Jan 30, 2017 at 22:25

66 Answers 66

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\$
    – isaacg
    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\$
    – l4m2
    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\$

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

C++ (gcc), 125 124 123 115 bytes

Very boring obvious solution. We use GCC's internal header to save many includes. Conveniently, std::ranges::is_sorted() accepts equal adjacent elements, so we don't need to pass a std::less_equal<>() to it.

#include<bits/stdc++.h>
int f(auto s){using namespace std::ranges;return is_sorted(s)|is_sorted(s|views::reverse);}

Demo program:

#include <cstdio>
#include <string>

int main(int argc, char **argv)
{
    for (int i = 1;  i < argc;  ++i)
        std::printf("  %s -> %d\n", argv[i], f(std::string{argv[i]}));
}
\$\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\$
    – clismique
    Feb 1, 2017 at 10:47
  • \$\begingroup\$ @Qwerp-Derp Thanks, I forgot to inline that in my golfed version. \$\endgroup\$ 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\$
    – user41805
    Mar 12, 2017 at 15:41
  • \$\begingroup\$ @KritixiLithos The / operator was implemented after this challenge. \$\endgroup\$
    – fergusq
    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\$
1
\$\begingroup\$

Standard ML (MLton), 99 93 bytes

open Char
fun g(x::y::r)c=c(x,y)andalso g(y::r)c|g&c=1=1
(fn$ =>g$op<=orelse g$op>=)o explode

Try it online! The last line is an anonymous function. Example usage: ((fn$ =>g$op<=orelse g$op>=)o explode) "somestring". Returns true or false.

Ungolfed code:

open Char
fun g (x::y::r) c = c(x,y) andalso g (y::r) c
  | g     _     c = true
fun h s = g s op<= orelse g s op>=
val f = h o explode
\$\endgroup\$
1
\$\begingroup\$

APL NARS 30 19 chars

{(⊂⍵[⍋⍵])∊(⊂⍵),⊂⌽⍵}

{(⍵[⍋⍵]≡⍵[⍳⍴⍵])∨⍵[⍋⍵]≡⍵[⌽⍳⍴⍵]}

Copy the algo of 'Emigna' in APL...Test

  f¨'ABCDEF' 'ZYX' 'tree' 'q'
1 1 1 1 
  f¨'ABCDC' 'yes' 'deed' 
0 0 0 
\$\endgroup\$
4
  • \$\begingroup\$ Couple of questions: 1) link to interpreter? and 2) bytecount? I get 66 bytes, not 30 chars... \$\endgroup\$
    – steenbergh
    Dec 18, 2017 at 6:50
  • \$\begingroup\$ @steenbergh the request origin of Nars Apl is here nars2000.org the char count is 30 characters; the bytes count would be here 69 bytes. Each character seems more than 2 bytes...In a different code page would be possibly 30 bytes; but the advantage to have Unicode seems to me > of win some codegolf competition \$\endgroup\$
    – user58988
    Dec 18, 2017 at 7:32
  • \$\begingroup\$ @steenbergh this seems to run tio.run/##SyzI0U2pTMzJT///P/… \$\endgroup\$
    – user58988
    Dec 18, 2017 at 7:55
  • \$\begingroup\$ 15: {⍵(⌽⍵)∊⍨⊂⍵[⍋⍵]} \$\endgroup\$
    – Adám
    Mar 6, 2018 at 22:41
1
\$\begingroup\$

q/kdb+, 20 bytes

Solution:

{x in(asc;desc)@\:x}

Examples:

q){x in(asc;desc)@\:x}"tree"
1b
q){x in(asc;desc)@\:x}"yes"
0b
q){x in(asc;desc)@\:x}"ABCDEF"
1b

Explanation:

{x in(asc;desc)@\:x} / the solution
{                  } / anonymous lambda function
                   x / implicit input
               @\:   / apply (@) each left (\:) to x
     (asc;desc)      / list of two functions, sort ascending and descending respectively
 x in                / is x in either sorted/unsorted list?

Notes:

Closest equivalent in K4 would be {x in x@(>:;<:)@\:x} for 20 bytes too...

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

APL (Dyalog Unicode), 9 bytesSBCS

∨/⍬∘⍋⍷⍒,⍋

Try it online!

∨/ Is it anywhere true that (lit. OR-reduction of)

⍬∘⍋ the indices (viz. those that would put the argument into its current order)

 are found in (each position of)

 the indices that would put the argument into descending order

, followed by

 the indices that would put the argument into ascending order?

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