title: They call me Inspector Morse

text:
# Question
Title: They call me Inspector Morse
A string is dot-heavy when its morse representation contains more dots than dashes. For example, the letter E is a single dot, which means it is Dot-heavy.

# Input

* The input string will only contain characters in the range of `[a-z]` or `[A-Z]`. You can decide if they should *all* be upper case, or all lower case. `AAA` is fine, `aaa` is fine, `aAa` is not.
* The input string will always be at least 1 character in length.
* You may assume that input strings will never have an equal amount of dots and dashes.

# Output

You should return Truthy for inputs that contain more dot characters.
You should return Falsy for inputs that contain more dash characters.
Edit: I will allow a positive value for dot and a negative value for dash as well.

# Test cases

```
| input | morse representation | result          |
|------------------------------------------------|
| S     | ...                  | Truthy          |
| k     | -.-                  | Falsy           |
| HELLO | .... . .-.. .-.. --- | Truthy          |
| code  | -.-. --- -.. .       | Falsy           |

```

# Reference

This is . Shortest code in bytes wins.

# Answer
> 7 votes
# APL (Dyalog Extended), ~~24~~ 15 bytesSBCS

-9 thanks to Ven

Anonymous tacit prefix function taking uppercase as argument.

```
>/'.-'⍧∊∘⌂morse

```

Try it online!

`⌂morse` convert to list of Morse strings
then
**ϵ**nlist (flatten)
`'.-'⍧` count the number of dots and dashes in that
`>/` more dots than dashes? (lit. greater-than reduction)

# Answer
> 9 votes
# x86-16 machine code, 42 bytes

```
00000000: fc32 e4bb 1c01 ac24 1fd0 e8d7 7206 51b1  .2.....$....r.Q.
00000010: 04d2 e859 240f 2c03 02e0 e2ea c353 4452  ...Y$.,......SDR
00000020: 7412 5130 3146 2452 3100                 t.Q01F$R1.

```

**Listing:**

```
FC          CLD                 ; LODS string functions forward
32 E4       XOR  AH, AH         ; running sum = 0
BB 0119     MOV  BX, OFFSET TBL-1 ; offset data by -1 byte for one-based index
        LETTER_LOOP:
AC          LODSB               ; load next char from DS:SI into AL, advance SI
24 1F       AND  AL, 1FH        ; convert ASCII letter to one-based index
D0 E8       SHR  AL, 1          ; divide index by 2, CF=1 if odd index
D7          XLAT                ; look up letter in table
72 06       JC   ODD            ; odd index use low nibble; even use high
51          PUSH CX             ; save loop counter
B1 04       MOV  CL, 4          ; set up right shift for 4 bits
D2 E8       SHR  AL, CL         ; bit shift right
59          POP  CX             ; restore loop counter
        ODD:
24 0F       AND  AL, 0FH        ; isolate low nibble
2C 03       SUB  AL, 3          ; dash/dot difference remove +3 positive bias
02 E0       ADD  AH, AL         ; add difference to sum, set result flags
E2 EA       LOOP LETTER_LOOP    ; loop until end of input
C3          RET                 ; return to caller

        TBL:
            DB   53H, 44H, 52H, 74H, 12H, 51H
            DB   30H, 31H, 46H, 24H, 52H, 31H, 30H

```

**Explanation**

Input: string at `DS:SI` (upper or lower case OK). Output: Truthy if `SF == OF` (use `JG` or `JL` to test).

The letter difference table values are stored as binary nibbles, so only takes 13 bytes in total. One byte can be saved by converting the input ASCII into a one-based index (`'a' = 1`, etc), however that would offset the table lookup index by one byte, not one nibble. Fortunately for us, the opcode of the previous `RET` instruction is `C3`, so that `3` is used for the `'a' = 1` nibble index.

**Example Output:**

# Answer
> 7 votes
# Java (JDK), ~~131~~ ~~124~~ ~~110~~ ~~84~~ 64 bytes

Interestingly, "dot" is dash-heavy and "dash" is dot-heavy.

Takes input in all caps as an `IntStream` (scroll down for a version with an actual `String` for an extra 8 bytes). I've had quite a lot of help golfing this one: Thanks to Expired Data for golfing 20 bytes, to Neil for golfing 26 bytes, to Olivier Grégoire for golfing 18 bytes and to Kevin Cruijssen for golfing 2 bytes.

Contains 26 unprintable characters inside the double quotes.

```
c->c.map(a->"".charAt(a-65)-4).sum()>0

```

Try it online!

Ungolfed:

```
c -> // lambda taking input as an IntStream in upper case and returning a boolean
  c.map(a -> "" // map each character's ASCII value to its net dot impact (unprintable characters here)
    .charAt(a - 65) // translate the ASCII code into a zero-based index into the above string (65 is 'A')
    - 4) // unprintables are > 0, this restores the proper values
  .sum() > 0 // add up all the values, positive sum indicates a dot-heavy input string

```

# Java (JDK), ~~131~~ ~~124~~ ~~110~~ ~~84~~ 72 bytes

For purists; takes input as a `String`. Thanks to Expired Data for golfing 20 bytes, to Neil for golfing 26 bytes and to Olivier Grégoire for golfing 10 bytes.

```
s->s.chars().map(a->"".charAt(a-65)-4).sum()>0

```

Try it online.

Ungolfed:

```
s -> // lambda taking input as a String in upper case and returning a boolean
  s.chars() // convert to a stream of characters
  .map(a -> "" // map each character's ASCII value to its net dot impact (unprintable characters here)
    .charAt(a - 65) // translate the ASCII code into a zero-based index into the above string (65 is 'A')
    - 4) // unprintables are > 0, this restores the proper values
  .sum() > 0 // add up all the values, positive sum indicates a dot-heavy input string

```

# Answer
> 5 votes
# Jelly, 21 bytes

```
Oị“ÆġwıMƥ)ɠịṙ{’D¤Æm>4

```

**Try it online!**

### How?

```
Oị“ÆġwıMƥ)ɠịṙ{’D¤Æm>4 - Link: list of characters ([A-Z]), S
                ¤     - nilad followed by link(s) as a nilad:
  “ÆġwıMƥ)ɠịṙ{’       -   base 250 integer = 14257356342446455638623624
               D      -   to decimal digits
                      -   -- that is the number of dots less the number of dashes plus 4
                      -      ... for each of OPQRSTUVWXYZABCDEFGHIJKLMN
O                     - ordinals of S   e.g. "ATHROUGHZ" -> [65,84,72,82,79,85,71,72,90]
 ị                    - index into (1-indexed & modular, so O gets the 79%26 = 1st item
                      -                                  or A gets the 65%26 = 13th item
                 Æm   - arithmetic mean
                   >4 - greater than 4?

```

# Answer
> 4 votes
# C# (Visual C# Interactive Compiler), 47 bytes

```
n=>n.Sum(i=>("[E[LduRgmQSMK"[i%13]>>i%2*3)%8-3)

```

Uses Level River St's 'magic string'. Be sure to upvote their solution as well!

It's not everyday C# beats Ruby, Python, Javascript, C, Retina, and Perl!

Try it online!

# Answer
> 4 votes
# 05AB1E, ~~22~~ 21 bytes

Saved a byte thanks to *Kevin Cruijssen*

```
SA•U(Õþć6Δ
»›I•‡3-O.±

```

Try it online!

**Explanation**

```
•U(Õþć6Δ
»›I•

```

is **35344527512513031462452313** compressed to base 255.

```
S              # split input into list of chars
       ‡       # transliterate
 A             # the lowercase alphabet
  •...•        # with the digits from the compressed string
        3-     # subtract 3 from each
          O    # then sum the result
           .±  # and take the sign

```

# Answer
> 3 votes
# JavaScript (Node.js),  ~~69 68~~  65 bytes

*-3 bytes thanks to @l4m2*

Expects the input string in uppercase. Returns \\$0\\$ or \\$1\\$.

```
s=>!Buffer(s).map(n=>s='30314624523133534452741251'[n%26]-4-~s)<s

```

Try it online!

# Answer
> 3 votes
# Jelly, 23 bytes

```
9“¡ȷṡẓh)ėḂYF@’ḃ_4ị@OS0<

```

Try it online!

# Answer
> 3 votes
# C (gcc), ~~84~~ ~~82~~ ~~81~~ ~~79~~ 75 bytes

Assumes all caps.

```
r;f(char*s){for(r=0;*s;r+="+-+,,-*/--*-)+(+),.*,-*+)+"[*s++%65]-43);s=r>0;}

```

Try it online!

# Answer
> 3 votes
# Python 2, ~~73~~ ~~70~~ 69 bytes

```
lambda s:sum(int(`0x21427b563e90d7783540f`[ord(c)%25])-3for c in s)>0

```

Try it online!

Uppercase only

-3 bytes, thanks to Erik the Outgolfer

---

Both upper- and lowercase version:

# Python 2, ~~73~~ 71 bytes

```
lambda s:sum(int(oct(0x1d7255e954b0ccca54cb)[ord(c)%32])-3for c in s)>0

```

Try it online!

# Answer
> 2 votes
# Stax, 20 bytes

```
ÉBÜ◙ƒ╣<Hf6─òÉ¼säS╗◄↔

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
"45D.J57KBJa`"I"    string literal with code points [52 53 68 46 74 53 55 75 66 74 97 34 73]
$                   flatten to string "52536846745355756674973473"
;                   push input
@                   get string characters at indices
                    (using input codepoints as indices; lookups wrap around)
:V                  arithmetic mean
53>                 is greater than 53

