title: Subtract my odds from my evens

text:
# Question
Title: Subtract my odds from my evens
Given a non-negative integer, return the absolute difference between the sum of its even digits and the sum of its odd digits.

## Default Rules

* Standard Loopholes apply.
* You can take input and provide output by any standard Input / Output method.
* You may take input as a String, as an Integer or as a list of digits.
* This is , so the shortest code in bytes **in every language** wins!

## Test Cases

```
Input ~> Output

0 ~> 0 (|0-0| = 0)
1 ~> 1 (|1-0| = 1)
12 ~> 1 (|2-1| = 1)
333 ~> 9 (|0-(3+3+3)| = 9)
459 ~> 10 (|4-(5+9)| = 10)
2469 ~> 3 (|(2+4+6)-9| = 3)
1234 ~> 2 (|(2+4)-(1+3)| = 2)

```

# Answer
> 11 votes
# Jelly, 6 bytes

```
-*æ.¹A

```

Try it online!

### How it works

```
-*æ.¹A  Main link. Argument: A (digit array)

-*      Raise -1 to A's digits, yielding 1 for even digits and -1 for odd ones.
    ¹   Identity; yield A.
  æ.    Take the dot product of the units and the digits.
     A  Apply absolute value.

```

# Answer
> 8 votes
# SHENZHEN I/O MCxxxx scripts, 197 (126+71) bytes

Chip 1 (MC6000):

* x0: Input as list
* x2: Chip 2 x1
* x3: MC4010

```
mov 0 dat
j:
mov x0 acc
mov 70 x3
mov -1 x3
mov acc x3
mul x3
mov acc x2
mov dat acc
add 1
tlt acc 3
mov acc dat
+jmp j
slx x0

```

Chip 2 (MC4000):

* p0: Output
* x0: MC4010
* x1: Chip 1 x2

```
mov x1 acc
add x1
add x1
mov 30 x0
mov 0 x0
mov acc x0
mov x0 p0
slx x1

```

# Answer
> 6 votes
## Python 2, 39 bytes

Takes integer as list. Try it online

```
lambda A:abs(sum((-1)**i*i for i in A))

```

-3 bytes thanks to @Mr.Xcoder
-1 byte thanks to @ovs

# Answer
> 5 votes
# TI-Basic, ~~18~~ 9 bytes

```
abs(sum((-1)^AnsAns

```

**Explanation**

Multiplies each digit in the list by -1 to its power, negating each odd digit, before summing them.

# Answer
> 5 votes
# Mathematica, 20 bytes

```
Abs@Tr[(-1)^(g=#)g]&

```

takes as input a list of digits

special thanx to @LLlAMnYP for letting me know about the "new rules"

# Answer
> 4 votes
# C (gcc), ~~59~~ ~~58~~ 57 bytes

```
i;f(char*v){for(i=0;*v;v++)i+=*v%2?*v-48:48-*v;v=abs(i);}

```

Try it online!

# Answer
> 4 votes
## R, 30 29 bytes

```
abs(sum((d=scan())-2*d*d%%2))

```

`d = scan()` takes the input number by one digit after the other.

-1 byte thanks to @Giuseppe!

# Answer
> 4 votes
# C#, 57 bytes

```
namespace System.Linq{i=>Math.Abs(i.Sum(n=>n%2<1?n:-n))}

```

Takes input as `i` and sums the integers by turning the odds to negative.

# Answer
> 3 votes
## JavaScript (ES6), ~~43~~ 38 bytes

Takes input as ~~a string~~ an array of digits.

```
a=>a.map(d=>s+=d&1?d:-d,s=0)&&s>0?s:-s

```

### Test cases

```
let f =

a=>a.map(d=>s+=d&1?d:-d,s=0)&&s>0?s:-s

console.log(f([1]))     // ~> 1 ( |1-0| = 1)
console.log(f([0]))     // ~> 0 ( |0-0| = 0)
console.log(f([1,2]))    // ~> 1 ( |1-2| = 1)
console.log(f([4,5,9]))   // ~> 10 ( |4-(5+9)| = 10)
console.log(f([2,4,6,9]))  // ~> 3 ( |(2+4+6)-9| = 3)
console.log(f([3,3,3]))   // ~> 9 ( |(3+3+3)-0| = 9)
```

# Answer
> 3 votes
# Japt, 8 bytes

```
x_*JpZÃa

```

Test it online!

### Explanation

```
 x_  *JpZÃ a
UxZ{Z*JpZ} a
                Implicit: U = list of digits
UxZ{     }      Take the sum of each item Z in U mapped through the following function:
      JpZ         Return (-1) ** Z
    Z*            times Z. This gives Z if even, -Z if odd.
           a    Take the absolute value of the result.
                Implicit: output result of last expression

```

# Answer
> 3 votes
# APL, 8 bytes

```
|⊢+.×¯1*⊢

```

Try it online!

**How?**

`¯1*⊢` \- -1n for `n` in

\[`4 5 9``1 ¯1 ¯1`\]

`⊢+.×` \- verctorized multiplication with `o`, then sum

\[`+/ 4 5 9 × 1 ¯1 ¯1``+/ 4 ¯5 ¯9``¯10`\]

`|` \- absolute value

# Answer
> 3 votes
# Husk, 7 bytes

```
≠0ṁṠ!¡_

```

Try it online!

Takes a list of digits as input.

Still missing an "abs" builtin, but a good result all the same :)

### Explanation

`Ṡ!¡_` is a function that takes a number `n` and then applies `n-1` times the function `_` (negation) to `n`. This results in `n` for odd `n` or `-n` for even `n`.

applies a function to each element of a list and sums the results.

`≠0` returns the absolute difference between a number and 0.

# Answer
> 3 votes
# Neim, 7 bytes

```
ΓDᛃΞ}

```

Explanation:

```
Γ        Apply the following to each element in the input array
 D         Duplicate
  ᛃ        Modulo 2, then perform logical NOT
   Ξ       If truthy, then:
            Multiply by -1
      }  Close all currently running loops/conditionals etc
        Sum the resulting array

```

# Answer
> 3 votes
# Mathematica, 67 bytes

```
(s=#;Abs[Subtract@@(Tr@Select[IntegerDigits@s,#]&/@{EvenQ,OddQ})])&

```

# Answer
> 3 votes
***EDIT: A more golf-centered approach:***

## EXCEL, 42 36 29 bytes

Saved 6 bytes thanks to Magic Octopus Urn Saved 7 bytes by using Dennis' -1^ approach (which, I just learned, works on arrays in excel)

```
=ABS(SUMPRODUCT(A:A,-1^A:A))

```

Takes a list of integers in A column for input. Probably can be golfed further, or by using the string version, taking a string in A1 for input.

## EXCEL, 256 bytes

```
=ABS(LEN(SUBSTITUTE(A1,1,""))-2*LEN(SUBSTITUTE(A1,2,""))+3*LEN(SUBSTITUTE(A1,3,""))-4*LEN(SUBSTITUTE(A1,4,""))+5*LEN(SUBSTITUTE(A1,5,""))-6*LEN(SUBSTITUTE(A1,6,""))+7*LEN(SUBSTITUTE(A1,7,""))-8*LEN(SUBSTITUTE(A1,8,""))+9*LEN(SUBSTITUTE(A1,9,""))-5*LEN(A1))

```

# Answer
> 2 votes
# Julia 0.5, 19 bytes

```
!x=(-1).^x⋅x|>abs

```

Try it online!

# Answer
> 2 votes
# PHP, 54 bytes

```
for(;~$n=$argn[$i++];)${eo[$n&1]}+=$n;echo abs($e-$o);

```

Try it online!

# PHP, 57 bytes

store the even and odd sums in an array

```
for(;~$n=$argn[$i++];)$r[$n&1]+=$n;echo abs($r[0]-$r[1]);

```

Try it online!

# PHP, 57 bytes

store the even and odd sums in two variables

```
for(;~$n=$argn[$i++];)$n&1?$o+=$n:$e+=$n;echo abs($e-$o);

```

Try it online!

# Answer
> 2 votes
# Haskell, 47 42 39 38 26 25 bytes

*-1 thanks to nimi*

*-12 thanks to Bruce*

*-1 thanks to xnor*

```
abs.sum.map(\x->x*(-1)^x)

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 6 bytes

Thanks to Dennis for the -1 power trick. Takes input as a list of digits

```
®sm*OÄ

```

Try it online!

### Explanation

```
®sm*OÄ                                               Example [4, 5, 9]
®      # Push -1                                   % STACK: -1
 sm    # Take -1 to the power of every number      % STACK: [1, -1, -1]
         in the input list
   *   # Multiply with original input              % Multiply [1, -1, -1] with [4, 5, 9] results in STACK: [4, -5, -9]
    O  # Sum them all together                     % STACK: -10
     Ä # Absolute value                            % STACK: 10
       # Implicit print

```

# Answer
> 2 votes
# PHP, 51 bytes

```
while(~$n=$argn[$i++])$s+=$n&1?$n:-$n;echo abs($s);

```

adds digit to `$s` if odd, subtracts if even. Run as pipe with `-nR`.

or

```
while(~$n=$argn[$i++])$s+=(-1)**$n*$n;echo abs($s);

```

using Dennis´ `-1` power trick.

# Answer
> 2 votes
# K (ngn/k), ~~18~~ ~~15~~ 12 bytes

```
#!+/{x-:/x}'

```

Try it online!

Takes input as a list of digits.

* `{x-:/x}'` negate each digit of the input that many times (e.g., negate `4` four times, and `9` nine times). this makes odd digits negative, leaving even digits positive
* `+/` take the sum
* `#!` take the absolute value (and implicitly return)

# Answer
> 1 votes
# J, 14 bytes

```
|-/(2&|+//.[),

```

Try it online!

## explanation

```
|                absolute value of
 -/              the difference between
                 the items on the list returned by this fork
   (2&|          is an item odd? (1 for yes, 0 for no)
       +//.      the "key" verb /. which partitions on above (even / odd) then sums
           [)    identity, ie, the list of digits passed
             ,   turn it into a list (to handle 1 element case)

```

# Answer
> 1 votes
# Perl 6, 28 bytes

```
{abs sum $_ Z*.map(*%2*2-1)}

```

Try it online!

Takes a list of digits as input.

* `$_` is the input argument.
* `.map(* % 2 * 2 - 1)` maps each digit to either `1` or `-1` depending on whether the digit is odd or even, respectively.
* `Z*` zips the original list of digits with the even/odd list using multiplication.

# Answer
> 1 votes
# Bash ~~141~~ ~~139~~ 99 Bytes

```
while read -n1 a; do
[ $[a%2] = 0 ]&&e=$[e+a]||o=$[o+a]
done
(($[e-o]>0))&&echo $[e-o]||echo $[o-e]

```

Try it online!

# Answer
> 1 votes
# R, ~~72~~ 43 bytes

```
b=(d=scan())%%2<1;abs(sum(d[b])-sum(d[!b]))

```

First, `d = scan()` takes the number as input, one digit after the other (thanks to @Giuseppe comment !)
Then, `b = d %% 2 <1` associates to `b` a `TRUE` or `FALSE` value at each index depending on the digits' parity. Therefore, `b` values are `TRUE` for even numbers, and `!b` are `TRUE` for odd values.

Finaly, `abs(sum(d[b]) - sum(d[!b]))` does the job.

# Answer
> 1 votes
# Braingolf, 18 bytes

```
{.2%?M|}&+v&+c-!s*

```

Try it online!

Takes input as a list of digits

## Explanation

```
{.2%?M|}&+v&+c-!s*  Implicit input from commandline args
{......}            Foreach loop, runs on each item in the stack..
 .2%                ..Parity check, push 1 if odd, 0 if even
    ?               ..If last item != 0 (pops last item)..
     M              ....Move last item to next stack
      |             ..Endif
        &+          Sum entire stack
          v&+       Switch to next stack and sum entire stack
             c-     Collapse into stack1 and subtract
               !s   Sign check, push 1 if last item is positive, -1 if last item is
                    negative, 0 if last item is 0
                 *  Multiply last item by sign, gets absolute value
                    Implicit output

```

# Answer
> 1 votes
## TI-BASIC, ~~11~~ 6 bytes

```
abs(sum(Anscos(πAns

```

Takes input as a list. `i²^Ans` saves two bytes over `(-1)^Ans` because we don't need the parentheses.

