title: Am I a Rude Number?

text:
# Question
Title: Am I a Rude Number?
For a while now, I've been running into a problem when counting on my fingers, specifically, that I can only count to ten. My solution to that problem has been to count in binary on my fingers, putting up my thumb for one, my forefinger for two, both thumb and forefinger for three, etc. However, we run into a bit of a problem when we get to the number four. Specifically, it requires us to put up our middle finger, which results in a rather unfortunate gesture, which is not typically accepted in society. This type of number is a *rude number*. We come to the next rude number at 36, when we raise the thumb on our second hand and the middle finger of our first hand. The definition of a rude number is any number that, under this system of counting, results in us putting up *only* the middle finger of any hand. Once we pass 1023 (the maximum number reachable on one person, with two hands of five fingers each), assume we continue with a third hand, with additional hands added as required.

## Your Task:

Write a program or function that receives an input and outputs a truthy/falsy value based on whether the input is a rude number.

## Input:

An integer between 0 and 109 (inclusive).

## Output:

A truthy/falsy value that indicates whether the input is a rude number.

## Test Cases:

```
Input:    Output:
0   --->  falsy
3   --->  falsy
4   --->  truthy
25  --->  falsy
36  --->  truthy
127 --->  falsy
131 --->  truthy

```

## Scoring:

This is , so the lowest score in bytes wins.

# Answer
# APL (dzaima/APL), 5 bytes

```
4∊32⊤

```

Try it online!

`4∊` is 4 a member of

`32⊤` to-base-32?
> 33 votes

# Answer
# Regex (ECMAScript), 37 bytes

Input is in unary, as the length of a string of `x`s.

```
^((?=(x+)(\2{31}x*))\3)*(x{32})*x{4}$

```

Try it online!

```
^
(
    (?=(x+)(\2{31}x*))    # \2 = floor(tail / 32); \3 = tool to make tail = \2
    \3                    # tail = \2
)*                        # Loop the above as many times as necessary to make
                          # the below match
(x{32})*x{4}$             # Assert that tail % 32 == 4

```
> 19 votes

# Answer
# JavaScript (SpiderMonkey), 23 bytes

```
f=x=>x&&x%32==4|f(x>>5)

```

Try it online!

This is a trivial solution, you just want to convert to base 32 and check if there is a 4 in it.

---

# JavaScript (SpiderMonkey), 26 bytes

```
x=>x.toString(32).match(4)

```

Try it online!

It's interesting that `/4/.test(...)` cost one more byte than `....match(4)`.
> 15 votes

# Answer
## Ruby, ~~36~~ 19 bytes

```
->n{n.to_s(32)[?4]}

```

Try it online!

Saved 17 bytes with @tsh's method.
> 10 votes

# Answer
# Japt, 5 bytes

```
sH ø4

```

Try it online!

### Explanation

```
      // Implicit input
sH    // To a base-H (=32) string
   ø  // Contains
    4 // 4 (JavaScript interprets this as a string)

```
> 10 votes

# Answer
# APL+WIN, 10 bytes

Prompts for input of integer

```
4∊(6⍴32)⊤⎕

```

Noting six hands are required to represent 10^9 converts to vector of 6 elements of the base 32 representation and checks if a 4 exists in any element.
> 8 votes

# Answer
# Python 2, ~~34~~ 32 bytes

```
f=lambda a:a%32==4or a>0<f(a/32)

```

Try it online!

2 bytes thanks to tsh
> 7 votes

# Answer
# Perl 6, 16 bytes

```
{.base(32)~~/4/}

```

Try it online!

Checks if there is a `4` in the base 32 representation of the number. Returns either Nil as false or a Match containing a `4`.

You can prove this by the fact that \\$2^5 = 32\\$ so each digit is the state of each hand.
> 6 votes

# Answer
# x86 Machine Code, 17 bytes

```
6A 20 59 85 C0 74 09 99 F7 F9 83 FA 04 75 F4 91 C3

```

The above bytes define a function that takes the number as input in the `EAX` register, and returns the result as a Boolean value in the `EAX` register (`EAX` == 0 if the input is *not* a rude number; `EAX` != 0 if the input *is* a rude number).

In human-readable assembly mnemonics:

```
; Determines whether the specified number is a "rude" number.
; Input:    The number to check, in EAX
; Output:   The Boolean result, in EAX (non-zero if rude; zero otherwise)
; Clobbers: ECX, EDX
IsRudeNumber:
    push    32           ; \ standard golfing way to enregister a constant value
    pop     ecx          ; /  (in this case: ECX <= 32)
CheckNext:
    test    eax, eax     ; \ if EAX == 0, jump to the end and return EAX (== 0)
    jz      TheEnd       ; /  otherwise, fall through and keep executing
    cdq                  ; zero-out EDX because EAX is unsigned (shorter than XOR)
    idiv    ecx          ; EAX <= (EAX / 32)
                         ; EDX <= (EAX % 32)
    cmp     edx, 4       ; \ if EDX != 4, jump back to the start of the loop
    jne     CheckNext    ; /  otherwise, fall through and keep executing
    xchg    eax, ecx     ; store ECX (== 32, a non-zero value) in EAX
TheEnd:
    ret                  ; return, with result in EAX

```

**Try it online!**
> 6 votes

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

```
n=>{for(;n>0;n/=n%32==4?0:32);}

```

Outputs by throwing an exception. The way you convert one number from decimal to another base is to divide the decimal number by that base repeatedly and take the remainder as a digit. That is what we do, and we check if any of the digits have a value of 4 in base-32;

Try it online!
> 4 votes

# Answer
# , 12 bytes

```
4 e.32#.inv]

```

Try it online!
> 4 votes

# Answer
# Julia 1.0, 25 bytes

```
f(n)=n%32==4||n>0<f(n>>5)

```

Try it online!

### Julia 1.0, 26 bytes

Alternative that is 1 character shorter, but 1 byte longer, too bad that  takes 3 bytes in unicode.

```
n->'4'∈string(n,base=32)

```

Try it online!
> 4 votes

# Answer
# 05AB1E, 5 bytes

```
32B4å

```

Port of *@Adám*'s APL (dzaima/APL) answer.

Try it online or verify all test cases.

**Explanation:**

```
32B    # Convert the (implicit) input to Base-32
   4å  # And check if it contains a 4
       # (output the result implicitly)

```
> 4 votes

# Answer
# Catholicon, 4 bytes

```
ǔ?QǑ

```

Takes a number as a base-256 string.

Try it online!

Test suite
> 4 votes

# Answer
# , ~~50~~ 48 bytes

```
any(2^(0:4)%*%matrix(scan()%/%2^(0:34)%%2,5)==4)

```

Try it online!

Uses a neat matrix-based approach now (courtesy of @Giueseppe). It generates a 5x7 matrix of bits, converts this to a series of base 32 integers, and checks for any 4s.
> 3 votes

# Answer
# ES6, ~~31~~ ~~30~~ 26 bytes

```
b=>b.toString(32).match`4`

```

Feel free to say ideas on how to reduce this further, if any.
> 3 votes

# Answer
# Python 3, 43 bytes

Checks every 5-bit chunk to see if it is rude (equal to 4).

```
lambda n:any(n>>5*i&31==4for i in range(n))

```

Try it online!
> 2 votes

# Answer
# C (gcc), 34 bytes

```
f(i){return i?i&31^4?f(i/32):1:0;}

```

Try it online!
> 2 votes

# Answer
# Charcoal, 6 bytes

```
№⍘Ｎ³²4

```

Try it online! Link is to verbose version of code. Outputs `-`s according to how rude the number is. Explanation:

```
  Ｎ     Input as a number
 ⍘      Convert to base as a string
   ³²   Literal 32
№       Count occurrences of
     4  Literal string `4`

```

I use string base conversion to avoid having to separate the numeric literals for `32` and `4`.
> 2 votes

# Answer
# Tidy, 18 bytes

```
{x:4∈base(32,x)}

```

Try it online! Checks if `4` is an element of `base(32,x)` (base conversion).
> 2 votes

# Answer
# Haskell, 31 bytes

```
elem 9.(mapM(:[6..36])[0..5]!!)

```

Try it online!
> 2 votes

# Answer
# MATL, 8 bytes

```
32YA52=a

```

Try it online!
> 2 votes

# Answer
# Cubix, 26 bytes

```
u!@-W14;OIS%/\;;,p;?wO@u/s

```

Try it online!

Wraps onto a cube with edge length 3 as follows

```
      u ! @
      - W 1
      4 ; O
I S % / \ ; ; , p ; ? w
O @ u / s . . . . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

```

Watch it run

A fairly basic implementation, without all the redirects it does :

* `IS` initiates the program by pushing the input and 32 to the stack
* `%4-!` gets the remainder and checks if it is 4 by subtraction
* `1O@` output 1 if it was 4 and halt
* `;;,` clean up the stack and do integer divide
* `p;?` clean up bottom of the stack and check div result for 0
* `O@` if div result zero output and halt
* `s` swap the top of stack and start back at step 2 above
> 2 votes

# Answer
## Batch, ~~77~~ 45 bytes

```
@cmd/cset/a"m=34636833,n=%1^m*4,(n-m)&~n&m*16

```

Based on these bit twiddling hacks. Explanation: Only 6 hands need to be checked due to the limited range (30 bits) of the input that's required to be supported. The magic number `m` is equivalent to `111111` in base 32, so that the first operation toggles the rude bits in the input number. It then remains to find which of the 6 hands is now zero.
> 2 votes

# Answer
# x86 machine code, 14 bytes

(same machine code works in 16-bit, 32-bit, and 64-bit. In 16-bit mode, it uses AX and DI instead of EAX and EDI in 32 and 64-bit mode.)

Algorithm: check low 5 bits with `x & 31 == 4`, then right-shift by 5 bits, and repeat if the shift result is non-zero.

Callable from C with `char isrude(unsigned n);` according to the x86-64 System V calling convention. 0 is truthy, non-0 is falsy (this is asm, not C1).

```
 line   addr    code bytes
  num
     1                             ; input:  number in EDI
     2                             ; output: integer result in AL: 0 -> rude, non-zero non-rude
     3                             ; clobbers: RDI
     4                         isrude:
     5                         .check_low_bitgroup:
     6 00000000 89F8               mov    eax, edi
     7 00000002 241F               and    al, 31          ; isolate low 5 bits
     8 00000004 2C04               sub    al, 4           ; like cmp but leaves AL 0 or non-zero
     9 00000006 7405               jz    .rude            ; if (al & 31 == 4) return 0;
    10
    11 00000008 C1EF05             shr    edi, 5
    12 0000000B 75F3               jnz   .check_low_bitgroup
    13                             ;; fall through to here is only possible if AL is non-zero
    14                         .rude:
    15 0000000D C3                 ret

    16          0E             size:  db $ - isrude

```

This takes advantage of the short-form `op al, imm8` encoding for AND and SUB. I could have used `XOR al,4` to produce 0 on equality, but SUB is faster because it can macro-fuse with JZ into a single sub-and-branch uop on Sandybridge-family.

Fun fact: using the flag-result of a shift by more than 1 will be slow on P6-family (front-end stalls until the shift retires), but that's fine.

---

Footnote 1: This is an assembly language function, and x86 asm has both `jz` and `jnz`, so as per meta I can choose either way. I'm not intending this to match C truthy/falsy.

It happened to be convenient to return in AL instead of EFLAGS, so we can describe the function to a C compiler without a wrapper, but my choice of truthy/falsy isn't constrained by using a C caller to test it.
> 2 votes

# Answer
# Nibbles, 4.5 bytes

```
?`@32$4

```

Attempt This Online!

```
?`@32$4
?        Find the first index of
      4  4
 `@32    in the base 32 representation of
     $   input

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~37 bytes~~ ~~36 bytes~~ 29 bytes

*-2 bytes by Jonathan Frech*

```
#~IntegerDigits~32~MemberQ~4&

```

Try it online!

31-byte solution:

```
MemberQ[IntegerDigits[#,32],4]&

```

Try it online!
> 1 votes

# Answer
# Java 8, ~~40~~ 33 bytes

```
n->n.toString(n,32).contains("4")

```

Port of *@Adám*'s APL (dzaima/APL) answer.

Try it online.

**Explanation:**