```

Run this one

# Answer
> 2 votes
# Ruby, 64 bytes

```
->s{n=0;s.bytes{|i|n+=("[E[LduRgmQSMK"[i%13].ord>>i%2*3)%8-3};n}

```

Try it online!

Uses a 13-byte magic string, 2 numbers `0..7` encoded in each byte. Subtract 3 for a range `-3..4`.

The ASCII code for `A` (and also `N`) taken modulo 13 is by coincidence, zero.

# Answer
> 2 votes
# GNU sed, 113 bytes

Accepts lower-case inputs, one per line. Output is 1 for dot-heavy or 0 for dash-heavy. Since the question didn't specify the output for exactly balanced lines, I produce an empty line in that case.

```
s/[acnpxz]//g
y/bdfgjklqruvwy/ieitmtimeeitm/
:e
s/h/ii/
s/s/ie/
s/i/ee/
s/o/mt/
s/m/tt/
s/et\|te//
te
/e/c1
/t/c0

```
1. First, remove the letters which are themselves balanced.
2. Replace unbalanced letters with their equivalents (e.g. Q is `--·-`, so its net contribution is `--`, i.e. M).
3. Expand these equivalents into the corresponding count of E or T.
4. Remove paired E and T
5. If we have an E remaining, we're dot-heavy; if we have a T remaining, we're dash-heavy; otherwise (nothing remaining) evenly balanced.

# Answer
> 1 votes
# Retina 0.8.2, 51 bytes

```
T`L`35344527412513031462452313
.
$*<>>>
+`<>|><

^<

```

Try it online! Link includes test cases. Only accepts upper case (+6 bytes for mixed case). Shamelessly stealing @Arnauld's string but I was going to use the same algorithm anyway. Explanation:

```
T`L`35344527412513031462452313
.

```

Change each letter into the difference in numbers of dots and dashes, plus three, so `O=0` and `H=7`.

```
$*<>>>

```

Represent the difference as that number of `<`s and three `>`s. (Sadly I can't use dots because they're special in regex.)

```
+`<>|><

```

Remove matched pairs of `<`s and `>`s.

```
^<

```

Check whether there are still any dots left.

# Answer
> 1 votes
# Bash+coreutils,  64 60 bytes

```
tr a-z 35344526512513031462452313|sed s/./\&z-+/g|dc -eIK?^p

```

Try it online!

Takes a string in lowercase, outputs zero for falsy, nonzero for truthy

# Explanation

Uses tr and sed to create a dc program that looks like (for the example input 'hello'):

```
IK6z-+4z-+5z-+5z-+0z-+^p

IK     Push 10, then 0 to the stack
6z-+  Push 6 (three more than the dots minus dashes in 'h'), subtract 3, and accumulate
...    Do the same for all other letters, so the stack now has the total dots minus dashes
^      Raise 10 to this power - precision is zero so this turns negative/positive to falsy/truthy
p      Print result

```

# Answer
> 1 votes
# ,  74  70 bytes

```
f=utf8ToInt;sum(f("42433250265364746315325464")[f(scan(,''))-96]-52)<0

