title: Is this word Lexically Ordered?

text:
# Question
Title: Is this word Lexically Ordered?
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

```

# Answer
# 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]

```
> 9 votes

# Answer
# Python 2, ~~53~~ ~~44~~ ~~40~~ 39 bytes

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

```

Try it online!
> 17 votes

# Answer
# 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]

```
> 14 votes

# Answer
# 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.
> 11 votes

# Answer
# JavaScript (ES6), 43 bytes

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

```
> 10 votes

# Answer
# 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

```
> 7 votes

# Answer
# 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

```
> 6 votes

# Answer
## Clojure, 47 bytes

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

```
> 6 votes

# Answer
# 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!
> 6 votes

# Answer
# 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!
> 6 votes

# Answer
# 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

```
> 5 votes

# Answer
## 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.
> 5 votes

# Answer
# 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 `-des`cending order.
> 4 votes

# Answer
# 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).
> 4 votes

# Answer
# 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.
> 4 votes

# Answer
# 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.
> 4 votes

# Answer
# 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

```
> 3 votes

# Answer
## 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`.
> 3 votes

# Answer
# 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`.
> 3 votes

# Answer
# Ruby, 44 bytes

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

```

Try it online!
> 3 votes

# Answer
# 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
> 3 votes

# Answer
# K (ngn/k), 19 bytes

```
{t:!#x;(t~<x)|t~>x}

```

Try it online!

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

```
> 3 votes

# Answer
# Thunno 2, 5 bytes

```
r,sṠƇ

```

Attempt This Online!

#### Explanation

```
r,sṠƇ  # Implicit input
r,     # Pair the input with its reverse
  sṠ   # Sort the input
    Ƈ  # Is this in the list?
       # Implicit output

```
> 3 votes

# Answer
# 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}

```

Attempt This Online!
> 3 votes

# Answer
# Arturo, 39 bytes

```
$->s[some?@[reverse<=split s]=>sorted?]

```

Try it!

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

```
> 3 votes

# Answer
# Nekomata \+ `-e`, 4 bytes

```
oᶜ↔=

```

Attempt This Online!

```
o       Sort
 ᶜ↔     Optionally reverse
   =    Check equality

```
> 3 votes

# Answer
# 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`.
> 2 votes

# Answer
# MATLAB / Octave, 38 bytes

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

```

Online demo
> 2 votes

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

```
> 2 votes

# Answer
# 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

```
> 2 votes

# Answer
# 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

```
> 2 votes

# Answer
# Scala, 47 bytes

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

```
> 2 votes

# Answer
# Octave, 24 bytes

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

```

Try It Online!
> 2 votes

# Answer
## 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

```
> 2 votes

# Answer
# Swift 4, 70 bytes

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

```

Try it online!
> 2 votes

# Answer
## Python 3.5+, 37 bytes

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

```
> 2 votes

# Answer
# 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

```
> 2 votes

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

```
> 2 votes

# Answer
# Add++, ~~28~~ 18 bytes

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

```

Try it online!
> 2 votes

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

```
> 2 votes

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

```
> 2 votes

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

```
> 2 votes

# Answer
# Vyxal, 2 bytes

```
ÞȮ

```

Try it Online!

Simple means `is ordered?`
> 2 votes

# Answer
# Ruby, 39 bytes

Returns `false` for ordered and `true` for unordered.

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

```

Attempt This Online!
> 2 votes

# Answer
# K (ngn/k), 14 bytes

```
{^(<x;>x)?!#x}

```

Try it online!

Returns `0` for "truthy" inputs and `1` for "falsy" inputs.

* `!#x` generate `0..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 returns `0N` (the integer null). otherwise, the 0-based index of the matching element is returned (i.e. `0` or `1`)
* `^` null - returns `1` if its input is null, and `0` otherwise
> 2 votes

# Answer
# 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

```
> 1 votes

# Answer
## Retina, 36 bytes

Byte count assumes ISO 8859-1 encoding.

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

```

Try it online!
> 1 votes

# Answer
## Pyke, 5 bytes

```
SD_]{

```

Try it here!

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

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# Pyth, 5 bytes

```
}SQ,_

```

### Explanation:

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

```
> 1 votes

# Answer
## Scala, 52 bytes

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

```
> 1 votes

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

```
> 1 votes

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

```
> 1 votes

# Answer
# PHP 7, 63 bytes

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

```
> 1 votes