```
n->                 // Method with Integer parameter and boolean return-type
  n.toString(n,32)  //  Convert the input to a base-32 String
   .contains("4")   //  And check if it contains a "4"

```
> 1 votes

# Answer
# Retina 0.8.2, 31 bytes

```
.+
$*
+`(1+)\1{31}
$1;
\b1111\b

```

Try it online! Link includes test cases. Outputs zero unless the number is rude. Works by converting the input to unary and then to unary-encoded base 32 and counting the number of `4`s in the result.
> 1 votes

# Answer
# \>\<\>, 28 bytes

Outputs **4** for rude numbers throws an exception for non-rude numbers.

```
:1(?^:" ":\
,&-v?=4:%&/
 ;n<

```

Try it online!
> 1 votes

# Answer
# Java 8, ~~28~~ ~~22~~ 21 bytes

```
n->n%32==4|n>>5%32==4

```

Inspired by *@kevin-cruijssen*'s answer. Only works for 2 hands.

Try it online!

**Explanation:**

```
n->                 // Method with int parameter and boolean return-type
  n%32              // Only consider right 5 bytes (fingers)
  ==4               // Middle finger
  | ... n>>5       // Repeat with shifted bits for other hand

```
> 1 votes

# Answer
# Jelly, 6 bytes

```
ḃ32=4Ẹ

```

Try it online!

Returns 1 if the number is rude, 0 otherwise

```
ḃ32=4Ẹ
ḃ32      # convert to base 32
   =4    # For each entry, is it equal to 4?
     Ẹ   # Are any equal to 4??

```
> 1 votes

# Answer
# Scala, 44 bytes

Try it online!

```
def f(a:Int):Boolean=a%32==4||(a>0&&f(a/32))

```
> 1 votes

# Answer
# Vyxal `G`, 36 bits1, 4.5 bytes

```
32τ4=

```

Try it Online! (link is to bitstring)

Suggested by @lyxal

### Vyxal, 37 bits1, 4.625 bytes

```
32τ4c

```

Try it Online! (link is to bitstring) or see all the rude numbers up to 200

#### Explanation

```
32τ4=  # Implicit input
32τ    # Input in base 32
   4=  # Equals 4 (vectorised)?
       # Implicit output of maximum

```

```
32τ4c  # Implicit input
32τ    # Input in base 32
   4c  # Contains 4?
       # Implicit output

```
> 1 votes

# Answer
# Thunno 2, 5 bytes

```
32B4Ƈ

```

Try it online! or see all the rude numbers up to 200

Does the base-32 (`32B`) version of the input contain 4 ()?
> 1 votes

# Answer
# Perl 5, 43 bytes

```
sub f{sprintf("%099b",@_)=~/00100(.{5})*$/}

```

Try it online!
> 0 votes

# Answer
# Ink, ~~38~~ 36 bytes

```
=r(n)
{n:{n%32-4:->r(n/32)|1}|0}->->

```

Try it online!

Edit: Saved 2 bytes by simplifying the first conditional to "if n" rather than "if n\>0".
> 0 votes

# Answer
# K 8 Bytes

```
|/4=32\:

```

True if any digit of 32-base is 4

* `32\:` converts its argument to 32-base
* `4=32\:` compares 4 with each of the digits of 32: (generates a boolean list)
* `|/` is max-over the boolean list (any)

NOTES:

* Use example: for argument 131 `|/4=32\:131` returns `1b` (`1b` for true `0b` for false)
* For all the case tests: `(|/4=32\:)'0 3 4 25 36 127 131` returns `0010101b`
* If a function is needed, use `{|/4=32\:x}` (lambda, 11 Bytes) or with name `r:{|/4=32\:x}`. For all case tests `{|/4=32\:x}'0 3 4 25 36 127 131` or `r'0 3 4 25 36 127 131`
* `4 in 32\:` is easier to read than `|/4=32\:`, but it's longer (9 bytes)
> 0 votes

# Answer
# Java 1, ~~42~~ 40 bytes

```
r(int n){return n>0&&(4==n%32|r(n>>5));}

```

Edit: Replaced ternary operator with && to save 1 char, thanks to @Dillon Davis, which works due to short-circuit; inspiring me to change || to | to save another character

Try it online.

**Explanation:**

```
r(int n)        // Method with int parameter and boolean return-type
  n>0           // Stop recursion if no more bits
  &&            // Short-circuit stops recursion
  n%32=4        // Rude
  | r(n>>5)     // Recurse with shifted bits

```
> 0 votes

# Answer
# Kotlin, 24 bytes

Simple base-32 conversion approach.

```
{'4' in it.toString(32)}

{  // lambda implicitly takes an int and returns a boolean
 '4' in  // 4 is within...
        it.toString(32)  // arg written in base-32
}

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 5 bytes

```
32в4¢

```

Try it online!

Returns a truthy value (\> 1) if the input is a rude number, and 0 otherwise. Uses a conversion to base 32 (to group by 5 bits) and tests for a 4 (00100 in binary, a rude number)
> 0 votes

# Answer
## Perl 6, 16 bytes

```
{.base(32)~~/4/}

```

Returns `｢4｣` (truthy) when given a rude number and `Nil` (falsy) otherwise.
> 0 votes

# Answer
# GolfScript, 10 bytes

Empty list is false, a list with something is true. (Seems like cheating. But it isn't.)

```
~32base 4&

```

Try it online!

## Explanation

```
~           # Evaluate the input
 32base     # Convert to base-32
            # Copy
        4&  # Setwise and: does this list have 4?

```
> 0 votes

---
Tags: code-golf, number, decision-problem
---


title: Numbers with Rotational Symmetry

text:
# Question
Title: Numbers with Rotational Symmetry
Given an integer, output a truthy value if it is the same upside-down (rotated 180°) or a falsy value otherwise.

`0`, `1`, and `8` have rotational symmetry. `6` becomes `9` and vice versa.

Sequence of numbers producing truthy results: OEIS A000787

```
0, 1, 8, 11, 69, 88, 96, 101, 111, 181, 609, 619, 689, 808, 818, 888, 906, 916, 986, 1001, 1111, 1691, 1881, 1961, 6009, 6119, 6699, 6889, 6969, 8008, 8118, 8698, 8888, 8968, 9006, 9116, 9696, 9886, 9966, 10001, 10101, 10801, 11011, 11111, 11811, 16091, ...

```

This question is inspired by my own reputation at the time of posting: `6009`.

# Answer
> 7 votes
# 05AB1E, 12 bytes

```
žhÀ•yΘOñ•‡RQ

```

Try it online!

I somehow managed to beat Adnan's 05AB1E answer lol. This

## Explained

```
žhÀ             # Push "1234567890"
   •yΘOñ•       # Push "1000090860"
         ‡      # Transliterate the input based upon the previous two strings
          RQ    # Check if the reverse of that equals the input

```

# Answer
> 15 votes
## Python 2, 50 bytes

```
lambda n:`n`==`map('01xxxx9x86'.find,`n`)`[-2::-3]

```

The method `'01xxxx9x86'.find` takes a digit character to it's upside-down number, with any unflippable digit giving `-1`. This function is mapped to the reversed number string, producing a list of digits.

This is converted to a string with the `[1::3]` trick, except it's reversed instead by doing `[-2::-3]` (thanks to Dennis for this, saving 4 bytes), and compared to the original number string. Any `-1`'s from unflippable digits will misalign the conversion, making it fail.

---

**56 bytes:**

```
lambda n:`n`[::-1]==`n`.translate('01xxxx9x86______'*16)

```

Checks if the number string reversed is the same as it with the upside-down replacements. Digits that can't be flipped are replaced with `'x'` to always give the wrong answer.

The replacement is done with `translate` on a string of 256 chars, replacing the corresponding ASCII values. Only the 10 values `48` to `57` matter, but I padded to length 16 to make the total length be 256. I wonder if there's a shorter way.

Some other approaches (lengths 59, 60, 60):

```
lambda n:set(zip(`n`,`n`[::-1]))<=set(zip('01896','01869'))
r=lambda s:set(zip(s,s[::-1]));lambda n:r(`n`)<=r('9018106')
lambda n:all(a+b in'001188969'for a,b in zip(`n`,`n`[::-1]))

```

# Answer
> 9 votes
# Regex (ECMAScript / Python), ~~366~~ ~~323~~ ~~254~~ ~~201~~ ~~180~~ ~~148~~ 135 bytes

`^(x$|x{8}$|(?=.*?(?=(((x*)\4{8}(?=\4$))+x$))(x*)\5{99})(?=(\2x)(|\6{5}(\6\6|\2{3}|xxx))(?!\2)(x*)\9{9}$)(?=(x*(?=\5|$))(|\5x)\9$)\10)*$`

Takes its input in unary, as the length of a string of `x`s.

Try it online! \- ECMAScript
Try it online! \- Python
Try it on replit.com! \- RegexMathEngine (much faster), in ECMAScript mode

It's impossible for a ECMAScript regex to match the sequence in decimal, but as demonstrated here, it's possible in unary.

The regex works by looping the following logic:

1. Carve away both the leading and trailing digit if they are an allowed pair, or (for single-digit values) an allowed single digit.
2. Prevent the value sent to the next iteration from having any leading zeroes, since the regex operates on numbers, not strings, so any leading zeroes would be stripped. If it has a leading zero, add \\$1\\$ to both the leading and trailing digit. If both were zero, both will be changed to \\$1\\$, preserving the trait of symmetry. If the trailing digit was nonzero (meaning the input is not a rotationally symmetric number), adding one of \\$11, 101, 1001, ...\\$ is guaranteed not to change it to one that is symmetric, because for example \\$1001\\$ could only be added to any number in the range \\$0001\\$ to \\$0999\\$ with a nonzero last digit, which can only yield a number in the range \\$1002\\$ to \\$2000\\$ with a last digit other than \\$1\\$, none of which are rotationally symmetric. This allows us to golf off 13 bytes, due to not needing the trailing zero check `(?=(x{10})*$)`.

The 135 byte version has been tested from 0 to 1000000 using RegexMathEngine without finding any false positives or negatives. The test took 29.342 hours (single-threaded) on my i7-4930K @ 4.1 GHz.

(This was originally part of this answer and was split due to being very different in nature. See that post's edit history for changes made prior to the 254 byte length.)

```
^                        # tail = input number
(
    x$                   # If tail==1, let tail=0 and end the loop
|
    x{8}$                # If tail==8, let tail=0 and end the loop
|
    # Assert tail >= 10; find \2 = the largest power of 10 that is <= tail
    (?=
        .*?              # Decrease tail by the minimum necessary to satisfy
                         # the following assertion:
        (?=
            # Assert tail is a power of 10 >= 10; \2 = tail
            (((x*)\4{8}(?=\4$))+x$)
        )
        (x*)\5{99}       # \5 = floor(tail / 100)
    )

    # Require tail is of the form 1.*1, 8.*8, 6.*9, or 9.*6
    (?=
        (\2x)            # \6 = \2 + 1
        (
                         # 1.*1
        |
            \6{5}
            (
                \6\6     # 8.*8
            |
                \2{3}    # 9.*6
            |
                xxx      # 6.*9
            )
        )
        (?!\2)
        (x*)\9{9}$       # Assert tail is divisible by 10;
                         # \9 = tail / 10 == floor((N % \2) / 10)
    )

    # Set tail = \9, but if \9 is of the form 0.*0, the next iteration would
    # not be able to see its leading zero, so change it to the form 1.*1 in
    # that case, otherwise leave it unchanged. If \9 is of the form 0.*[1-9],
    # don't go to the next iteration.
    (?=
        (                # \10 = tool to make tail = \9 or \9 + \5 + 1
            x*
            # Assert that the leading digit of tail is not 0, unless tail==0
            (?=
                \5       # Assert that the leading digit of tail is not 0
            |            # or
                $        # Assert that tail==0
            )
        )
        # Iff necessary to satisfy the above, tail += \5 + 1
        (
        |
            \5x
        )
        \9$              # tail = \9
    )
    \10                  # tail = \9 or \9 + \5 + 1
)*                       # Execute the above loop as many times as possible,
                         # with a minimum of zero iterations.
$                        # Assert tail==0

```

# Answer
> 8 votes
# 05AB1E, ~~22~~ ~~16~~ ~~15~~ 14 bytes

Code:

```
Â23457ð«-69Â‡Q

```

Try it online!

---

Previous code:

```
Â69Â‡Q¹¹„vd•ÃQ*

```

To figure out if the string is rotational symmetric, we just need to transliterate `69` with `96`, reverse the string and check if they are equal. The other thing we need to know is if the number *only* contains the digits `0`, `1`, `8`, `6` and `9`. So that's exactly what we are going to do:

```
Â                     # Bifurcate the input, which pushes input and input[::-1]
 69Â                  # Bifurcate 69, which pushes 69 and 96.
    ‡                 # Transliterate 69 with 96 in the input, e.g. 1299 becomes 1266.
     Q                # Check for equality.
      ¹¹              # Push input again twice.
        „vd•          # Compressed version for 10869.

```

The `„vd•` part actually converts the string `vd` from *base 190* to *base 10*. You can try this out here.

```
            Ã        # Keep the characters of the second string in the first string.
                       667788 would become 6688 (since 7 is not in 10869).
             Q       # Check for equality.
              *      # Multiply the top two numbers, which actually does an AND function.

```

Uses **CP-1252** encoding. Try it online!

# Answer
> 6 votes
# Ruby, 54 46 bytes

```
 ->a{(b=a.to_s).tr('1-9','1w-z9x86').reverse==b}

```

I don't know, is anonymous functions like that allowed or not

Basically same idea as Python2 answer. If input is not integer, act bad (i.e. `aba` gives `true`)

# Answer
> 6 votes
# Regex (Perl / PCRE2 / Boost / Python`regex`), 35 bytes

```
^(([018])((?1)\2|)|6(?1)9|9(?1)6|)$

```

Takes its input in decimal.

Try it online! \- Perl
Try it online! \- PCRE2
Try it online! \- Boost
Attempt This Online! \- Python `import regex`

```
^              # Assert this is the start of the string
(              # Define (?1) recursive subroutine call
    ([018])    # \2 = match a 0, 1, or 8
    ((?1)\2|)  # Optionally match (?1) followed by \2
|              # or
    6(?1)9
|              # or
    9(?1)6
|              # or
    # Match an empty string
)
$              # Assert this is the end of the string

```

## Regex (Ruby), 43 bytes

```
^(([018])(\g<1>\k<2+0>|)|6\g<1>9|9\g<1>6|)$

```

Try it online!

This is a direct port of the Perl/PCRE2/Boost version to Ruby's subroutine call syntax and behavior; `(?1)` has been changed to `\g<1>`, and `\2` to `\k<2+0>`.

In Perl, PCRE, and Boost, the contents of capture groups are passed to deeper recursion levels, but upon return from a subroutine call, all captures are returned to the state they were in before the subroutine was called, i.e. there is no way to pass captures done within a subroutine call back to its caller. But in Ruby, captures *are* passed to the caller. So `\2` will refer to whatever it captured at the deepest recursion level, and so would `\k<2>`. It is possible, however, to refer to a capture's value at a specific recursion level; that is why `\k<2+0>` is used here to refer to its value at the current level.

## Regex (.NET), ~~94~~ ~~77~~ ~~66~~ 53 bytes

```
^((?=([018]|6.*9|9.*6)(?<=(.))).?)+(?<-3>\3)*(?(3)^)$

```

Try it online!

Implementing this using .NET's Balancing Groups feature turns out to provide an edge over the 57 byte .NET-compatible version that doesn't use any .NET-specific features.

```
^                 # Assert we're at the beginning of the string
(
    (?=
        # Depending on what the next left-edge digit is, push its corresponding
        # right-edge digit onto the Group 3 stack.
        (
            [018]
        |
            6.*9
        |
            9.*6
        )
        (?<=(.))  # \3 = the right-edge digit (push it onto the Group 3 stack)
    )
    .?
)+
(?<-3>\3)*        # Match all right-edge digits in reverse order as they're
                  # popped from the stack.
(?(3)^)           # Assert that the Group 3 stack is now empty (literally: if
                  # its stack is not empty, assert something impossible, that
                  # we're at the beginning of the string).
$                 # Assert we've reached the end of the string, having matched
                  # all of its characters.

```

## Regex (Perl / PCRE / .NET), ~~106~~ ~~62~~ 57 bytes

```
^((?=([018]|6.*9|9.*6)(?<=(.))).?(?=.*(\3(?(4)\4))))*\4?$

```

Try it online! \- Perl
**Try it online! \- PCRE1**
Try it online! \- PCRE2
Try it online! \- .NET

In PCRE1, subroutine calls are atomic, which prevents the Perl/PCRE2/Boost version (which requires backtracking to extend into nested subroutine calls) from working. As for .NET (and Java), subroutine calls are not supported.

In this version, instead of using recursion, we read inward from the left and right edges, one pair of characters at a time, remembering the right-edge position using capture group `\4`. A set of alternatives followed by a lookbehind is used to set the required right-edge digit based on whether the left-edge digit was `[018]`, `6`, or `9`.

```
^
(
    # Depending on the next left digit, capture the required right digit in \3
    (?=
        (
            [018]
        |
            6.*9
        |
            9.*6
        )
        (?<=(.))       # Capture the previous character (the right digit) in \3
    )
    .?
    (?=
        .*
        (              # Capture \4 as the following:
            \3
            # Match \4 iff it has been captured (i.e., iff this is not the
            # first iteration). As such, \4 will be prepended with the current
            # right digit.
            (?(4)\4)
        )
    )
)*
\4?
$

```

## Regex (Perl / PCRE / Java / .NET), ~~113~~ ~~76~~ ~~69~~ 64 bytes

```
^((?=([018]|6.*9|9.*6)(?<=(.))).?(?=.*(\3(\6\4|(?!\6))())))*\4?$

```

Try it online! \- Perl
Try it online! \- PCRE1
Try it online! \- PCRE2
**Try it online! \- Java**
Try it online! \- .NET

This is a port of the Perl/PCRE/.NET version, removing the use of the conditional due to their lack in Java, and emulating it with an empty capture whose set/unset status can be detected. Only the modified portion is shown below:

```
            # Match \4 iff it has been captured (i.e., iff this is not the
            # first iteration). As such, \4 will be prepended with the current
            # right digit.
            (
                \6\4
            |
                (?!\6)
            )
            ()         # \6 = set and empty, to signal \4 is captured

```

# Answer
> 4 votes
## JavaScript (ES6), 56 bytes

```
n=>n==[...''+n].reverse().map(c=>'0100009086'[c]).join``

```

# Answer
> 4 votes
## Retina, ~~40~~ ~~38~~ 33 bytes

```
$
;$_
T`92-7`69`;.+
+`(.);\1
;
^;

```

Try it online!

### Explanation

This uses a completely different approach from the other Retina answer. Instead of removing all symmetric parts, we simply perform the transformation of reversing the string and swapping `6` and `9`s and then compare for equality. To make sure that no non-symmetric digits appear we also turn them into `9`s in one half.

```
$
;$_

```

We duplicate the input by matching the end of the string and inserting `;` followed by the entire input.

```
T`92-7`69`;.+

```

This performs a character transliteration only on the second half by matching it with `;.+`. The two transliteration sets expand to:

```
9234567
6999999

```

Because `2-7` denotes a range and the target set is padded with the last character to match the length of the source set. Hence, the stage swaps `6` and `9` and also turns all of `23457` into `9`s.

```
+`(.);\1
;

```

Repeatedly (`+`) remove a pair of identical characters around the `;`. This will either continue until only the `;` is left or until the two characters around the `;` are no longer identical, which would mean that the strings aren't the reverse of each other.

```
^;

```

Check whether the first character is `;` and print `0` or `1` accordingly.

# Answer
> 4 votes
# sh, ~~40~~ 33 bytes

```
[ `rev<<<$1|tr 6923457 96` = $1 ]

```

Input via command line argument, output via exit code. Generate all testcases:

```
for i in `seq 0 10000`
do
  if [ `rev<<<$i|tr 6923457 96` = $i ]
  then
    echo $i
  fi
done

```

# Answer
> 4 votes
# C, 73 ~~82~~ bytes

```
f(x){int y=0,z=x;for(;x;x/=10)y=y*10+"0100009086"[x%10]-'0';return z==y;}

```

## Expanded

```
static const char s[] = "0100009086";
int f(int x)
{
    int y=0, z=x;
    for(; x; x/=10)
        y = y*10 + s[x%10]-'0';
    return z==y;
}

```

## Explanation

We reverse the digits of `x` using modulo-10 arithmetic, replacing 6 and 9 by their reflections as we go. We replace the rotationally-asymmetric digits by zeros (note that we can handle symmetric fives and/or twos by simply changing the replacement table `s`). If the new number is equal to the original (saved in 'z'), then it is rotationally symmetric.

## Test program

```
#include <stdio.h>
int main()
{
    int i;
    for(i=0;  i <= 16091; ++i)
        if (f(i))
            printf("%d\n", i);
}

```

This prints the list of symmetric numbers given in the question.

# Answer
> 4 votes
# Knight, 70 bytes

```
;=p=sP;=a'';Ws;=a+I|?54=bAs?57bA-111bI||?48b?49b?56bAb''a=sSsF1''O?a p

```

Working with strings is a pain in Knight

Try It Online!

Test Suite

# Answer
> 3 votes
# GNU sed, 84 bytes

(including +1 for `-r` flag)

```
:
s/^6(.*)9$/\1/
s/^9(.*)6$/\1/
s/^([081])(.*)\1$/\2/
t
s/^[081]$//
s/.+/0/
s/^$/1/

```

If the line ends with a rotation of its beginning character, trim both ends by one. Repeat until there's no match. Account for a single symmetric character, then if anything remains, the input was not symmetric, and we return false; otherwise return true.

# Answer
> 3 votes
# Jelly, ~~16~~ 15 bytes

```
,ȷ9+90860¤Dị/⁼Ṛ

```

Try it online!

### How it works

```
,ȷ9+90860¤Dị/⁼Ṛ  Main link. Argument: n (integer)

         ¤       Evaluate the three links to the left as a niladic chain:
 ȷ9              Yield 1000000000.
    90860        Yield 90860.
   +             Add to yield 1000090860.
,                Pair; yield [n, 1000090860].
          D      Convert both integers to base 10.
           ị/    Reduce by index, i.e., for each digit of n, retrieve the element
                 of [1, 0, 0, 0, 0, 9, 0, 8, 6, 0] at that index (1-based).
              Ṛ  Yield the digits of n in reversed order.
             ⁼   Test for equality.

```

# Answer
> 3 votes
# Retina, ~~57~~ 49 bytes

8 bytes saved thanks to @Martin Büttner.

```
+`^(([018])(.*)\2|9(.*)6|6(.*)9)$
$3$4$5
^[018]?$

```
* Apply reduction as such: `1610880191` -\> `61088019` -\> `108801` -\> `0880` -\> `88` -\> (empty).
* Returns `1` if only `0`, `1`, `8`, or (empty) is left.
* Returns `0` otherwise.

Try it online!

# Answer
> 3 votes
# TSQL, 122 bytes

I am new to code golf, so not quite sure how to count the characters. Counting it as 1 here since the number used in this case is 8

This will return 1 when the reversed value match and nothing when it doesn't match:

```
SELECT 1FROM(values(8))x(x)WHERE(x)NOT like'%[23457]%'and REPLACE(REPLACE(x,6,4),9,6)=REVERSE(REPLACE(REPLACE(x,9,4),9,6))

```

Human readable:

```
SELECT 1
FROM
  (values(808))x(x)
WHERE(x)
  NOT like'%[23457]%'
  and REPLACE(REPLACE(x,6,4),9,6)=REVERSE(REPLACE(REPLACE(x,9,4),9,6))

```

# Answer
> 3 votes
# Wolfram Language (Mathematica), 56 bytes

```
#~ContainsNone~{2,3,4,5,7}&&Reverse@#==(#/.{6->9,9->6})&

```

Try it online!

Takes input as a list of digits.

## Explanation:

---

`#~ContainsNone~{2,3,4,5,7}` Check if the input contains no unflippable digits

`&&Reverse@#` and that the reverse of the input

`==(#` is equal to the input

`/.{6->9,9->6})&` where all 6s are replaced with 9s and 9s with 6s.

# Answer
> 3 votes
# Julia

## 47 bytes

The first attack.

```
!x=10(d=digits(x))+reverse(d)⊆[0,11,88,69,96]
```

Attempt This Online!

## 39 bytes

Using `@b_str` it can be golfed further as proposed by @MarcMush and @Deadcode:

Attempt It Online!

# Answer
> 3 votes
# Pure bash, 99 bytes

Using `shopt -s extglob`:

```
o=;for i in ${1//*()/ };do o=${i//6/_}$o;done; o=${o//9/6} o=${o//_/9}
[[ ${o//[23457]} == "$1" ]]

```

There are 98 bytes +1 for *extglob* -\> 99 bytes.

## Without extglob, 101 bytes

```
o=;for((i=${#1};i--;)){ o+=${1:i:1};};o=${o//6/_} o=${o//9/6} o=${o//_/9}
[[ $1 == "${o//[23457]}" ]]

```

Sample:

```
rotatable() {
    o=;for i in ${1//*()/ };do o=${i//6/_}$o;done; o=${o//9/6} o=${o//_/9}
    [[ ${o//[23457]} == "$1" ]]
}
for((x=0;x<10000;x++)){ rotatable $x&&echo $x;}|column
0       69      111     689     906     1111    6009    6969    8888    9696
1       88      181     808     916     1691    6119    8008    8968    9886
8       96      609     818     986     1881    6699    8118    9006    9966
11      101     619     888     1001    1961    6889    8698    9116

```

# Answer
> 2 votes
# Perl, ~~29~~ 26 bytes

Includes +1 for `-p`

Run with the input on STDIN:

```
rotation.pl <<< 69

```

`rotation.pl`:

```
#!/usr/bin/perl -p
$_=reverse==y/962-7/69a/r

```

# Answer
> 2 votes
# MATL, ~~25~~ ~~21~~ 22 bytes

```
j69801VmAGtP69VtPXE=vA

```

**Try it Online!**

**Explanation**

```
j       % Explicitly grab input as string
69801   % Number literal
V       % Convert to a string
mA      % Check if all input chars are members of this list
G       % Explicitly grab the input
tP      % Duplicate and flip it
69      % Number literal
V       % Convert to string ('69')
tP      % Duplicate and flip it ('96')
XE      % Replace all '6' with '9', and '9' with '6'
=       % Check that this substituted string is equal to the original
v       % Vertically concatenate all items on the stack
A       % Ensure everything is true
        % Implicitly print boolean result

```

# Answer
> 2 votes
# Pyth, 17 bytes

```
!-FmC_B`d,QC\

```

Test it in the Pyth Compiler.

### How it works

```
!-FmC_B`d,QC\  (implicit) Store the input in Q.

            \  Yield the Unicode character with code point 1068901.
           C    Compute its code point.
         ,Q     Pair the input and 1068901.
   m            Map; for each d in [Q, 1068901]:
       `d         Yield the string representation of d.
     _B           Yield the pair of `d` and `d` reversed.
    C             Zip. For the second string, this gives
                  ['11', '00', '69', '88', '96', '00', '11'].
 -F             Fold by difference, i.e., removes all pairs in the second list
                from the first list.
!               Logically negate the result, returning True iff the list is empty.

```

# Answer
> 2 votes
## Visual Basic for Applications, ~~150~~ 111 bytes

Usable in console or as an UDF.

```
Function c(b)
c=(Not b Like"*[!01869]*")And b=Replace(Replace(Replace(StrReverse(b),9,7),6,9),7,6)
End Function

```

Improved by taking advantage of implicit type conversions and by doing three steps swapping instead of two steps on each side of the equation. Count includes `Function` and `End Function` statements.

# Answer
> 2 votes
# AWK, ~~85~~ ~~84~~ ~~82~~ 80 bytes

```
{n=split($1,a,s="");for(;n;){b=a[n--];s=s (b~/[2-57]/?9:b~6?9:b~9?6:b)}$1=s~$1}1

```

This feels like brute-forcing, but awk has very limited tools, mostly aimed to text processing. This code allows multiple inputs.

```
{
n=split($1,a,s="");    # this splits $1 (the input) into the array _a_
                       # using an empty string as token. each element of the
                       # array is a digit of the input number.
                       # also, sets the number of elements to _n_,
                       # and sets the empty string to _s_.

for(;
    n;          # loops until n==0 (evaluates to false)
   ){
      b=a[n--]; # sets the _n_ element of the array to _b_. this will save bytes later
                # immediately after, decrements _n_ by 1 (one less byte here)

                        # here the magic happens:
      s=s (             # this appends a chaining conditional to the variable _s_
          b~/[2-57]/?9: # if _b_ equals 2, 3, 4, 5 or 7, returns 9 (dummy number)
          b~6?9:        # otherwise, if _b_ equals 6, returns 9
          b~9?6:        # otherwise, if _b_ equals 9, returns 6
          b             # otherwise, returns its value
          )
    }
$1=s~$1      # evaluates if _s_ matches $1, and sets this boolean to $1
}
1            # prints $1.

```

Try it online!

---

# AWK, 78 bytes

This is almost the same as above, but without the `s` variable. Two less bytes, with the effect of allowing only one input.

```
{n=split($1,a,"");for(;n;){b=a[n--];s=s (b~/[2-57]/?9:b~6?9:b~9?6:b)}$1=s~$1}1

```

Try it online!

# Answer
> 2 votes
# Stax, 16 bytes

```
ê±°";╙ñ♀C¼EE^☼ùΣ

```

Run and debug it

# Answer
> 2 votes
# Julia 1.0, 45 bytes

```
!x=prod(d->"01....9.86"[1+d],digits(x))=="$x"

```

Try it online!

# Answer
> 2 votes
# Vyxal, 12 bytes

```
»\Π»F∑69S*Ṙ=

```

Try it Online!

```
    F∑       # Remove elements of...
»\Π»         # 23457
         *   # Ring translate by...
      69S    # "69"
          Ṙ= # Does it, reversed, equal the input?

```

# Answer
> 2 votes
# JavaScript (Node.js), 55 bytes

```
n=>!(e=[...''+n]).some(c=>'0x'+'01aaaa9a86'[c]-e.pop())

```

Try it online!

Half test of `n=>![...''+n].some((c,i,e)=>'0100009086'[c]-e.slice(~i)[0])`

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 58 bytes

```
n=>$"{n}".Aggregate("",(z,c)=>"01----9-86"[c-48]+z)==n+"";

```

Try it online!

# Answer
> 2 votes
# PHP, 49 bytes (anonymous function)

```
fn($s)=>$s==strrev(strtr($s,"6923457","9600000"))

```

Try it online!

The `strtr` translates `6` to `9`, `9` to `6`, and all non-symmetric digits to `0` (any character other than themselves would work). The digits `0`, `1`, and `8` are left unchanged. (The order I put them in is purely a stylistic choice; I don't think it even makes a difference in speed.)

Then `strrev` reverses this result, which is then compared with the original string; if they're equal, it has rotational symmetry.

# PHP `-F`, 51 bytes (full program)

```
<?=$argn==strrev(strtr($argn,"6923457","9600000"));

```

Try it online!

# Answer
> 1 votes
# Pyth - 21 bytes

```
&!-z+`180K`69qzX_z_KK

```

Test Suite.

# Answer
> 1 votes
## Seriously, 23 bytes

```
,$;`"01xxxx9x86"í`MRεj=

```

Try it online!

This is essentially a port of xnor's Python 2 solution.

Explanation:

```
,$;`"01xxxx9x86"í`MRεj=
,$;                      push two copies of str(input)
   `"01xxxx9x86"í`M      map: get each digit's rotated digit (or x if not rotatable)
                   Rεj   reverse and join on empty string to make a string
                      =  compare equality with original input

```

# Answer
> 1 votes
# Kotlin, 69 bytes

This takes the number, converts it to a string, rotates it, and then compares it with the original as a string for equality. Non-rotatable digits are simply converted to `0`

```
{i->"$i".map{"0100009086"[it-'0']}.joinToString("").reversed()=="$i"}

```

Test it Here!

# Answer
> 1 votes
# , 111 bytes

With integer input and 0 output corresponding to `truthy`

```
f=sum
p=1:nchar(a<-scan())
b=a%%(l<-10^p)%/%(l/10)
d=(b-rev(b))^2
f(b>2&b<8&b!=6)+f(d[b<2|b==8])+f(d[!b%%3]!=9)

```

Try it online!

# Answer
> 1 votes
Nobody had posted a Python 3 solution so I'll go with my rubbish one

# Python 3, ~~190~~ 95 bytes

```
lambda x:not str(x).replace('0','').replace('1','').replace('6','').replace('8','').replace('9','').replace('0','')and str(x)[::-1].replace('6','z').replace('9','6').replace('z','9')==str(x)

```

EDIT:

```
lambda x:(x:=str(x))==[x:=x[::-1].replace(*p)for p in['6z','96','z9']][2]and not{*x}-{*'01689'}

```

# Answer
> 1 votes
# K (ngn/k), ~~25~~ 24 bytes

```
{d~|"01986""01689"?d:$x}

```

Try it online!

-1 byte thanks to @ngn

My first version was 74 bytes but then I read @xnor's solution and decided to translate that.

# Answer
> 1 votes
# K (ngn/k), 21 bytes

```
{y~|x[>x]x?y}/$68910,

```

Try it online!

`68910,` prepend 68910 to the argument

`$` format both as strings

`{` `}/` apply a function to x=`"68910"` and y= the original argument as string

`x?y` find the positions of the elements of `y` among `x`. use "null" (`0N`) for "nout found".

`x[>x]` down-sorted `x`, i.e. `"98610"`

`x[>x]x?y` index `x[<x]` with `x?y`. out-of-bounds indexing produces spaces

`|` reverse

`y~` test if `y` matches that

# Answer
> 1 votes
# Zsh, ~~65~~ 56 bytes

*Thanks to pxeger for saving a whopping **9 bytes**!*

```
>${(j..)${(Oas..)1}}<${${${${1//6/.}//<2-7>}//9/6}//./9}

```

~~Try it online!~~ Try it online!

Outputs via return code. The `>` construct *creates* and opens a file whose name is the reversed number for writing. The program will only exit truthy when the `<` construct attempts to read from a file with 6/9 swapped, and 2/3/4/5/7 removed.

# Answer
> 0 votes
# PHP, 83 bytes

```
<?=$argn==strrev(str_replace([6,9,x],[x,6,9],preg_replace("/[^01689]/","",$argn)));

```

Save the code in a file (let's say `symmetry.php`) and run it as:

```
php -d error_reporting=0 -F symmetry.php

```

Run it online on TIO.

The algorithm is simple: remove the non-symmetric characters, replace `6` with `9` and `9` with `6` then reverse the result. If it equals the input string then it is a rotationally symmetrical number.

# Answer
> 0 votes
# Brev, 80 bytes

```
(define(r n)(= n((as-list reverse(over(vector-ref #(0 1 3 4 5 6 9 8 8 6)x)))n)))

```

Non-minified:

```
(define (rotsym? n)
  (= n ((as-list reverse (over (vector-ref #(0 1 3 4 5 6 9 8 8 6) x))) n)))

```

# Answer
> 0 votes
# Swift, 148 bytes

```
var a=[0,1,6,8,9],b=[0,1,9,8,6],c=readLine()!.map {Int(String($0))!},f = false,t = c.count;for i in 0..<t{f = c[t-i-1] == b[a.index(of: c[i]) ?? 0]}

```

# Answer
> 0 votes
# Scala, 184 bytes

Golfed version. Try it online!

```
def f(n:Int)=n.toString.map{case '1'=>'1';case '2'=>'w';case '3'=>'z';case '4'=>'y';case '5'=>'x';case '6'=>'9';case '7'=>'x';case '8'=>'8';case '9'=>'6';case c=>c}==n.toString.reverse

```

Ungolfed version. Try it online!

```
object Main {
  def f(n: Int): Boolean = {
    val original = n.toString
    val transformed = original.map {
      case '1' => '1'
      case '2' => 'w'
      case '3' => 'z'
      case '4' => 'y'
      case '5' => 'x'
      case '6' => '9'
      case '7' => 'x'
      case '8' => '8'
      case '9' => '6'
      case c => c
    }
    original == transformed.reverse.mkString
  }

  def main(args: Array[String]): Unit = {
    for (n <- 1 until 1005 if f(n)) {
      println(s"$n satisfies the condition")
    }
  }
}

```

# Answer
> 0 votes
# Lua, 73 bytes

```
r=''s=...s:gsub('.',load'r=({0,1,0,0,0,0,9,0,8,6})[...+1]..r')print(r==s)

```

Try it online!

# Answer
> 0 votes
# Thunno 2, 12 bytes

```
kDḣ»©®£~»Ṇr=

```

Try it online!

Thunno 2, Vyxal, and 05AB1E all at 12 bytes!

#### Explanation

```
kDḣ»©®£~»Ṇr=  # Implicit input
kDḣ           # Push "123456789"
   »©®£~»     # Push "100009086"
         Ṇ    # Transliterate
          r   # Reverse it
           =  # Equals the input?

```

---
Tags: code-golf, number, sequence, decision-problem
---


title: EvenSt-ring C ode - g ol!f

text:
# Question
Title: EvenSt-ring C ode - g ol!f
An 'Even string' is any string where the parity of the ASCII values of the characters is always alternating. For example, the string `EvenSt-ring$!` is an even-string because the ASCII values of the characters are:

```
69 118 101 110 83 116 45 114 105 110 103 36 33

```

And the parities of these numbers are:

```
Odd Even Odd Even Odd Even Odd Even Odd Even Odd Even Odd

```

Which is alternating the whole way. However, a string like `Hello world!` is *not* an even string because the ASCII values are:

```
72 101 108 108 111 32 87 111 114 108 100 33

```

And the parities are:

```
Even Odd Even Even Odd Even Odd Odd Even Even Even Odd

```

Which is clearly not always alternating.

# The challenge

You must write either a full program or a function that accepts a string for input and outputs a truthy value if the string is even, and a falsy value otherwise. You can take your input and output in any reasonable format, and you can assume that the input will only have printable ASCII (the 32-127 range). You do *not* have to handle empty input.

# Examples

Here are some examples of even strings:

```
#define
EvenSt-ring$!
long
abcdABCD
3.141
~
0123456789
C ode - g ol!f
HatchingLobstersVexinglyPopulateJuvenileFoxglove

```

And all of these examples are not even strings:

```
Hello World
PPCG
3.1415
babbage
Code-golf
Standard loopholes apply
Shortest answer in bytes wins
Happy golfing!

```

You may also use this ungolfed solution to test any strings if you're curious about a certain test-case.

# Answer
> 20 votes
# MATL, ~~4~~ 3 bytes

Thanks to *Emigna* for saving a byte and thanks to *Luis Mendo* for fixing some bugs. Code:

```
doA

```

Explanation:

```
d     # Difference between the characters
 o    # Mod 2
  A   # Matlab style all

```

Try it online!

# Answer
> 17 votes
# 05AB1E, ~~5~~ 4 bytes

Saved 1 byte thanks to *Adnan*.

```
Ç¥ÉP

```

Try it online!

**Explanation**

```
Ç       # convert to ascii values
 ¥      # compute delta's
  É     # mod by 2
   P    # product

```

# Answer
> 13 votes
# Jelly, ~~7~~ ~~5~~ 4 bytes

```
OIḂẠ

```

Saved 2 bytes using the deltas idea from @Steven H.

Saved 1 byte thanks to @Lynn.

Try it online! or Verify all test cases.

## Explanation

```
OIḂẠ  Input: string S
O     Ordinal
 I    Increments
  Ḃ   Mod 2
   Ạ  All, 0 if it contains a falsey value, else 1

```

# Answer
> 8 votes
# Python 2, 54 Bytes

```
lambda s:all((ord(x)-ord(y))%2for x,y in zip(s,s[1:]))

```

# Answer
> 7 votes
# Mathematica, ~~50~~ 44 bytes

*The current version is basically all Martin Ender's virtuosity.*

```
Differences@ToCharacterCode@#~Mod~2~FreeQ~0&

```

Returns `True` or `False`. Nothing too clever: takes the mod-2 sum of each pair of consecutive ASCII codes, and checks that 0 is never obtained.

Old version:

```
Union@Mod[Most[a=ToCharacterCode@#]+Rest@a,2]=={1}&

```

# Answer
> 6 votes
## R, 41 35 bytes

EDIT: Saved a few bytes thanks to @JDL by using `diff` instead of `rle`.

```
all(diff(utf8ToInt(readline())%%2))

```

---

```
all(rle(utf8ToInt(readline())%%2)[[1]]<2)

```

**Explanation**

1. `readline()` read input.
2. `utf8ToInt()%%2` convert to ascii values and mod 2 (store as R-vector)
3. `all(rle()==1)` run length encoding of to find runs. All runs should be equal to one or smaller than 2 since no runs cant be negative or 0 (saves one byte instead of `==`).

# Answer
> 6 votes
# JavaScript (ES6), ~~60~~ ~~50~~ 46 bytes

```
s=>[...s].every(c=>p-(p=c.charCodeAt()%2),p=2)

```

I tried recursion, but at 51 bytes, it doesn't seem to be quite worth it:

```
f=([c,...s],p=2)=>c?p-(p=c.charCodeAt()%2)&f(s,p):1

```

### Test snippet

```
f=s=>[...s].every(c=>p-(p=c.charCodeAt()%2),p=2)
```

```
<input id=I value="Evenst-ring"><button onclick="console.log(f(I.value))">Run</button>
```

# Answer
> 6 votes
# Brain-Flak, ~~138~~ ~~114~~ ~~112~~ 84 + 3 = 87 bytes

Thanks to @Riley for help golfing.

This program treats empty input as a noneven string.

```
{({}(())){({}[()]<(()[{}])>)}{}(({})<>[[]{}]()){{}(<>)}{}({}<>)<>}<>(([])[()]){<>}{}

```

Try it online!

## Explanation (outdated)

Shifts the input from the left stack to the right while modding by 2. Finds the difference between each adjacent character until all have been checked or one of the differences is equal to zero (which would only occur in a noneven string). If the loop terminated due to a noneven string then switch back to the left stack and pop the value remaining on it. Otherwise, stay on the right stack and pop the zero above the 1 remaining on the stack.

# Answer
> 5 votes
# Pyth (fork), 9 bytes

```
.A%R2.+CM

```

No Try It Online link because the fork does not have its own version in the online interpreters.

Explanation:

```
       CM       Map characters to their ASCII codes.
     .+         Get deltas (differences between consecutive character codes)
  %R2           Take the modulo of each base 2
.A              all are truthy (all deltas are odd)

```

# Answer
> 5 votes
# Brachylog, 17 bytes

```
@c:{:2%}a@b:{l1}a

```

Try it online!

### Explanation

```
@c                   Input to a list of char codes
  :{:2%}a            Apply X mod 2 for each X in the list of char codes
         @b          Split the list into a list of lists where each sublist elements are the
                       same, e.g. turn [1,0,1,1,0,0] into [[1],[0],[1,1],[0,0]]
           :{l1}a    The length of each sublist must be 1

```

# Answer
> 5 votes
# Java 8, ~~77~~ ~~76~~ ~~72~~ 57 bytes

```
a->{int i=2,b=1;for(int c:a)b=i==(i=c%2)?0:b;return b>0;}

```

-4 bytes thanks to *@Geobits*.

**Explanation:**

Try it online.

```
a->{               // Method with character-array parameter and boolean return-type
  int i=2,         //  Integer `i`, starting at any integer not 0 or 1
      b=1;         //  Flag-integer `b`, starting at 1
  for(int c:a)     //  Loop over the input-array
    b=i==(i=c%2)?  //   If two adjacent characters were both odd or even:
       0           //    Set the flag-integer `b` to 0
      :            //   Else:
       b;          //    The flag-integer `b` remains the same
  return b>0;}     //  Return if the flag-integer `b` is still 1

```

# Answer
> 4 votes
# Brain-Flak 155 151 141 121

Includes +3 for -a

Saved 30 bytes thanks to 1000000000

```
{({}(())){({}[()]<(()[{}])>)}{}({}()<>)<>}<>{({}[({})]<(())>){((<{}{}>))}{}({}[()]<>)<>}<>{{}}([]<(())>){((<{}{}>))}{}

```

Output:
**truthy**: 1
**falsy**: 0 on top of the stack

Try it online! (truthy)
Try it online! (falsy)

---

Better explanation coming later (if I can remember how it works after a few hours...)

```
#compute ((mod 2) + 1) and put on other stack
{({}(())){({}[()]<(()[{}])>)}{}({}()<>)<>}<>

#compare top two (remove top 1) push on other stack (-1 for different 0 for same)
{({}[({})]<(())>){((<{}{}>))}{}({}[()]<>)<>}<>

#remove all of the top -1s
{{}}

#take the logical not of the stack height
([]<(())>){((<{}{}>))}{}

```

# Answer
> 4 votes
# Starry, 85 bytes

```
 ,       +    *   ` , +               + * ' +  ' `       +    * +   + *   '     +  `.

```

Try it online!

Note that since a Starry program has no way of telling when an input of arbitrary length ends, this program uses a trailing newline in the input to mark the end of the string. If you get a cryptic error message about and undefined method `ord` for `nil:NilClass` then the input is missing a trailing newline.

## Explanation

The basic strategy that the program employs is it reads the characters one by one from input and if they are not a newline (character 10) it mods they ASCII value of the character by 2 and finds the difference between it and the previously read character. If the difference is zero the program terminates and prints `0` (falsey). Otherwise the program loops back and does the process over again. If the program reads a newline it terminates and prints `10` (truthy).

### Annotated Program

```
 ,               Push the first character
       +         Push 2
    *            Replace the first character and 2 with the first character mod 2
   `             Label 3 <--------------------------------------------------------\
 ,               Push the next the character                                      |
 +               Push a duplicate of it                                           |
               + Push 10                                                          |
 *               Replace the 10 and the duplicate with their difference           |
 '               Pop and if not zero (the read char is not 10) goto label 1 >-\   |
 +               Push a duplicate of the character which must be newline (10) |   |
  '              Pop and goto label 2 >---------------------------------------+-\ |
 `               Label 1 <----------------------------------------------------/ | |
       +         Push 2                                                         | |
    *            Replace the character and 2 with the character mod 2           | |
 +               Duplicate it ^                                                 | |
   +             Roll the top three items on the stack. The top goes to         | |
                   the bottom. The top three items are now                      | |
                   (from top to bottom) the current character, the previous     | |
                   character, the current character (all modded by 2).          | |
 *               Replace the current character and previous character           | |
                   with their difference                                        | |
   '             Pop if nonzero goto label 3 >----------------------------------+-/
     +           Push zero                                                      |
  `              Label 2 <------------------------------------------------------/
.                Print out the number on top of the stack
                    0 if we came by not following the goto label 3
                   10 if we came by going to label 2

```

# Answer
> 3 votes
## Perl, 24 + 1 (`-p`) = 25 bytes

*-4 bytes thanks to @Ton Hospel !*

```
s/./$&&v1/eg;$_=!/(.)\1/

```

Needs `-p` flag. Outputs 1 is the string is even, nothing otherwise. For instance :

```
perl -pe 's/./$&&v1/eg;$_=!/(.)\1/' <<< "#define
Hello World"

```

*Explanations* : replaces each character by its value mod 2 (so the string contains only 0s and 1s after that). Then search for two following 1 or 0 : if it finds some, then the string isn't even, otherwise it is.

# Answer
> 2 votes
# J, 15 bytes

```
0=1#.2=/\2|3&u:

```

## Usage

```
   f =: 0=1#.2=/\2|3&u:
   f 'C ode - g ol!f'
1
   f 'Code-golf'
0

```

## Explanation

```
0=1#.2=/\2|3&u:  Input: string S
           3&u:  Get ordinals of each char
         2|      Take each modulo 2
     2  \        For each pair of values
      =/           Test if they are equal, 1 if true else 0
  1#.            Treat the list of integers as base 1 digits and convert to decimal
                 This is equivalent to taking the sum
0=               Is it equal to 0, 1 if true else 0, and return

```

# Answer
> 2 votes
# Vim, 38 bytes

`qqs<C-R>=char2nr(@")%2<CR><Esc>l@qq@q:g/00\|11/d<CR>`

Assumes input string in buffer, and empty `"q`. Outputs binary nonsense if true, nothing if false.

* `s<C-R>=char2nr(@")%2<CR>`: Replaces a character with 1 if odd, 0 if even. The macro this is in just does this to every character in the line (no matter how long it is).
* `:g/00\|11/d<CR>`: Deletes the line if 2 consecutive "bits" have the same value. Faster than a back-reference.

Normally, in vimgolf, when you use an expression function inside a macro, you're supposed to do the macro itself on the expression register and use some trickery to tab-complete. That's more difficult this time. I may find a way to shorten that later.

# Answer
> 2 votes
## Retina, 39 bytes

Byte count assumes ISO 8859-1 encoding.

```
S_`
%{2`
$`
}T01`p`_p
..

Mm`.¶.|^¶$
^0

```

Outputs `1` for truthy and `0` for falsy.

Try it online! (The first line enables a linefeed-separated test suite.)

### Explanation

Inspired by a answer of mbomb007's I recently developed a reasonably short `ord()` implementation in Retina. This is largely based on that, although I was able to make a few simplifications since I don't need a decimal result in since I only need to support printable ASCII (and I only care about the parity of the result, so ending up with an arbitrary offset is fine, too).

**Stage 1: Split**

```
S_`

```

This simply splits the input into its individual characters by splitting it around the empty match and dropping the empty results at the beginning and end with `_`.

**Stage 2: Replace**

```
%{2`
$`

```

The `%{` tells Retina a) that this stage and the next should be run in a loop until the string stops changing through a full iteration, and that these two stages should be applied to each line (i.e each character) of the input separately.

The stage itself is the standard technique for duplicating the first character of the input. We match the empty string (but only look at the first two matches) and insert the prefix of that match. The prefix of the first match (at the beginning of the string) is empty, so this doesn't do anything, and the prefix of the second match is the first character, which is therefore duplicated.

**Stage 3: Transliterate**

```
}T01`p`_o

```

`}` indicates the end of the loop. The stage itself is a transliteration. `01` indicates that it should only be applied to the first character of the string. `p` is shorthand for all printable ASCII characters and `_` means "delete". So if we expand this, the transliteration does the following transformation:

```
from:   !"#$%...
to:    _ !"#$...

```

So spaces are deleted and all other characters are decremented. That means, these two stages together will create a character range from space to the given character (because they'll repeatedly duplicate and decrement the first character until it becomes a space at which point the duplication and deletion cancel).

The length of this range can be used to determine the parity of the character.

**Stage 4: Replace**

```
..

```

We simply drop all pairs of characters. This clears even-length lines and reduces odd-length lines to a single character (the input character, in fact, but that doesn't really matter).

**Stage 5: Match**

```
Mm`.¶.|^¶$

```

It's easier to find inputs which *aren't* even, so we count the number of matches of either two successive empty lines or two successive non-empty lines. We should get `0` for even inputs and something non-zero otherwise.

**Stage 6: Match**

```
^0

```

All that's left is to invert the result, which we do by counting the number of matches of this regex, which checks that the input starts with a `0`. This is only possible if the result of the first stage was `0`.

# Answer
> 2 votes
# Clojure, 59 bytes

```
#(every?(fn[p](odd?(apply + p)))(partition 2 1(map int %)))

```

Generates all sequential pairs from string `n` and checks if every pair sum is odd. If a sequence of ints is considered a reasonable format then it's 50 bytes.

```
#(every?(fn[p](odd?(apply + p)))(partition 2 1 %))

```

See it online : https://ideone.com/USeSnk

# Answer
> 2 votes
## Haskell, ~~42~~ 40 bytes

```
all odd.(zipWith(-)=<<tail).map fromEnum

```

Usage example: `all odd.(zipWith(-)=<<tail).map fromEnum $ "long"` -\> `True`.

How it works:

```
               map fromEnum         -- turn into a list of ascii values
    (zipWith(/=)=<<tail)            -- build a list of neighbor differences
all odd                             -- check if all differences are odd

```

Edit: @xnor saved two bytes. Thanks!

# Answer
> 2 votes
## Julia, ~~55~~ 53 Bytes

```
f(s)=!ismatch(r"00|11",join(map(x->Int(x)%2,[s...])))

```

**Explained**

Map chars to 0|1 and check if the resulting string contains "00" or "11", which makes the string not alternating.

# Answer
> 2 votes
## Python, 52 bytes

```
f=lambda s:s==s[0]or(ord(s[0])-ord(s[1]))%2*f(s[1:])

```

A recursive function. Produces 1 (or True) for even strings, 0 for odd ones. Multiplies the parity of the difference of the first two characters by the recursive value on the remainder. A single-character string gives True, as checked by it equaling its first character. This assumes the input is non-empty; else, one more byte is needed for `s==s[:1]` or `len(s)<2`.

---

**Python 2, 52 bytes**

```
p=r=2
for c in input():x=ord(c)%2;r*=p-x;p=x
print r

```

Alternatively, an iterative solution. Iterates over the input characters, storing the current and previous character values mod 2. Multiplies the running product by the difference, which because 0 (Falsey) only when two consecutive parities are equal.

The "previous" value is initialized to 2 (or any value not 0 or 1) so that the first character never matches parity with the fictional previous character.

---

**Python, 42 bytes, outputs via exit code**

```
p=2
for c in input():x=ord(c)%2;p=x/(p!=x)

```

Outputs via exit code. Terminates with a ZeroDivisionError when two consecutive characters have the same parities, otherwise terminates cleanly.

# Answer
> 2 votes
# Ruby, ~~41~~ 30 (+1) bytes

```
p gsub(/./){$&.ord%2}!~/(.)\1/

```

Call this from the command line with the `-n` flag, like so:

```
ruby -ne 'p gsub(/./){$&.ord%2}!~/(.)\1/'

```

Replaces each character with the parity of its ASCII value and then compares to a regex. If even, the `=~` comparison will return the index of the first match (i.e. 0), which is a truthy value in Ruby; if not even, the comparison will return `nil`.

Thanks to Jordan for the improvements!

# Answer
> 2 votes
# Mathematica, ~~41~~ 40 Bytes

```
And@@OddQ@Differences@ToCharacterCode@#&

```

-1 character, thanks to Martin Ender

# Answer
> 2 votes
## C, 52 bytes

```
int f(char*s){return s[1]?(s[0]-s[1])%2?f(s+1):0:1;}

```

Compares the parity of first 2 characters, recursively moving through the string until it finds 2 characters with the same parity or the string with the length of 1 (`s[1] == 0`).

Code with some of the test cases

# Answer
> 1 votes
# C#, 69 bytes

```
s=>{int i=1,e=0;for(;i<s.Length;)e+=(s[i-1]+s[i++]+1)%2;return e<1;};

```

Full program with test cases:

```
using System;

namespace EvenStrings
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,bool>f= s=>{int i=1,e=0;for(;i<s.Length;)e+=(s[i-1]+s[i++]+1)%2;return e<1;};

            Console.WriteLine(f("lno")); //false

            //true:
            Console.WriteLine(f("#define"));
            Console.WriteLine(f("EvenSt-ring$!"));
            Console.WriteLine(f("long"));
            Console.WriteLine(f("abcdABCD"));
            Console.WriteLine(f("3.141"));
            Console.WriteLine(f("~"));
            Console.WriteLine(f("0123456789"));
            Console.WriteLine(f("C ode - g ol!f"));
            Console.WriteLine(f("HatchingLobstersVexinglyPopulateJuvenileFoxglove"));

            //false:
            Console.WriteLine(f("Hello World"));
            Console.WriteLine(f("PPCG"));
            Console.WriteLine(f("3.1415"));
            Console.WriteLine(f("babbage"));
            Console.WriteLine(f("Code-golf"));
            Console.WriteLine(f("Standard loopholes apply"));
            Console.WriteLine(f("Shortest answer in bytes wins"));
            Console.WriteLine(f("Happy golfing!"));
        }
    }
}

```

# Answer
> 1 votes
## Pyke, 8 bytes

```
m.o$2m%B

```

Try it here!

```
m.o      -    map(ord, input)
   $     -   delta(^)
    2m%  -  map(> % 2, ^)
       B - product(^)

```

# Answer
> 1 votes
# PHP, 69 Bytes

```
for(;$i<strlen($s=$argv[1])-1;)$d+=1-ord($s[$i++]^$s[$i])%2;echo$d<1;

```

solution with Regex 81 Bytes

```
for(;$i<strlen($s=$argv[1]);)$t.=ord($s[$i++])%2;echo 1-preg_match("#00|11#",$t);

```

# Answer
> 1 votes
## PowerShell v2+, 47 bytes

```
-join([char[]]$args[0]|%{$_%2})-notmatch'00|11'

```

(Can't *quite* catch PowerShell's usual competitors ...)

Takes input `$args[0]` as a string, casts it as a `char`-array, loops through it `|%{...}`, each iteration placing the modulo on the pipeline (with implicit `[char]` to `[int]` conversion). Those are encapsulated in parens and `-join`ed into a string, which is fed into the left-hand of the `-notmatch` operator, checking against `00` or `11` (i.e., returns `True` iff the `0`s and `1`s alternate). That Boolean result is left on the pipeline and output is implicit.

### Test Cases

```
PS C:\Tools\Scripts\golfing> '#define','EvenSt-ring$!','long','abcdABCD','3.141','~','0123456789','C ode - g ol!f','HatchingLobstersVexinglyPopulateJuvenileFoxglove'|%{"$_ --> "+(.\evenst-ring-c-ode-g-olf.ps1 $_)}
#define --> True
EvenSt-ring$! --> True
long --> True
abcdABCD --> True
3.141 --> True
~ --> True
0123456789 --> True
C ode - g ol!f --> True
HatchingLobstersVexinglyPopulateJuvenileFoxglove --> True

PS C:\Tools\Scripts\golfing> 'Hello World','PPCG','3.1415','babbage','Code-golf','Standard loopholes apply','Shortest answer in bytes wins','Happy golfing!'|%{"$_ --> "+(.\evenst-ring-c-ode-g-olf.ps1 $_)}
Hello World --> False
PPCG --> False
3.1415 --> False
babbage --> False
Code-golf --> False
Standard loopholes apply --> False
Shortest answer in bytes wins --> False
Happy golfing! --> False

```

# Answer
> 1 votes
# \>\<\>, ~~29~~ 27 bytes

```
i2%\0 n;n 1<
0:i/!?-}:%2^?(

```

Outputs 1 if the word is even, 0 if the word is odd.

You can try it online.

Edit : saved two bytes thanks to Martin Ender

# Answer
> 1 votes
# Perl 6,  ~~47~~  26 bytes

```
{?all .ords.rotor(2=>-1).map({(.[0]+^.[1])%2})}

```

```
{[~](.ords X%2)!~~/(.)$0/}

```

## Expanded:

```
# bare block lambda with implicit parameter $_
{
  [~](             # reduce using concatenation operator ( no space chars )
    .ords X[%] 2   # the ordinals cross modulus with 2 ( 1 or 0 )
  # ^-- implicit method call on $_
  )

  ![~~]            # negating meta operator combined with smartmatch operator

  / ( . ) $0 /     # is there a character followed by itself?
}

```

# Answer
> 1 votes
# Scala, 54 bytes

```
(_:String)sliding 2 map(t=>t(0)%2!=t(1)%2)reduce(_&&_)

```

I'm sure this can be improved.

# Answer
> 1 votes
# Node.js (ES6), ~~45~~ 44 bytes

```
s=>![...Buffer(s)].some((b,c,d)=>b+c-d[0]&1)

```

The `Buffer` object saved me alot of trouble over `charCodeAt()`.

Also felt like including my attempts via JavaScript (ES6), though they aren't as short as ETHproduction's:

```
a=>![...a].some((b,c,d)=>b.charCodeAt()+c-d[0]&1) // 49 bytes

```

```
a=>!/(.),\1/.test([...a].map(b=>b.charCodeAt()&1)) // 50 bytes

```

```
a=>new Set([...a].map((b,i)=>b.charCodeAt()+i&1)).size<2 // 56 bytes

```

The first in the JavaScript (ES6) equivalent of what I went with in Node.js. The second was an attempt to use regex to simplify the pattern matching (45 bytes in Node.js). The third was an attempt to use `Set`'s ability to determine unique values, combined with math that made valid arrays be either all `1`'s or `0`'s (51 bytes in Node.js).

# Answer
> 1 votes
# C, 54 bytes

```
int c,p=*s^1,r=1;while(c=*s++){r&=p^c;p=c;}return r&1;

```

An xor of previous and current chars equal to `xxxxxxx1` indicates a difference in parity. ANDing the results of every pair of chars in the string computes the string parity. A zero length string returns true.

# Answer
> 1 votes
# Attache, 17 bytes

```
All@Odd@Delta@Ord

```

Try it online!

Checks if `All` of the `Delta`s are `Odd`.

## Alternatives

19 bytes: `All##Odd''Even##Ord`

26 bytes: `All##Odd@Sum=>Slices&2@Ord`

# Answer
> 0 votes
# Groovy, ~~33~~ 30 Bytes

```
{(int)(it.getChars().sum())%2}

```

Basically collects the chars in the string into an array as their values modulo 2, sums them, then modulos the answer. In groovy a 0 is false and a 1 is a true. 0 for odd (false), 1 for true (even). This also implicitly handles empty input...

Try it: https://groovyconsole.appspot.com/script/5132426728701952

*-2 Bytes if I can output an odd number if odd, even if even.*

# Answer
> 0 votes
## APL, 26 or 25 bytes

```
{~1∊↑(2/¨0 1)⍷¨2⍴⊂2|⍵}⎕UCS

```

One byte can be saved if `⎕IO` is `0`: `{~1∊↑(2/¨⍳2)⍷¨2⍴⊂2|⍵}⎕UCS`

The dyadic function returns `1` if the string is even, `0` otherwise.

# Answer
> 0 votes
**Python 3, 65 Bytes**

```
l=p=print
for i in input():
    c=ord(i)%2
    if l==c:
        p(1>2)
        break
    l=c
else: p(1<2)

```

# Answer
> 0 votes
# C#, 55 bytes

```
s=>{var f=1;for(;0<*++s;)f&=(*--s+*++s)%2;return 0<f;};

```

For all the dangerous golfers out there.

```
/*unsafe delegate bool Function(char* s);*/ // Function signature
/*unsafe Function Lambda = */ s =>
{
    var f = 1;                              // Output var, initialized to true
    for (; 0 < *++s;)                       // Enumerate string, starting from the 2nd char
         f &= (*--s + *++s) % 2;            // Bitwise AND whether previous and current
                                            // chars are alternating because
                                            // even+odd = odd,
                                            // even+even = odd+odd = even.
    return 0 < f;                           // Cast int to bool
};

```

# Answer
> 0 votes
# MATLAB, 18 bytes

```
@(s)mod(diff(s),2)

```

This returns

```
f=@(s)mod(diff(s),2)
f('PPCG')
ans =
     0     1     0
f('#define')
ans =
     1     1     1     1     1     1

```

In MATLAB, if `x` is a vector, then `if x` is equivalent to `if all(x)`. According to this Meta post, it's enough to return `x`.

# Answer
> 0 votes
## Racket 131 bytes

```
(let p((l (map even?(map char->integer(string->list s)))))(cond[
(= 1(length l))#t][(equal?(car l)(second l))#f][else(p(cdr l))]))

```

Ungolfed:

```
(define (f s)
    (let loop ((lst (map even? (map char->integer(string->list s)))))
      (cond
        [(= 1 (length lst)) #t]
        [(equal? (first lst) (second lst)) #f]
        [else (loop (rest lst))]
        )))

```

Testing:

```
(f "EvenSt-ring$!")
(f "#define")
(f "abcdABCD")
(f "babbage")
(f "Code-golf")
(f "PPCG")

```

Output:

```
#t
#t
#t
#f
#f
#f

```

# Answer
> 0 votes
# Clean, 55 bytes

```
\x->all(\(a,b)->(toInt a-toInt b)rem 2>0)(zip2 x(tl x))

```

# Answer
> 0 votes
# Brain-Flak, 60 bytes

```
(()){{}({}({})(())){({}[()]<(()[{}])>)}{}}{}((){[()]<{{}}>})

```

Try it online!

`-a` no longer costs 3 bytes, so this is a 24-byte improvement over 0 ''s answer. Output is `0` for falsy and `1\n0` for truthy.

The general idea is to calculate the parity of sums of adjacent characters until an even sum is reached. If the string is alternating, the stopping condition will occur after reaching the implicit zeroes below the stack. It thus suffices to check whether the next character is a null.

# Answer
> 0 votes
# Thunno 2, 3 bytes

```
Ṣɗp

```

Try it online!

#### Explanation

```
Ṣɗp  # Implicit input
Ṣ    # Deltas
 ɗ   # Mod 2
  p  # Product
     # Implicit output

```

# Answer
> 0 votes
# Vyxal, 4 bytes

```
C¯∷Π

```

Try it Online!

#### Explanation

```
C¯∷Π  # Implicit input
C     # Charcodes
 ¯    # Deltas
  ∷   # Mod 2
   Π  # Product
      # Implicit output

```

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


title: Brainf**k to Unary and Back

text:
# Question
Title: Brainf**k to Unary and Back
A language that is very useful in restricted source and other such challenges is Unary, a brainfuck derivative in which programs are written in with only one character. Your job is to write a program to convert programs from brainfuck to unary and a program to do the opposite, both programs in the same language. Your score will be the sum of the lengths of the two programs.

## How do you convert from brainfuck to Unary?

* First convert your brainfuck code to binary according to this table:

| Brainfuck | Binary |
| --- | --- |
| \> | 000 |
| \< | 001 |
| + | 010 |
| - | 011 |
| . | 100 |
| , | 101 |
| \[ | 110 |
| \] | 111 |

* Now concatenate the code into one giant binary number in order of the code.
* Prepend a `1` to the string to ensure a unique binary number.
* Convert from a binary number to a unary number using any character.
* Example:

```
+.

```

would become

```
000000000000000000000000000000000000000000000000000000000000000000000000000000000000

```

which is 84 zeroes.

## brainfuck → Unary specification:

* Since the resulting programs will be impossibly huge, print not the actual program but merely the length of the resulting program.
* Take the brainfuck program as a string through stdin, function arg, etc and output the length.
* The program will always be valid and have only those 8 chars in it.

## Unary → brainfuck specification:

* You will have to implement the reverse of the above algorithm.
* Again because of the huge sizes in question, the input will be a number describing the length of the Unary code.
* Same I/O rules as always.
* The program will always be valid and have only those 8 chars in it.

## Test Cases

* Hello World:

```
++++++[>++++++++++++<-]>.>++++++++++[>++++++++++<-]>+.+++++++..+++.>++++[>+++++++++++<-]>.<+++[>----<-]>.<<<<<+++[>+++++<-]>.>>.+++.------.--------.>>+.

```

becomes:

```
239234107117088762456728667968602154633390994619022073954825877681363348343524058579165785448174718768772358485472231582844556848101441556`

```
* Fibonacci:

```
++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++++>++++++++++++++++>>+<<[>>>>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[<+>-]>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]<[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]<<<++++++++++++++++++++++++++++++++++++++++++++++++.[-]<<<<<<<.>.>>[>>+<<-]>[>+<<+>-]>[<+>-]<<<-]<<++...

```

becomes:

```
13067995222095367150854793937817629722033205198624522624687536186118993888926522550140580142585590431635487113180955099384652678100247403485397450658564826143160529351955621991895221530908461364045400531236124980271740502887704217664044858614821622360156740992393765239123681327824577149595724956207165558106099868913919959549896553103116795519592552089266360725543244154867904980260

```

This is so the shortest code in bytes wins!

Anyone up for a solution in Unary? ;P

# Answer
# Pyth, 17 + 17 = 34 bytes

BF -\> Unary, 17 bytes

```
i+1xL"><+-.,[]"z8

```

Unary -\> BF, 17 bytes

```
s@L"><+-.,[]"tjQ8

```
> 12 votes

# Answer
# brainfuck, ~~563 335 318 316~~ 296 + ~~529 373 366~~ 336 = 632 bytes

Since this was obviously missing a solution in a related language, here is the solution in brainfuck and Golunar. I couldn't post an answer in unary, because that would need a few fantasticatillion times more memory than there are atoms in the universe ^^

The "back" routine won't check if the Golunar/Unary code is valid. If the bit count mod 3 != 1 then it will run into an endless loop printing a lot of "\>"s.

Thanks to Nitrodon for helping me getting below 300 chars for the bf to unary code

**brainfuck to unary**

```
->+>>>>,[>+++[>+++++<-]>[<+<---->>-]<<--[<+>++[<<+>>>[<+>-]<[<->++[<<<+>->+>-[<->--[<<+>>>+++++++++[<----->-]<[<+>--]]]]]]]>[-]>>,]<<<<+[<+]>[>]->+[<]>+[[->+]->[->[<++>-[<++>-[<++>-[<++>-[<-------->>[-]++<-[<++>-]]]]]]<[>+<-]+>>]<<[<<]>[<]>-[[->+]->>+<[<<]>[<]]>+]>[>>]<<[+++++++[>++++++<-]>.<<<]

```

Try it online!

**and back**

```
->>,[<++++++[>--------<-]+>>>>>>,]>->-<<<+[-<+]>[[->[->+<[->->+>]<[<<<]>]<+>>>[-<<+>>]<[>>>>++++++++++<<<<-]>>>]>>>+[->+]>-<+[-<+]-<[>>+[->+]-<++[-<+]-<[-]]<<<<<<[<<<<<]>>>>>>[<<]<[->>>]>>]>>>+[->+]<-<+[-[<++>-]<[<++>-]>+++[>+++++<-]>[<+<++++>>-]<<++<[>--<-[>>[<->-]<--<-[>++<-[>+<-[>--<-[>+[>+<-]>[<++>-]<+<-[>++<-]]]]]]]>.[-]>[-]<<<+]

```

Try it online!

# Golunar/unary-digits, ~~509 303 288 286~~ 268 + ~~478 337 331~~ 304 = 572 bytes

**brainfuck to unary**

```
2845581296974449674357817038179762273623136917867627972159702240227366875240878616687779429553529795902322625321040063298921498529640547483869509829184440577052825434462245755576011912505085065586076069824710351537537205287083477698633592357950165322060367940923703887

```

**and back**

```
3775574485023133646619269732540391678811443648964274086227256847322821618228135493733703990523803451383315165001915937932498966394771849173263120467073642011339214182483748816052890450078070151307011943625602391238338941712116968736593594971620990210178757280976709140113340322124688909388916094040773207

```

---

**Source codes**

brainfuck to unary

```
[
unary:
><+-.,[]
01234567

62 > 62
60 < -2
45 - 15
43 + 2
44 , 1
46 . 2
91 [ 45
93 ] 2

tape (while reading input): Left tape end marker/LTE, [binary data], input, 15, (15 multiplicator)
tape (while base conversion): LTE, [binary data], Value Start/VS, [decimal digits]

decimal digits: digit used/DU, value
]

-                       set LTE
>+                      set leading 1
>>>>,[                  while input
  >+++[>+++++<-]        set 15 (multiplicator)
  >[<+<---->>-]         set 15 and decrease input by 60

                    check for greater than
                        set current bits = 000 (greater than)
  <<--[                 if input != 62 try next char

                    check for less than
  <+>                   set current bits = 001 (less than)
  ++[                   if input != 60 try next char

                    check for minus
  <<+>>                 set current bits = 011 (minus)
  >[<+>-]<[             if input != 45 try next char

                    check for plus
  <->                   set current bits = 010 (plus)
  ++[                   if input != 43 try next char

                    check for comma
  <<<+>->+>             set current bits = 101 (comma)
  -[                    if input != 44 try next char

                    check for dot
  <->                   set current bits = 100 (dot)
  --[                   if input != 46 try next char

                    check for left bracket
  <<+>>                set current bits = 110 (left bracket)
  >+++++++++[<----->-]<[   if input != 91 go to next char

                    use right bracket
  <+>                   set current bits = 111 (right bracket)
  --                    decrease input by 2 / should be 0 now

  ]]]]]]]               close all ifs
  >[-]>>                delete 15 if still existant
  ,                     input next character
]
<<<<+[<+]>[>]           add one to each bit and delete LTE (for shorter search routine)

                    Start of binary to decimal routine

-                       set value start marker (VS)
>+                      set digit used marker (DU)
[<]                     go to LTE

                    binary to decimal loop: use "double and add algorithm" to calculate the digits of the decimal value
>+[                     if not on VS then
  [->+]-                restore current bit value and go to VS
  >                     go to first DU
  [                     digit doubling loop
    ->                  remove DU and go to corresponding digit
    [
      <++>-             decrement current value and add 2 to temp value four times
      [
        <++>-
        [
          <++>-
          [
            <++>-
            [                   if value was greater than 4 then
              <---- ----        subtract 8 from temp
              >>[-]++           set next digit temp = 2 (DU plus 1)
              <-                decrement current digit
              [<++>-]           set temp = remaining value * 2
            ]
          ]
        ]
      ]
    ]
    <[>+<-]             set current digit = temp
    +                   set DU
    >>                  go to next digit
  ]                     end of digit doubling loop
  <<[<<]>[<]>           go to current bit
  -[                    if bit is 2 (used plus 1)
    [->+]-              delete bit and go to VS
    >>+                 increment least significant digit
    <[<<]>[<]           go to current bit
  ]
  >+                    if not on VS then repeat
]                   end of binary to decimal loop

>[>>]<                  go to most significant digit
<[                  printing loop: for each DU print corresponding value
  +++++++[>++++++<-]>.  add 48 to value (ASCII 0) and print
  <<<                   go to next DU
]

```

and back

```
[
tape: left tape end marker/LTE(-1), [digits], digit end marker/DE(0), carry, SB(-1), [binary data], 60, 15
digits: digit used marker/DU(1), digit, remainder, solution, 0
        else]                                    [exit else, exit if
binary data: value (, else, exit if, exit else)
]

                    input decimal value
->>                     set LTE
,[                      while input
  <++++++[>--------<-]  decrease input by 48
  +                     set DU
  >>>>> >,              input next digit
]
>->-                    set start of bits (SB) and first CCB
<<<+[-<+]>              delete LTE and go to first DU

                    division loop: calculate the remainders of the input divided by 2 repeatedly to get the (inverted) bits
[
                        divide each digit by 2
  [                     for each DU
    -                   delete DU (for exit if)
    >                   go to digit
    [->+<               dec digit / set remainder
      [->->+>]          if digit gt 0: dec digit / del remainder / inc solution / goto 0
                        pointer: (value(0) remainder is set) or (0 solution gt 1)
      <[<<<]            go to DU
      >                 go to digit
    ]
    <+                  set DU
    >>>[-<<+>>]         move solution to digit
    <[                  if remainder
      >>>>              go to next digit
      +++++ +++++       add 10 to digit/carry
      <<<<-             go back and delete remainder
    ]
    >>>                 go to next DU
  ]

                    append new bit
  >>>+[->+]             go to and delete CCB
  >-                    set new CCB
  <+[-<+]-<             go to carry
  [                     if carry
    >>+[->+]-<+         set last bit
    +[-<+]-<[-]         go to and clear carry
  ]

                    check if first digit became 0 / neccessary to check if value has been completely processed
  < <<<<<[<<<<<]>>>>>   go to first DU
  >[                    if digit gt 0
    <<                  go to exit if
  ]<[                   else
    -                   delete DU
    >>>                 go to exit else of next digit
  ]
  >>                    go to DU / DE if all digits processed
]                   end of division loop

                    decode binary values
>>>+[->+]               go to and delete CCB (after last bit)
<-                      delete leading 1
<                       go to first bit

                    Start of bit decoder
[
unary:
><+-.,[]
01234567

62 > 62
60 < -2
43 + -17
45 - 2
46 . 1
44 , -2
91 [ 47
93 ] 2

tape: start of bytes marker/SB(-1), [binary data], 60(print char/PC), 15
]

+[-                     while not SB

                    Set least significant to octal value of three bits
  [<++>-]               if first bit set add 2 to second bit
  <[<++>-]              for each second bit add 2 to third bit

  >+++[>+++++<-]        multiplier 15
  >[<+<++++>>-]         setup table 60 15

                    run through the 8 possibilities

                    0 greater than
  <<++                  set PC = 62 (greater than)
  <[                    if value gt 0 go to next char

                    1 less than
  >--                   set PC = 60 (less than)
  <-[                   if value gt 1 go to next char

                    2 plus
  >>[<->-]<--           set PC = 43 (plus)
  <-[                   if value gt 1 go to next char

                    3 minus
  >++                   set PC = 45 (minus)
  <-[                   if value gt 1 go to next char

                    4 dot
  >+                    set PC = 46 (dot)
  <-[                   if value gt 1 go to next char

                    5 comma
  >--                   set PC = 44 (comma)
  <-[                   if value gt 1 go to next char

                    6 left bracket
  >+[>+<-]>[<++>-]<+    set PC = 91 (left bracket) (inc (45) / double (90) / inc (91))
  <-[                   if value gt 1 go to next char

                    7 right bracket
  >++                   set PC = 93 (right bracket)
  <-                    decrease value the last time to exit if

  ]]]]]]]               close all ifs
  >.[-]                 print char and clear PC
  >[-]                  clear 15 if still existant

  <<<                   go to next bits
  +                     repeat if not SB
]

```
> 10 votes

# Answer
# Python 2, ~~80~~ ~~79~~ ~~63~~ 55 + ~~86~~ 64 = 119 Bytes

*Thanks to Sp3000 for his numerous suggestions, saving a lot of bytes.*

**Brainfuck to Unary, ~~78~~ ~~77~~ ~~61~~ 53 + 2 = 55 bytes**

*Added two bytes to account for surrounding "s on input.*

```
print int(`[1]+map("><+-.,[]".find,input())`[1::3],8)

```

**Unary to Brainfuck, ~~86~~ 64 bytes**

```
print''.join("><+-.,[]"[int(i)]for i in oct(input())[2:]if'L'>i)

```

Check it out on ideone here.
> 6 votes

# Answer
# CJam, 35 bytes

## Brainfuck to Unary, 17 bytes

```
1r"><+-.,[]"f#+8b

```

Try it online.

### How it works

```
 r                e# Read a whitespace-separated token from STDIN.
            f     e# For each character in the token:
  "><+-.,[]" #    e#     Find its index in this string.
1             +   e# Prepend a 1 to the results.
               8b e# Convert to integer, using base 8 conversion.

```

## Unary to Brainfuck, 18 bytes

```
ri8b"><+-.,[]"f=1>

```

Try it online.

### How it works

```
r                  e# Read a whitespace separated token from STDIN.
 i                 e# Interpret as integer.
  8b               e# Convert to array using base 8 conversion.
              f    e# For each digit:
    "><+-.,[]" =   e#     Select the corresponding character from the string.
                1> e# Discard the first character.

```
> 3 votes

# Answer
# Bash + coreutils, 39 + 47 = 86

### `b2u.sh`:

```
dc -e8i1`tr '<>+-.,[]' 0-7`p|tr -dc 0-9

```

### `u2b.sh`:

```
dc -e8o?p|tr -dc 0-9|tr 0-7 '<>+-.,[]'|cut -c2-

```

### Test output:

```
$ echo "++++++[>++++++++++++<-]>.>++++++++++[>++++++++++<-]>+.+++++++..+++.>++++[>+++++++++++<-]>.<+++[>----<-]>.<<<<<+++[>+++++<-]>.>>.+++.------.--------.>>+." | ./b2u.sh
239234206933197750788456456928845900180965531636435002144714670872282710109774487453364223333807054152602699434658684117337034763550216789
$ echo 239234206933197750788456456928845900180965531636435002144714670872282710109774487453364223333807054152602699434658684117337034763550216789 | ./u2b.sh
++++++[>++++++++++++<-[>.>++++++++++[>++++++++++<-[>+.+++++++..+++.>++++[>+++++++++++<-[>.<+++[>----<-[>.<<<<<+++[>+++++<-[>.>>.+++.------.--------.>>+.
$

```
> 2 votes

# Answer
# Japt, 13 + 13 = 26 bytes

## Brainfuck to Unary

```
i< n"><+-.,[]

```

Try it!

Explanation:

```
i<               :Insert a "<" at the start of the string (representing 1)
   n             :Convert string to decimal by interpreting as:
    "><+-.,[]    : A base 8 number represented by the 8 characters of BF

```

## Unary to Brainfuck

```
s"><+-.,[]" Å

```

Try it!

Explanation:

```
s                :Convert decimal to string representation of:
 "><+-.,[]"      : Base 8 using the BF characters to represent the 8 digits
            Å    :Remove the extra "<" at the front

```

## Notes

I can't find the meta post, but if my memory serves correctly answers are allowed to limit I/O to numbers that their language can support, as long as they implement an algorithm that would work if the language starts supporting larger numbers. That is the case here, Japt's ability to treat a string as "base `n` using these `n` characters for the digits" can only use the `number` data type on the other side of the operation, and thus the test cases won't actually run successfully; the output of the first program and the input of the second program will coerce the number to one which can be represented as a `number`, rather than using the actual number. For numbers which can be perfectly represented by Japt's `number` data type these programs will work as desired, and if the `number` data type changes to support larger numbers then these programs will start supporting those numbers as well.
> 1 votes

# Answer
# 05AB1E, 33 (17 + 16) bytes

**Brainfuck to Unary-length:**

```
"><+-.,[]"sSk1š8β

```

Try it online or verify all test cases.

**Explanation:**

```
"><+-.,[]"           # Push string "><+-.,[]"
          s          # Swap to take the (implicit) input
           S         # Convert it to a list of characters
            k        # Check for each the index in the string
             1š      # Prepend a 1 to the list of indices
               8β    # Convert the list to Base-8 (and output implicitly)

```

**Unary-length to Brainfuck**

```
8в¦"><+-.,[]"sèJ

```

Try it online or verify all test cases.

**Explanation:**

```
8в                  # Convert the (implicit) input-list from Base-8 to Base-10
  ¦                 # Remove the first 1
   "><+-.,[]"       # Push string "><+-.,[]"
             s      # Swap the list and string on the stack
              è     # Index each integer into this string
               J    # Join everything together (and output implicitly)

```
> 0 votes

# Answer
# Dart, 77 + 142 = 219 bytes

```
f(s)=>BigInt.parse('1'+s.split('').map('><+-.,[]'.indexOf).join(''),radix:8);

F(n)=>BigInt.parse(n).toRadixString(8).split('').map((s)=>'><+-.,[]'.substring(int.parse(s),int.parse(s)+1)).join('').toString().substring(1);

```

Try it online!
> 0 votes

# Answer
# C (gcc), 254 bytes

```
#include"gmp.h"
f(i,o)char*i,*o;{mpz_t l;char*c="><+-.,[]";if(*i>47&*i<58)for(mpz_init_set_str(l,i,0),mpz_get_str(o,8,l);*o;*o++=o[1]?c[o[1]-48]:0);else for(mpz_init_set_si(l,1);mpz_get_str(o,10,l),*i;mpz_mul_si(l,l,8),mpz_add_ui(l,l,strchr(c,*i++)-c));}

```

Try it online!

Determines which direction to go based on input (`i`), stores the result in the passed buffer (`o`). Note that some compilers allow saving of 4 bytes based on the implementation-defined ordering of the o++. In these cases the provided solution will truncate an extra character off of the Unary-\>BF conversion and the `o[1]`'s can all be replaced by `*o` to recover behaviour.
> 0 votes

# Answer
# Thunno 2, 17 + 15 = 32 bytes

```
"><+-.,[]"$€Ȯ1Ƥ8ḋ

```

Try it online! (Brainfuck -\> Unary)

```
8Bḣ"><+-.,[]"si

```

Try it online! (Unary -\> Brainfuck)

#### Explanation

```
"><+-.,[]"$€Ȯ1Ƥ8ḋ  # Implicit input
"><+-.,[]"         # Push the string
          $€Ȯ      # Index of each character in the input
             1Ƥ    # Prepend a 1
               8ḋ  # Convert from base 8
                   # Implicit output

```

```
8Bḣ"><+-.,[]"si  # Implicit input
8B               # Convert to base 8
  ḣ              # Remove the leading 1
   "><+-.,[]"si  # Index into the string
                 # Implicit output

```
> 0 votes

---
Tags: code-golf, brainfuck, base-conversion, compiler
---