| Bytes | Lang | Time | Link |
|---|---|---|---|
| 005 | Vyxal 3 | 250818T084219Z | Themooni |
| 375 | Bespoke | 250601T152933Z | Josiah W |
| 042 | JavaScript Node.js | 250606T103930Z | l4m2 |
| 048 | AArch64 machine code | 250606T101458Z | 鳴神裁四点一号 |
| 008 | Uiua SBCS | 240103T214926Z | chunes |
| 073 | Tcl | 180425T110510Z | sergiol |
| 113 | Google Sheets | 240103T235840Z | z.. |
| 014 | K ngn/k | 240103T190725Z | coltim |
| 115 | C++ gcc | 180308T174632Z | Toby Spe |
| 004 | Nekomata + e | 230621T065452Z | alephalp |
| 039 | Arturo | 230621T030821Z | chunes |
| 028 | Juby | 230620T190759Z | Jordan |
| 005 | Thunno 2 | 230620T182103Z | The Thon |
| 019 | K ngn/k | 221015T125717Z | oeuf |
| 039 | Ruby | 221015T031727Z | Jordan |
| 002 | Vyxal | 221015T020449Z | DialFros |
| 049 | PowerShell | 190306T045904Z | mazzy |
| 003 | √ å ı ¥ ® Ï Ø ¿ | 170312T222715Z | caird co |
| 013 | Add++ | 180307T223023Z | ASCII-on |
| 026 | Retina | 180309T030310Z | Leo |
| 068 | C | 180308T172304Z | Toby Spe |
| 018 | Add++ | 180306T200729Z | caird co |
| 009 | APL Dyalog Unicode | 180306T223716Z | Adá |
| 033 | Haskell | 170130T200618Z | xnor |
| 020 | q/kdb+ | 171218T143546Z | mkst |
| 019 | APL NARS | 171217T222300Z | user5898 |
| 070 | Swift 4 | 170309T174822Z | Mr. Xcod |
| 093 | Standard ML MLton | 171213T211845Z | Laikoni |
| 035 | Perl | 170130T184443Z | Dada |
| nan | 170130T213419Z | MickyT | |
| 047 | Scala | 170131T013041Z | Aria Ax |
| 015 | Alice | 170415T225946Z | Martin E |
| 039 | 8086 machine code | 170310T114332Z | user5434 |
| 005 | Brachylog | 170309T225727Z | Leo |
| 075 | Röda | 170309T184011Z | fergusq |
| 037 | Python 3.5+ | 170309T182739Z | shooqie |
| 011 | CJam | 170130T183301Z | Business |
| 084 | SmileBASIC | 170216T150242Z | 12Me21 |
| 063 | PHP 7 | 170216T060545Z | user6395 |
| nan | GNU sed | 170203T150918Z | seshouma |
| 093 | Racket | 170202T000328Z | Rodrigo |
| 066 | Clojure | 170131T010543Z | Carcigen |
| 138 | C++ | 170201T180451Z | Steadybo |
| 044 | Ruby | 170131T104746Z | Fig |
| 070 | C gcc | 170131T172825Z | nwellnho |
| 024 | Octave | 170131T115929Z | rahnema1 |
| 052 | Scala | 170130T225519Z | Michael |
| 005 | Pyth | 170130T192312Z | TheBikin |
| 007 | Pushy | 170130T183320Z | FlipTack |
| 066 | PHP | 170130T214903Z | Titus |
| 033 | Mathematica | 170130T214800Z | Martin E |
| 047 | Clojure | 170130T210537Z | NikoNyrh |
| 005 | Jelly | 170130T190536Z | miles |
| 050 | Haskell | 170130T191610Z | nimi |
| 043 | JavaScript ES6 | 170130T174413Z | Luke |
| 005 | Pyth | 170130T200053Z | user4854 |
| 025 | Perl 6 | 170130T190946Z | smls |
| 046 | Haskell | 170130T193951Z | Laikoni |
| 059 | Bash + coreutils | 170130T184629Z | Mitchell |
| 007 | MATL | 170130T185509Z | Luis Men |
| 005 | Pyke | 170130T184751Z | Blue |
| 039 | Python 2 | 170130T175955Z | Rod |
| 008 | MATL | 170130T175532Z | Suever |
| 038 | MATLAB / Octave | 170130T175110Z | Suever |
| 036 | Retina | 170130T175206Z | Martin E |
| 043 | JavaScript ES6 | 170130T174514Z | ETHprodu |
| nan | TIBasic | 170130T174037Z | Timtech |
| 061 | PowerShell | 170130T174021Z | AdmBorkB |
| 005 | Jelly | 170130T174015Z | Jonathan |
| 005 | 05AB1E | 170130T173700Z | Emigna |
Vyxal 3, 5 bytes
⇄⎂/S∨
⇄⎂/S∨
# bottom of stack has infinite copies of input
⇄ # reverse first
⎂ # to both the top 2:
/S # are they invariant by sort?
∨ # logical or
💎
Created with the help of Luminespire.
<script type="vyxal3">
⇄⎂/S∨
</script>
<script>
args=[["ABCEF"],["ZYX"],["no"],["tree"],["q"],["ABCDC"],["yes"],["deed"]]
</script>
<script src="https://themoonisacheese.github.io/snippeterpreter/snippet.js" type="module"/>
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).
JavaScript (Node.js), 42 bytes
([l,...x])=>x.some(c=>c!=l&&x-(x=l<(l=c)))
1 extra byte if must match true and false
At least not longer than sort
AArch64 machine code, 48 bytes
$ objdump -dh f.o
f.o: file format elf64-littleaarch64
Sections:
Idx Name Size VMA LMA File off Algn
0 .text 00000030 0000000000000000 0000000000000000 00000040 2**2
CONTENTS, ALLOC, LOAD, READONLY, CODE
1 .data 00000000 0000000000000000 0000000000000000 00000070 2**0
CONTENTS, ALLOC, LOAD, DATA
2 .bss 00000000 0000000000000000 0000000000000000 00000070 2**0
ALLOC
Disassembly of section .text:
0000000000000000 <f>:
0: 38401509 ldrb w9, [x8], #1
4: d280002b mov x11, #0x1 // #1
8: d280002c mov x12, #0x1 // #1
c: 14000005 b 20 <f+0x20>
10: 6b0a013f cmp w9, w10
14: 9a8bc3eb csel x11, xzr, x11, gt
18: 9a8cb3ec csel x12, xzr, x12, lt // lt = tstop
1c: 2a0a03e9 mov w9, w10
20: 3840150a ldrb w10, [x8], #1
24: 35ffff6a cbnz w10, 10 <f+0x10>
28: aa0c0160 orr x0, x11, x12
2c: d65f03c0 ret
Synopsis
adr x8,.L.string
bl f
// 1-bit value is stored to x0
ret
.data:
.L.string: .asciz "string"
Algorithm
Kinda ported smls's Perl 6 answer. Here is equivalent one:
def f(s: str) -> bool:
flag1, flag2 = True, True
for a,b in zip(s[:-1], s[1:]):
flag1 = False if a>b else flag1
flag2 = False if a<b else flag2
return flag1 or flag2
Original source
/// fn (x8: [*:0]const u8) x0: u1
/// x0: 1 for truthy
.globl f
f:
ldrb w9,[x8],1
mov x11,1; mov x12,1
b 2f
1:
cmp w9,w10
csel x11,xzr,x11,gt
csel x12,xzr,x12,lt
mov w9,w10
2:
ldrb w10,[x8],1
cbnz w10,1b
orr x0,x11,x12
ret
How I tested
$ as -o f.o f.s
$ cat main.s
//! Usage: $0 INPUT
//! Exit status shows
.globl _start
_start:
ldr x8,[sp,16]
bl f
mov x8,93
svc 0
$ as -o main.o main.s
$ ld -o main main.o f.o
$ for x in ABCDEF ZYX no tree q ABCDC yes deed; do ./main "$x"; echo "$x: $?"; done
ABCDEF: 1
ZYX: 1
no: 1
tree: 1
q: 1
ABCDC: 0
yes: 0
deed: 0
$
Tcl, 73 bytes
proc L s {expr {[set C [split $s ""]]in[list [lsort $C] [lsort -de $C]]}}
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)))
K (ngn/k), 14 bytes
{^(<x;>x)?!#x}
Returns 0 for "truthy" inputs and 1 for "falsy" inputs.
!#xgenerate0..len(x)(<x;>x)create a two-length list containing the grade up and grade down of the input(...)?...find the indices in the list; if the indices (as a whole) are not present, this returns0N(the integer null). otherwise, the 0-based index of the matching element is returned (i.e.0or1)^null - returns1if its input is null, and0otherwise
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]}));
}
Arturo, 39 bytes
$->s[some?@[reverse<=split s]=>sorted?]
$->s[ ; a function taking an argument s
some?@[...]=>sorted? ; is at least one item in the list [...] sorted?
split s ; convert s from string to block of length-1 strings
<= ; duplicate
reverse ; reverse; both stack items get trapped in the list
] ; end function
J-uby, 28 bytes
(:>>+(A|:==%:sort)&:any?)%:~
This is equivalent to the below Ruby code, with A equivalent to chars and :~ equivalent to reverse:
->s{[s,s.reverse].any?{_1.chars==_1.chars.sort}
Thunno 2, 5 bytes
r,sṠƇ
Explanation
r,sṠƇ # Implicit input
r, # Pair the input with its reverse
sṠ # Sort the input
Ƈ # Is this in the list?
# Implicit output
K (ngn/k), 19 bytes
{t:!#x;(t~<x)|t~>x}
A little bit lengthy. I have considered using inline assignment, but it seems to be on the same length as this one. Returns 0 for false and 1 for true.
Explanations:
{t:!#x;(t~<x)|t~>x} Main function. Takes x as input
t: Assign variable t to
! Range between 0 to
#x; Length of x (exclusive)
( <x) Ascended version of x
~ Matches (deep equal)
t Variable t
| Or
>x Descended version of x
~ Matches
t Variable t
Ruby, 39 bytes
Returns false for ordered and true for unordered.
->s{!(s+$/+s.reverse)[s.chars.sort*""]}
√ å ı ¥ ® Ï Ø ¿ , 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
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")
Retina, 26 bytes
O`.
V`
$
¶$+¶$+1¶
(.+)¶\1¶
I still haven't seen a Retina program anywhere making use of the history feature, so here it is.
Explanation
O`.
Sort the input
V`
Reverse it
$
¶$+¶$+1¶
Append at the end of the string a newline ¶, followed by the original input to the program $+, another newline, the result of the first stage $+1, and a final newline. What we get is "input sorted descending¶original input¶input sorted ascending¶"
(.+)¶\1¶
Count the pairs of consecutive identical lines. This can be either 0, if the input was unordered, or 1 if the input was ordered.
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]));
}
APL (Dyalog Unicode), 9 bytesSBCS
∨/⍬∘⍋⍷⍒,⍋
∨/ 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?
Haskell, 33 bytes
(%)=scanl1
f s=s==max%s||s==min%s
Thanks to Ørjan Johansen for 1 byte with aliasing scanl1 infix.
Haskell is an interesting language to golf sorting-based challenges because it does not have a built-in sort, barring a lengthy import Data.List. This encourages finding a way to do the task by hand without explicitly sorting.
The code uses scanl1, which folds an operation over the list from left to right, keeping track of the intermediate results. So, scanl1 max has the effect of listing the cumulative maxima of the list, i.e. the maxima of progressively longer prefixes. For example, scanl1 max [3,1,2,5,4] == [3,3,3,5,5].
The same with min checks whether the list is decreasing. The code checks the two cases and combines them with ||.
Compare to other expressions:
(%)=scanl1;f s=s==max%s||s==min%s
f s=or[s==scanl1 q s|q<-[min,max]]
f s=s==scanl1 max s||s==scanl1 min s
f s=any(\q->scanl1 q s==s)[min,max]
f s=any((==s).(`scanl1`s))[min,max]
f s=elem s$(`scanl1`s)<$>[min,max]
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...
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
Swift 4, 70 bytes
var o=Array(readLine()!);var g=o.sorted();print(o==g||o==g.reversed())
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
Perl, 35 bytes
Saved 4 bytes thanks to @Xcali directly, and 4 more indirectly.
31 bytes of code + -pF flag.
@b=reverse@a=sort@F;$_=/@a|@b/x
The code sorts the input, and checks if the inputs matches itself sorted (or in reverse order).
R, 48 50 61 bytes
As an unnamed function
function(s)sd(range(sign(diff(utf8ToInt(s)))))<1
Thanks to @guiseppe for a few extra bytes.
charToRaw takes s and splits into a raw vector. This is converted to integers and a diff applied. sign makes the diffs a single unit. range reduces the vector to it's minimum and maximum. Then if the standard deviation sd is less than 1 it is TRUE
Scala, 47 bytes
def f(x:String)=x==x.sorted|x==x.sorted.reverse
Alice, 15 bytes, non-competing
/o.zz./
@inssR\
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.
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
Brachylog, 5 bytes
I've tried to find a 4 bytes solution without success, so for now here's the most interesting 5 bytes solution I've found:
:No₎?
o, the ordering function, can take a parameter: 0 means ascending order, 1 means descending order. We set that parameter to an unbound variable N. Brachylog will try different values for N (only 0 or 1 are possible), try to unify the result with the input, and return whether any of those tries succeeded.
Röda, 75 bytes
f s{x=[split(s,sep="")];[s=[sort(x)]&""or s=[sort(x,cmp={|a,b|[a>b]})]&""]}
Alternative solution:
f s{x=[split(s,sep="")];[s in[[sort(x)]&"",[sort(x,cmp={|a,b|[a>b]})]&""]]}
It is possible that shorter solutions exist, but I couldn't find them now.
Python 3.5+, 37 bytes
lambda a:sorted(a)in([*a],[*a][::-1])
CJam, 12 11 bytes
q_$_W%+\#)g
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)
SmileBASIC, 91 89 84 bytes
DIM A[1]INPUT S$WHILE LEN(S$)>1PUSH A,ASC(POP(S$))-ASC(POP(S$))WEND?MIN(A)*MAX(A)==0
Makes an array of the differences between consecutive characters (and an extra 0), and checks if either the min or max is 0.
PHP 7, 63 bytes
for($s=$argv[1];$s[++$i]&a;)${$s[$i-1]<=>$s[$i]}=1;echo!$${-1};
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
Racket, 93 bytes
(define(f s)(let([t(string->list s)])(or(equal?(sort t char<=?)t)(equal?(sort t char>=?)t))))
Ungolfed:
(define (lex-sorted? string)
(let ([char-list (string->list string)])
(or
(equal? (sort char-list char<=?) char-list)
(equal? (sort char-list char>=?) char-list))))
Using the sort then compare to original approach
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))))
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;}
C (gcc), 70 bytes
o(s,a)char*s;{for(a=0;s[1];s++)a|=s[1]-*s&64|*s-s[1]&32;return a!=96;}
I was hoping to find a shorter solution based on a recursive function, but it didn't work out due to the output requirement. So here's an imperative approach. At least, C's operator precedence works nicely for the inner loop statement.
Scala, 52 bytes
def p(s:String)=List(s,s.reverse).contains(s.sorted)
Pyth, 5 bytes
}Q_BS
A program that takes input of a "quoted string" and prints True or False as appropriate.
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
Pushy, 7 bytes
ogoGo|#
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
PHP, 66 bytes
$a=$s=$r=str_split($argv[1]);sort($s);rsort($r);echo$s==$a|$r==$a;
takes input from command line argument. Run with -r.
Mathematica, 33 bytes
0<=##||##>=0&@@ToCharacterCode@#&
Based on this tip. Unfortunately, I have to use ToCharacterCode instead of Characters, because <= and >= don't compare strings.
Clojure, 47 bytes
#(let[c(map int %)a apply](or(a <= c)(a >= c)))
Jelly, 4 5 bytes
Ṣm0ẇ@
Originally was Ṣm0w at four bytes.
Explanation
Ṣm0ẇ@ Input: string S
Ṣ Sort S
m0 Concatenate sort(S) with reverse(sort(S))
ẇ@ Sublist exists? Check if S is contained in the previous result
Haskell, 54 50 bytes
t a=or[and(zipWith(<=)`f`tail$a)|f<-[(=<<),(<*>)]]
Usage example: t "defggh" -> True. Try it online!.
Maybe using sort like may other answers is shorter although it requires import Data.List. Here's a different approach:
For every function f from [(=<<),(<*>)], calculate and(zipWith(<=)`f`tail$a) and require any of the results to be True. The functions are
((=<<) (zipWith(<=)) tail) a
((<*>) (zipWith(<=)) tail) a
which both perform comparisons of neighbor elements of the input list a with <=, but one with the arguments flipped resulting in a >=. and checks if all comparisons are True.
JavaScript (ES6) 74 62 50 47 43 bytes
([...a],b=a+'')=>b==a.sort()|b==a.reverse()
After some golfing and bugfixing, this answer ended up being pretty much the same as ETHProduction's, so please check his answer out and give it a +1.
Pyth, 5 bytes
}SQ,_
Explanation:
}SQ,_
}SQ Check if the sorted input is a member ...
,_QQ ... of [reversed input, input]
Perl 6, 25 bytes
{[le] .comb or[ge] .comb}
How it works:
.combsplits the input into a sequence of characters.leandgeare the "less or equal" and "greater or equal" string comparison operators.[ ]around an infix operator, reduces ("folds") the argument list with that operator. (It's smart enough to return True if the input has only zero or one characters.)orreturns True if the expressions on either side of it is true.
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.
Bash + coreutils, 59 bytes
f()(sed 's/\(.\)/\1\
/g'<<<$s|grep .|sort -c$1)
s=$1
f||f r
The input string is passed as an argument.
The output is returned in the exit code (0 for truthy, 1 for falsy, as usual), as allowed by PPCG I/O methods.
MATL, 7 bytes
dZSuz2<
Try it online! Or verify all test cases.
d % Implicitly input string. Push array of consecutive differences of code points
ZS % Sign. Transforms each entry into 1, 0 or -1
u % Unique
z % Number of nonzeros
2< % Is it less than 2? Implicit display
MATL, 8 bytes
tPvGSXma
Explanation
% Implicitly grab the input as a string
tP % Create a copy that is reversed
v % Vertically concatenate these
GS % Grab the input again and sort it
Xm % Check if each row of the normal and reversed matrix is equal to the sorted one
a % Check if either row matched
% Implicitly display the result
JavaScript (ES6), 43 bytes
([...s],q=s+"")=>q==s.sort()|q==s.reverse()
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
PowerShell, 61 bytes
param($a)$a-in-join(($b=[char[]]$a)|sort),-join($b|sort -des)
Takes input $a, then checks whether it's -in a two-element array. The array is formed by taking $a, casting it as a char-array, storing that in $b for later, piping it to sort-object which sorts lexically. The other element is $b sorted in -descending order.
Jelly, 5 bytes
,Ue@Ṣ
How?
,Ue@Ṣ - Main link: string
, - pair string with
U - reverse(string)
Ṣ - sorted(string)
e@ - exists in with reversed arguments
05AB1E, 5 bytes
Â)¤{å
Explanation
Â) # pair the input with it's reverse in a list
¤{ # get a copy of the reverse and sort it
å # check if the sorted copy is in the list of [input,reverse_input]