```
abs(sum(Anscos(πAns
           cos(πAns                  1 for evens, -1 for odds
        Ans                          Multiply by original list
abs(sum(                             Sum the list and take absolute value, which also
                                     fixes rounding errors from cos(.

```

# Answer
> 1 votes
# Pyth, ~~16 12 11 10~~ 8 bytes

```
.asm*^tZ

```

**Try it online!**

---

# How?

```
.asm*^tZ – Full program. Q = input.
   m*^tZ – Raise -1 to the power of each d in Q and multiply by d.
  s      – Sum.
.a       – Absolute value.

```

# Answer
> 1 votes
# \>\<\>, 32 bytes

```
00\~:00@(?$-n;
(?\c%:0@2%?$-+i:0

```

Try it online!

# Answer
> 1 votes
# Java (OpenJDK 8), 55 bytes

```
a->{int s=0;for(int d:a)s+=d%2<1?-d:d;return s<0?-s:s;}

```

Try it online!

Naive implementation.

# Answer
> 1 votes
# C#, 67 bytes

```
namespace System.Linq{a=>Math.Abs(a.Sum(n=>n%2<1)-a.Sum(n=>n%2>1))}

```

# Answer
> 1 votes
# 05AB1E, 7 bytes

```
È2*<*OÄ

```

Try it online!

```
        # Input              | 1234567
È       # Is Even?           | [0,1,0,1,0,1,0]
 2*<    # (a * 2) - 1        | [-1,1,-1,1,-1,1,-1]
    *   # Multiply w/ input. | [-1,2,-3,4,-5,6,-7]
     O  # Sum.               | -10
      Ä # Absolute value of. | 10

```

# Answer
> 1 votes
# x86-64 Machine Code, 30 bytes

```
31 C0 99 8B 4C B7 FC F6 C1 01 74 04 01 CA EB 02 01 C8 FF CE 75 ED 29 D0 99 31 D0 29 D0 C3

```

The above code defines a function that accepts a list/array of integer digits and returns the absolute difference between the sum of its even digits and the sum of its odd digits.

As in C, assembly language doesn't implement lists or arrays as first-class types, but rather represents them as a combination of a pointer and a length. Therefore, I have arranged for this function to accept two parameters: the first is a pointer to the beginning of the list of digits, and the second is an integer specifying the total length of the list (total number of digits, one-indexed).