# Answer
# 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.
> 1 votes

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

```
> 1 votes

# Answer
# 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

```
> 1 votes

# Answer
# 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

```
> 1 votes

# Answer
# 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...
> 1 votes

# Answer
# APL (Dyalog Unicode), 9 bytes<sup>SBCS</sup>

```
∨/⍬∘⍋⍷⍒,⍋

```

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?
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# Tcl, 75 bytes

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

```

Try it online!
> 1 votes

# Answer
# PowerShell, 49 bytes

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

```

Try it online!
> 1 votes

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

```
> 1 votes

# Answer
# 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.
> 0 votes

# Answer
# Uiua <sup>SBCS</sup>, 9 bytes

```
∊:⊏⊟⊃⍖⍏..

```

Try it!
> 0 votes

---
Tags: code-golf, string
---


title: Landmine Number III

text:
# Question
Title: Landmine Number III
## Background

You have again, again been given the task of calculating the number of landmines in a field. But this time, the field is foggy.

You must calculate the landmine score given a list/string of numbers, the landmine number, and the land distance (all are numbers).

The landmine number tells you where landmines are.

For each digit in the landscape (first number), if the digits left and right add to the landmine number, add the digit in focus to the landmine score.

Note: The very first and last numbers cannot have landmines because they have no numbers to the left and right of them respectively.

Because the field is foggy however, we need to clear the fog and expand the landscape. This is done by repeatedly adding the last two digits of the given landscape and appending it to the end. If the result of the addition has two digits, append the ones digit. This is done until the length of the landscape is equal to the land distance.

## Your Task

* Sample Input: The landscape, the landmine number, and the land distance. It is given that the land distance is greater than or equal to the length of the number landscape. It is also given that the landscape contains at least two digits.
* Output: Return the landmine score.

**Explained Examples** Note: Expansions are grouped in 5 for demonstration.

```
Input => Output
178 9 11 => 16

When expanded, the landscape is:
17853 81909 9

Of these:
178 => 1+8 = 9, so add 7
099 => 0+9 = 9, so add 9

7+9 = 16

```

```
Input => Output
012 7 21 => 16

Expanding:
01235 83145 94370 77415 6

Of these:
235, 2+5 = 7, add 3
314, 3+4 = 7, add 1
077, 0+7 = 7, add 7
156, 1+6 = 7, add 5

3+1+7+5 = 16

```

```
Input => Output
10 10 10 => 0

Expanding:
10112 35831

Of these, there are no landmines.

```

```
Input => Output
090909 0 10 => 18

Expanding:
09090 99875

Of these:
090, 0+0=0, add 9
090, 0+0=0, add 9

9+9=18

```

**Test Cases**

```
Input => Output
178 9 11 => 16
012 7 21 => 16
10 10 10 => 0
090909 0 10 => 18

00 0 99 => 0
00 99 99 => 0
91900 18 42 => 1
123121 10 15 => 18
1111111111 2 10 => 8

```

This is , so shortest answer wins.

...

**Landmine Number Series**

# Answer
> 7 votes
# Python 3.8+, ~~91~~ ~~85~~ ~~84~~ ~~82~~ ~~80~~ 78 bytes

```
f=lambda s,n,d:d-1and f((s:=s+[sum(s[-2:])%10])[1:],n,d-1)+s[1]*(s[0]+s[2]==n)

```

Try it online!

Takes a list of `int` digits, the landmine number and then the land number

## Explanation

Recursive implementation where `f` is called `d-1` times. In every call, the digit `sum(s[-2:])%10` is appended to `s`. This may add extra digits to the landscape, but the function will terminate before reaching them so this is not a problem. Additionally, the recursive call removes the first digit of the landscape (`(...)[1:]`) so that extra parameters are avoided, and so that `s[1]*(s[0]+s[2]==n)` can use single digit numbers to index the list, saving bytes.

# Answer
> 5 votes
# Vyxal `d`, 96 bitsv1, 12 bytes

```
‡+tdḞẎ3lƛy$∑⁰=*

```

Try it Online!

I do love a good opportunity to use a generator. Takes landmine digits as a list of digits, land area number, then landmine number.

## Explained

