Is this word Lexically Ordered?

44

3

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

steenbergh

Posted 2017-01-30T17:32:48.407

Reputation: 7 772

1Can you clarify about the output: does the truthy value need be the same regardless of what input is given? – Business Cat – 2017-01-30T19:12:25.793

1@BusinessCat I've added a clarification. – steenbergh – 2017-01-30T20:01:44.117

What if your language's implementation of a string is a list of characters? Many of the answers posted here are using such languages... – theonlygusti – 2017-01-30T20:40:35.067

@theonlygusti If your language of choice treats strings as lists of characters, that's fine. If your language has a string type, input may not be given as a list. – steenbergh – 2017-01-30T21:35:06.997

1If 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. – FlipTack – 2017-01-30T21:50:47.980

@FlipTack You're right. What I mean is that it doesn't matter what value resembles TRUE or FALSE, as long as it is always the same value. – steenbergh – 2017-01-30T21:53:19.270

3

related: Find the Wavy Words!

– Titus – 2017-01-30T22:25:46.127

Has any one got to deal well with all the invalid values? I found no one in a quick look – Patrick Bard – 2017-02-01T16:47:17.623

@PatrickBard No, they're marked invalid because those cases do not need to be handled. Submissions need not concern themselves with those inputs. – steenbergh – 2017-02-01T16:49:33.867

@steenbergh I see, I understood this different the first time I read. My mistake. – Patrick Bard – 2017-02-01T17:08:09.610

Can we output 0 for ordered, and 1 for not? – caird coinheringaahing – 2018-03-06T19:38:06.827

@cairdcoinheringaahing Yes you can, as long as it's consistent between all cases. – steenbergh – 2018-03-07T06:49:47.830

Some more test cases: deer, AAAAA, aabb (we can't infer direction from only first or last pair, order has to continue after a double letter). – Toby Speight – 2018-03-08T16:13:40.800

@TobySpeight all truthy, and imo all covered by existing cases. – steenbergh – 2018-03-08T16:29:21.767

Sorry, I should have said that they are all truthy, and that I meant them as stress-tests for solutions that take unjustified short-cuts to pass the suite. – Toby Speight – 2018-03-08T17:48:40.743

@TobySpeight do you have an example of a solution that does this? - I'm a little reluctant to change a question this old... – steenbergh – 2018-03-09T06:28:20.643

No, I spotted the problem before I posted my answer. – Toby Speight – 2018-03-09T08:59:56.407

Answers

8

05AB1E, 5 bytes

Â)¤{å

Try it online!

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]

Emigna

Posted 2017-01-30T17:32:48.407

Reputation: 50 798

{¹å for 4, deleted my answer. Didn't notice the use of bifurcate, mine was too similar. – Magic Octopus Urn – 2017-01-30T17:46:04.967

@carusocomputing: that would unfortunately only check if the input is in the reverse of the sorted input. – Emigna – 2017-01-30T17:47:33.620

Or equal to the sorted input. aba => ['aab', 'baa'] => is in? => 0| aab => same => 1 – Magic Octopus Urn – 2017-01-30T17:47:54.973

@carusocomputing: The sorted input is ignored as it's below the reverse on the stack. You never pair them in a list.

– Emigna – 2017-01-30T17:49:28.497

Coulda sworn bifurcate wrapped output; nvm, ignore me. – Magic Octopus Urn – 2017-01-30T17:50:47.143

17

Python 2, 53 44 40 39 bytes

lambda a:`sorted(a)`[2::5]in(a,a[::-1])

Try it online!

Rod

Posted 2017-01-30T17:32:48.407

Reputation: 17 588

Nice, but it returns true for invalid values

– Patrick Bard – 2017-02-01T16:46:01.917

5@PatrickBard mixed case is an invalid input, does not have to be handled – Rod – 2017-02-01T16:51:40.100

13

Haskell, 33 bytes

(%)=scanl1
f s=s==max%s||s==min%s

Try it online!

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]

xnor

Posted 2017-01-30T17:32:48.407

Reputation: 115 687

Actually your version with || wins if you define (?)=scanl1. – Ørjan Johansen – 2017-12-17T20:59:31.537

11

Perl 6, 25 bytes

{[le] .comb or[ge] .comb}

How it works:

  • .comb splits the input into a sequence of characters.
  • le and ge are 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.)
  • or returns True if the expressions on either side of it is true.

smls

Posted 2017-01-30T17:32:48.407

Reputation: 4 352

10

JavaScript (ES6), 43 bytes

([...s],q=s+"")=>q==s.sort()|q==s.reverse()

ETHproductions

Posted 2017-01-30T17:32:48.407

Reputation: 47 880

Didn't know you could modify variables in the argument itself. Nice! – Luke – 2017-01-30T18:13:45.290

1