The function conforms to the System V AMD64 calling convention, which is standard on Gnu/UNIX systems. In particular, the first parameter (pointer to the beginning of the list) is passed in `RDI` (as this is 64-bit code, it is a 64-bit pointer), and the second parameter (length of the list) is passed in `ESI` (this is only a 32-bit value, because that's more than enough digits to play with, and naturally it is assumed to be non-zero). The result is returned in the `EAX` register.

If it's any clearer, this would be the C prototype (and you can use this to call the function from C):

```
int OddsAndEvens(int *ptrDigits, int length);

```

**Ungolfed assembly mnemonics:**

```
; parameter 1 (RDI) == pointer to list of integer digits
; parameter 2 (ESI) == number of integer digits in list (assumes non-zero, of course)
OddsAndEvens:
   xor  eax, eax              ; EAX = 0 (accumulator for evens)
   cdq                        ; EDX = 0 (accumulator for odds)
.IterateDigits:
   mov  ecx, [rdi+rsi*4-4]    ; load next digit from list
   test cl, 1                 ; test last bit to see if even or odd
   jz   .IsEven               ; jump if last bit == 0 (even)
.IsOdd:                       ; fall through if last bit != 0 (odd)
   add  edx, ecx              ; add value to odds accumulator
   jmp  .Continue             ; keep looping
.IsEven:
   add  eax, ecx              ; add value to evens accumulator
.Continue:                    ; fall through
   dec  esi                   ; decrement count of digits in list
   jnz  .IterateDigits        ; keep looping as long as there are digits left

   sub  eax, edx              ; subtract odds accumulator from evens accumulator

   ; abs
   cdq                        ; sign-extend EAX into EDX
   xor  eax, edx              ; XOR sign bit in with the number
   sub  eax, edx              ; subtract sign bit

   ret                        ; return with final result in EAX

```

Here's a brief walk-through of the code:

* First, we zero out the `EAX` and `EDX` registers, which will be used to hold the sum totals of even and odd digits. The `EAX` register is cleared by `XOR`ing it with itself (2 bytes), and then the `EDX` register is cleared by sign-extending the EAX into it (`CDQ`, 1 byte).
* Then, we go into the loop that iterates through all of the digits passed in the array. It retrieves a digit, tests to see if it is even or odd (by testing the least-significant bit, which will be 0 if the value is even or 1 if it is odd), and then jumps or falls through accordingly, adding that value to the appropriate accumulator. At the bottom of the loop, we decrement the digit counter (`ESI`) and continue looping as long as it is non-zero (i.e., as long as there are more digits left in the list to be retrieved).

The only thing tricky here is the initial MOV instruction, which uses the most complex addressing mode possible on x86.* It takes `RDI` as the base register (the pointer to the beginning of the list), scales `RSI` (the length counter, which serves as the index) by 4 (the size of an integer, in bytes) and adds that to the base, and then subtracts 4 from the total (because the length counter is one-based and we need the offset to be zero-based). This gives the address of the digit in the array, which is then loaded into the `ECX` register.
* After the loop has finished, we do the subtraction of the odds from the evens (`EAX -= EDX`).
* Finally, we compute the absolute value using a common trick—the same one used by most C compilers for the `abs` function. I won't go into details about how this trick works here; see code comments for hints, or do a web search.

\__
* The code can be re-written to use simpler addressing modes, but it doesn't make it any shorter. I was able to come up with an alternative implementation that dereferenced `RDI` and incremented it by 8 each time through the loop, but because you still have to decrement the counter in `ESI`, this turned out to be the same 30 bytes. What had initially given me hope is that `add eax, DWORD PTR [rdi]` is only 2 bytes, the same as adding two enregistered values. Here is that implementation, if only to save anyone attempting to outgolf me some effort :-)

```
                    OddsAndEvens_Alt:
31 C0                   xor    eax, eax
99                      cdq
                    .IterateDigits:
F6 07 01                test   BYTE PTR [rdi], 1
74 04                   je     .IsEven
                    .IsOdd:
03 17                   add    edx, DWORD PTR [rdi]
EB 02                   jmp    .Continue
                    .IsEven:
03 07                   add    eax, DWORD PTR [rdi]
                    .Continue:
48 83 C7 08             add    rdi, 8
FF CE                   dec    esi
75 ED                   jne    .IterateDigits
29 D0                   sub    eax, edx
99                      cdq
31 D0                   xor    eax, edx
29 D0                   sub    eax, edx
C3                      ret
```

# Answer
> 1 votes
# Tcl, 55 bytes

```
lmap e $V {incr s [expr $e*-1**$e]}
puts [expr abs($s)]

```

Try it online!

# Answer
> 1 votes
# Ruby, 45 bytes

***Function; Full number***

```
->n{s=0
n.digits.map{|x|s+=x%2>0?x:-x}
s.abs}

```

Try it online!

# Ruby, 38 bytes

***Function; List of digits***

```
->n{s=0
n.map{|x|s+=x%2>0?x:-x}
s.abs}

```

Try it online!

# Answer
> 1 votes
# Rust, 73 bytes

```
fn f(mut a:i32)->i32{let mut s=0;while a>0{s+=a%10*(a%2*2-1);a/=10}s.abs()}

```

Try it online!

# Rust, 68 bytes

This takes a slice of digits rather than an integer.

```
fn z(a:&[i32])->i32{a.iter().map(|x|x*(x%2*2-1)).sum::<i32>().abs()}

```

Try it online!

# Answer
> 1 votes
# , 11 bytes

Credit to Uriel’s APL solution

```
1|@#.[*_1^]

```

Try it online!

# Answer
> 1 votes
# Vyxal, 6 bytes

```
u$eÞ•ȧ

```

Try it Online!

Port of Jelly.

```
u$eÞ•ȧ
u$e     # Raise -1 to the power of each
   Þ•   # Dot product with the input
     ȧ  # Absolute value

```

# Answer
> 1 votes
# Ly, 24 bytes

```
0spSy[f:2%2*,*l+sp,]lar-

```

Try it online!

This is pretty brute force, it just adds or subtracts each number to an accumulator depending on whether it's odd or even. The post-loop bit is the shortest way to get an `abs()` in Ly I could think of.

```
0sp                       - initialize the backup cell to 0, clear stack
   S                      - convert the number on STDIN to digits on the stack
    y                     - push the number of digits onto the stack
     [f           ,]      - loop decrementing the digit count, stop on 0
       :                  - duplicate the next digit
        2%                - modulo by 2 to get odd/even
          2*,             - do "(x*2)-1" to map 1 to 1, and 0 to -1
             *            - multiple the digit by that 1/-1
              l+sp        - add to backup cell, pop from stack
                    l     - load the final difference from accumulator
                     a    - sort stack (has a 0 and the accumulator val)
                      r   - reverse stack
                       -  - subtract to flip the sign if difference was <0

```

The programs with a positive number on the stack, which is printed automatically.

# Answer
> 1 votes
# Desmos, 24 bytes

```
f(l)=abs(total(l(-1)^l))

```

Input as a list of digits.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 1 votes
# Nibbles, 6 bytes (12 nibbles)

```
!=+$*+|$%$~~

```

Calculates the absolute difference between the sum of all digits and twice the sum of the odd digits.

```
!=+$*+|$%$~~
!=              # absolute difference between
  +             #   sum of
   $            #   input
                # and
     +          #   sum of
       $        #   input
      |         #   filtered for nonzero when
        %$      #     modulo
          ~     #     2 (default for modulo)
    *           #   multiplied by
           ~    #   2 (default for multiplication)

```

# Answer
> 1 votes
# MathGolf, 6 bytes

```
b▬m*Σ±

```

Port of *@Dennis*' Jelly answer.

Input as a list of digits.

Try it online.

**Explanation:**

```
b      # Push -1
 ▬     # Take -1 to the power of each integer in the (implicit) input-list
  m*   # Multiply the values at the same positions of this list and the (implicit) input
    Σ  # Sum this list together
     ± # Get its absolute value
       # (after which the entire stack is output implicitly as result)

```

# Answer
> 1 votes
# Japt, 8 bytes

```
üv mx ra

```

Try it

Takes input as a digit array

```
üv mx ra     :Implicit input of digit array
ü            :Group by
 v           :  Divisible by 2?
   m         :Map
    x        :  Sum
      r      :Reduce by
       a     :  Absolute difference

```

# Answer
> 1 votes
# Fig, \\$6\log\_{256}(96)\approx\\$ 4.939 bytes

```
AS*^N1

```

Try it online!

Port of MathGolf. Surprisingly, beats Jelly.

```
AS*^N1 # Input as list of digits
    N1 # -1
   ^   # To the power of each in the input
  *    # Multiply the list of 1s and -1s by each digit
 S     # Sum
A      # Absolute value

```

# Answer
> 1 votes
# J-uby, 33 bytes

```
:partition+:odd?|:*&:sum|+:-|:abs

```

Attempt This Online!

# Answer
> 1 votes
# Pip, 9 bytes

```
AB$+g*vEg

```

Try It Online!

# Answer
> 1 votes
# Arturo, 26 bytes

```
$=>[abs∑map&'x->x*^0-1x]

```

Try it

# Answer
> 1 votes
# Thunno, \\$ 9 \log\_{245}(96) \approx \\$ 7.41 bytes

```
D1n@z*SZA

```

Attempt This Online! or verify all test cases.

#### Explanation

```
D1n@z*SZA  # Implicit input        [1, 2, 3, 4]
D          # Duplicate             [1, 2, 3, 4], [1, 2, 3, 4]
 1n@       # Push -1 ** each       [1, 2, 3, 4], [-1, 1, -1, 1]
    z*     # Multiply elementwise  [-1, 2, -3, 4]
      S    # Sum this list         2
       ZA  # Absolute value        2
           # Implicit output

```

# Answer
> 1 votes
# x86-16 machine code, 18 bytes

```
00000000: 33d2 ada8 0174 02f7 d803 d0e2 f579 02f7  3....t.......y..
00000010: dac3                                     ..

```

**Listing**

```
33 D2       XOR  DX, DX         ; result in DX
        IN_LOOP:
AD          LODSW               ; next digit
A8 01       TEST AL, 1          ; odd or even?
74 02       JZ   EVEN           ; jump if even
F7 D8       NEG  AX             ; complement to subtract odd digit
        EVEN:
03 D0       ADD  DX, AX         ; add to running result
E2 F5       LOOP IN_LOOP        ; next digit
79 02       JNS  DONE           ; jump if result is positive
F7 DA       NEG  DX             ; complement for absolute value
        DONE:
C3          RET                 ; return to caller

```

Callable function, input list of digits at `DS:SI`, length in `CX`. Output to `DX`.

# Answer
> 0 votes
# Common Lisp, 52 bytes

```
(defun f(x)(abs(loop as i in x sum(*(expt -1 i)i))))

```

Try it online!

Translation of Dead Possum answer.

# Answer
> 0 votes
## **C#, 59 bytes**

```
Math.Abs(a.Where(x=>(x%2<1)).Sum()-a.Where(x=>x%2>0).Sum())

```

# Answer
> 0 votes
# Java (OpenJDK 8), 64 bytes

Takes n as int input, uses mod 10 and div 10 to sum from least significant digit and return Absolute value when done.

```
n->{int r=0;for(;n>0;n/=10)r+=n%2>0?-n%10:n%10;return r<0?-r:r;}

```

Try it online

# Answer
> 0 votes
# CJam, ~~16~~ 14 Bytes

```
q{si_W\#*}%:+z

```

Try it online

```
q{si_W\#     e# Take -1 to power of digit
*}%          e# Multiply result by digit
:+z          e# Sum altered digits and return the absolute value

```

# Answer
> 0 votes
**java** , **314 bytes**

```
public  static int f (String s)
{
    char [] m =s.toCharArray();
    int o=0 ,e=0;
    for(int i =0 ;i<m.length;i++)
    { int n=(int)m[i]-48;
    if(n%2==0)
        e+=n;
    else
        o+=n;
    }
    return abs(e-o);

   }

```

# Answer
> 0 votes
# Bash, 51 bytes

***Full program; Full number***

Or "bash with awk" for the pedantics.

```
grep -o .|awk '{a+=$0%2?$0:-$0}END{print a<0?-a:a}'

```

Try it online!

## Explanation

```
grep -o .| # every /./ on a new line
awk '{
            // a is initialized to 0 cuz awk lol
  a+=$0%2   // Is odd?
    ?$0:-$0 // true -> add +, false -> add -
}
END{
  print a<0?-a:a // to absolute value
}'

```

# Answer
> 0 votes
# AWK, 35 bytes

***Full program; List of digits***

```
{a+=$0%2?$0:-$0}END{print a<0?-a:a}

```

Try it online!

Technically not the same as my other answer. I still think that one is better because using a list of digits feels cheap.

# Answer
> 0 votes
# APL NARS 26 chars

```
{∣(+/-a)+2×+/(2∣a)/a←⍎¨⍕⍵}

```

test

```
  f←{∣(+/-a)+2×+/(2∣a)/a←⍎¨⍕⍵}
  f¨0 1 12 333 459 2469 1234
0 1 1 9 10 3 2

```

# Answer
> 0 votes
# Thunno 2, 6 bytes

```
u@$Ø.A

```

Attempt This Online!

Port of Dennis's Jelly answer.

#### Explanation

```
u@$Ø.A  # Implicit input
u@      # Take -1 to the power of
        # each of the digits
  $     # Push the input again
   Ø.   # Take the dot product
     A  # Absolute value
        # Implicit output

```

# Answer
> 0 votes
# Vyxal 3, 3 bytes

```
ṂḋȦ

```

Try it Online!

Port of Dennis's Jelly answer.

Certified Vyxal Moment, -1^n and dot product are now one byte builtins.

Input is a list of digits

# Answer
> 0 votes
# Uiua, 17 bytes

```
⌵-∩/+∩▽¬,,◿2.∵⋕°⋕

```

Test pad

## Explanation

```
⌵-∩/+∩▽¬,,◿2.∵⋕°⋕
             ∵⋕°⋕  # Parse integer into digits
          ◿2.      # Get each digit mod 2
        ,,         # Copy the digits and the mask over
       ¬           # Invert the mask
     ∩▽            # Filter for both masks and arrays
  ∩/+              # Sum both results up
⌵-                 # Get the absolute difference

```

Created with the help of Luminespire.

---
Tags: code-golf, number, number-theory
---


title: Even and Odd Numbers

text:
# Question
Title: Even and Odd Numbers
Sandbox

*Adapted from exercise 4 of 100 little Keg exercises*

The ability to repeat chunks of code within a program is an important part of any programming language. Also just as important is the ability to make decisions based on different values.

## The Challenge

I want you to write a program that:

* Starts at the number 0, and:
* For each number from 0 to 100 (inclusive):
* If the number is even, print the letter `E` (uppercase or lowercase)
* Otherwise: print the number

Keeping in the spirit of this challenge, your source code must fit the pattern of having characters with an odd ordinal value followed by characters with an even ordinal value. *Note that ordinal value is defined here as if I called python's `ord()` function on the character using your language's prefered code page.* In other words, the code points of your program should be as such:

```
Odd Even Odd Even Odd Even ...

```

or

```
Even Odd Even Odd Even Odd ...

```

More concisely, the code points of your program must alternate between being odd and even.

## Example Output

```
E 1 E 3 E 5 E 7 E 9 E 11 E 13 E 15 E 17 E 19 E 21 E 23 E 25 E 27 E 29 E 31 E 33 E 35 E 37 E 39 E 41 E 43 E 45 E 47 E 49 E 51 E 53 E 55 E 57 E 59 E 61 E 63 E 65 E 67 E 69 E 71 E 73 E 75 E 77 E 79 E 81 E 83 E 85 E 87 E 89 E 91 E 93 E 95 E 97 E 99 E

```

Output can be in any other convenient format with any other separator. Leading and trailing whitespace is acceptable.

## Script Validation (UTF-8 only)

Here is a Keg script to see if your program fits the parity pattern requirement

Note that this can only be used for languages that use utf-8 as their codepage.

Here is an alternate Haskell script written by @WheatWizard which can handle newlines and shows which characters are invalid.

Here is a Python Script that tells you where you need to insert extra characters. (As well as the binary codes and the ord code of the characters)

## Scoring

This is so the answer with the fewest amount of bytes wins.

Let it be known that flags don't count towards being in the pattern. They also don't count towards byte count in this challenge.

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

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

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

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

# Answer
# Python 3, 72 bytes

```
x="E";z= 1
while 	z	<101:	x=x+ ["E"	,	f' {z} ' ] [z%2] ;z=z+ 1
exit	(	x)

```

Try it online!

Just by coincidence, `exit` and `while` are both available. The rest is just the program separated by spaces and tabs to make it alternate.

I'm hoping it's forgivable to output as an exit code, since `print` is unavailable.
> 10 votes

# Answer
# JavaScript (ES6), 42 bytes

Contains a literal `Tab`.

```
f= y =>y>98? ' E ':' E ' + -~y +f   (1 -~y )

```

Try it online!
> 9 votes

# Answer
## Ruby, 41 bytes

```
n= 1
eval'puts"E";p	n;n=n+2; '*50;puts"E"

```

Try it online! (with parity check)

This builds a string that contains the code to output `"E"` and `n`, then add 2 to `n`. Then it multiplies the string by 50 (repeating it 50 times) and `eval`s it. Finally, it prints the last `"E"` at the end.
> 7 votes

# Answer
# MATL, 14 bytes

```
69H!Vo:E q"c@y

```

Try it online!

MATL uses ASCII encoding. The code points of the source code are

```
54  57  72  33  86 111  58  69  32 113  34  99  64 121

```

### How it works

```
69    % Push 69. This is the code point of 'E'
H     % Push 2
!     % Transpose: does nothing to 2
V     % Convert to string: gives '2'
o     % Convert to double: gives code point of '2', which is 50
:     % Range. Gives [1 2 ... 50]
E     % Multiply each element by 2. Gives [2 4 ... 100]
      % (Space:) Does nothing
q     % Subtract 1 from each element. Gives [1 3 ... 99]
"     % For each k in [1 3 ... 99]
  c   %   Convert to char. In the first iteration the top of the stack contains 69,
      %   which is converted into 'E'. In subsequent iterations the top of the stack
      %   contains 'E', which is left as is
  @   %   Push current k
  y   %   Duplicate from below: pushes another copy of 'E'
      % End (implicit)
      % Display stack, botom to top (implicit)

```
> 6 votes

# Answer
# 05AB1E, ~~15~~ ~~11~~ 9 bytes

```
т Ýxт>çÞ‡

```

-2 bytes thanks to *@Grimmy*.

Outputs as a list with lowercase `e`.

Try it online.

**Explanation:**

Shortest base version I could find was **~~8~~ 7 bytes**: `тÝx'EÞ‡` (Outputs as a list with uppercase `E`.)

-1 byte thank to *@Grimmy*.

```
т        # Push 100
 Ý       # Pop and push a list in the range [0, 100]
  x      # Push a list with each value doubled (without popping the original list)
   'E   '# Push "E"
     Þ   # Pop and push an infinite list of "E": ["E","E","E",...]
      ‡  # Transliterate each doubled number to "E" in the original list
         # (after which this list is output implicitly as result)

```

The codepoints of this 7-byter are `[15,221,120,39,69,222,135]` / `[1,1,0,1,1,0,]`, which is already pretty good.

So I now have this:

```
т          # Push 100
           # No-op space
  Ý        # Pop and push a list in the range [0, 100]
   x       # Push a list with each value doubled (without popping the original list)
    т      # Push 100
     >     # Increase it by 1 to 101
      ç    # Convert this integer to a character with this ASCII codepoint: "E"
       Þ   # Pop and push an infinite list of "e": ["e","e","e",...]
        ‡  # Transliterate each doubled number to "e" in the original list
           # (after which this list is output implicitly as result)

```

This 9-byter has the codepoints: `[15,32,221,120,15,62,231,222,135]` / `[1,0,1,0,1,0,1,0,1]`.
> 6 votes

# Answer
# Haskell, ~~112~~ ~~105~~ 99 bytes

The code produces a string as in the example.

```
[ c|s<-"E 1 E 3 E 5 E 7 E 9 E"	:[ ' ':k:m:' ':	"E"	|k<-"123456789"	,m<-"1 3 5 7 9"	,m>' ' ],c<- s ]

```

I was not able to find a way to print an integer or convert it to string. This is why the solutions looks like this.

Try it online!
> 6 votes

# Answer
# Pyth, 16 bytes

```
V101p? %N/T5NK\E

```

Try it online!

Verify it online!

Separated by `""`

## How it works:

```
V101p? %N/T5NK\E
V101                  - For 'N' in 0..100
     ? %N/T5        - If N modulo (10÷5) (or N%2) is truthy...
            N       - ...return N
             K\E    - Otherwise, return 'E' (K here is just a separator)
    p               - Print the result

```
> 5 votes

# Answer
# Jelly, 13 bytes

```
³Ż¹⁾E Ḥ‘{$¦ K

```

Code-points: `[131, 210, 129, 142, 69, 32, 175, 252, 123, 36, 5, 32, 75]`

A full program, which given no arguments prints the result.

**Try it online!**

(As a bonus given a non-negative integer argument it will print the sequence for that number, e.g.)

### How?

```
³Ż¹⁾E Ḥ‘{$¦ K - Main Link: no arguments
³             - literal 100 (if there are arguments provided, this is the 1st)
 Ż            - zero-range = [0,1,2,3,...,100]
  ¹           - identity (no-op)
          ¦   - sparse application...
         $    -   ...to indices: last two links as a monad:
      Ḥ       -      double = [0,2,4,6,...,200]
        {     -      use left argument as input to:
       ‘      -        increment = [1,3,5,7,...,201]
                     (note Jelly uses 1-based indexing)
   ⁾E.        -   ...what: literal character pair =  ['E', ' ']
           .  - no-op
            K - join with spaces
              - implicit, smashing print

```
> 5 votes

# Answer
# C (gcc) with `-trigraphs` flag, ~~161~~ 141 bytes

Thanks to WheatWizard for the validation script, which revealed that I mistakenly identified line endings as `CR` instead of `LF`! The fix didn't change the byte count, however.

To get this to even work, in addition to the many spaces and tabs, I used a macro that uses digraphs and token-pasting to generate the disallowed function names (`main` and `printf`). As Unix line endings are `LF` (decimal 10), I had to add a space at the end of the first line to continue the odd/even pattern. Saving some more space, I could coalesce `in` because the two letters fit the odd/even pattern.

Parity verification

```
#define y(a,c,g,i ) a %:%:c %:%:	 in%:%:g %:%:i
	b; y(m,a,	,	 )() {for	(; 	b	<101 ;b	 = 	b+ 1 ) y(	p	,	r	,	t	,	f)(	b%2?"%d	"	:	"E 	"	,	b) ; }

```

Try it online!
> 5 votes

# Answer
# Jelly, 18 bytes

```
ØA 5ị¶ 101Ḷ× Ḃ$oÑK

```

Try it online!

In the Jelly code page, these character have the byte values of

```
12 41 20 35 D8 7F 20 31 30 31 B2 11 20 BF 24 6F 10 4B

```

which follows the pattern `Even Odd Even Odd ...`

## How it works

Removing the extra spaces we get:

```
ØA5ị
101Ḷ×Ḃ$oÑK

```

which is:

```
ØA5ị       - Helper link: Yield "E"
ØA         - Yield the upper case alphabet
  5ị       - Take the fifth element ("E")

101Ḷ×Ḃ$oÑK - Main link: Yield "E 1 E 3 ... E 99 E"
101        - Yield 101
   Ḷ       - Lowered range:            [0, 1, 2, ..., 99, 100]
     Ḃ$    - Take the parity of each:  [0, 1, 0, ..., 1, 0]
    ×      - Multiply each together:   [0, 1, 0, 3, ..., 99, 0]
        Ñ  - Call the helper link:     "E"
       o   - Replace the 0s with "E"s: ["E", 1, "E", ..., 99, "E"]
         K - Join with spaces:         "E 1 E 3 ... E 99 E"

```
> 4 votes

# Answer
# Runic Enchantments, 32 bytes

```
>'D1+k$1:/$'D1+k$/2+:1.C(1+?.;8?
EOEOEOEOEOEOEOEOEOEOEOEOEOEOEOEO

```

Try it online!

`EO` sequence above just indicates whether each byte is even or odd.
> 4 votes

# Answer
# , 35 bytes

Thanks to ErikF for correcting a bug.

```
x=0	:{ 98+2} ;x[ c(	T	,!T) ] ="E";x

```

Try it online!

Defines `x` as the vector of integers from 0 to 100, then replaces all the even values with `"E"` and outputs `x`.

Previous, quite different version:

# , 42 bytes

```
for	(i in	 1:50) write(c(i*+2- 1,	"E"),1 )

```

Try it online!

Includes a few tabs instead of spaces. Uses newlines as separators.

`cat` and `print` are unusable, but luckily `write` is OK. I had to resort to `i*+2 -1` instead of `i*2-1` to keep the alternation.
> 4 votes

# Answer
# Python 3, 65 bytes

```
exit	([ ["E"	,	j] [j%2]for	j	 in	 eval	('ran' +"g"+"e")(101 ) ] )

```

Try it online!

This submission was built on using tabs *and* spaces, as well as a Very Clever™ abuse of `eval`.

**Edit**: Fixed program to adhere to (I had an extra space by mistake).
> 4 votes

# Answer
# GolfScript, 18 bytes

I didn't expect such a small amount of whitespace ...

```
101,{.3(%\"E"if} %

```

Try it online!

## Explanation

```
101,               # Generate range [0 1 2 ... 99 100]
    {          } % # Map every item using this scheme
     .             # Copy the item
      3(%          # Modulo by 3-1 (2)
         \         # If modulo-ing by 2 is truthy: return the item
          "E"if    # Otherwise, return "E"

```
> 3 votes

# Answer
# Jelly, 15 bytes

```
101Ḷ¹⁾E Ḃ ?€Ḣ€K

```

Try it online! Try it online with parity!

A full program that takes no argument and prints the desired output. The footer demonstrates both the parity and result.
> 2 votes

# Answer
# MathGolf, 20 bytes

```
"E"q♀{î♥☻/÷i¿{"E"}îq

```

Try it online!

Very similar to the FizzBuzz example. Uses the MathGolf codepage, can verify parity with this script.

```
"E"q                # Push and output "E"
    ♀               # Push 100
     {              # Loop from 1 to 100
      î             # Push loop counter
       ♥☻/          # Push 32, 16, and divide (basically pushes 2)
         ÷          # Is the loop counter divisible by 2?
          i         # Convert to integer (does nothing)
           ¿{"E"}   # If so, push "E"
                 î  # If not, push the loop counter
                  q # Output

```
> 2 votes

# Answer
# Ruby, 50 bytes

Adaptation of the Python answer. Unlike Python, however, Ruby `puts` is valid code to use for output, eliminating the need for `exit` hacks.

I didn't want to do a direct port, but `map`, `each`, `upto`, and `times` are all forbidden by the spec...

```
x=0;(	puts ["E"	,	x] [x%2] ;x=x+ 1 ) while 	x	<101

```

Try it online!
> 2 votes

# Answer
## `z`, 19 bytes

```
10#0#.a2m a&#"E"#|M

```

Pretty much the same as below. `100.a2ma&"E"|M` The only difference is the 0-range (which does no good for the program).

## W, 19 bytes

```
101 a2m"E"#&a 1 -|M

```

## Explanation

Pretty simple: `#` and  are both readability characters here and have no result on the stack.

```
101a2m"E"&a1-|M

```

```
101           M % Foreach the range 1 -> 101
   a2m          % Modulo the current item by 2
      "E"&      % If true, return "E" (Because odd-1 -> even)
          a1-|  % Otherwise, return a-1

```
> 2 votes

# Answer
# Japt, 15 bytes

```
ò#d_v) ?"E"):»Z

```

Test it

```
ò#d               range [0-100]
   _              passed through
    v) ?          divisible by 2?
        "E"):»Z   replace with 'E' else replace with number

```

Layout : \[242,35,100,95,118,41,32,63,98,69,98,41,58,187,90\]
> 2 votes

# Answer
# Haskell, 296 bytes

```
w = k 1
a(c:e ) = c
i =(id)
e a =(a:)
m 1 =(a"1")
m 3 =(a"3")
m 5 =(a"5")
m 7 =(a"7")
m 9 =(a"9")
m c|c<1 = '0'|c<3 = '2'|c<5 = '4'|c<7 = '6'|c<9 = '8'
m c =(m$c - 10)
q 1 =0;
q c|m c<a"1"= 1 + q(c - 1 )
q c = q$c - 1
k c|c>98= e(a"E")$e(a"9")$e(a"9")$i"E";
k c = e(a"E")$e(m$q c )$e(m c )$k$c +2

```

Try it online!

This was pretty hard since `show` and `print` are both unusable, so I had to convert integers to strings on my own.
> 2 votes

# Answer
# PowerShell, 72 bytes

```
for`t(`t`$i =0;`$i -le 101 - 1 ;`$i =`$i + 1 ) {`$ab=(' e ',`t`$i ) ;`$ab[`$i %2] }