```
‡+tdḞẎ3lƛy$∑⁰=*
‡  dḞ            # A generator where each term:
  t              #   is the tail of
 +               #   the sum of the last 2 terms
# The generator takes the landmine digits as the initial list of terms and works from there.
     Ẏ           # Take the first land-area digits of the generator
      3lƛ        # And to each overlapping window of size 3:
         y$      #   Uninterleave and swap so that the first and last item of the window are on the top of the stack in a list
            ⁰=   #   Check whether the sum of that list is equal to the landmine number
              *  #   And multiply the middle of the window by that. If the sum was equal, this will return the number as-is. Otherwise, it will return 0.
# The d flag flattens the result of the map before summing the list.

 Created with the help of Luminespire at https://vyxal.github.io/Luminespire

```

# Answer
> 3 votes
# Mathematica, 164 bytes

Golfed version. Try it online!

```
f[l_,m_,d_]:=Module[{a=l,b=0},While[Length[a]<d,AppendTo[a,Mod[Last[a]+If[Length[a]>1,a[[-2]],0],10]]];For[i=2,i<Length@a,i++,If[a[[i-1]]+a[[i+1]]==m,b+=a[[i]]]];b]

```

Ungolfed version. Try it online!

```
LandmineScore[landscape_List, mineNum_, dist_] :=
Module[{land = landscape, score = 0},
  While[Length[land] < dist,
    If[Length[land] > 1,
        AppendTo[land, Mod[Last[land] + land[[-2]], 10]],
        AppendTo[land, land[[-1]]]
    ]
  ];
  For[i = 2, i < Length[land], i++,
    If[land[[i - 1]] + land[[i + 1]] == mineNum,
      score += land[[i]]
    ]
  ];
  score
]

Print[LandmineScore[{1, 7, 8}, 9, 11]];  (* 16 *)
Print[LandmineScore[{0, 1, 2}, 7, 21]];  (* 16 *)
Print[LandmineScore[{1, 0}, 10, 10]];  (* 0 *)
Print[LandmineScore[{0, 9, 0, 9, 0, 9}, 0, 10]];  (* 18 *)
Print[LandmineScore[{0, 0}, 0, 99]];  (* 0 *)
Print[LandmineScore[{0, 0}, 99, 99]];  (* 0 *)
Print[LandmineScore[{9, 1, 9, 0, 0}, 18, 42]];  (* 1 *)
Print[LandmineScore[{1, 2, 3, 1, 2, 1}, 10, 15]];  (* 18 *)
Print[LandmineScore[{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, 2, 10]];  (* 8 *)

```

# Answer
> 3 votes
# Charcoal, 39 bytes

```
ＮθＮηＦη≔⁺ζＩ﹪Σ…⮌ζ²χζＩΣΦ✂ζ¹⊖η¹⁼θΣ⁺§ζκ§ζ⁺²κ

```

Try it online! Link is to verbose version of code. Takes the landmine number and field length as the first two inputs. Explanation:

```
ＮθＮη

```

Input the landmine number and field length.

```
Ｆη≔⁺ζＩ﹪Σ…⮌ζ²χζ

```

Extend the field so it's at least as long as the required length.

```
ＩΣΦ✂ζ¹⊖η¹⁼θΣ⁺§ζκ§ζ⁺²κ

```

Slice out the part that can have landmines, then filter out those digits whose neighbours have the wrong sum, then take the digital sum of the result.

# Answer
> 2 votes
# 05AB1E, 16 bytes

```
λ£₂+θ}Ð¦¦+IQ0šÏO

```

Inputs in the order *landscape, land distance, landmine number*, where *landscape* is a list of digits.

Try it online or verify all test cases.

**Explanation:**

```
λ           # Start a recursive environment,
 £          # to generate the first second (implicit) input amount of items,
            # Starting with a(0),a(1),...,a(l) at the first (implicit) input-list
            # And where every following a(n) is calculated as:
            #  (implicitly push a(n-1))
  ₂         #  Push a(n-2)
   +        #  Add them together
    θ       #  Pop and leave just its last digit
}           # Close the recursive environment,
            # (we now have the expanded landscape as a list of digits)
 Ð          # Triplicate the resulting list
  ¦¦        # Remove the first two items of the top copy
    +       # Add the values at the same positions together (ignoring the last two)
     IQ     # Check which values are equal to the third input
       0š   # Prepend a 0 to these checks
         Ï  # Only keep the values at the truthy indices
          O # Sum them together
            # (after which the result is output implicitly)

```

# Answer
> 2 votes
# Excel, 172 bytes