@Luke This is just a tricky use of default parameters: if you were to call the function with a second argument, q would be set to that value instead.

– ETHproductions – 2017-01-30T19:50:15.720

I actually meant the spread operator which (in this case) converts it into an array right away. – Luke – 2017-01-30T20:05:45.243

Oh, OK. Yeah, destructuring assignments are really handy too ;-) – ETHproductions – 2017-01-30T20:09:06.400

Clever using the mutating .sort() to implicitly sort in the reverse check – Cyoce – 2017-02-02T01:56:23.730

7

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

Luis Mendo

Posted 2017-01-30T17:32:48.407

Reputation: 87 464

It returns true for all invalid cases

– Patrick Bard – 2017-02-01T16:35:17.580

1@PatrickBard As the directions say, none of those need to be handled. – Suever – 2017-02-01T16:57:05.847

6

Clojure, 47 bytes

#(let[c(map int %)a apply](or(a <= c)(a >= c)))

NikoNyrh

Posted 2017-01-30T17:32:48.407

Reputation: 2 361

Couldn't figure out how to decide which operator to apply concisely. This is great. – Carcigenicate – 2017-01-31T00:35:39.337

Wait you can put builtin function names into variables in Clojure? Huh, that's cool. It does make the <= and >= look infix though, which is really weird. – clismique – 2017-02-01T10:47:40.540

(let[+ *](+ 2 3)) = 6 :D It works on any function but apparently not on macros: "Can't take value of a macro" – NikoNyrh – 2017-02-01T12:01:07.083

6

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

Try it online!

MickyT

Posted 2017-01-30T17:32:48.407

Reputation: 11 735

You can save 9 bytes using function(s,d=utf8ToInt(s))all(d==sort(d)) or function(s,d=utf8ToInt(s))!is.unsorted(d) – mnel – 2017-02-01T22:19:30.540

Or down to 34 bytes with !is.unsorted(utf8ToInt(scan(,''))) – mnel – 2017-02-01T22:24:54.270

@mnel unfortunately these do not handle the reverse sort eg cba and the last one would require a cat() to make it a full program – MickyT – 2017-02-01T22:59:03.073

Save 5 bytes with function(s)all(!diff(order(utf8ToInt(s)),,2)) (works with the reverse sort too!) – mnel – 2017-02-02T22:03:15.063

@mnel sorry again, that fails for tree – MickyT – 2017-02-03T00:42:25.040

[facepalm]. One final attempt, function(s)prod(sign(diff(unique(utf8ToInt(s))))) (outputs 1 for true, -1 for false), saves a byte. – mnel – 2017-02-03T01:01:50.700

@mnel apologies this fails on quite a number. Try this 'abcddcba' – MickyT – 2017-02-03T01:18:55.030

Let us continue this discussion in chat.

– MickyT – 2017-02-03T01:22:36.477

there's a beautiful 48 byte solution if you replace diff with sd and <2 with <1 for your second submission, so function(s)sd(range(sign(diff(utf8ToInt(s)))))<1 – Giuseppe – 2017-12-13T16:23:39.587

6

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.

Try it online!

nwellnhof

Posted 2017-01-30T17:32:48.407

Reputation: 10 037

5

MATL, 8 bytes

tPvGSXma

Try it Online!

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

Suever

Posted 2017-01-30T17:32:48.407

Reputation: 10 257

Nice, but it returns true for '\n' and 'Hello' :/ – Patrick Bard – 2017-02-01T16:41:43.733

1@PatrickBard The input will be all the same case and will only be [A-Za-z] as stated in the initial post. They are in the "invalid" section because they explicitly don't need to be handled. – Suever – 2017-02-01T16:55:56.340

5

Jelly, 4 5 bytes

Ṣm0ẇ@

Try it online!

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

miles

Posted 2017-01-30T17:32:48.407

Reputation: 15 654

I was sure there was a four byter, but couldn't think of it! – Jonathan Allan – 2017-01-30T20:23:45.947

1...unfortunately the OP has clarified output is not truthy/falsy, but two distinct values. Four bytes still possible with though, I believe. Edit: ugh Ṣm0ẇ@. – Jonathan Allan – 2017-01-30T20:28:23.357

@JonathanAllan Unfortunate since it did meet the original rule of using the true/false style of the language. Another form might be Ṣẇm0$. If the argument order wasn't different for w and ... – miles – 2017-01-30T20:59:34.283

Nice, but it returns true on invalid values

– Patrick Bard – 2017-02-01T16:43:41.923

@PatrickBard Huh? '\n' and 'Hello' are perfectly valid values. – Erik the Outgolfer – 2017-03-12T12:04:37.547

5

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.

Martin Ender

Posted 2017-01-30T17:32:48.407

Reputation: 184 808

4

PowerShell, 61 bytes

param($a)$a-in-join(($b=[char[]]$a)|sort),-join($b|sort -des)