```

For testing:

```
$a = "for`t(`t`$i =0;`$i -le 101 - 1 ;`$i =`$i + 1 ) {`$ab=(' e ',`t`$i ) ;`$ab[`$i %2] }"

# Even/odd ok?
0..($a.Length-1) | % { [char]$a[$_] + "  " + ([byte][char]$a[$_] % 2)}
$a.Length

Invoke-Expression $a

```

Missed the even-odd part in the code, thanks for pointing it out!

Try It Online
> 2 votes

# Answer
# Vyxal `HM`, 5 bytes

```
r⁽\EẆ

```

Try it Online!

This works in both the Vyxal codepage and UTF-8. -2 thanks to pacman256.

The `H` flag can be removed if you place a  at the start, although it only works with UTF-8 then.
> 2 votes

# Answer
# Charcoal, ~~24~~ 18 bytes

```
Ｆ¹⁰¹«¿⊗﹪⊕ι²E↥Ｉ⌈ι⁰→

```

Try it online! Link is to verbose version of code. Here are the 18 hex codes in Charcoal's code page:

```
C6 B1 B0 B1 A8 BF 9E A5 9C E9 B2 45 18 C9 1A A9 B0 13

```

Explanation:

```
Ｆ¹⁰¹«

```

Loop from 0 to 100.

```
¿⊗﹪⊕ι²

```

Test whether the index is even. The index is incremented to comply with the source code restriction, which reverses the sense of the test. The result of the test is doubled to comply with the source code restriction, but this doesn't change the outcome of the decision.

```
E

```

If the number was even then output an `E`.

```
↥Ｉ⌈ι

```

Otherwise take the ceiling of the number to comply with the source code restriction, cast the result to string, and uppercase the result to comply with the source code restriction.

Print 0 `-`s to comply with the source code restriction.

Leave a space between successive outputs.

Note: If a trailing space is acceptable, then the last two characters can be replaced with a space for 17 bytes, although there are alternative solutions, such as this:

```
Ｆ¹⁰¹«¿⊗﹪⊕ι²E ⁺⌈ι

```

Try it online! Link is to verbose version of code. Here are the 17 hex codes in Charcoal's code page:

```
C6 B1 B0 B1 A8 BF 9E A5 9C E9 B2 45 20 AB 1A E9 20

```

Explanation: Much like the above, except that in the even case we directly include the space in the literal while in the odd case the ceiling of the number is concatenated with a space.
> 1 votes

# Answer
# Zsh, ~~50 30~~ 34 bytes

*Bug fix: I was checking each pair of letters to make sure it had a character of each parity, instead of ensuring it alternated.*

```
"e"cho E"	"{"1"'.'.9"9"'.'.'0'2} E

```

~~Try it online! Try it online!~~ Try it online! Self-tests. Contains a literal tab.

~~I couldn't figure out a way to finagle the most straightforward `echo E\ {1..99..2} E` into anything, mostly due to the double period.~~ EDIT: I did it. Turns out in normal expressions, quotes inside brace ranges don't really matter.
> 1 votes

# Answer
# Pip, 16 bytes

```
1 +2	*	,50	JW"E"

```

Try it online!

Outputs without separators.

Spaces and tabs are no-ops, so this boils down to:

```
    ,50       Range(50)                                               0, 1, ..., 49
  2*          Multiply each by 2                                      0, 2, ..., 98
1+            Add 1                                                   1, 3, ..., 99
       JW"E"  Join with "E", wrapping the outside with "E"s as well   E1E3E...E99E