Named variable `z` defined as:

```
=LAMBDA(x,n,
    IF(n=LEN(x),x,z(x,n-1)&MOD(SUM(0+MID(z(x,n-1),n-{1,2},1)),10))
)

```

Formula within the worksheet:

```
=LET(
    a,z(A1,C1),
    b,SEQUENCE(LEN(a)-2),
    SUM(IF(MMULT(0+MID(a,b+{0,2},1),{1;1})=B1,0+MID(a,b+1,1)))
)

```

Landscape, landmine number and land distance in `A1`, `B1` and `C1` respectively.

Fails in some cases (e.g. `00|99|99`), perhaps due to IEEE 754 precision on the return from `MOD`.

# Answer
> 1 votes
# JavaScript (ES13), 74 bytes

Expects `(number)(landscape)(distance)`, where `landscape` is given as a string.

```
n=>s=>g=k=>k>2&&g(--k,s+=-(-s.at(-1)-s.at(-2))%10)+s[k-1]*!(n-s[k-2]-s[k])

```

Attempt This Online!

### Commented

```
n =>              // n = landmine number
s =>              // s = landscape string
g = k =>          // k = land distance
k > 2 &&          // if k is greater than 2:
  g(              //   do a recursive call:
    --k,          //     decrement k
    s += -(       //     append to s:
      -s.at(-1) - //       the sum of the last digit in s
      s.at(-2)    //       and the penultimate digit
    ) % 10        //     modulo 10
  )               //   end of recursive call
                  //   the code below is executed once all recursive
                  //   calls have been initiated, which means that s
                  //   is now guaranteed to be long enough
  + s[k - 1] * !( //   add s[k - 1] to the final result if:
    n             //     n is equal to
    - s[k - 2]    //     the sum of s[k - 2]
    - s[k]        //     and s[k]
  )               //

```

---

# JavaScript (ES6), 64 bytes

Same input format as above. Due to limited IEEE 754 precision, this version cannot see very far in the fog...

```
n=>s=>g=k=>--k>1&&g(k,s+=(+s+s/10)%10|0)+s[k-1]*!(n-s[k-2]-s[k])

```

Try it online!

# Answer
> 1 votes
# Q, 61 bytes

```
{while[z>(#:)x;x,:sum[-2#x]mod 10];sum x(&:)y=next[x]+prev x}

```

**ungolfed**:

```
{ [x; y; z]
    while[ z>count x;
        x,: (sum -2#x) mod 10
    ];
    : sum x where y=next[x] + prev[x]
    }

```

# Answer
> 1 votes
# Pyth, 28 bytes

```
sm*@d1qQs%2d.:<u+Ges>2GKEEK3

```

Try it online!

Takes three inputs: landmine number, length, and starting sequence as a list.

### Explanation

```
                       KE       # K = second input
               u         E      # repeat lambda G K times, with third input as the starting value
                +G              #   append to G
                  e             #   the last digit of
                   s            #   the sum of
                    >2G         #   the last two elements of G
              <           K     # first K elements of the last value of G
            .:             3    # all length 3 sublists
 m                              # map this to lambda d
  *@d1                          #   middle element of d times
      qQs%2d                    #   Q == sum of first and last elements of d
s                               # sum all terms

```

# Answer
> 1 votes
# C (clang), ~~94~~ 88 bytes

```
f(*a,m,n,l,*s){for(;*s=m<n;)a[m++]=(a[m-2]+a[m-1])%10;for(;--m>1;)*s+=*a+a++[2]-l?0:*a;}

```

Try it online!

*Saved 6 bytes thanks to ceilingcat!!!*

# Answer
> 1 votes
# Python 3.8 (pre-release), 127 bytes

```
lambda s,n,d:(s:=(g:=lambda w:w if d==len(w)else g(w+[(w[-1]+w[-2])%10]))(s))and sum(z*(x+y==n)for x,y,z in zip(s,s[2:],s[1:]))

```

Try it online!

So I have Python 3.10.0 installed on my computer (and it works) but it doesn't work on TIO's "Python 3"? IDK at least it works on this version.

So there are two parts to this function, chained by the `and` operator. The first part expands the landscape to the proper length using a recursive lambda function. The second part uses `zip` to loop over every pair of elements and checks to see if they sum to the landmine number. And finally, `sum` is used to add up all the landmine scores found to get the answer.