Try it online!

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.

AdmBorkBork

Posted 2017-01-30T17:32:48.407

Reputation: 41 581

4

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

Try it online!

The code sorts the input, and checks if the inputs matches itself sorted (or in reverse order).

Dada

Posted 2017-01-30T17:32:48.407

Reputation: 8 279

Slightly different method, but cuts it down to 38 bytes: Try it online!

– Xcali – 2017-12-14T03:23:17.610

@Xcali Very nice, thanks. We can then get rid of $"=$, and use /x modifier instead to save 5 more bytes. – Dada – 2017-12-14T07:09:28.460

3

Jelly, 5 bytes

,Ue@Ṣ

Try it online!

How?

,Ue@Ṣ - Main link: string
,     - pair string with
 U    - reverse(string)
    Ṣ - sorted(string)
  e@  - exists in with reversed arguments

Jonathan Allan

Posted 2017-01-30T17:32:48.407

Reputation: 67 804

3

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.

Mitchell Spector

Posted 2017-01-30T17:32:48.407

Reputation: 3 392

3

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.

Titus

Posted 2017-01-30T17:32:48.407

Reputation: 13 814

3

Ruby, 44 bytes

->s{[s,s.reverse].include?s.chars.sort.join}

Try it online!

Fig

Posted 2017-01-30T17:32:48.407

Reputation: 31

3

Racket, 93 bytes

(define(f s)(let([t(string->list s)])(or(equal?(sort t char<=?)t)(equal?(sort t char>=?)t))))

Try it online!

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

Rodrigo Ruiz Murguía

Posted 2017-01-30T17:32:48.407

Reputation: 81

3

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₎?

Try it online!

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.

Leo

Posted 2017-01-30T17:32:48.407

Reputation: 8 482

Seems to no longer work :( o?|o₁? works for an extra byte tho

– hakr14 – 2018-08-27T00:54:54.137

Seems to work if you replace the colon with a semicolon. Another one-byte-longer variant would be o{|↔}?. – Unrelated String – 2019-03-20T22:00:25.907

2

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.

Luke

Posted 2017-01-30T17:32:48.407

Reputation: 4 675

Fixed the bug.. – Luke – 2017-01-30T18:02:54.623

1You caught me, I posted the comment before editing... – Luke – 2017-01-30T18:04:34.813

I found the cause of the bug, and I now fixed it properly by arranging everything cleverly... – Luke – 2017-01-30T18:08:28.620

Bug is back... https://repl.it/FZrs/2

– steenbergh – 2017-01-30T18:12:45.813

1Well, this is pretty much @ETHProduction's answer now, so I added a notice. Please +1 his answer. – Luke – 2017-01-30T20:14:11.873

2

MATLAB / Octave, 38 bytes

@(x)any(all([x;flip(x)]'==sort(x)',1))

Online demo

Suever

Posted 2017-01-30T17:32:48.407

Reputation: 10 257

2

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)

Business Cat

Posted 2017-01-30T17:32:48.407

Reputation: 8 927

2

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

FlipTack

Posted 2017-01-30T17:32:48.407

Reputation: 13 242

This does not return one distinct true-value. – steenbergh – 2017-01-30T18:35:58.857

1

@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.

– FlipTack – 2017-01-30T19:11:46.023

If Pushy has a bitwise OR operator, that should work instead. – ETHproductions – 2017-01-30T19:20:13.110

@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. – steenbergh – 2017-01-30T21:38:47.667

@steenbergh The meta consensus is there for a reason and makes sense, but if you insist... – FlipTack – 2017-01-30T21:39:46.773

2

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.

nimi

Posted 2017-01-30T17:32:48.407

Reputation: 34 639

2

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

TheBikingViking

Posted 2017-01-30T17:32:48.407

Reputation: 3 674

You can save a byte (and become the shortest answer) by replacing }Q with /, which uses an implicit Q. – isaacg – 2017-03-09T18:33:22.407

2

Scala, 47 bytes

def f(x:String)=x==x.sorted|x==x.sorted.reverse

Aria Ax

Posted 2017-01-30T17:32:48.407

Reputation: 321

2

Octave, 24 bytes

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

Try It Online!

rahnema1

Posted 2017-01-30T17:32:48.407

Reputation: 5 435

2

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

seshoumara

Posted 2017-01-30T17:32:48.407

Reputation: 2 878

2

Swift 4, 70 bytes

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

Try it online!

Mr. Xcoder

Posted 2017-01-30T17:32:48.407

Reputation: 39 774

2

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

user5434231

Posted 2017-01-30T17:32:48.407

Reputation: 1 576

2

√ å ı ¥ ® Ï Ø ¿ , 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

caird coinheringaahing

Posted 2017-01-30T17:32:48.407

Reputation: 13 702

2

Add++, 28 18 bytes

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