```
> 1 votes

# Answer
# Perl 5 \+ `-p`, 55 bytes

```
} {do {$_.=$- %2?$-.' ':q(E ) } while(+$- =$- + 1 )<101

```

Try it online!
> 1 votes

# Answer
# Stax, 13 bytes

```
101rm2% _"E"?

```

Run and debug it

The program has these ASCII codes.

```
49 48 49 114 109 50 37 32 95 34 69 34 63

```
> 1 votes

# Answer
# Ly, ~~36~~ 34 bytes

```
"E"' _&s&o '2_R_r_p[:+,u>' _l_&o<]

```

Try it online!

At a high level, this one works like this...

* print the initial `E`
* generate the sequence `1..49`
* loops over that list printing the `N*2-1` plus `E`

Here's the decimal codepoints for the source:

```
34 69 34 39 32 95 38 115 38 111 32 39 50 95 82 95 114 95 112 91 58 43 44 117 62 39 32 95 108 95 38 111 60 93

```

The code uses a couple of Ly specific tricks to achieve the even/odd sequence. First spaces can be added most places and are ignored, which allows for an "even" no-op. And `_` (underscores) work as "odd" no-op's the same way. Finally, quoting characters can be done using double quotes (even) or as a series of single characters after single quotes (odd).

And the gory details:

```
"E"'                               - push "E " on stack
     _&s                           - stash a copy of the stack
        &o                         - print "E "
         '2                        - push 50 on the stack
             _R                    - gen seq 0..49
               _r                  - reverse stack
                 _p                - pop 0 (first entry) off stack
                   [             ] - loop while stack not empty
                    :+,            - calc: <TOP>*2-1
                       u           - print as number
                        >          - switch to new stack
                         '         - push space
                           _l      - push "E " from stashed stack
                             _&o   - print stack
                                <  - switch back to original stack

```
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, restricted-source
---


title: Find the finest building blocks

text:
# Question
Title: Find the finest building blocks
Given a string \\$X\\$ we will say two strings, \\$a\\$ and \\$b\\$, are **building blocks** of \\$X\\$ if \\$X\\$ can be made by concatenating some \\$n\\$ \\$a\\$s with \\$m\\$ \\$b\\$s in any order. For example the string `tomato` has building blocks `to` and `ma`:

```
to ++ ma ++ to

```

We will say that the **fineness** of a set of building blocks is the sum \\$n+m\\$. That is the number of blocks required to build \\$X\\$. So in the example `tomato` here are some building blocks with their fineness:

```
to, ma -> 3
tom, ato -> 2
tomato, z -> 1

```

## Task

Given a non-empty string as input output a set of two building blocks with maximal fineness. In the case of a tie you may output any or all of the maximal building blocks.

You may assume the input will contain only the alphabetic ASCII characters.

If there is a correct output where \\$a\\$ is the empty string, you may output only the \\$b\\$ value.

This is so the goal is to minimize the size of your source code as measured in bytes.

*However*, I make explicit what is usually implicit: you should consider submissions of differing time complexity as belonging to different categories for scoring. I encourage people to try and golf both efficient and inefficient algorithms to this problem.

## Test cases

The following examples have unambiguous (up to order) solutions:

```
tomato -> to ma  F=3
tomcat -> t omca  F=3
banana -> ba na  F=3
axaaaaaaxa -> a x  F=10
axaaaaaaja -> a xaaaaaaj  F=3
aaxaaaajaaaajaaaaxaa -> a xaaaajaaaajaaaax  F=5

```

The following have ambiguous solutions. I've given a possible valid solution and its fineness to compare to your result. I've used the character `*` in the output to represent cases where that string may be empty or omitted (these two options are non-exhaustive).

```
bobcat -> bob cat  F=2
axaaaajaaaaxa -> axa aaajaaa  F=3
axaaaajaaaajaaaaxa -> axa aaajaaaajaaa  F=3
aaaaaaaaaa -> a *  F=10
x -> x *  F=1

```

# Answer
# Pyth, ~~14~~ ~~13~~ ~~10~~ 9 bytes, \\$O(2^n)\\$

-1 byte thanks to @isaacg

```
e<I#2{M./

```

Attempt This Online!

```
e<I#2{M./Q
       ./Q  # all partitions of input
     {M     # remove duplicates in each partition
 <I#2       # filter for elements where elem[:2] == elem
e           # last element

```
> 6 votes

# Answer
# JavaScript (ES11), 107 bytes, \\$O(n^3)\\$ *

** or worse, depending on the time complexity of the regular expression algorithm, which is likely to be implementation-dependent*

A regex-based solution. Much more convoluted than I would like.

```
f=(s,n=(w=s.length)*w)=>n--?s.match(`^(.+)\\1{${x=n%w}}(.+)(\\1|\\2){${n/w-x|0}}$`)?.slice(1,3)||f(s,n):[s]

```

Attempt This Online!

---

# JavaScript (ES6), 107 bytes, \\$O(2^n)\\$

```
f=([c,...a],k,u=o=[],s,b=[...u,s])=>c?f(a,k,u,[s]+c)|f(a,-~k,b,c)||new Set(o):new Set(b).size>2||o[k]?0:o=b

```

Try it online!
> 4 votes

# Answer
# Haskell, 155 bytes, \\$O(n^3)\\$

```
(%)=splitAt
l=length
x#w=maximum$((w==[],0),x):[((a,b+1),c)|((a,b),c)<-[x#p|y<-x,(s,p)<-[l y%w],s==y]++[(s:x)#p|l x<2,(s,p)<-map(%w)[1..l w]]]
f x=snd$[]#x

```

Attempt This Online!

Outputs a list of two strings if the input has length \\$\geq 2\\$, otherwise a list of a single string.

Can be reduced to 136 bytes if outputting more stuff is allowed.
> 3 votes

# Answer
# Jelly, 11 bytes, \\$O(2^n)\\$

```
ŒṖLÞQ€ṫÐḟ3Ṫ

```

Try it online!

A monadic link taking a string and returning a list of two strings.

## Explanation

```
ŒṖ          | Partition
  LÞ        | Sort by length (number of pieces in the partition)
    Q€      | Ubiquity each
      ṫÐḟ3  | Filter out those length 3 or longer (technically those where taking the tail starting at position 3 is non-empty)
          Ṫ | Tail

```
> 2 votes

# Answer
# Vyxal 3, 9 bytes, \\$O(2^n)\\$

```
ṗSᵛuᶻϩḢḢt

```

Try it Online!

```
ṗSᵛuᶻϩḢḢt
ṗ          # all partitions of input
 S         # sort by length
  ᵛu       # uniquify each
    ᶻϩḢḢ   # keep only elements with length less than 3
        t  # last element

```
> 2 votes

# Answer
# Retina, 65 bytes, \\$ O(n^3) \\$

```
L$w`(.+)(?=((.+?)\3*)?$(?<=^(\1|\3)+))
$#4¶$1¶$3
N^`.+¶.+¶.*
1G`¶

```

Try it online! Link includes test cases. Explanation:

```
L$w`(.+)(?=((.+?)\3*)?$(?<=^(\1|\3)+))
$#4¶$1¶$3

```

List the fineness and pair of building blocks all substrings of the input whose suffix is a multiple of a second building block whereby the input string can be constructed using only the two building blocks, unless the suffix is empty, in which case it is not counted (this would otherwise throw off the count by `1`).

```
N^`.+¶.+¶.*

```

Sort in descending order of fineness.

```
1G`¶

```

Keep only the pair of building blocks with the greatest fineness. (Alternatively, the `^` can be removed to sort the building blocks in ascending order in which case a `-` must be prefixed to this line so that the greatest fineness is selected.)
> 1 votes

# Answer
# Python, 116 bytes, between \\$O(n^3)\\$ and \\$O(2^n)\\$

Port of Xcali's answer

```
lambda x,l="":max((subn(a:=(l:=l+i)+sub(r'^(%s)*(.+?)(\2|\1)*$'%l,"|\\2",x),i,x)[1],a)for i in x)[1]
from re import*

```

Attempt This Online!

# Python, 135 bytes, between \\$O(n^3)\\$ and \\$O(2^n)\\$

Port of Arnauld's regex answer

```
lambda x:[n:=len(x),[x],*[[m[1],m[2]]for i in range(n*n)if(m:=re.match(r"^(.+)\1{%d}(.+)(\1|\2){%d}$"%(i/n-i%n,i%n),x))]][-1]
import re

```

Attempt This Online!
> 0 votes

# Answer
# 05AB1E, 11 bytes, \\$O(2^n)\\$

```
.œé€Ùʒg3‹}θ

```

Try it online or verify (almost) all test cases.

**Explanation:**

```
.œ         # Get all partitions of the (implicit) input-string
  é        # Sort them by length
   €Ù      # Uniquify the parts of each partition
     ʒ     # Filter the partitions by:
      g    #  Where the length (aka the amount of unique parts)
       3‹  #  Is smaller than 3
     }θ    # After the filter: pop and keep the last one
           # (which is output implicitly as result)

```
> 0 votes

# Answer
# Charcoal, 88 bytes, worst case \\$ O(2^n) \\$

```
ＦＬθ⊞υ⟦¹…θ⊕ιω✂θ⊕ι⟧ＦυＦΦ⎇§ι²✂ι¹¦³¦¹⊞ＯＥ§ι³…§ι³⊕λ§ι¹¬⌕§ι³κ⊞υ⟦⊕§ι⁰§ι¹⎇⁼κ§ι¹§ι²κ✂§ι³Ｌκ⟧✂⌈Φυ¬⊟ι¹

```

Try it online! Link is to verbose version of code. Explanation:

```
ＦＬθ⊞υ⟦¹…θ⊕ιω✂θ⊕ι⟧

```

Get all the prefixes of the input string as a list `[1, prefix, empty string, suffix]` where `1` represents the number of building blocks used so far.

```
Ｆυ

```

Perform a search over the possible building blocks.

```
ＦΦ⎇§ι²✂ι¹¦³¦¹⊞ＯＥ§ι³…§ι³⊕λ§ι¹¬⌕§ι³κ

```

If two building blocks have already been picked for this entry then just search those entries otherwise search both the original building block and all of the prefixes of the string remaining. Keep only those where the string remaining starts with the prefix.

```
⊞υ⟦⊕§ι⁰§ι¹⎇⁼κ§ι¹§ι²κ✂§ι³Ｌκ⟧

```

Create a new entry with `1` more building block and the block removed from the suffix, updating the second building block if it is new.

```
✂⌈Φυ¬⊟ι¹

```

Get the entries where the entire string was successfully built, find the one with the most blocks used and output the blocks.

The performance is \\$ O(2^n) \\$ because on an input of `n` `a`s the code will try both the building block `a` as the first possible building block and also `a` as the next possible building block for each character, generating two child entries each time. An input of `16` `a`s takes about half a minute on TIO. This can be improved at a cost of `6` bytes so something probably about \\$ O(n^3) \\$:

```
ＦＬθ⊞υ⟦¹…θ⊕ιω✂θ⊕ι⟧ＦυＦΦ⎇§ι²✂ι¹¦³¦¹⊞ＯΦＥ§ι³…§ι³⊕λ⁻κ§ι¹§ι¹¬⌕§ι³κ⊞υ⟦⊕§ι⁰§ι¹⎇⁼κ§ι¹§ι²κ✂§ι³Ｌκ⟧✂⌈Φυ¬⊟ι¹

```

Try it online! Link is to verbose version of code. Explanation: As above, but when choosing the second building block, does not allow it to be the same as the first building block (or a multiple, not that that makes much difference, since the pathological case was for the two being equal).
> 0 votes

# Answer
# Haskell \+ hgl, 16 bytes, \\$\mathcal{O}(n2^n)\\$

```
g1 lL3<nb<<sJ<pt

```

Attempt This Online!

## Explanation

* `pt`: get all partitions
* `sJ`: sort them by length
* `nb`: remove duplicate elements from each partition
* `g1`: get the first one such that ...
* `lL3`: its length is shorter than 3

## Reflection

I've tried many ways to do this. I was working on a fast version, but there were so many serious gaps where I couldn't make it work.

* There should be versions of `pt` and `pST` which output partitions sorted by length. There should also be functions to get partitions of a certain size. This would not only shorten the existing code, but it would make it \\$\mathcal{O}(2^n)\\$.
* There should be joined versions of `l2q` and `l3q`. While we're at it, there should also be a joined version of `l2`.
* There are a bunch of related things I really would have liked here:
    + There should be a function to take a substring and split along that. (There exists one for elements, but not substrings.)
    + There should be a function to take a substring and split along the substring leaving occurences of it in place. e.g. `f "ma" "tomato" = ["to", "ma", "to"]`.
    + There should be a function to take a string and replace all instances of that string with another string. (There exists one that replaces the *first* instances but no more.)
    + There should be a function to take two elements `a` and `b` and replace all instances of `a` with `b`.
    + There should be a function to take a predicate and an element and replace all elements in a structure satisfying the predicate with the given element.
> 0 votes

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


title: Disco Zoo animal hunt

text:
# Question
Title: Disco Zoo animal hunt
This question is inspired by the game Disco Zoo

## Background

Disco Zoo is a game where you can go into the wild and rescue animals. Once you have found an animal you can put it in your zoo for your visitors to see.

To find animals you first select a field to search, and you get to see a 5x5 grid where the animals are hiding. At the top of the screen you can see which animals are hiding in the field.

Each animal has a different pattern, which never changes for the same animal. E.g. (`X` is pattern, `o` is padding)

```
Animal=Sheep    Animal=Unicorn
Pattern:        Pattern:

 XXXX            Xoo
                 oXX

```

Some animals use 2 blocks, some 3 and some 4. The pattern will be translated, but not rotated.

## Task

The user gives you a pattern or the name of an animal (your choice) and you have to generate an optimum strategy to search for that animal/pattern. A strategy is a set of blocks from the 5x5 grid; an optimum strategy is one which guarantees to find at least 1 block from the pattern, and where there is no strategy with fewer blocks which can make the same guarantee.

For sheep and unicorns the optimum strategy would be searching the middle column:

```
ooXoo
ooXoo
ooXoo
ooXoo
ooXoo

```

Another example:

```
Animal: Hippo
Pattern:       Optimum strategy:
               ooooo
 XoX           oXXoo
 ooo           oXXoo
 XoX           ooooo
               ooooo

```

The Disco Zoo wiki's Patterns page lists all the animals and their patterns. You may hard-code the patterns. The wiki also lists optimum strategies for all the animals. Feel free to look at them but you're not allowed to hard-code them.

Input: Either a pattern made of `X` and `O` or the name of the animal.
Output: a 5x5 grid made of `X` or `O` where X marks an optimum strategy.

# Answer
> 3 votes
# Ruby 221

```
->a{l=a.join(?o*(5-w=a[0].size))
s=?o*25
q=(0..25-l.size).select{|i|i/5==(i+w-1)/5}.map{|i|(?o*i+l+s)}
(h=q[0].size.times.map{|i|q.count{|p|p[i]<?o}}
s[c=h.index(h.max)]=?X
q.reject!{|p|p[c]<?o})while q!=[]
s.scan /.{5}/}

```

### Input and Output

This is a Ruby function that takes one parameter representing the animal and returns the solution, both being represented as string arrays.

For example, the Hippo is represented as:

```
['XoX',
 'ooo',
 'XoX']

```

and its solution is:

```
['ooooo',
 'oXXoo',
 'oXXoo',
 'ooooo',
 'ooooo']

```

### Test

Here's a working version. Feel free to experiment with it and enter more animals as parameters.

### Algorithm

I found this problem very interesting and I experimented to solve it in different ways, including brute force, which is less feasible, but possible for the given inputs (it would be terribly inefficient for the input `['X']` though).

The algorithm I found to be the most efficient is the following:

1. Compute all possible positions for the animal on the 5x5 board
2. Given the existing positions, compute a map of frequencies for each of the 25 cells
3. Take one of the cells that contain the max number of "hits" and make it part of the solution. Exclude all positions that are "hit" in that particular cell.
4. Repeat steps 2-3 until there are no positions left.

I don't have a proof of optimality for this algorithm, but it tested most animals present on the wiki page and it returned optimal solutions for all.

Note that for some animals the solutions are not identical to the ones presented in the wiki, but involve the same number of blocks.

For example, the Wooly Rhino page presents this solution:

```
ooooo
ooooo
oXXXo
ooooo
ooooo

```

and the algorithm returns this one:

```
ooooo
oooXo
ooXXo
ooooo
ooooo

```

which is also correct and optimal (3 blocks).

Here's the (slightly more) readable version of the program:

```
SIZE = 5

# return all possible placements for the animal on a 5x5 board
def get_placements(animal)
  # represent the 5x5 board and the animal as linear arrays
  linear_animal = animal.join(?o*(SIZE - animal[0].size))
  d = SIZE*SIZE
  (0..d-linear_animal.size)
    .select{|i| i/5 == (i+animal[0].size-1)/5} # to avoid wrap-around positions
    .map { |i|
      (?o*i + linear_animal + ?o*d)[0...d]
    }
end

# given a set of possible placements,
# return a map of frequencies for every cell
def heatmap(placements)
  placements[0].size.times.map do |i|
    placements.count {|p|p[i] < ?o}
  end
end

# given an animal, return the solution as an array of 5 5-character strings
def solve(animal)
  placements = get_placements animal
  solution = []

  while placements.any?
    h = heatmap(placements)

    solution << chosen = h.index(h.max)

    placements = placements.reject {|pl| pl[chosen] < ?o }
  end

  (0...25).map{|i| solution.include?(i) ? ?X : ?o }.join.scan /.{5}/
end

```

# Answer
> 0 votes
# Python3, 474 bytes

```
R=range
E=enumerate
V=lambda d,p,X,Y:not all((x+X,y+Y)in d for x,y in p)
def f(p):
 d={(x,y):[]for x in R(5)for y in R(5)}
 p=[(x,y)for x,r in E(p)for y,v in E(r)if'X'==v]
 X,Y,C=0,0,0
 while 1:
  C+=1
  Q,W=[],[]
  for x,y in p:d[(x+X,y+Y)]+=[C]
  Y+=1
  if V(d,p,X,Y):
   if V(d,p,X:=X+1,Y:=0):break
 M=[]
 while any(d.values()):t=max(d,key=lambda x:len(d[x]));M+=[t];d={i:{*d[i]}-{*d[t]}for i in d}
 s=[['0'for _ in R(5)]for _ in R(5)]
 for x,y in M:s[x][y]='1'
 return s

```

Try it online!

---
Tags: code-golf
---


# Question
Title: Check if a UUID is valid without using regexes
Given a string input, write a program that prints a truthy value to STDOUT or equivalent if the input is a valid UUID, without using regexes.

A valid UUID is

> 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens).
>
> <sub>**Source**</sub>

## Test Cases

```
0FCE98AC-1326-4C79-8EBC-94908DA8B034
    => true
00000000-0000-0000-0000-000000000000
    => true
0fce98ac-1326-4c79-8ebc-94908da8b034
    => true
0FCE98ac-1326-4c79-8EBC-94908da8B034
    => true

{0FCE98AC-1326-4C79-8EBC-94908DA8B034}
    => false (the input is wrapped in brackets)
0GCE98AC-1326-4C79-8EBC-94908DA8B034
    => false (there is a G in the input)
0FCE98AC 1326-4C79-8EBC-94908DA8B034
    => false (there is a space in the input)
0FCE98AC-13264C79-8EBC-94908DA8B034
    => false (the input is missing a hyphen)
0FCE98AC-13264-C79-8EBC-94908DA8B034
    => false (the input has a hyphen in the wrong place)
0FCE98ACD-1326-4C79-8EBC-94908DA8B034
    => false (one of the groups is too long)
0FCE98AC-1326-4C79-8EBC-94908DA8B034-
    => false (has a trailing hyphen)
0FCE98AC-1326-4C79-8EBC-94908DA8B034-123
    => false (too many groups)
0FCE98AC13264C798EBC94908DA8B034
    => false (there is no grouping)

```

## Rules

* Regular Expressions are not allowed
* Literal pattern matching which is *like* a regex is not allowed. For example, using `[0-9a-fA-F]` or other hexadecimal identifiers (we'll call this `n`) and then matching `nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn` or `n[8]-n[4]-n[4]-n[4]-n[12]` is not allowed
* The input may either be taken from `STDIN` or as an argument to a function
* The input is case insensitive
* It is safe to assume that the input will *not* contain linefeeds or newlines.
* The input may contain any printable ASCII characters (spaces included)
* A truthy value must be printed to `STDOUT` or equivalent if the input is a valid uuid
* A falsey value must be printed to `STDOUT` or equivalent if the input is *not* a valid uuid
* If using a function, instead of using `STDOUT`, the output can be the return value of the function
* The truthy/falsey value cannot be printed to `STDERR`.
* Standard loopholes apply
* This is , so the shortest program in bytes wins. Good luck!

## Leaderboard

This is a Stack Snippet that generates both a leaderboard and an overview of winners by language.

To ensure your answer shows up, please start your answer with a headline using the following Markdown template

```
## Language Name, N bytes

```

Where N is the size, in bytes, of your submission

If you want to include multiple numbers in your header (for example, striking through old scores, or including flags in the byte count), just make sure that the actual score is the *last* number in your header

```
## Language Name, <s>K</s> X + 2 = N bytes

```

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

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

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

# Answer
> 15 votes
## CJam, ~~31~~ ~~30~~ 29 bytes

```
8 4__C]Nf*'-*qA,s'G,_el^+Ner=