Defining the second lambda function is really costly so I wouldn't be surprised is someone else found a better way to generate the new landscape.

# Answer
> 1 votes
# Retina 0.8.2, 127 bytes

```
\G\d|\d+
$*_,
+`^((_*,)*(_*),(_*,))(¶.*¶(?<-2>_)*(?(2)^)___)
$1$3$4$5
+`^(.*)_{10}
$1
M!`(?<=(_*),)(_*)(?=,(_*))(?=,.+¶\1\3,)
_

```

Try it online! Takes input on separate lines but link is to test suite that splits on spaces for convenience. Explanation:

```
\G\d|\d+
$*_,

```

Convert to unary.

```
+`^((_*,)*(_*),(_*,))(¶.*¶(?<-2>_)*(?(2)^)___)
$1$3$4$5

```

Extend the field until it reaches the distance.

```
+`^(.*)_{10}
$1

```

Keep only the ones digits of the field.

```
M!`(?<=(_*),)(_*)(?=,(_*))(?=,.+¶\1\3,)

```

Match only the landmines.

```
_

```

Take their sum.

# Answer
> 1 votes
# Swift 5.9, 113 bytes

```
while l.count<d{l+=[(l[l.count-2]+l.last!)%10]};return(1...l.count-2).reduce(0){$0+(l[$1-1]+l[$1+1]==n ?l[$1]:0)}

```

Where the function header is:

```
func landmineScore(landscape l: inout [Int], mineNumber n: Int, distance d: Int) -> Int

```

Ungolfed version (plus header):

```
func landmineScore(landscape: inout [Int], mineNumber: Int, distance: Int) -> Int {
    while landscape.count < distance {
        landscape += [(landscape[landscape.count - 2] + landscape.last!) % 10]
    }

    return (1...(landscape.count - 2)).reduce(0) { result, index in
        result + (landscape[index - 1] + landscape[index + 1] == mineNumber ? landscape[index] : 0)
    }
}

```

I chose to make `landscape` an `inout` because that prevents me from having to declare `var m=l` at the beginning, saving 8 bytes total. I also used `Array.reduce` instead of a `for`-`in` loop or `Array.forEach`, saving a fair amount of bytes (since it also allowed me to eliminate using a separate `score` variable).

Using `l.count` instead of `l.endIndex` saved 3 bytes per use (both values are always the same).

The space before the `?` is needed to prevent Swift from trying to optional-chain.

# Answer
> 1 votes
# Scala, 147 bytes

Golfed version. Attempt This Online!

```
(l,m,d)=>{var L=l;var s=0;while(L.size<d)L:+=(if(L.size>1)(L.last+L.init.last)%10 else L.last);for(i<- 1 to L.size-2)if(L(i-1)+L(i+1)==m)s+=L(i);s}

```

Ungolfed version. Attempt This Online!

```
object Main {
  def main(args: Array[String]): Unit = {
    println(landmineScore(List(1, 7, 8), 9, 11))  // 16
    println(landmineScore(List(0, 1, 2), 7, 21))  // 16
    println(landmineScore(List(1, 0), 10, 10))    // 0
    println(landmineScore(List(0, 9, 0, 9, 0, 9), 0, 10)) // 18
    println(landmineScore(List(0, 0), 0, 99))     // 0
    println(landmineScore(List(0, 0), 99, 99))    // 0
    println(landmineScore(List(9, 1, 9, 0, 0), 18, 42))   // 1
    println(landmineScore(List(1, 2, 3, 1, 2, 1), 10, 15)) // 18
    println(landmineScore(List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), 2, 10)) // 8
  }

  def landmineScore(landscape: List[Int], mineNum: Int, dist: Int): Int = {
    var land = landscape
    var score = 0

    while (land.length < dist) {
      land = land :+ (if (land.length > 1) (land.last + land.init.last) % 10 else land.last)
    }

    for (i <- 1 until land.length - 1) {
      if (land(i - 1) + land(i + 1) == mineNum) {
        score += land(i)
      }
    }

    score
  }
}

```

# Answer
> 0 votes
# Perl 5, 110 bytes

```
/ (\d+) /;$_=$`;$l=$';$n=$&;/(.)(.)$/,$_.=($1+$2)%10while y///c<$l;/(.)(.)(.)(?{$s+=$2if$1+$3==$n})^/g;$_=$s|0

```

Try it online!

---
Tags: code-golf
---