```

input should be lower case, returns TRUE or FALSE

Try it online

# Answer
> 1 votes
# TI-BASIC (TI-84), 111 bytes

```
:Ans→Str1:"ABCDEFGHIJKLMNOPQRSTUVWXYZ→Str2:"35344527512513031462452312→Str3:0<sum(seq(expr(sub(Str3,inString(Str2,sub(Str1,X,1)),1)),X,1,length(Str1))-3

```

I used the same string for determining dot-heaviness as some of the other answers.
Program returns truthy (`1`) if the input string is dot-heavy, falsy (`0`) if not.
Input string must be in all-caps.
Input is stored in `Ans`. Output is stored in `Ans` and is automatically printed out when the program completes.

**Ungolfed:**

```
:Ans→Str1
:"ABCDEFGHIJKLMNOPQRSTUVWXYZ→Str2
:"35344527512513031462452312→Str3
:0<sum(seq(expr(sub(Str3,inString(Str2,sub(Str1,X,1)),1)),X,1,length(Str1))-3

```

**Example:**

```
"HELLO
HELLO
prgmCDGF3
           1
"CODE
CODE
prgmCDGF3
           0

```

**Explanation:**
(TI-BASIC doesn't have comments, assume that `;` indicates a commment)

```
:Ans→Str1                          ;store the input into Str1
:"ABCDEFGHIJKLMNOPQRSTUVWXYZ→Str2  ;store the uppercase alphabet into Str2
:"35344527512513031462452312→Str3  ;store dot-dash+3 for each letter into Str3

:0<sum(seq(expr(sub(Str3,inString(Str2,sub(Str1,X,1)),1)),X,1,length(Str1))-3 ;full logic

   sum(                                                                       ;sum the elements of
       seq(                                                               )    ;the list evaluated by
                sub(                                    )                       ;the substring of
                    Str3,                                                        ;Str3
                         inString(                  ),                           ;at the index of
                                       sub(        )                              ;the substring of
                                           Str1,                                   ;Str1
                                                X,                                 ;starting at X
                                                  1                                ;of length 1
                                  Str2,                                           ;in Str2
                                                      1                          ;of length 1
           expr(                                        ),                       ;converted to an integer
                                                          X,                    ;using X as the increment variable
                                                            1,                  ;starting at 1
                                                              length(Str1)      ;ending at the length of Str1
                                                                           -3   ;then subtract 3 from all elements in the list
  0<                                                                           ;then check if the sum is greater than 0
                                                                               ;implicitly output the result

```

---

**Note:** The byte count of a program is evaluated using the value in **\[MEM\]**\>**\[2\]**\>**\[7\]** (124 bytes) then subtracting the length of the program's name, `CDGF3`, (5 bytes) and an extra 8 bytes used for storing the program:

124 - 5 - 8 = 111 bytes

# Answer
> 1 votes
# Thunno 2, 21 bytes

```
Ạ»œfḅ“ƈ©OMṾȤØ»ṆdN3-Sʂ

```

Attempt This Online!

Port of Emigna's 05AB1E answer.

#### Explanation

```
Ạ»œfḅ“ƈ©OMṾȤØ»ṆdN3-Sʂ  # Implicit input
Ạ                      # Push the lowercase alphabet
 »œfḅ“ƈ©OMṾȤØ»         # Push compressed integer 35344527512513031462452313
              Ṇ        # Transliterate the input string (^^ --> ^)
               dN      # Convert to a list of digits
                 3-    # Subtract 3 from each
                   S   # Sum the list
                    ʂ  # Sign of the sum
                       # Implicit output

```

# Answer
> 1 votes
# Morsecco 175 bytes

morsecco has a small advantage here: it knows morse code by nature. Do `. - .-.` to `R`ead the stdin (special address `-`), `-.- .-` to `K`onvert from `·T`ext, `-.- --` to `K`onvert to `M`orse and you already have the morse transcript. But then the work begins!

```
. - .-. -.- .- -.- -- . . - .
-- - -.-. - - - . . -... -.. --.. --.
- .- . . - . -.-. . - .. .- - . -- --.. --.
. - .- - .. .- - . - - .-.. --.. --.
- .- --.
- .- -.-. - ---

```

One funny golfing trick in the third line (handling of space or dash): `C`oncatening a dot in front of the character turns the space into a null `.` , but the dash into a minus 1 (`.-`), so this value can simply be added to the total count.

The \`Output is simply the first character of the count, which happens to be a dot for negative numbers and a dash for positive numbers, so the output is the character with less occurrences.

# Answer
> 0 votes
# Perl 5 `-pF`, 53 bytes

```
$p+=y/a-z/35344526512513031462452313/r-3for@F;$_=$p>0

```

Try it online!

# Answer
> 0 votes
# C++ (compiled with Visual Studio 2017) 171bytes

```
int f(string i){const char*c="1322131421130102123023121211210120032121323101112232";int j=0,h[2]={0};while(j<sizeof(i)/28)*h+=c[i[j]-97],h[1]+=c[i[j++]-71];return*h>h[1];}

```

if we take the main program that exists for test purposes into account as well its more.

this is the ungolfed "tidy" variant

```
#include "stdafx.h"
int main()
{
    const int dotCount[] = {1,3,2,2,1,3,1,4,2,1,1,3,0,1,0,2,1,2,3,0,2,3,1,2,1,2};
    const int dashCount[] = {1,1,2,1,0,1,2,0,0,3,2,1,2,1,3,2,3,1,0,1,1,1,2,2,3,2};
    std::cout << "Enter String:\n";
    std::string input;
    std::cin >> input;
    int inputsHeavyness[2] = { 0 };
    for(int i = 0;i < sizeof(input)/sizeof(std::string);i++)
    {
        inputsHeavyness[0] += dotCount[input[i] - 'a'];
        inputsHeavyness[1] += dashCount[input[i] - 'a'];
    }
    if (inputsHeavyness[0] > inputsHeavyness[1])
    {
        std::cout << "Dot Heavy\n";
    }
    else
    {
        std::cout << "Dash Heavy or Neutral\n";
    }
    return 0;
}

```

assumes all lowercase

# Answer
> 0 votes
# Factor, 66 bytes

```
: f ( s -- ? ) >morse [ [ 45 = ] count ] [ [ 46 = ] count ] bi < ;

```

Try it online!

# Answer
> 0 votes
**c (118 characters)** returns a positive value for over-dot-ness and negative value for over-dash-ness

```
int n(char* c){int v=25124858,d=3541434,i=0,o=0;for(;c[i]!=0;i++)o=(1&(v>(c[i]-65)))>0?(1&(d>>(c[i]-65)))>0?o+1:o-1:o;return o;}

```

un-golfed

```
int n(char* c)
{
  // Bitwise alpha map:
  // more dots = 1
  // more dashes or equal = 0
  int d=3541434;
  // validation bit map.
  // dot/dash heavy = 1
  // even = 0
  int v=25124858;
  int i=0,o=0;
  for(;c[i]!=0;i++)   // iterate through all values
  {
    // There is no way to make this pretty
    // I did my best.
    // If the little endian validation bit corresponding
    // to the capitol letter ascii value - 65 = 0,
    // the output does not increment or decrement.
    // If the value is one it increases or decreases based
    // on the value of the d bitmap.
    o=(1& ( v > (c[I] - 65))) > 0 ?
      (1 & (d >> (c[I] - 65))) > 0 ?
        o + 1 :
        o - 1 :
      o;
  }
  return o;
}

```

# Answer
> 0 votes
# Python 2, ~~90~~ 86 bytes

```
import morse
s=''.join(morse.string_to_morse(input()))
print s.count('.')>s.count('-')

```

worked on my local with the morse library. -4 bytes. Thanks for the tip @JoKing!

Also, it's 1 byte more if it's in Python 3.

# Python 3, 87 bytes

```
import morse
s=''.join(morse.string_to_morse(input()))
print(s.count('.')>s.count('-'))

```

Though the question assumes the number of '.'s and '-'s will not be equal; in case they are equal, this code will return True.

# Answer
> 0 votes
# MathGolf, 22 bytes

```
{▄="Yⁿ∩┐↑rⁿ¼~<↔"$▒3-§+

```

Try it online!

Uses the same method as many other answers, where `ⁿ∩┐↑rⁿ¼~<↔"` represents the magic number `35344527512513031462452313`.

# Answer
> 0 votes
# Vyxal, 19 bytes

```
n»¨g±„ẇ⟇PNĖṡø»Ŀ3-∑±

```

Try it Online!

Saying the same joke but ~~louder~~ shorter is fun :p

Ports 05AB1E

## Explained

```
n»¨g±„ẇ⟇PNĖṡø»Ŀ3-∑±
n                     # Lowercase alphabet
 »¨g±„ẇ⟇PNĖṡø»        # 35344527512513031462452313
              Ŀ       # transliterate
               3-     # - 3
                 ∑±   # sign of sum

```

# Answer
> 0 votes
# C++, 76 bytes

This assumes the input is in ASCII (or any encoding that's compatible for letters, e.g. UTF-8 or ISO-8859.1). Input may be in either case.

```
[](auto s,int&i){i=0;for(int c:s)i+="DDFDEEECHFBCFBDADBEGCEFCDBD"[c&31]-68;}

```

It's a function that accepts a string and and integer reference. The integer gets assigned a positive number (truthy) for dot-heavy input or a negative number (falsey) for dot-light input. Balanced input returns zero.

The magic string encodes the weight of each of `A`..`Z`, offset by `D` (i.e. D represents a Morse-balanced letter). That's the `68` we subtract from each value.

I did attempt encoding two Morse symbols per char in the magic string, but the cost of unpacking was too great.

### Test program:

```
auto f = [](auto s,int&i){i=0;for(int c:s)i+="DDFDEEECHFBCFBDADBEGCEFCDBD"[c&31]-68;};

#include <iostream>
#include <string>

int main(int argc, char **argv)
{
    int i;
    while (*++argv) {
        std::string s{*argv};
        f(s, i);
        std::cout << s << ": " << i << '\n';
    }
}

```

### Output:

```
./181318 S k HELLO code
S: 3
k: -1
HELLO: 6
code: -1

```

# Answer
> 0 votes
# Nibbles, 16.5 bytes (33 nibbles)

```
+.$-=$`D8 3 2954b0ccca54cb75c957

```

Attempt This Online!

Approach based on Emigna's O5AB1E answer.

Input is lowercase. Outputs the dot-dash sum: positive values are truthy in Nibbles, negative values (as well as zero) are falsy.
To directly compare to the Vyxal, Thunno, O5AB1E etc. answers, add 2 nibbles (+1 byte; prefix  ``$`) to output the sign of the sum, although this isn't necessary here due to Nibbles' truthy/falsy convention.

```
      `D    2954b0ccca54cb75c957    # interpret hex 2954b0ccca54cb75c957
        8                           # in base 8
                                    # (digits: 51251303146245231335344527)
 .$                                 # now map over the input
    =$                              # getting the digit at the modular index
                                    # of each input codepoint
   -      3                         # subtract 3 from each
+                                   # and sum the result

```

# Answer
> 0 votes
# GNU sed `-E`, 112 bytes

An approach could not differ more from the existing `sed` solution, but beating it by only one byte! This one builds a map from +4 dots to +3 dashes then two `s` commands taking turns in moving one of their side down until one of them has no moves left:

```
s/^/H S IFLV EDRU :_GKWT_JQYM_O!/
:1
s/((\S)\S* (.).*)\2/\1\3/
T-
s/((.)_[^_]*([^_]).*!.*)\3/\1\2/
t1
c.
q
:-
c-

```

Try it online!

# Answer
> 0 votes
# Scala 3, 91 bytes

A port of @Level River St's Ruby answer in Scala.

---

Golfed version. Attempt This Online!

```
s=>{var n=0;s.getBytes.foreach{i=>n+=(("[E[LduRgmQSMK".apply(i%13).toInt>>(i%2*3))%8-3)};n}

```

Ungolfed version. Attempt This Online!

```
object Main {
  def main(args: Array[String]): Unit = {
    val f = (s: String) => {
      var n = 0
      s.getBytes.foreach { i =>
        val index = i % 13
        val shift = i % 2 * 3
        val char = "[E[LduRgmQSMK"(index)
        n += ((char.toInt >> shift) % 8 - 3)
      }
      n
    }

    List("S", "K", "HELLO", "CODE").foreach { j =>
      println(s"$j -> ${f(j)}")
    }

    ('A' to 'Z').foreach { j =>
      println(s"$j -> ${f(j.toString)}")
    }
  }
}

```

---
Tags: code-golf, morse
---


title: All together now

text:
# Question
Title: All together now
Given a list of digits 1 through 9, output whether each digit is grouped together as a single contiguous block. In other words, no two of the same digit are separated by different digits. It's OK if a digit doesn't appear at all. Fewest bytes wins.

**Input:** A non-empty list of digits 1 through 9. This can be as a decimal number, string, list, or similar sequence.

**Output:** A consistent Truthy value if all the digits are grouped in contiguous blocks, and a consistent Falsey value if they are not.

True cases:

```
3
51
44999911
123456789
222222222222222222222

```

False cases:

```
818
8884443334
4545
554553
1234567891

```

```
var QUESTION_ID=77608,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/77608/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Python 3, ~~38~~ ~~34~~ 33 bytes

```
lambda s:s==sorted(s,key=s.index)

```

This expects a list of digits or singleton strings as argument. Test it on Ideone.

*Thanks to @xsot for golfing off 4 bytes!*

*Thanks to @immibis for golfing off 1 byte!*
> 19 votes

# Answer
## JavaScript (ES6), 27 bytes

```
s=>!/(.)(?!\1).*\1/.test(s)

```

Uses negative lookahead to look for two non-contiguous digits. If at least two such digits exist, then they can be chosen so that the first digit precedes a different digit.
> 14 votes

# Answer
# 05AB1E, 4 bytes

Code:

```
Ô¹ÙQ

```

Explanation:

```
Ô     # Push connected uniquified input. E.g. 111223345565 would give 1234565.
 ¹    # Push input again.
  Ù   # Uniquify the input. E.g. 111223345565 would give 123456.
   Q  # Check if equal, which yields 1 or 0.

```

Uses **CP-1252** encoding.

Try it online!
> 14 votes

# Answer
# Jelly, 5 bytes

```
ĠIFPỊ

```

Try it online!

### How it works

```
ĠIFPỊ  Main link. Input: n (list of digits or integer)

Ġ      Group the indices of n by their corresponding values, in ascending order.
       For 8884443334, this yields [[7, 8, 9], [4, 5, 6, 10], [1, 2, 3]].
 I     Increments; compute the all differences of consecutive numbers.
       For 8884443334, this yields [[1, 1], [1, 1, 4], [1, 1]].
  F    Flatten the resulting 2D list of increments.
   P   Product; multiply all increments.
    Ị  Insignificant; check if the product's absolute value is 1 or smaller.

```
> 11 votes

# Answer
# Pyth, ~~6~~ 5 bytes

*1 bytes thanks to FryAmTheEggman*

```
SIxLQ

```

Inspired by the Python solution here.

Test suite

**Explanation:**

```
SIxLQ
  xLQ   Map each element in the input to its index in the input. Input is implicit.
SI      Check whether this list is sorted.

```
> 9 votes

# Answer
# R, ~~66~~ ~~48~~ ~~46~~ ~~43~~ 38 bytes

```
function(s)!any(duplicated(rle(s)$v))

```

This is a function that accepts the input as a vector of digits and returns a boolean. To call it, assign it to a variable.

Not the shortest but I thought it was a fun approach. We run length encode the input and extract the values. If the list of values contains duplicates then return `FALSE`, otherwise return `TRUE`.

Verify all test cases online

Saved 20 bytes thanks to MickyT, 3 thanks to Albert Masclans, and 5 thanks to mnel!
> 8 votes

# Answer
# MATL, 8 bytes

```
t!=tXSP=

```

The output is an array containing only ones for truthy, or an array containing at least one zero for falsey.

**Try it online!**

### Explanation

Consider the input `22331`, which satisfies the condition. Testing if each character equals each other gives the 2D array

```
1 1 0 0 0
1 1 0 0 0
0 0 1 1 0
0 0 1 1 0
0 0 0 0 1

```

The final result should be truthy if *the rows of that array (with rows considered as atomic) are in decreasing lexicographical order*. For comparison, input `22321` gives the array

```
1 1 0 1 0
1 1 0 1 0
0 0 1 0 0
1 1 0 1 0
0 0 0 0 1

```

in which the rows are not in order.

```
t!   % Take string input. Duplicate and tranpose
=    % Test for equality, element-wise with broadcast: gives a 2D array
     % that contains 0 or 1, for all pairs of characters in the input
t    % Duplicate
XS   % Sort rows (as atomic) in increasing order
P    % Flip vertically to obtain decreasing order
=    % Test for equality, element-wise

```
> 8 votes

# Answer
## Java, 161 156 bytes

Because Java...

Shamelessly stealing borrowing the regex from this answer because I started out trying to do this with arrays and math manipulation, but it got hideously complex, and regex is as good a tool as any for this problem.

```
import java.util.regex.*;public class a{public static void main(String[] a){System.out.println(!Pattern.compile("(.)(?!\\1).*\\1").matcher(a[0]).find());}}

```

Ungolfed:

```
import java.util.regex.*;

public class a {
    public static void main(String[] args) {
        System.out.println(!Pattern.compile("(.)(?!\\1).*\\1").matcher(args[0]).find());
    }

```

Laid out like a sensible Java person:

```
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class  {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("(.)(?!\\1).*\\1");
        Matcher m = p.matcher(args[0]);
        System.out.println(!m.find());
    }
}

```
> 5 votes

# Answer
## Retina, 17 bytes

```
M`(.)(?!\1).+\1
0

```

Try it online! (Slightly modified to run all test cases at once.)

The first regex matches digits which *are* separated by other digits, so we get a `0` for valid inputs and anywhere between `1` and `9` for invalid inputs (due to the greediness of the the `.+`, we can't get more than `n-1` matches for `n` different digits).

To invert the truthiness of the result, we count the number of `0`s, which is `1` for valid inputs and `0` for invalid ones.
> 5 votes

# Answer
# J, 8 bytes

```
-:]/:i.~

```

Test it with J.js.

### How it works

```
-:]/:i.~  Monadic verb. Argument: y (list of digits)

     i.~  Find the index in y of each d in y.
  ]/:     Sort y by the indices.
-:        Match; compare the reordering with the original y.

```
> 5 votes

# Answer
# Regex (Perl / PCRE / Java / Boost / Python`regex` / Ruby), 17 bytes

```
^(?!(.)+\1*+.+\1)

```

Try it online! \- Perl
Try it online! \- PCRE
Try it online! \- Java
Try it online! \- Boost
Try it online! \- Python `import regex`
Try it online! \- Ruby

```
^             # Anchor to start of string
(?!           # Assert that the following can't match:
    (.)+      # Skip any number of characters (minimum zero), then capture
              # the next character in \1
    \1*+      # Skip all subsequent occurrences of \1, and lock in that match
              # using a possessive quantifier.
    .+        # Skip at least one character, or as many as necessary to make the
              # following match:
    \1        # Match the character captured in \1
)

```

## Regex (Perl / PCRE / Java / Boost / Python`regex` / Ruby), 11 bytes

```
(.)\1*+.+\1

```

Returns a match for false, and a non-match for true.

Try it online! \- Perl
Try it online! \- PCRE
Try it online! \- Java
Try it online! \- Boost
Try it online! \- Python `import regex`
Try it online! \- Ruby

This beats the regex in the previous Java answer, Perl answer, and Ruby answer by 2 bytes.

```
(.)   # \1 = a character anywhere in the string
\1*+  # Skip all subsequent occurrences of \1, and lock in that match using a
      # possessive quantifier.
.+    # Skip at least one character, or as many as necessary to make the
      # following match:
\1    # Match the character captured in \1

```

## Regex (ECMAScript (or better) / Python / .NET), 13 bytes

```
(.)(?!\1).+\1

```

Returns a match for false, and a non-match for true.

**Try it online! \- ECMAScript**
Try it online! \- Perl
Try it online! \- PCRE
Try it online! \- Java
Try it online! \- Boost
**Try it online! \- Python**
Try it online! \- Python `import regex`
Try it online! \- Ruby
**Try it online! \- .NET**

## \\$\large\textit{Anonymous functions}\\$

# Ruby, 21 bytes

```
->s{/(.)\1*+.+\1/!~s}

```

Try it online!

# JavaScript (ES6), 27 bytes

```
s=>!/(.)(?!\1).+\1/.test(s)

```

Try it online!

Included for completeness; already done in Neil's answer.

# PowerShell, 29 bytes

```
!($args-match'(.)(?!\1).+\1')

```

Try it online!

# Julia v0.7+, 30 bytes

```
s->!occursin(r"(.)\1*+.+\1",s)

```

Attempt This Online! / Try it online!

# Julia v1.3+, 28 bytes

```
s->count(r"(.)\1*+.+\1",s)<1

```

Attempt This Online!

*-2 bytes compared to v0.7+, thanks to MarcMush*

# , 32 bytes

```
\(s)!grepl('(.)\\1*+.+\\1',s,,1)

```

Attempt This Online!

Beaten by Alex A.'s non-regex answer by 2 bytes, or by 6 bytes with pajonk's improvement.

# Java, 33 bytes

```
s->!s.matches("(.)+\\1*+.+\\1.*")

```

Try it online!

# PHP, 39 bytes

```
fn($s)=>!preg_match('/(.)\1*+.+\1/',$s)

```

Try it online!

## \\$\large\textit{Full programs}\\$

# Perl `-p`, 17 bytes (18 bytes including flag)

```
$_=!/(.)\1*+.+\1/

```

Try it online!

# Retina 0.8.2, 17 bytes

```
M`(.)(?!\1).+\1
0

```

Try it online!

Included for completeness; already done in Martin Ender's answer.

# Retina 1.0, 17 bytes

```
C`(.)(?!\1).+\1
0

```

Try it online!

# Pip, ~~19~~ 18 bytes

```
`(.)(?!\1).+\1`NIa

```

Try it online!

Thanks to DLosc.
> 5 votes

# Answer
# Pyth, 7 bytes

```
{IeMrz8

```

Test Suite.
> 4 votes

# Answer
# Ruby, 23 bytes

Anonymous function. Accepts a string. Regex strat.

```
->n{/(.)(?!\1).*\1/!~n}

```

**Regex breakdown**

```
/(.)(?!\1).*\1/
 (.)            # Match a character and save it to group 1
    (?!\1)      # Negative lookahead, match if next character isn't
                #  the same character from group 1
          .*    # Any number of matches
            \1  # The same sequence as group 1

```

`!~` means if there are no matches of the regex within the string, return `true`, and otherwise return `false`.
> 4 votes

# Answer
# MATL, ~~13~~ 11 bytes

```
u"G@=fd2<vA

```

Thanks to *Luis Mendo* for saving two bytes!

**Try it Online!**

**Explanation**

```
        % Grab the input implicitly
u       % Find the unique characters
"       % For each of the unique characters
    G   % Grab the input again
    @=  % Determine which chars equal the current char
    f   % Find the locations of these characters
    d   % Compute the difference between the locations
    2<  % Find all index differences < 2 (indicating consecutive chars)
    v   % Vertically concatenate all stack contents
    A   % Ensure that they are all true
        % Implicit end of the for loop

```
> 4 votes

# Answer
# Mathematica, 26 bytes

```
0<##&@@Sort[#&@@@Split@#]&

```
> 4 votes

# Answer
# Haskell, 37 bytes

```
f l=(==)=<<scanl1 min$(<$>l).(==)<$>l

```

Try it online!

Uses the same approach as Luis Mendo's MATL answer: creates a vector for each entry which indices equal it, and checks that the result is sorted in decreasing order.

`(<$>l).(==)<$>l` is shorter version of `[map(==a)l|a<-l]`. The function `(<$>l).(==)` that takes `a` to `map(==a)l` is mapped onto `l`.

`scanl1 min` takes the cumulative smallest elements of `l`, which equals the original only if `l` is reverse-sorted. `(==)=<<` checks if the list is indeed invariant under this operation.

A recursive strategy also gave **37 bytes**:

```
f(h:t)=t==[]||f t>(elem h t&&h/=t!!0)

```

Try it online!

This checks each suffix to see if its first element doesn't appear in the remainder, excusing cases where the first two elements are equal as part of a contiguous block.

Other approaches:

**42 bytes**

```
f l=and[all(/=a)t|a:b:t<-scanr(:)[]l,a/=b]

```

Try it online!

**43 bytes**

```
import Data.List
((==)<*>nub).map nub.group

```

Try it online!
> 4 votes

# Answer
# Jelly, 4 bytes

```
i@ÞƑ

```

Try it online!

Semi-based on several of DLosc's 5-byters.

```
   Ƒ    The input is not changed by
  Þ     sorting its elements by
i@      their first indices in the input.

```

Kind of like cutting the `F` out of `¹ƙ`F⁼`, but also kind of like cutting the ``ṢƑ` out of `iⱮ`ṢƑ.`
> 4 votes

# Answer
# Vyxal, 4 bytes

```
)ġf⁼

```

Try it Online!

Takes input as a list of singleton strings. Happens to be a different algorithm to the existing vyxal answer.

## Explained

```
)ġf⁼
)ġ    # Group by the identity function, by order of first appearance.
  f   # Flatten the list
   ⁼  # Does that equal the input?

```
> 4 votes

# Answer
# Python, 56 55 bytes

```
a=lambda s:~(s[0]in s.lstrip(s[0]))&a(s[1:])if s else 1

```
> 3 votes

# Answer
## Haskell, 44 bytes

```
import Data.List
((==)<*>nub).map head.group

```

Usage example: `((==)<*>nub).map head.group $ "44999911"` -\> `True`.

A non-pointfree version:

```
f x = q == nub q                -- True if q equals q with duplicates removed
  where
  q = map head $ group x        -- group identical digits and take the first
                                -- e.g. "44999911" -> ["44","9999","11"] -> "491"
                                -- e.g  "3443311" -> ["3","44","33","11"] -> "3431"

```
> 3 votes

# Answer
# C#, 119 bytes

```
bool m(String s){for(int i=0;i<9;i++){if(new Regex(i.ToString()+"+").Matches(s).Count>1){return false;}}return true;}

```

---

## Ungolfed

```
bool m(String s) {
    for(int i=0;i<9;i++) {
        if(new Regex(i.ToString() + "+").Matches(s).Count > 1) {
            return false;
        }
    }

    return true;
}

```
> 3 votes

# Answer
# Brachylog, ~~5~~ 4 bytes

```
≡ᵍc?

```

Try it online!

*-1 thanks to DLosc*

Takes input as a list of digits through the input variable, and succeeds or fails as output.

```
≡ᵍ      The input with identical elements grouped in order of first appearance
  c     with the groups concatenated
   ?    is the input.

```
> 3 votes

# Answer
# Vyxal, 4 bytes

```
vḟÞṠ

```

Try it Online!

```
vḟ  # Index of B in A, vectorized (B will be each individual character in the
    # string / item in the list, and A will be the string/list itself)
ÞṠ  # Is the result sorted?

```

Answers that use this method, in chronological order:

# Vyxal, 5 bytes

```
₌ÞǓU=

```

Try it Online!

```
₌     # Parallel Apply - apply the following two elements to the input and keep
      # both results on the stack.
  ÞǓ  # Connected Uniquify - Remove occurences of adjacent duplicates.
  U   # Uniquify - Remove all duplicates.
=     # Are the two results equal?

```

Turned out to be a port of Adnan's 05AB1E answer.
> 3 votes

# Answer
# K (ngn/k), ~~11~~ 10 bytes

-1 byte thanks to @ovs

```
~/,/'='^:\

```

Try it online!

`^:` test for spaces - always returns 0s, as the input consists only of digits. The `:` here means monadic.

`^:\` repeat until convergence. This will return a pair of the original argument and a list of 0s of the same length as the argument.

`='` group each. To "group" a list means to make a dictionary that maps each distinct element of the list to the positions where it occurs.

`,/'` raze each, i.e. ignore the keys and concatenate the values. For the list of all 0s this will result in 0,1,...,length-1. For the other list, it will depend on the presence of non-continuous blocks - if there aren't any, the result will be 0,1,...,length-1 too.

`~/` do they match?
> 3 votes

# Answer
# Prolog (SWI), 40 bytes

```
\[A|S]:-S=[];(S=[A|_];\+member(A,S)),\S.

```

Try it online!

-3 thanks to Jo King

Similar to xnor's second Haskell answer.

This won't work on TIO because it is too old of a version, and it's longer, but I think it's more interesting:

# Prolog (SWI), 57 bytes

```
\A:-clumped(A,B),maplist([X-_,X]>>!,B,C),list_to_set(A,C).

```
> 3 votes

# Answer
# Julia, 35 bytes

```
s->issorted(s,by=x->findfirst(s,x))

```

For whatever reason, `sort` does not take a string, but `issorted` does...
> 2 votes

# Answer
## Lua, ~~107~~ ~~94~~ 85 Bytes

**13 bytes saved thanks to @LeakyNun**

At least, it beats Java :D. Lua sucks at manipulating strings, but I think it is good enough :).

It takes its input as a command-line argument, ~~and outputs `1` for truthy cases and `false` for falsy ones.~~ Now outputs using its exit code. Exit code 0 for truthy, and 1 for falsy

```
o=os.exit;(...):gsub("(.)(.+)%1",function(a,b)if 0<#b:gsub(a,"")then o(1)end end)o(0)

```

### Ungolfed

Be care, there's two magic-variables called `...`, the first one contains the argument of the program, the second one is local to the anonymous function and contains its parameters

```
o=os.exit;               -- ; mandatory, else it would exit instantly
(...):gsub("(.)(.+)%1",  -- iterate over each group of the form x.*x and apply an anonymous
  function(a,b)          -- function that takes the captured group as parameters
  if 0<#b:gsub(a,"")     -- if the captured group (.+) contain other character than
  then                   -- the one captured by (.)
    o(1)                 -- exit with falsy
  end
end)
o(0)                     -- exit with truthy, reached only when the string is okay

```
> 2 votes

# Answer
# Factor, 22 bytes

```
[ dup natural-sort = ]

```

Does what it says on the tin. As an anonymouse function, you should `call` this, or make it a `: word ;`.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 18 bytes

```
Gather@#==Split@#&

```

Try it online!

`Gather` gathers a list into sublists of identical elements, and `Split` splits a list into sublists of consecutive identical elements. They give the same result if and only if each value appears in only one contiguous block.
> 2 votes

# Answer
# BQN, ~~9~~ 5 bytes

```
≡⟜∧⊐˜

```

Anonymous tacit function. Takes a string or a list of integers. Try it at BQN online!

### Explanation

Inspired by Dennis's J answer, though the details are a bit different.

Given two lists,  works as follows: for each element of its right argument, it finds the first index of that value in its left argument.

We're using `⊐˜`, which passes the same list as both left and right arguments. The result is a list, for each digit, of the index of that digit's first occurrence.

If the digits are grouped together, these indices will occur in ascending order. However, if some copies of digit A are separated by digit B, B's (larger) index will come between the copies of A's (smaller) index.

```
≡⟜∧⊐˜
    ⊐˜  First index of each digit in the argument list
≡⟜      The result is identical to
   ∧     The result, sorted ascending

```
> 2 votes

# Answer
# Jelly, 5 bytes

```
iⱮ`ṢƑ

```

Takes a list of integers. Try it online!

### Explanation

Port of my BQN solution.

```
iⱮ`ṢƑ
i      First index of right argument in left argument
 Ɱ     mapped over right argument
  `    using the single argument as both left and right arguments
    Ƒ  The result is equal to
   Ṣ   itself sorted

```

---

Here's some other 5-byte solutions (see also Dennis's 5-byte solution):

```
ĠṢFṢƑ
Ġ      Group indices by their value in the list
 Ṣ     Sort list of lists of indices
  F    Flatten
    Ƒ  The result is equal to
   Ṣ   itself sorted

```

Try it online!

```
ĠṢF⁼J
Ġ      Group indices by their value in the list
 Ṣ     Sort list of lists of indices
  F    Flatten
   ⁼   The result is equal to
    J  Range from 1 up to len of original argument

```

Try it online!

```
¹ƙ`F⁼
¹ƙ`    Sort into buckets of identical items, ordered by first occurrence
   F   Flatten
    ⁼  The result is equal to the original list

```

Try it online!
> 2 votes

# Answer
# Arturo, 28 bytes

```
$=>[=squeeze<=sort squeeze&]

```

Try it!

```
$=>[          ; a function where input is assigned to &
    squeeze&  ; squeeze the input; e.g. [1 1 2 1 1 1 3 3] -> [1 2 1 3]
    sort      ; sort
    <=        ; duplicate
    squeeze   ; squeeze
    =         ; are they equal?
]             ; end function

```
> 2 votes

# Answer
# Thunno 2, 4 bytes

```
ñdḞ⁼

```

Try it online!

Input as a digit list.

## Thunno 2, 5 bytes

```
çµUUạ

```

Try it online!

Input as an integer.

#### Explanation

```
ñdḞ⁼  # Implicit input
ñd    # Group identical items together
  Ḟ   # Flatten the list
   ⁼  # Equals the input?

```

```
çµUUạ  # Implicit input
ç      # Pair apply on the input:
 µU    #  Connected uniquify
   U   #  Uniquify
    ạ  # Are they the same?
       # Implicit output

```
> 2 votes

# Answer
# Uiua, 6 bytes

```
≍⊝.⊜⊢.

```

Try it!

```
≍⊝.⊜⊢.
   ⊜⊢.  # get the first digit in each like contiguous group
  .     # duplicate
 ⊝      # deduplicate
≍       # do they match?

```
> 2 votes

# Answer
# Ly, 22 bytes

```
&i[s=[ppl=]pl~[!u;]p]1

```

Try it online!

This one isn't that all short, but as far as I can tell it works differently from the other programs posted. It deletes all "grouped" digits, then searches the remaining digits for the digit it just deleted. If if finds another one, `0` is printed and the code exits. If the stack is exhausted, the default `1` output is printed.

```
&i                     - read all the digits as codepoints
  [                 ]  - loop until the stack is empty
   s                   - save current digit
    =                  - is the next digit the same?
     [    ]            - yes, then loop deleting that digit
      p                - delete previous test results
       p               - delete digit we just checked
        l              - load the current digit
         =             - does the next one match?
           p           - delete loop/iterator var
            l          - load the current digit again
             ~         - is there another of those digits?
              [    ]   - yes, then time to exit...
               !ul;    - push "0", print and exit
                    p  - print test result variable
                     1 - push "1" for truthy result
                       - stack prints on exit

```
> 2 votes

# Answer
# TI-BASIC, ~~24~~ 22 bytes

```
Prompt A
sum(not(∆List(ʟA
SortA(ʟA
Ans=sum(not(∆List(ʟA

```

Takes input as a list ot integers.

-2 bytes thanks to MarcMush.
> 2 votes

# Answer
# GNU sed `-E`,  ~~32~~  28 bytes

Thank you, Jiří, for golfing off four bytes!

In the first line, remove all duplicate characters to avoid false positives, then check whether there is still a character twice. Output `F` for Falsy or `T` for Truthy:

```
s/(.)\1*/\1/g
/(.).+\1/cF
cT

```

Try it online!

Even without `-E`, it would only be 32 bytes, by far better than the current `sed` solution.
> 2 votes

# Answer
# JavaScript ES6, ~~71~~ 69 bytes

```
h=y=>y.match(/(.)\1*/g);x=>h((u=h(x)).sort().join``).length==u.length

```

Or, equivalently:

```
x=>((u=x.match(r=/(.)\1*/g)).sort().join``).match(r).length==u.length
x=>(h=y=>y.match(/(.)\1*/g))((u=h(x)).sort().join``).length==u.length

```

Golfing in progress.

## Verify test cases

```
var truthy = `3
51
44999911
123456789
222222222222222222222`.split `
`;
var falsey = `818
8884443334
4545
554553
1234567891`.split `
`;

var Q = x => ((u = x.match(r = /(.)\1*/g)).sort().join ``).match(r).length == u.length;
truthy.concat(falsey).forEach(e => {
  t = document.createTextNode(`${e} => ${Q(e)}`);
  o.appendChild(t);
  o.appendChild(document.createElement("br"));
});
```

```
* {
  font-family: Consolas, monospace;
}
```

```
<div id=o></div>
```
> 1 votes

# Answer
# Perl 5, 20 bytes

19, plus 1 for `-pe` instead of `-e`.

```
$_=!/(.)(?!\1).+\1/

```
> 1 votes

# Answer
# C, ~~74~~ ~~73~~ 71 bytes

Shaved ~~one~~ three byte thanks to @xsot!

```
a[99],c,m;main(d){for(;~c;m|=c^d&&a[d=c]++)c=getchar();putchar(48+!m);}

```
> 1 votes

# Answer
## C# 111 bytes

```
bool f(string s){for(int i=0;i<s.Length-1;i++)if(s[i]!=s[i+1]&&s.LastIndexOf(s[i])!=i)return 1==2;return true;}

```

*old strategy* **131 bytes**

```
bool s(string i){var f=Regex.Matches(i,@"([0-9])\1{0,}").Cast<Match>().Select(m=>m.Value[0]);return f.Distinct().SequenceEqual(f);}

```

first golf i think i did ok in
> 1 votes

# Answer
# Racket, 53 bytes

The dumb, simple version.

```
(λ(s)(let([s(string->list s)])(eq?(sort s char<?)s)))

```

Ungolfed:

```
(define (lame-all-together s)
  (let ([s (string->list s)])
    (eq? (sort s char<?) s)))

```

# Racket, 86 bytes

Here's the version implementing @xnor's comment about more efficient ways to do this.

```
(λ(s)(let([s(string->list(regexp-replace#px"(.)\\1+"s"\\1"))])(eq?(sort s char<?)s)))

```

Ungolfed:

```
(define (all-together s)
    (let ([s (string->list (regexp-replace #px"(.)\\1+" s "\\1"))])
      (eq? (sort s char<?) s )))

```

Okay, this may actually just shift the weight of computation from the `sort` function to `regexp-replace`, but it was an interesting solution. Basically, it removes runs of duplicate characters *first* (see here), then tests if the remaining length-1 runs are in sorted fashion.
> 1 votes

# Answer
# sed, 54 bytes

```
:a
/^1/{s/1*//;/1/cF
}
y/123456789/912345678/
/./ba
cT
```

Attempt This Online!
> 1 votes

# Answer
# Desmos, 83 bytes

```
A=[1...l.length][l=i]
L=join(A.min-1,A)
f(l)=[0^{max(L[2...]-L-1)}fori=l[1...]].min

```

Try It Online!

Try It Online! - Prettified
> 1 votes

# Answer
# Ruby, 30 bytes

```
->s{(s*'').squeeze==s.uniq*''}

```

Try it online!

Longer than using regex, but uses a builtin that doesn't need to exist.

`squeeze` is connected-uniquify. It's on strings, but not lists, and `uniq` is on lists, and not strings...
> 1 votes

# Answer
## Convex, 17 bytes

```
9´\f{\s'++\ð½¬}ª!

```

Try it online!
> 0 votes

# Answer
# Japt, 9 bytes

```
ò¦ mÌ
eUâ

```

Try it

---

## Explanation

```
          :Implicit input of string U             :e.g., "8884443334"
ò¦        :Split on inequality                    :["888","444","333","4"]
   mÌ     :Map and return the last digit of each  :["8","4","3","4"]
\n        :Assign to U
  Uâ      :Remove duplicates                      :["8","4","3"]
e         :Test for equality with U               :false
          :Implicit output of result

```
> 0 votes

# Answer
# APL (Dyalog), 17 bytes

```
(⍋≡⍳∘≢)∘⌽∘∊2⊥∘.=⍨

```

Try it online!
> 0 votes

# Answer
# Oracle SQL, 158 bytes

```
select decode(count(*),count(unique y),1,0)from(select regexp_substr(x,'(.)\1*',1,level,'',1)y from t connect by regexp_substr(x,'(.)\1*',1,level)is not null)

```

It works with an assumption that input data is stored in a table t(x), e.g.

```
with t(x) as (select '44999911' from dual)

```
> 0 votes

# Answer
# brev, 86 bytes

```
(fn(with(call-table)((as-list(c every(fn(or(eq?(it'l)x)(it x(not(it(it'l x))))))))x)))

```

or 79 if it doesn't have to reset its memory between each call, i.e. doesn't have to be idempotent:

```
(with(call-table)(as-list(c every(fn(or(eq?(it'l)x)(it x(not(it(it'l x)))))))))

```
> 0 votes

# Answer
# Scala 3, 58 bytes

A port of @JamesENL's Java answer in Scala.

---

Golfed version. Attempt This Online!

```
x=> !new Regex("(.)(?!\\1).*\\1").findFirstIn(x).isDefined

```

Ungolfed version. Attempt This Online!

```
import scala.util.matching.Regex

object Main {
  def main(args: Array[String]): Unit = {
    val pattern = new Regex("(.)(?!\\1).*\\1")

    val testCases = List(
      ("3", true),
      ("51", true),
      ("44999911", true),
      ("123456789", true),
      ("222222222222222222222", true),
      ("818", false),
      ("8884443334", false),
      ("4545", false),
      ("554553", false),
      ("1234567891", false)
    )

    testCases.foreach { case (input, expected) =>
      val result = !pattern.findFirstIn(input).isDefined
      assert(result == expected, s"Test case '$input' failed, expected $expected but got $result")
      println(s"Test case '$input' passed")
    }
  }
}

```
> 0 votes

---
Tags: code-golf, sequence
---


# Question
Title: Does the nth char equal the nth from last char?
Inspired by Does the start equal the end

Given a string `s` and an integer `n`, output a truthy/falsey as to whether the `n`th char in `s` equals the `n`th from the end char in `s`.

# Input

A non-empty string and an integer. You can use 0-based indexing or 1-based indexing. The integer is guaranteed to be valid based on the string. For example, if the string is "supercalifragalistic123", the integer can be from 1 to 23 for 1-based indexing, and 0 to 22 for 0-based indexing. Please note that `n` can be larger than half the length of `s`.

Input is limited to printable ASCII.

# Output

A truthy/falsey value based on whether the `n`th value in `s` equals the `n`th from last value in `s`.

Please note that the last char is in position 0 for 0-based indexing and position 1 for 1-based indexing. Think of it as comparing the string to its reverse.

# Test Cases

0-indexed

```
"1", 0         Truthy 1 == 1
"abc", 1       Truthy b == b
"aaaaaaa", 3   Truthy a == a
"[][]", 1      Falsey ] != [
"[][]", 0      Falsey [ != ]
"ppqqpq", 2    Truthy q == q
"ababab", 5    Falsey a != b
"12345", 0     Falsey 1 != 5
"letter", 1    Truthy e == e
"zxywv", 3     Falsey w != x

```

1-indexed

```
"1", 1         Truthy 1 == 1
"abc", 2       Truthy b == b
"aaaaaaa", 4   Truthy a == a
"[][]", 2      Falsey ] != [
"[][]", 1      Falsey [ != ]
"ppqqpq", 3    Truthy q == q
"ababab", 6    Falsey a != b
"12345", 1     Falsey 1 != 5
"letter", 2    Truthy e == e
"zxywv", 4     Falsey w != x

```

# Answer
# Jelly, ~~5~~  4 bytes

```
=UƓị

```

Try it online!

There should be no shorter answers in Jelly. An program would need comparison, reversal/negation, an index call, and a byte for control flow (`Ɠ` in this case), which adds up to four bytes.

**How it works**

```
 =UƓị
       - (implicit) input string
 =     - equals (vectorizing by characters because a string is a charlist)
  U    - the reversed string
    ị  - get the element at the index of:
   Ɠ   - the input index

```

*-1 byte thanks to @ais523, using `Ɠ`*
> 11 votes

# Answer
# JavaScript (ES6), 26 bytes

```
s=>n=>s[n]==s.substr(~n,1)

```

Alternatively:

```
s=>n=>s[n]==s.slice(~n)[0]

```

This one almost works, but fails when `n == 0` (because `s.slice(-1,0) == ""`):

```
s=>n=>s[n]==s.slice(~n,-n)

```

Another 26-byte solution that @RickHitchcock pointed out:

```
s=>n=>s[n]==s[s.length+~n]

```
> 15 votes

# Answer
# MATL, 5 bytes

```
tP=w)

```

Try it online!

Explanation:

```
t   % Duplicate the input

Stack:
    ['ppqqpq' 'ppqqpq']

P   % Reverse the top element of the stack

Stack:
    ['ppqqpq' 'qpqqpp']

=   % Equals. Push an array of the indices that are equal

Stack:
    [[0 1 1 1 1 0]]

w   % Swap the top two elements

Stack:
    [[0 1 1 1 1 0], 3]

)   % Grab the a'th element of b

```
> 10 votes

# Answer
# Python, ~~24~~ 22 bytes

*-2 bytes thanks to Adnan.*

```
lambda s,n:s[n]==s[~n]

```

Try it online!
> 6 votes

# Answer
# Octave, 22 bytes

```
@(s,n)s(n)==s(end-n+1)

```

Try it online!

Or the same bytecount:

```
@(s,n)s(n)==flip(s)(n)

```

Try it online!

**Explanation:**

It's quite straight forward. The first one takes a string `s` and an integer `n` as inputs and checks the n'th element `s(n)` against the "last-n+1" element for equality.

The second one checks the n'th element `s(n)` against the n'th element of `s` reversed.
> 6 votes

# Answer
# 05AB1E, ~~7~~ 5 bytes

-2 bytes thanks to Adnan

```
ÂøsèË

```

Try it online! or Try all tests

```
Â     # Add a reversed copy on top of the original string
 ø    # Zip
  sè  # Extract the nth element
    Ë # Check if they are equal

```

Try it online!
> 5 votes

# Answer
## Haskell, 22 bytes

```
s#n=s!!n==reverse s!!n

```

0-basd. Usage example: `"letter" # 1` -\> `True`.

Try it online!
> 5 votes

# Answer
# Alice, 24 bytes

```
/t.~e?/-mom
\I!RtI&1n;@/

```

Try it online!

Input consists of the string on one line, and the number on the second line. Output is `Jabberwocky` if the characters are the same, and nothing otherwise.

### Explanation

This program is mostly in ordinal mode, with one command in cardinal mode. Linearized, the program is as follows:

```
I.ReI&1m;mt!~t?&-no

I  % Input first line
   % STACK: ["ppqqpq"]
.  % Duplicate top of stack
   % STACK: ["ppqqpq", "ppqqpq"]
R  % Reverse top of stack
   % STACK: ["ppqqpq", "qpqqpp"]
e  % Push empty string
   % STACK: ["ppqqpq", "qpqqpp", ""]
I  % Input next line
   % STACK: ["ppqqpq", "qpqqpp", "", "3"]
&  % (cardinal mode) Pop stack and repeat next command that many times
   % STACK: ["ppqqpq", "qpqqpp", ""], ITERATOR: [3]
1  % Append "1" to top of stack
   % STACK: ["ppqqpq", "qpqqpp", "111"]
m  % Truncate so the top two strings on the stack have the same length
   % STACK: ["ppqqpq", "qpq", "111"]
;  % Discard top of stack
   % STACK: ["ppqqpq", "qpq"]
m  % Truncate again
   % STACK: ["ppq", "qpq"]
t  % Extract last character
   % STACK: ["ppq", "qp", "q"]
!  % Move top of stack to tape
   % STACK: ["ppq", "qp"]
~  % Swap
   % STACK: ["qp", "ppq"]
t  % Extract last character
   % STACK: ["qp", "pp", "q"]
?  % Copy data from tape onto top of stack
   % STACK: ["qp', "pp", "q", "q"]
&  % Iterator: effectively a no-op in ordinal mode when the top of the stack is a 1-character string
   % STACK: ["qp", "pp", "q"], ITERATOR: ["q"]
-  % Remove occurrences: here, result is "" iff the characters are equal
   % STACK: ["qp", "pp", ""]
n  % Logical Not (for a consistent truthy value)
   % STACK: ["qp", "pp", "Jabberwocky"]
o  % Output top of stack

```
> 5 votes

# Answer
# , ~~26, 16~~, 13 bytes

```
ä$Àñã2xñVpøˆ±

```

Try it online!

Hexdump:

```
00000000: e424 c0f1 e332 78f1 5670 f888 b1         .$...2x.Vp...

```

1 indexed.

Explanation:

```
ä$                  " Duplicate this line horizontally
  Àñ   ñ            " Arg1 times...
    ã               "   Move to the center of this line
     2x             "   And delete two characters
        V           " Select this whole line
         p          " And replace it with the last pair of characters we deleted
          ø         " Count the number of matches of the following regex...
           <0x88>   "   Any character
                 ±  "   Followed by itself

```

For reference, my original answer was:

```
Àñx$x|ñxv$hhpÓ¨.©±/1
ñllS0

```

Try it online! (0 indexed)

Hexdump:

```
00000000: c0f1 7824 787c f178 7624 6868 70d3 a82e  ..x$x|.xv$hhp...
00000010: a9b1 2f31 0af1 6c6c 5330                 ../1..llS0

```
> 4 votes

# Answer
# Java 8, ~~43~~ 42 bytes

```
s->n->s.charAt(n)==s.charAt(s.length()+~n)

```

Try it here.
> 4 votes

# Answer
# Cubix, 22 bytes

```
..@.IAp):tBvpptc?1.\O0

```

1-indexed, takes input as `index`,`string`, separated by a space.

Try it online

Cubified

```
    . .
    @ .
I A p ) : t B v
p p t c ? 1 . \
    O 0
    . .

```

### Explanation

This is mostly linear. The main logic is

```
IAp):tBpptc

IA           Get the first input as an int and the rest as a string.
  p):        Move the index to the top of the stack, increment it, and copy it.
     t       Look up the appropriate character in the string.
      Bpp    Reverse the stack and put the index and character back on top.
         t   Look up the appropriate character in the reversed string.
          c  XOR the two characters.

```

We then branch with `?` to `O`utput `1` if the result is 0 and `0` otherwise.
> 4 votes

# Answer
# C#, ~~28~~ 27 bytes

```
s=>n=>s[n]==s[s.Length+~n];

```

*Saved a byte thanks to @KevinCruijssen.*

Compiles to a `Func<string, Func<int, bool>>`.
> 3 votes

# Answer
## Ruby, ~~22~~  ~~20~~ 18 bytes

```
->s,n{s[n]==s[~n]}

```
> 3 votes

# Answer
# CJam, 8 bytes

```
l~_W%.==

```

Try it online!

0-indexed index goes first.
> 3 votes

# Answer
## R 51 bytes

```
function(s,n){s=el(strsplit(s,''));s[n]==rev(s)[n]}

```

Anonymous function, uses 1-based indexing
> 3 votes

# Answer
## Clojure, 27 bytes

```
#(nth(map =(reverse %)%)%2)

```

Wow, this was shorter than I expected.
> 3 votes

# Answer
# APL (Dyalog), ~~10~~ 5 bytes

```
⊃=⊃∘⌽

```

This is a tacit function, which needs to be assigned a name such as `f←⊃=⊃∘⌽`, and then called as `int f string`.

Thanks to @Adám for a whopping 5 bytes.

### How it works:

```
⊃=⊃∘⌽  ⍝ Main function; tacit.
       ⍝ Inputs are ⍺ = 1 (left) and ⍵ = 'abca' (right).
⊃      ⍝ ⍺⊃⍵, meaning 'pick the ⍺-th element of ⍵'
 =     ⍝ Compare to
    ⌽  ⍝ ⌽⍵, meaning 'invert ⍵'
  ⊃    ⍝ Again, ⍺⊃⍵, but:
   ∘   ⍝ Compose. This turns ⌽ into the right argument for ⊃,
       ⍝ which becomes 'pick the ⍺-th element from ⌽(the inverse of)⍵'

```

Try it online!

The 22 byte answer was edited out. If you want to see it, check the revision history.
> 3 votes

# Answer
# , ~~6~~ 5 bytes

```
{]=|.

```

Try it online!

*-4 bytes thanks to FrownyFrog for `{(=|.)`*

See original answer explanation -- idea is similar enough, but this is accomplished with a dyadic hook whose right verb is itself a monadic hook.

Try it online!

### original answer (10 bytes)

```
{=/@(,:|.)

```

`,:|.` right arg on top of reverse right arg

`=/` are they elementwise equal?

`{` take from that boolean list the index indicated by the left arg

Try it online!
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), 20 bytes

I don't have enough reputation to comment on TheLethalCoder's answer, but in C# 8 you can save some more bytes.

```
s=>n=>s[n]==s[^++n];

```

Try it online!
> 3 votes

# Answer
# Lua, 46 bytes

```
function f(s,n)return s:byte(n)==s:byte(-n)end

```

Try it online!
> 2 votes

# Answer
# Mathematica, 34 Bytes

```
s=StringTake;s[#,{#2}]==s[#,{-#2}]&

```
> 2 votes

# Answer
# PHP\>=7.1, 36 Bytes

```
[,$t,$p]=$argv;echo$t[$p]==$t[~+$p];

```

Online Version
> 2 votes

# Answer
# Perl 6, 27 bytes

```
{[eq] $^a.comb[$^b,*-1-$b]}

```

Test it

```
{ # bare block lambda with two placeholder parameters ｢$a｣ and ｢$b｣

  [eq]        # reduce using string equality operator

    $^a       # declare first positional parameter

    .comb\    # split that into individual characters

    [         # index into that sequence

      $^b,    # declare and use second parameter

      *-1-$b  # closure that subtracts one and the
              # second parameter of the outer block
              # (｢*｣ is the parameter of this closure)

    ]
}

```
> 2 votes

# Answer
# Pyth, ~~8~~ 7 bytes

```
q@zQ@_z

```

With the input reversed: first the index, then the string. It is 0-indexed.

# Explanations:

```
q@zQ@_z
 @zQ        Get the nth (Qth) character
     _z     Reverse the string
    @       Get the nth character of the reversed string. Implicit input of the index
q           Test equality

```

Try it online!
> 2 votes

# Answer
# C, ~~36~~ 35 bytes

```
#define f(s,n)s[n]==s[strlen(s)+~n]

```

Uses 0-based indexing, naturally.

Try it online!
> 2 votes

# Answer
# Factor, 24 bytes

```
[ 2dup nth -rot nth* = ]

```

Try it online!

## Explanation

`nth*` is like `nth` except it indexes from the back; if `0 nth` is the first element, `0 nth*` is the last.

```
             ! 1 "[][]"
2dup         ! 1 "[][]" 1 "[][]"
nth          ! 1 "[][]" 93
-rot         ! 93 1 "[][]"
nth*         ! 93 91
=            ! f

```
> 2 votes

# Answer
# Thunno, \\$ 8 \log\_{256}(96) \approx \\$ 6.58 bytes

```
Drz.=sAI

```

Attempt This Online!

0-indexed. Change `AI` to `AH` if you want it to be 1-indexed.

#### Explanation

```
Drz.=sAI  # Implicit input
Dr        # Duplicate and reverse
  z.=     # Zipped equality
     sAI  # Swap and index in
          # Implicit output

```
> 2 votes

# Answer
# Vyxal, 4 bytes

```
fḂ=i

```

Try it Online!

#### Explanation

```
fḂ=i  # Implicit input
f     # Flatten into a list of characters
 Ḃ    # Bifurcate: duplicate and reverse
  =   # Are they equal (vectorises)
   i  # Index in
      # Implicit output

```
> 2 votes

# Answer
## ZSH, 32

```
f(){read s n;[ $s[n] = $s[-n] ]}

```

Try it online!
> 2 votes

# Answer
# Japt, ~~10 9~~ 8 bytes

```
gV ¥Ug~V

```

Try it online!
> 1 votes

# Answer
## QBIC, 18 bytes

```
?_s;,:,1|=_sA,-a,1

```

Explanation

```
?        =     PRINT -1 if equal, 0 otherwise, between
 _s     |      A substring of
   ;,:,1          A$ string (read from cmd line), from the n'th pos, length 1
 _sA,-a,1      And a substring of A$, n'th pos from the right, also 1 length
               The second Substring is auto-terminated because EOF.

```
> 1 votes

# Answer
## CJam, 11 bytes

```
q~_2$=@@~==

```

Bad. Too much stack manipulation.
> 1 votes

# Answer
# C++, 57 Bytes

Assuming header includes don't count.

```
bool c(std::string s,int i){return s[i]==s[s.size()-i];}

```
> 1 votes

# Answer
## \>\<\> (with this interpreter), 25 bytes

```
i:0(?v
]&=n;>~{:}[:}]&r[}

```

It doesn't work in TIO: the TIO interpreter doesn't reverse the new stack when doing the `[` instruction, but the fish playground does — compare `"abcde"5[ooooo;` run here and here, for example.

The string input is taken from STDIN, and we assume *n* is already on the stack. Uses 1-indexing.

The fish gets the *n*th character with `[:}]&`, which siphons off the first *n* things on the stack into a new, reversed stack, manipulates that a bit, then puts the things back and saves the *n*th character in the register. It then reverses the whole stack and does the same again, and returns 1 if the two characters are equal, and 0 otherwise.

This seems to work at TIO, for 26 bytes:

```
i:0(?v
]&=n;>~{:}[{:}]&r[{

```
> 1 votes

# Answer
# Crystal, 26 24 Bytes

```
def c(s,n)s[n]==s[~n]end

```

-2 Bytes from Felipe Nardi Batista, thanks.

Try it online!
> 1 votes

# Answer
# C, 73 bytes

Compiles as-is with GCC 6.3.1 (no flags). Some unnecessary obfuscation included.

```
main(c,v)char**v;{c=atoi(v[2]);putchar((*++v)[c]-(*v)[strlen(*v+1)-c]);}

```

Usage

```
$./a.out abcdcba 6

```

Truthy = nothing, falsey = garbage.
> 1 votes

# Answer
# Lua, 35 bytes

Uses 1-indexing.

```
s,n=...print(s:byte(n)==s:byte(-n))

```

Try it online!
> 1 votes

# Answer
## REXX, 41 bytes

```
parse arg n,=(n)l+1''-(n)r+1 .
return l=r

```

Arguments are given in `n,s` order since `n` is required for parsing `s`.
> 1 votes

# Answer
# shortC, 23 bytes

```
Df(s,n)s[n]==s[Ss)-1-n]

```

Try it online!

Substitutions in this program:

* `D` -\> `#define`
* `S` -\> `strlen(`
* No auto-inserted closing stuff :(
> 1 votes

# Answer
# Perl 5, 23 + 3 (`-lF`) = 26 bytes

```
say$F[$n=<>]eq$F[-1-$n]

```

Try it online!

Uses 0 indexing
> 1 votes

# Answer
# Thunno 2, 3 bytes

```
Ḳ=i

```

Try it online!

#### Explanation

```
Ḳ=i  # Implicit input
Ḳ    # Bifurcate the input string
 =   # Check for equality (vectorised)
  i  # Index into this list
     # Implicit output

```
> 1 votes

# Answer
# Itr, 6 bytes

`ä¡Y=à@`

0-indexed

online interpreter

## Explanation

```
ä       ; duplicate the first (implicit) input
 ¡      ; reverse it
  Y=    ; zip the two lists with equality
    à@  ; get the element at the index given by the second index
        ; implicit output

```
> 1 votes

# Answer
## Javascript, 20 bytes

```
s=>n=>s[n]==s.at(~n)

```
> 1 votes

# Answer
# PowerShell, 18 bytes

```
$a[$b]-eq$a[-$b-1]

```

Try it online!
> 1 votes

# Answer
# Uiua, 5 bytes

```
⊡:=⇌.

```

Try it!

```
⊡:=⇌.
    .  # duplicate
   ⇌   # reverse
  =    # elementwise equal
 :     # flip
⊡      # pick

```
> 1 votes

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


title: Bingo Cards SVG Code

text:
# Question
Title: Bingo Cards SVG Code
Generate the contents of an SVG file containing 6 bingo cards. Winner is the one that uses the shortest code. A qualifying answer has an output that can be directly pasted in a blank to get the required image. Rules are as follows.

* The generated SVG code should comply with SVG version 1.1 described here.
* The size of the image should be equal to either Letter or A4 page sizes.
* Cards should be arranged in 3 rows and 2 columns.
* Each card should be 3 inches in width and height.
* Each card should contain numbers 1 to 25 in random order, arranged in 5x5 squares. The numbers in all 6 cards should be generated independently.
* Text size should be 20 points and text color should be black.
* Text font should be Helvetica, Arial, Calibri or Open Sans. Text should be centered in each cell.
* The line in the cards should have thickness either 0.5 or 1 points, and black color.
* The cards should be arranged evenly around the image: The vertical distances between cards and the vertical distances between the cards and image boundaries should all be the same. Similar for horizontal distances.
* There is a margin of 5% allowed in each dimension, but all cards should be strictly equal in size.

The following image shows the intended layout of the image, although sizes and spacing may not be accurate.

Can someone please close my older question and open up this one? This question is more realistic for because it doesn't need file-write operations or libraries. I could update the older question to remove the PDF requirement, but it was already getting allegations of a chameleon question so I didn't want to risk it. I can delete the older question if there is no other option but I would prefer to keep it (even if closed).

# Answer
# Python 3.10 ~~1954~~ 943 bytes

Thanks to the suggestion by lyxal, the code is almost half the original length.

```
from random import shuffle
def m(h,j,k,l):
    print('<line x1="'+str(h)+'pt" y1="'+str(j)+'pt" x2=\"'+str(k)+'pt"
y2="'+str(l)+'pt" stroke="black" stroke-width="1pt" />')
print('<svg version="1.1" width="612pt" height="792pt"
xmlns="http://www.w3.org/2000/svg">')
a=[i for i in range(1,26)]
for b in range(0,3):
    for c in range (0,2):
        shuffle(a)
        e=252*b
        d=276*c
        m(60+d,36+e,276+d,36+e)
        m(276+d,36+e,276+d,246+e)
        m(60+d,36+e,60+d,246+e)
        m(60+d,246+e,276+d,246+e)
        for g in range(0,5):
            f=g*43.2
            m(60+d,36+e+f,276+d,36+e+f)
            m(60+d+f,36+e,60+d+f,246+e)
            for i in range(0,5):
                print('<text x="'+str(81.6+d+f)+'pt" y="'+str(57.6+e+i*43.2)+'pt" dominant-baseline="middle" text-anchor="middle" font-size="20pt" font-family="Arial, Helvetica, sans-serif">'+str(a[i+5*g])+'</text>')
print("</svg>")

```
> -3 votes

---
Tags: code-golf, random
---