```

Run all test cases here.

### Explanation

Instead of pattern matching the input directly, we're first transforming it to a simpler form which can be easily compared against a single pattern string.

```
8 4__C] e# Push the array of segment lengths, [8 4 4 4 12].
Nf*     e# Turn that into strings of linefeeds of the given length.
'-*     e# Join them by hyphens, giving "NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN".
q       e# Read the input.
A,s     e# Push the string "0123456789".
'G,_el^ e# Push the string "ABCDEFabcdef".
+       e# Concatenate the two strings.
N       e# Push a linefeed.
er      e# Replace all hexadecimal digits with linefeeds.
=       e# Check for equality with the pattern string.

```

# Answer
> 24 votes
# JavaScript ES6, ~~73~~ ~~55~~ 56 chars

```
s=>s.split`-`.map(x=>x.length+`0x${x}0`*0)=="8,4,4,4,12"

```

The previous 55 chars version has a problem with trailing spaces in group:

```
s=>s.split`-`.map(x=>x.length+("0x"+x)*0)=="8,4,4,4,12"
// "00000000-0000-0000-000 -000000000000" true

```

Test:

```
f=s=>s.split`-`.map(x=>x.length+`0x${x}0`*0)=="8,4,4,4,12"
;`0FCE98AC-1326-4C79-8EBC-94908DA8B034
0fce98ac-1326-4c79-8ebc-94908da8b034
0FCE98ac-1326-4c79-8EBC-94908da8B034
0GCE98AC-1326-4C79-8EBC-94908DA8B034
0FCE98AC-13264C79-8EBC-94908DA8B034
0FCE98AC-13264-C79-8EBC-94908DA8B034
0FCE98ACD-1326-4C79-8EBC-94908DA8B034
0FCE98AC-1326-4C79-8EBC-94908DA8B034-123
00000000-0000-0000-0000-000000000000
D293DBB2-0801-4E60-9141-78EAB0E298FF
0FCE98AC-1326-4C79-8EBC-94908DA8B034-
00000000-0000-0000-000 -000000000000`.split(/\n/g).every(s=>f(s)==/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i.test(s))

```

# Answer
> 11 votes
## PowerShell, ~~29~~ ~~21~~ ~~84~~ ~~49~~ 37 Bytes

```
param($g)@{36=$g-as[guid]}[$g.length]

```

Many thanks to the folks in the comments assisting with this golfing to keep up with the changing rules -- TessellatingHeckler, iFreilicht, Jacob Krall, and Joey. Please see the edit history for revisions and older versions.

This revision takes input as `$g`, then creates a new hash table `@{}` with one element, index `36` is set equal to `$g-as[guid]`. This uses the built-in `-as` operator to attempt conversion between two .NET data types -- from `[string]` to `[guid]`. If the conversion is successful, a `[guid]` object is returned, else `$null` is returned. This portion ensures that the input string is a valid .NET GUID.

The next step is to index into the hash table with `[$g.length]`. If `$g` is not exactly 36 characters in length, the hash table will return `$null`, which will be output as a falsey value. If `$g` is 36 characters in length, then the result of the .NET call will be output. If `$g` is not a valid .NET GUID (in any form), then it will output `$null` as a falsey value. Otherwise it will output a .NET GUID object as a truthy value - the only way that can be output is if it matches the requested format of the challenge.

### Examples

Here I am encapsulating the script call in parens and explicitly casting as a Boolean for clarity.

```
PS C:\Tools\Scripts\golfing> [bool](.\check-if-a-uuid-is-valid.ps1 '0FCE98AC-1326-4C79-8EBC-94908DA8B034')
True

PS C:\Tools\Scripts\golfing> [bool](.\check-if-a-uuid-is-valid.ps1 '0FCE98AC-1326-4C79-8EBC-94908DA8B034D')
False

PS C:\Tools\Scripts\golfing> [bool](.\check-if-a-uuid-is-valid.ps1 '0FCE98AC13264C798EBC94908DA8B034')
False