Try it online!

caird coinheringaahing

Posted 2017-01-30T17:32:48.407

Reputation: 13 702

2

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")

ASCII-only

Posted 2017-01-30T17:32:48.407

Reputation: 4 687

1

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

Timtech

Posted 2017-01-30T17:32:48.407

Reputation: 12 038

1

Retina, 36 bytes

Byte count assumes ISO 8859-1 encoding.

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

Try it online!

Martin Ender

Posted 2017-01-30T17:32:48.407

Reputation: 184 808

1

Pyke, 5 bytes

SD_]{

Try it here!

S     -   sorted(input)
   ]  -  [^, v]
 D    -    ^
  _   -   reverse(^)
    { - input in ^

Blue

Posted 2017-01-30T17:32:48.407

Reputation: 26 661

1

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.

Laikoni

Posted 2017-01-30T17:32:48.407

Reputation: 23 676

1

Pyth, 5 bytes

}SQ,_

Explanation:

}SQ,_
}SQ      Check if the sorted input is a member ...
   ,_QQ  ... of [reversed input, input]

user48543

Posted 2017-01-30T17:32:48.407

Reputation:

1

Scala, 52 bytes

def p(s:String)=List(s,s.reverse).contains(s.sorted)

Malvolio

Posted 2017-01-30T17:32:48.407

Reputation: 141

1

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))))

Carcigenicate

Posted 2017-01-30T17:32:48.407

Reputation: 3 295

Wouldn't it be shorter if you remove r altogether and put the definition of r in the second equality check? – clismique – 2017-02-01T10:47:03.520

@Qwerp-Derp Thanks, I forgot to inline that in my golfed version. – Carcigenicate – 2017-02-01T21:27:15.313

1

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;}

Steadybox

Posted 2017-01-30T17:32:48.407

Reputation: 15 798

1

PHP 7, 63 bytes

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

user63956

Posted 2017-01-30T17:32:48.407

Reputation: 1 571

1

Python 3.5+, 37 bytes

lambda a:sorted(a)in([*a],[*a][::-1])

shooqie

Posted 2017-01-30T17:32:48.407

Reputation: 5 032

1

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.

fergusq

Posted 2017-01-30T17:32:48.407

Reputation: 4 867

Why not s/"" instead of split? – user41805 – 2017-03-12T15:41:10.910

@KritixiLithos The / operator was implemented after this challenge. – fergusq – 2017-03-12T15:46:38.113

1

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.

Martin Ender

Posted 2017-01-30T17:32:48.407

Reputation: 184 808

1

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

Laikoni

Posted 2017-01-30T17:32:48.407

Reputation: 23 676

1

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 

RosLuP

Posted 2017-01-30T17:32:48.407

Reputation: 3 036

Couple of questions: 1) link to interpreter? and 2) bytecount? I get 66 bytes, not 30 chars... – steenbergh – 2017-12-18T06:50:34.330

@steenbergh the request origin of Nars Apl is here http://www.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

– RosLuP – 2017-12-18T07:32:13.123

15: {⍵(⌽⍵)∊⍨⊂⍵[⍋⍵]}

– Adám – 2018-03-06T22:41:20.453

1

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

streetster

Posted 2017-01-30T17:32:48.407

Reputation: 3 635

1

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?

Adám

Posted 2017-01-30T17:32:48.407

Reputation: 37 779

1

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]));
}

Toby Speight

Posted 2017-01-30T17:32:48.407

Reputation: 5 058

1

C++ (gcc), 125 124 123 bytes

Very boring obvious solution. We use GCC's internal header to save many includes. Conveniently, std::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(std::string s){return std::is_sorted(s.begin(),s.end())|std::is_sorted(s.rbegin(),s.rend());}

Toby Speight

Posted 2017-01-30T17:32:48.407

Reputation: 5 058

1

Retina, 26 bytes

O`.
V`
$
¶$+¶$+1¶
(.+)¶\1¶

Try it online!

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.

Leo

Posted 2017-01-30T17:32:48.407

Reputation: 8 482

1

Tcl, 75 bytes

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

Try it online!

sergiol

Posted 2017-01-30T17:32:48.407

Reputation: 3 055

1

PowerShell, 49 bytes

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

Try it online!

mazzy

Posted 2017-01-30T17:32:48.407

Reputation: 4 832

0

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.

12Me21

Posted 2017-01-30T17:32:48.407

Reputation: 6 110

-1

Python, 95 bytes

t=[ord(c)for c in input()]
print(all(map(lambda i:i>0,[t[i+1]-t[i] for i in range(len(t)-1)])))

Roman Gräf

Posted 2017-01-30T17:32:48.407

Reputation: 2 915

1

This seems to return false on tree and dcba. Words that are in reverse lexical order should also return true. TIO

– steenbergh – 2017-02-02T07:27:26.430