```

# Answer
> 9 votes
## Emacs Lisp, 236 Bytes

```
(lambda(s)(and(eq(string-bytes s)36)(let((l(string-to-list s))(i 0)(h '(8 13 18 23))(v t))(dolist(c l v)(set'v(and v(if(member i h)(and v(eq c 45))(or(and(> c 47)(< c 58))(and(> c 64)(< c 91))(and(> c 96)(< c 123))))))(set'i(+ i 1))))))

```

Ungolfed:

```
(lambda (s)
  (and (eq (string-bytes s) 36) ; check length
       (let ((l (string-to-list s))
             (i 0)
             ; location of hyphens
             (h '(8 13 18 23))
             (v t))
         (dolist (c l v)
           (set 'v (and v (if (member i h)      ; check if at hyphen position
                              (and v (eq c 45)) ; check if hyphen
                            (or (and (> c 47) (< c 58))      ; check if number
                                (and (> c 64) (< c 91))      ; check if upper case letter
                                (and (> c 96) (< c 123)))))) ; check if lower case letter
           (set 'i (+ i 1)))))) ; increment

```

# Answer
> 8 votes
Due to changes to the rules, this answer is no longer competitive :(

# C, 98

```
main(a,n){printf("%d",scanf("%8x-%4hx-%4hx-%4hx-%4hx%8x%n%c",&a,&a,&a,&a,&a,&a,&n,&a)==6&&n==36);}

```

Mostly fairly self explanatory. The `%n` format specifier gives the number of bytes read so far, which should be 36. `scanf()` returns the number of matched items, which should be 6. The final `%c` should not match anything. If it does, then there is trailing text, and `scanf()` will return 7.

Compile with `-w` to suppress the pesky warnings (there are several).

# Answer
> 6 votes
# JavaScript ES6, 70 ~~83~~

**NOTE** thx to @Qwertiy for finding a bug (and suggesting some improvements and fixes)

Thx @CᴏɴᴏʀO'Bʀɪᴇɴ 2 bytes saved

Other 9 bytes saved simplifiying the length check (the complex way *was* shorter in the first draft, but not now)

```
u=>u.split`-`.every((h,l,u)=>u[4]&&-`0x${h}1`&&h.length-'40008'[l]==4)

```

**Explained**

```
u=>u.split`-` // make an array splitting at '-'
.every( // for every element the following must be true
 (h,l,u)=> // h is the element, l is the index, u is the whole array
 u[4] // element 4 must be present (at least 5 element in array)
 && -`0x${h}1` // element must be a valid hex string with no extraneous blanks (else NaN that is falsy)
 // get requested length from index (8,4,4,4,12 sub 4 to put in 1 char)
 // a 6th elements will be rejected as undefined != 4
 && h.length-'40008'[l]==4// then check element length
)

```

Test snippet

```
f=u=>u.split`-`.every((h,l,u)=>u[4]&&-`0x${h}1`&&h.length-'40008'[l]==4)

console.log=x=>O.innerHTML+=x+'\n'

;[
  ['0FCE98AC-1326-4C79-8EBC-94908DA8B034',true],
  ['0fce98ac-1326-4c79-8ebc-94908da8b034',true],
  ['0FCE98ac-1326-4c79-8EBC-94908da8B034',true],
  ['00000000-0000-0000-0000-000000000000', true],
  ['ffffffff-ffff-ffff-ffff-ffffffffffff', true],
  ['0GCE98AC-1326-4C79-8EBC-94908DA8B034',false],
  ['0FCE98AC-13264C79-8EBC-94908DA8B034',false],
  ['0FCE98AC-13264-C79-8EBC-94908DA8B034',false],
  ['0FCE98ACD-1326-4C79-8EBC-94908DA8B034',false],
  ['0FCE98AC-1326-4C79-8EBC',false],
  ['0FCE98AC-1326-4C79-8EBC-94908DA8B034-',false],
  ['00000000-0000-0000-000 -000000000000', false],
  ['0FCE98AC-1326-4C79-8EBC-94908DA8B034-123',false],
].forEach(x=>{
  var t=x[0], r=f(t), k=x[1]
  console.log('Test '+t+' result '+r+(r==k?' ok':' fail'))
})
```

```
<pre id=O></pre>
```

# Answer
> 5 votes
Due to changes to the rules, this answer is no longer competitive :(

# Pure Bash (no external utilities), 78

```
printf -vv %8s-%4s-%4s-%4s-%12s
p=${v// /[[:xdigit:]]}
[ "$1" -a ! "${1/$p}" ]

```

Takes input from the command line.

* The `printf` builds the following string `- - - -`.
* The `p=` line transforms this to the following pattern: `[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]-[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]-[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]-[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]-[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]`. Note this looks an awful lot like a regular expression. However, it is not in this context. It is a pattern for shell pattern matching. This is similar *in concept* to a regular expression, but is a different construct (and syntax).
* The last line checks if
    + the input is non-empty
    + if pulling the pattern out of the input string produces an empty string

Idiomatic to shell, a return code of 0 indicates success/TRUE and 1 indicates failure/FALSE. The return code may be inspected with `echo $?` after running the script.

# Answer
> 4 votes
# Jolf, 32 bytes

Try it here!

```
 eGi'-DN&bH*28=lH.[8,4,4,4,12]S}
 e                               Property "e"very of next object
  Gi'-                           Split i at hyphen
      DN                       } every comparison function
        &                        logical conjugation of next two arguments
         bH*28                   base 16 of H (first arg); is NaN (falsey) if invalid
              =                  equality of next two items
               lH                the length of H (first arg)
                 .            S  the Sth (index) member of the object inbetween
                  [8,4,4,4,12]   array of lengths

```

Because of an error in my code, this is longer than it should be. :( `[8,4,4,4,12]` *should* be the same as `{8444*26}`, but `}` is also the closing of a function :P

# Answer
> 4 votes
# MATL, 55 bytes

```
jttn36=?[9,5,5,5]XsXK)45=?36:Km~)4Y2'A':'F'hm?}F]]]N~1$

```

I refrained from using the `Yb` function (`strsplit`) because it's somewhat similar to `regexp(..., 'split')`. This only uses indexing and character comparisons.

### Example

```
>> matl
 > jttn36=?[9,5,5,5]XsXK)45=?36:Km~)4Y2'A':'F'hm?}F]]]N~1$
 >
> This is a test
0

>> matl
 > jttn36=?[9,5,5,5]XsXK)45=?36:Km~)4Y2'A':'F'hm?}F]]]N~1$
 >
> D293DBB2-0801-4E60-9141-78EAB0E298FF
1

```

### Explanation

```
jt                     % input string, duplicate
tn36=?                 % if length is 36
  [9,5,5,5]XsXK        % build and copy indices of required '-' positions
  )45=?                % if those entries are indeed '-'
    36:Km~)            % logical index of remaining positions
    4Y2'A':'F'h        % allowed chars in those positions
    m?                 % if all those entries are legal: do nothing
    }                  % else
      F                % false value
    ]                  % end
  ]                    % end
]                      % end
N~                     % true if stack is empty
1$                     % display last result only

```

# Answer
> 3 votes
## CJam, ~~52~~ 42 bytes

```
qeu__{A7*)<},\'-/83 3b{)4*}%.{\,=}[1]5*=*=

```

Try it online. Outputs the original string if true, outputs empty string if false (this is allowed).

Explanation:

```
qeu__                                      e# Take input, make 2 copies
     {A7*)<},\                             e# Remove invalid characters from first copy
              '-/                          e# Split top of stack on '-
                 83 3b{)4*}%               e# Array of group lengths: [8 4 4 4 12]
                            .{\,=}[1]5*=   e# Compare two arrays, return true if group lengths are correct
                                        *= e# Multiply this value by original string (0 = empty string, 1 = same string)

```

# Answer
> 3 votes
# Julia, 86 bytes

```
s->(t=split(s,"-");map(length,t)==[8,4,4,4,12]&&all(i->!isnull(tryparse(Int,i,16)),t))

```

This is an anonymous function that accepts a string and returns a boolean. To call it, give it a name, e.g. `f=s->...`.

Ungolfed:

```
function f(s::AbstractString)
    # Split the input into an array on dashes
    t = split(s, "-")

    # Ensure the lengths are appropriate
    ok1 = map(length, t) == [8, 4, 4, 4, 12]

    # Ensure each element is a valid hexadecimal number
    ok2 = all(i -> !isnull(tryparse(Int, i, 16)), t)

    return ok1 && ok2
end

```

# Answer
> 3 votes
## C# 196 bytes

```
using System.Linq;class P{bool T(string v){var r=v.Length==36;for(var i=0;i<v.Length;i++)r&=new[]{8,13,18,23}.Any(t=>t==i)?v[i]=='-':v[i]>47&&v[i]<58|v[i]>64&&v[i]<71|v[i]>96&&v[i]<103;return r;}}

```

Ungolfed:

```
using System.Linq;
class P
{
    public bool T(string v)
    {
        var r = v.Length == 36;
        for (var i = 0; i < v.Length; i++)
            r &= new[] { 8, 13, 18, 23 }.Any(t => t == i)
                ? v[i] == '-'
                : v[i] > 47 && v[i] < 58 | v[i] > 64 && v[i] < 71 | v[i] > 96 && v[i] < 103;
        return r;
    }
}

```

Method `T` can be invoked with any non-null string and will return `true` for valid GUID's, `false` otherwise. This is a constant-time validation; at the cost of three chars you can early-exit the method (change `i < v.Length` to `i < v.Length && r`).

Will try to get the bytecount down further later.

I've obviously left out the `Guid.ParseExact` way because where's the fun in that? Here it is, without much attempt to golf it down further in **86 bytes**:

```
using System;class P{bool T(string v){Guid x;return Guid.TryParseExact(v,"D",out x);}}

```

Ungolfed:

```
using System;
class P
{
    bool T(string v)
    {
        Guid x;
        return Guid.TryParseExact(v, "D", out x);
    }
}

```

# Answer
> 2 votes
## Perl 6,  ~~83~~  67 bytes

~~```
# 83 bytes
{
  (
    my@a=.uc.split('-')
  ).map(*.comb)⊆('0'..'9','A'..'F')
&&
  @a».chars~~(8,4,4,4,12)
}

```~~
```
# 67 bytes
{
  (
    $/=.split('-')
  ).map({:16($_)//|()})==5
&&
  $/».chars~~(8,4,4,4,12)
}

```

( counts do not include newlines or indents as they are not needed )

usage:

```
# give it a name
my &code = {...}

say map &code, «
  D293DBB2-0801-4E60-9141-78EAB0E298FF
  0FCE98AC-1326-4C79-8EBC-94908DA8B034
  0fce98ac-1326-4c79-8ebc-94908da8b034
  0FCE98ac-1326-4c79-8EBC-94908da8B034
  00000000-1326-4c79-8EBC-94908da8B034
»;
# (True True True True True)

say map &code, «
  0GCE98AC-1326-4C79-8EBC-94908DA8B034
 '0FCE98AC 1326-4C79-8EBC-94908DA8B034'
  0FCE98AC-13264C79-8EBC-94908DA8B034
  0FCE98AC-13264-C79-8EBC-94908DA8B034
  0FCE98ACD-1326-4C79-8EBC-94908DA8B034
  0FCE98AC-1326-4C79-8EBC-94908DA8B034-
  0FCE98AC-1326-4C79-8EBC-94908DA8B034-123
»;
# (False False False False False False False)

```

# Answer
> 2 votes
# Python 2, ~~99~~ 112 bytes

```
def f(u):
 try:u=u.split()[0];int(u.replace('-',''),16);print[8,4,4,4,12]==map(len,u.split('-'))
 except:print 0

```

On a valid input, it prints `True`. On an invalid input it prints `False` or `0`, depending on why it was invalid. `False` and `0` are both falsey in Python.

The function has to check 3 things:

* Every non-hyphen character is a digit or is in `ABCDEF`
* There are exactly 4 hyphens
* There are 8 characters before the first hyphen, 12 after the last, and 4 between any other two

Here's a breakdown to show how it checks for them. It's slightly out of date but I'm hungry so I'll update it later.

```
def f(u):
    try:
        int(u.replace('-',''),16) # Remove all hyphens from the string and parse what's
                                  # left as a base 16 number. Don't do anything with this
                                  # number, but throw an exception if it can't be done.

        return[8,4,4,4,12]==map(len,u.split('-')) # Split the string at each hyphen and
                                                  # get the length of each resulting
                                                  # string. If the lengths == [8,4,4,4,12],
                                                  # there are the right number of groups
                                                  # with the right lengths, so the string
                                                  # is valid.
    except:
        return 0 # The only way to get here is if the string (minus hyphens) couldn't be
                 # parsed as a base 16 int, so there are non-digit, non-ABCDEF characters
                 # and the string is invalid.

```

# Answer
> 2 votes
## Python 2, 57 bytes

Thank goodness for built-in! \- make sure to enclose strings in quotes.

```
import uuid
try:uuid.UUID(input());print 1
except:print 0

```

# Answer
> 2 votes
## Pyth, 39 bytes

```
&&!+1xzd.xi:zK\-k16ZqxKc+zK1mid36"8dinz

```

Try it here.

# Answer
> 2 votes
## Python 2, ~~93~~ ~~89~~ 85 bytes

```
lambda u:(set(u)<=set("-0123456789abcdefABCDEF"))*map(len,u.split("-"))==[8,4,4,4,12]

```

The `map()` call guarantees that the sections are of the right lengths, and the `all()` tests each character for being either a hyphen or an arbitrary-case hex digit. The generator expression is testing each character by iterating through that entire string, so it's not the most performant method, I'm afraid, but it should satisfy the test cases:

```
>>> f=lambda u:(set(u)<=set("-0123456789abcdefABCDEF"))*map(len,u.split("-"))==[8,4,4,4,12]
>>> testcases = """\
... D293DBB2-0801-4E60-9141-78EAB0E298FF
... 0FCE98AC-1326-4C79-8EBC-94908DA8B034
... 0fce98ac-1326-4c79-8ebc-94908da8b034
... 0FCE98ac-1326-4c79-8EBC-94908da8B034
... 00000000-0000-0000-0000-000000000000""".splitlines()
>>> failcases = """\
... 0GCE98AC-1326-4C79-8EBC-94908DA8B034
... 0FCE98AC 1326-4C79-8EBC-94908DA8B034
... 0FCE98AC-13264C79-8EBC-94908DA8B034
... 0FCE98AC-13264-C79-8EBC-94908DA8B034
... 0FCE98ACD-1326-4C79-8EBC-94908DA8B034
... 0FCE98AC-1326-4C79-8EBC-94908DA8B034-
... 0FCE98AC-1326-4C79-8EBC-94908DA8B034-123
... 00000000-0000-0000-000 -000000000000
... 00000000-0000-0000- 000-000000000000""".splitlines()
>>> all(f(u) for u in testcases)
True
>>> any(f(u) for u in failcases)
False
>>>

```

# Answer
> 2 votes
## Common Lisp - 161

```
(lambda(s &aux(u(remove #\- s)))(and(=(length s)36)(=(length u)32)(every(lambda(p)(char=(char s p)#\-))'(8 13 18 23))(ignore-errors(parse-integer u :radix 16))))

```

The returned value if true is the hash, as a number, which is a useful result to have.

### Ungolfed

```
(defun uuid-p (string &aux (undashed (remove #\- string)))
  (and
   ;; length of input string must be 36
   (= (length string) 36)

   ;; there are exactly 4 dashes
   (= (length undashed) 32)

   ;; We check that we find dashes where expected
   (every (lambda (position)
            (char= (char string position) #\-))
          '(8 13 18 23))

   ;; Finally, we decode the undashed string as a number in base 16,
   ;; but do not throw an exception if this is not possible.
   (ignore-errors
    (parse-integer undashed :radix 16))))

```

# Answer
> 2 votes
## F# 44 characters

```
fun s->System.Guid.TryParseExact(s,"D")|>fst

```

In F#, functions with `out` parameters can be called by omitting the out parameter; its value at return will be combined with the function's true return value into a tuple.

Here, the tuple is piped to the `fst` function, which returns its first member, which in this case is the Boolean return value of TryParseExact, indicating the success or failure of the call.

As a check for the correct format, we return `true` only if the string is 36 characters long.

Before I saw RobIII's C# answer, I had not thought of using TryParseExact, so my answer was to have been three characters longer:

```
fun s->System.Guid.TryParse s|>fst&&s.Length=36

```

`TryParse(string, Guid)` accepts input in the following formats:

```
00000000000000000000000000000000
00000000-0000-0000-0000-000000000000
{00000000-0000-0000-0000-000000000000}
(00000000-0000-0000-0000-000000000000)
{0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}

```

Of these, only the second is 36 characters long.

# Answer
> 1 votes
## SAS, ~~171~~ ~~144~~ 141

```
data;infile stdin;file stdout;input a$9b$14c$19d$24;e=(a!!b!!c!!d='----')*length(_infile_)=36*(1-missing(put(input(compress(_infile_,,'adk'),$hex32.),$hex32.)));put e;run;

```

Actually uses stdin and stdout - one of the lesser-known features of this particular language. Works for the examples given so far, but possibly not in all cases. Can probably be improved upon.

Better approach - one character at a time:

```
data;infile stdin;file stdout;do i=1 to 37;input@i c$1.@;a+ifn(i in(9,14,19,24),c='-',n(input(c,hex.))-36*(i>36&c^=''));end;b=a=36;put b;run;

```

Golfed another 6 characters off the central expression!

Ungolfed:

```
data;
infile stdin;
file stdout;
do i=1 to 37;
input@i c$1.@;
a+ifn(i in(9,14,19,24),c='-',n(input(c,hex.))-36*(i>36&c^=''));
end;
b=a=36;
put b;
run;

```

This generates quite a few warnings and notes in the log, but it doesn't print them to stdout or stderr, so I think this is fair game.

# Answer
> 1 votes
# C, 391 bytes

```
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define F printf("0")
#define T printf("1")
#define E return 0
main(){char s[99],*t;int k=1,l,i;scanf("%99[^\n]",s);if(s[strlen(s)-1]=='-'){F;E;}t=strtok(s,"-");while(t!=NULL){for(i=0,l=0;t[i]!=0;i++,l++){if(!isxdigit(t[i])){F;E;}}if((k==1&&l!=8)||((k>1&&k<5)&&l!=4)||(k==5&&l!=12)){F;E;}k++;t=strtok(NULL,"-");}if(k==6){T;E;};F;}

```

# Answer
> 1 votes
# MATLAB, 126 bytes

```
function f(a)
b='-';if length(a)==36&&a(9)==b&&a(13)==b&&a(17)==b&&a(21)==b;a(a==b)=[];if any(isnan(hex2dec(a)));0;end;1;end;0

```

# Answer
> 1 votes
## Python 3, 134 bytes

```
def a(i):
 try:l=[1+int(k,16)and(len(k)==c)for k,c in zip(i.split("-"),[8,4,4,4,12])];return(len(l)==5)&(0 not in l)
 except:return 0

```

int(k,16) tries to cast k to a base-16 int. On a character other than 0-9a-fA-F- it fails, in which case we return 0, which is falsy. Add 1 to that int and we get a guaranteed truthy value - we've stripped away all hyphens with str.split() so we can't get the value -1 and all non-0 ints are truthy.

# Answer
> 1 votes
# C function, 102

A rule change disallowed my previous c `scanf()`-based answer, so here's another c answer using `isxdigit()` which I think should be allowed to compete:

```
i;f(char *s){for(i=8;i<24;i+=5)s[i]=s[i]-45?1:s[i]+3;for(i=0;isxdigit(s[i]);i++);return i==36&&!s[i];}

```

Try it online.

* Check for `-` characters (ASCII 45) at the relevant positions - if so, replace them with `0`s (ASCII 48 (=45+3))
* Walk the string checking each char with `isxdigit()`
* Return TRUE if string length is 36 and final character is NUL.

# Answer
> 1 votes
## Batch, ~~148~~ 139 + 2 = ~~150~~ 141 bytes

```
@set/pu=
@for %%d in (1 2 3 4 5 6 7 8 9 A B C D E F)do @set u=!u:%%d=0!
@if -!u!==-00000000-0000-0000-0000-000000000000 exit/b0
@exit/b1

```

Added 2 bytes because you need to use the `/v` switch to `CMD.EXE`.

Exits with ERRORLEVEL 0 on success, 1 on failure.

Edit: Saved some bytes mainly because `:=` is case insensitive but there were other tweaks too.

# Answer
> 1 votes
## Java, 345 bytes

```
interface q{static void main(String[]a){int i=-1;char[]b=a[0].toCharArray();java.io.PrintStream u=System.out;if(b.length>36||b.length<36)u.print(1<0);if(b[8]!='-'||b[13]!='-'||b[18]!='-'||b[23]!='-')u.print(1<0);while(++i<b.length){if(i!=8&&i!=13&&i!=18&&i!=23){if(!((b[i]>='0'&&b[i]<='F')||(b[i]>='a'&&b[i]<='f')))u.print(1<0);}}u.print(1>0);}}

```

Input is first command line argument. Output is error code(0 means valid UUID, 1 means not valid)

Ungolfed with comments:

```
interface q {
    static void main(String[] a) {
        int i = -1;                                                             // Index
        char[] b = a[0].toCharArray();                                          // Characters from input
        java.io.PrintStream u = System.out;                                     // STDOUT
        if (b.length > 36||b.length < 36)                                       // If input length is not 36
            u.print(1<0);                                                       // Invalid
        if (b[8]!='-'||b[13]!='-'||b[18]!='-'||b[23]!='-')                      // If hasn't got separators at correct positions
            u.print(1<0);                                                       // Invalid
        while (++i<b.length) {                                                  // Iterate over all characters
            if (i!=8 && i!=13 & i!=18 && i!=23) {                               // If not at separator indexes
                if ( !( (b[i]>='0'&&b[i]<='F') || (b[i]>='a'&&b[i]<='f') ))     // If incorrect hexadecimal number
                    u.print(1<0);                                               // Invalid
            }
        }
        u.print(1>0);                                                           // Valid
    }
}

```

EDIT: Didn't notice the STDOUT part. Oops, fixed now.

# Answer
> 1 votes
# PHP, 109 Bytes

prints 1 for true and 0 for false

```
for($t=($l=strlen($a=$argn))==36;$i<$l;$i++)$t*=$i>7&$i<24&!($i%5-3)?$a[$i]=="-":ctype_xdigit($a[$i]);echo$t;

```

`$i>7&$i<24&!($i%5-3)` is 5 Bytes shorter then `in_array($i,[8,13,18,23])`

112 Bytes

```
echo array_filter(str_split($argn),function($i){return!ctype_xdigit($i);})==[8=>"-",13=>"-",18=>"-",23=>"-"]?:0;

```

113 Bytes

```
echo array_diff(str_split(strtolower($argn)),array_map(dechex,range(0,15)))==[8=>"-",13=>"-",18=>"-",23=>"-"]?:0;

```

# Answer
> 1 votes
# Swift 3, 50 bytes

Pass in a string `s`

```
import Foundation
print(UUID(uuidString:s) != nil)

```

# Answer
> 1 votes
# Vyxal, 167 bits<sup>v2</sup>, 20.875 bytes

```
ɽ\-€:@»S₌»f4*⁼ßk6vF¤J≈

```

Try it Online!

Bitstring:

```
00100110000000110100100100111101001111011101001010000101101010001100111010011110101100110110111011000100010111110110101000111001111000100010111010111000111011100101010

```

```
ɽ\-€:@»S₌»f4*⁼ßk6vF¤J≈
ɽ\-€:                   # to lowercase, split on "-" and push two copies to the stack
     @       ⁼          # does the vectorized length equal
      »S₌»              # the compressed number 21113
          f4*           # as a list of digits each multiplied by 4
              ßk6vF     # if so, remove all of the characters that are in the string "0123456789abcdef"
# This is NOT regex, vyxal has regex elements
                   ¤J≈  # append an empty string and check if all elements are equal

```

Created with the help of Luminespire.

# Answer
> 0 votes
## Java, ~~172 bytes~~ 168 bytes (Thanks Wheat Wizard)

Kinda cheaty since I used java.util.UUID, but here goes:

```
import java.util.UUID;class ValidUUID{public static void main(String[] a){try{UUID.fromString(a[0]);System.out.println(1);}catch(Exception e){System.out.println(0);}}}

```

Ungolfed version:

```
import java.util.UUID;

class ValidUUID {

    public static void main(String[] a) {
        try {
            UUID.fromString(a[0]);
            System.out.println(1);
        } catch(Exception e) {System.out.println(0);}
    }
}

```

# Answer
> 0 votes
## AWK, 98 bytes

```
BEGIN{FS=""}{for(j=4;k<NF;){h+=(j+=5)<25?$j=="-":0
s+=strtonum("0x"$++k 1)>0}$0=h+s==36&&NF==36}1

```

Simply splits the line at every character and checks if each character is a hex digit and that there are hyphens at the appropriate places. `strtonum` converts invalid characters to `0`. Making the comparison between `0` and `m` (and arbitrarily chosen invalid character) require additional steps. Luckily `01` is a valid hex number, but `m1` is not.

Initially I wrote two `for` loops, but I saved 1 byte by squeezing them together. :)

NOTE: `GAWK` can read input as hex numbers, but this requires a very long command line option.

# Answer
> 0 votes
# Python 2, 41 bytes

```
from uuid import*;lambda a:UUID(a).hex==a

```

Python has a builtin module for handling UUIDs.

---
Tags: code-golf, string, restricted-source
---