title: Sort odd numbers first

text:
# Question
Title: Sort odd numbers first
Rearrange a given list such that all the odd numbers appear before all the even numbers. Besides for this requirement, the output list may be in any order.

The input will only contain integers, but they may be negative and there may be duplicates, and they may appear in any order.

Shortest solution wins.

### Test cases

`[1,2]``[1,2]`

`[2,1]``[1,2]`

`[1,0,0]``[1,0,0]`

`[0,0,-1]``[-1,0,0]`

`[3,4,3]``[3,3,4]`

`[-4,3,3]``[3,3,-4]`

`[2,2,2,3]``[3,2,2,2]`

`[3,2,2,2,1,2]``[1,3,2,2,2,2]` or `[3,1,2,2,2,2]`

`[-2,-2,-2,-1,-2,-3]``[-1,-3,-2,-2,-2,-2,]` or `[-3,-1,-2,-2,-2,-2,]`

`[]``[]`

# Answer
# 05AB1E, 2 bytes

```
ΣÉ

```

Try it online!
> 12 votes

# Answer
# Pyth, ~~4~~ 3 bytes

-1 byte thanks to isaacg

```
iD2

```

Try it online!

crossed out 4 is still regular 4
> 10 votes

# Answer
# C++, ~~79~~ ~~76~~ 64 bytes

```
[](auto a,auto b){while(a<--b)*a%2?*++a:(*a^=*b,*b^=*a,*a^=*b);}

```

This function accepts a pair of iterators (which must be random access iterators), and steadily moves them towards each other. When `a` points to an odd number, it is advanced. Otherwise, `a` points to an even number; `b` is decremented, and `iter_swap`'ed with `a`. (We use XOR swap, which saves us having to include `<algorithm>` \- or `<utility>` for `std::swap`).

There are unnecessary swaps when `b` points to an even number, but we're golfing, not squeezing efficiency!

## Demo

```
auto f=[](auto a,auto b){while(a<--b)*a%2?*++a:(*a^=*b,*b^=*a,*a^=*b);};

#include <array>
#include <iostream>
int main()
{
    auto a = std::array{ 3,2,2,5,2,1,2 };

    f(a.begin(),a.end());

    for (auto i: a)
        std::cout << i << " ";
    std::cout << std::endl;
}

```

---

## Non-competitive answer

The natural C++ method is `std::partition`, but that comes out at **83** bytes:

```
#include<algorithm>
[](auto a,auto b){std::partition(a,b,[](auto x){return x&1;});}

```
> 10 votes

# Answer
# , ~~30~~ 24 bytes

```
(x=scan())[order(!x%%2)]

```

Try it online!

*-6 bytes thanks to JayCe*
> 9 votes

# Answer
# , 5 bytes

```
\:2&|

```

Try it online!

`\:` sort descending by

`2&|` mod-2
> 8 votes

# Answer
# Japt, 2 bytes

```
ñv

```

Try it online!
> 8 votes

# Answer
# Perl 6, 12 bytes

```
*.sort(*%%2)

```

Try it online!

Some Whatever code that sorts the input by parity, with odd numbers first. You can remove a `%` to get even numbers first instead. Note that 'Whatever' is the name of this sort of anonymous function.
> 7 votes

# Answer
# Haskell, ~~23~~ 22 bytes

```
f odd<>f even
f=filter

```

Try it online! This is equivalent to

```
g x = filter odd x ++ filter even x

```

*-1 byte thanks to Lynn*

---

Other approaches:

```
(<>).($odd)<*>($even)$filter
import Data.List;sortOn even
g x=[i|m<-[0,1],i<-x,odd$m+i]
g x=[i|m<-[1,0],i<-x,mod i 2==m]
g x=id=<<filter<$>[odd,even]<*>[x]

```
> 6 votes

# Answer
# MATL, 6 bytes

```
tog&)v

```

Try it on MATL Online

Alternately:

```
to_2$S

```

Try it on MATL Online
> 6 votes

# Answer
# Python 2, ~~37~~ 36 bytes

```
lambda a:sorted(a,key=lambda x:~x%2)

```

Try it online!

1 byte tip o' the hat to Mr. Xcoder.
> 5 votes

# Answer
# JavaScript (Node.js), 29 bytes

```
a=>a.sort((a,b)=>(b&1)-(a&1))

```

Try it online! Save 4 bytes by only supporting positive values using `b%2-a%2`. If you write this as:

```
function(a){return a.sort((a,b)=>(b&1)-(a&1))}

```

then it will work on all sorts of old JavaScript implementations that didn't sort stably.
> 5 votes

# Answer
# Stax, 5 bytes

```
{|eom

```

Run and debug it

Explanation:

```
{|eom Full program, implicit input
{  o  Sort by key:
 |e     Is odd?
    m Map over result:
        Implicit output with newline

```
> 5 votes

# Answer
# PHP, 55 bytes

~14 months later and I'm a little bit better at golfing now:

```
for(;''<$n=$argv[++$i];$s=$n%2?"$n $s":"$s $n");echo$s;

```

Try it online!

---

# PHP (\>=5.4), ~~84~~ 82 bytes

(-2 bytes, thanks to Ismael Miguel)

```
<?array_shift($a=&$argv);usort($a,function($i){return$i%2==0;});echo join(' ',$a);

```

To run it:

```
php -n <filename> <number_1> <number_2> ... <number_n>

```

Example:

```
php -n sort_odds_first.php 2 0 1 -1 3 8 29 -666

```

Or Try it online!
> 5 votes

# Answer
# Attache, 11 bytes

```
SortBy!Even

```

Try it online!

## Explanation

`Even` returns `true` for even numbers and `false` otherwise. `SortBy` ranks `false < true` (by a numerical cast to `0 < 1`), thus placing odd numbers before even ones.
> 5 votes

# Answer
# T-SQL, 26 bytes

```
SELECT*FROM t ORDER BY~i&1

```

Uses the bitwise AND operator "&" to compare the last digit with 1.

EDIT: Bitwise NOT then shorter than adding 1. EDIT2: Reorder to allow removal of the space.
> 5 votes

# Answer
# Jelly, 3 bytes

```
ḂÞṚ

```

**Try it online!**

One of the more oft-wanted atoms seems to be an is-even one (which would make this 2 bytes), without it we must reverse I believe...

```
ḂÞṚ - Link: list of integers
 Þ  - sort by:
Ḃ   -   bit (least significant bit - i.e. 1 if odd 0 if even)
  Ṛ - reverse

```
> 4 votes

# Answer
**JavaScript, ~~22~~ 20 bytes**

`a=>a.sort(a=>!(a%2))`

Try it online!
> 4 votes

# Answer
# Python, 35 bytes

```
lambda l:sorted(l,key=(-1).__pow__)

```

Try it online!

Sorts by the function `x -> (-1)**x`, which gives `-1` for odd and `1` for even.
> 4 votes

# Answer
# Prolog (SWI), 50 bytes

```
A+S:-predsort([X,Y,Z]>>(Y/\1>Z/\1,X= <;X= >),A,S).

```

Try it online!

-8 thanks to Jo King
> 4 votes

# Answer
# Red, 42 bytes

```
func[a][sort/compare a func[n][n % 2 = 1]]

```

Try it online!

If we need to account for negative values:

# Red, 43 bytes

```
func[a][sort/compare a func[n][n // 2 = 1]]

```

Try it online!
> 3 votes

# Answer
# Husk, 4 bytes

```
↔Ö%2

```

Try it online!

**Explanation**

```
 Ö     sort input according to the result of the following function
  %2   modulo 2
↔      reverse result to get odd numbers to the front

```
> 3 votes

# Answer
# Scala, 18 bytes

```
_.sortBy(_.+(1)%2)

```
> 3 votes

# Answer
# Ruby, 23 bytes

```
->a{a.sort_by{|i|~i%2}}

```

Try it online!

Explanation:

`sort_by` sorts every number as if its value were the result of the block (`~i%2`)

`~x` is equivalent to `-x-1` and takes precedence over `%2`

Odd numbers will evaluate to `0` and even numbers will evaluate to `1` so odd numbers will be sorted first.

### Barely related: this works on ruby from homebrew 2.5.1p57 (because it's based on a small bug) but only for non-negative integers, 20 bytes

```
->a{a.sort{|i|i%-2}}

```

Explanation:

This uses `sort` which expects a block that takes 2 values and returns `-1`, `0` or `1` depending on whether the first one is bigger, they're equal or the second one is bigger.

The block given here ignores the second value and returns `-1` if the first number is odd or `0` if it's even.

It's not guaranteed to work but it does in some (I think buggy) implementations.
> 3 votes

# Answer
# PowerShell, ~~22~~ 19 bytes

```
$args|sort{!($_%2)}

```

Try it online!

Takes input via splatting, e.g., `$a=(3,4,3); .\sort-odd-numbers-first.ps1 @a`, which on TIO manifests as separate arguments for each entry.

Like some other answers here, `Sort-Object` can compare based on an expression. Here the expression is `!($_%2)`, i.e., odds get sorted to `$false` and evens get sorted to `$true`. Thanks to how Boolean values are compared, falsey values are sorted first. This moves the odds to the beginning of the output, and the evens to the end. `Sort-Object` is stable, so the ordering of the individual items in their respective categories doesn't change (as in the TIO example).

*-3 bytes thanks to mazzy.*
> 3 votes

# Answer
# JavaScript (Chrome v67) - ~~24~~ ~~19~~ 23 bytes

```
a=>a.sort(a=>!(a&1)-.5)

```

The use of `&1` rather than `Math.abs()%2` was stolen from @Neil. Thanks!

Thanks to @Shaggy for showing my hacky 19 byte solution wasn't valid. If anyone wants it:

 ~~Depends on how the browser handles a hacky return value of `0`. Chrome v67, after 100000 iterations of random arrays never sorted it wrong. I'm very sure it works -- and it relies on the specific sort algorithm Chrome uses too, I believe. (It might work in other browsers, that's not the point)~~

~~`a=>a.sort(a=>++a&1)`~~
> 3 votes

# Answer
# C#, 23 bytes

```
i=>i.OrderBy(u=>u%2==0)

```

Quite straigt forward really: This basically converts the numbers to booleans, whilst `true` means that the number is even and `false` that it's odd. Because `true` is higher than `false` the even numbers appear first.

The formatted version looks like that:

```
i => i.OrderBy (u => u % 2 == 0)

```

And you can test it like that:

```
Console.WriteLine (string.Join (",", new Func <IEnumerable <int>, IEnumerable <int>> (
                                    i => i.OrderBy (u => u % 2 == 0)
                                ).Invoke (new [] {3, 2, 2, 2, 1, 2, 5, 5})));

```

Which results in the following:

```
3,1,5,5,2,2,2,2

```
> 3 votes

# Answer
# JavaScript, 23 bytes

6 bytes shorter than @Neil's answer using the same language :D

```
a=>a.sort(n=>-(n&1)||1)

```

**Explanation:**

The function passed to `sort` only cares about the first parameter. If it is odd it returns `-1` (the result of `-(n&1)`). Otherwise (when `-(n&1)` yields `0`) it returns `1`.

Try it online!
> 3 votes

# Answer
# JavaScript, 21 bytes

```
a=>a.sort(n=>(-1)**n)

```

Try it online
> 3 votes

# Answer
# 6502 machine code routine, 47 bytes

```
A0 00 84 FE B1 FB 4A 90 07 C8 C4 FD F0 20 D0 F4 2A 85 02 84 FE A4 FD 88 C4 FE
F0 12 B1 FB 4A 90 F6 2A AA A5 02 91 FB A4 FE 8A 91 FB 90 D6 60

```

Expects a pointer to an array of numbers in `$fb`/`$fc` and the length of this array in `$fd`. Manipulates the array in place to have all odd numbers in front. This is position independent code, so no load address is needed.

As the 6502 is an 8bit chip (so the instructions only deal with 8bit values, optionally signed), the valid number range is `[-128 .. 127]` and the maximum array size is `256`.

### Commented disassembly

```
; function to "partially sort" array, so all odd numbers come before all
; even numbers.
;
; input:
;   $fb/$fc: address of array to sort
;   $fd:     length of array to sort, 0 means 256 (maximum size)
;
; clobbers:
;   $fd/$fe: position from back/front of array
;   $2:      temporary for exchanging two values
;   A, X, Y

 .oddfirst:
A0 00       LDY #$00            ; initialize index from front
84 FE       STY $FE             ; to 0

 .search_front:
B1 FB       LDA ($FB),Y         ; load number from front
4A          LSR A               ; check for even/odd by shifting
90 07       BCC .search_back    ; if odd -> to searching from back
C8          INY                 ; next position from front
C4 FD       CPY $FD             ; same as position searching from back?
F0 20       BEQ .done           ; then we're finished
D0 F4       BNE .search_front   ; else check next from front
 .search_back:
2A          ROL A               ; shift carry back in
85 02       STA $02             ; and save number to temp
84 FE       STY $FE             ; save index from front
A4 FD       LDY $FD             ; load index from back
 .sb_loop:
88          DEY                 ; previous position from back
C4 FE       CPY $FE             ; same as position searching from front?
F0 12       BEQ .done           ; then we're finished
B1 FB       LDA ($FB),Y         ; load number from back
4A          LSR A               ; check for even/odd by shifting
90 F6       BCC .sb_loop        ; if odd -> check previous position
2A          ROL A               ; shift carry back in
AA          TAX                 ; remember in X
A5 02       LDA $02             ; load temporary from front
91 FB       STA ($FB),Y         ; store at current position
A4 FE       LDY $FE             ; load index from front
8A          TXA                 ; load remembered number
91 FB       STA ($FB),Y         ; store at current position
90 D6       BCC .search_front   ; and back to searching from front
 .done:
60          RTS

```

---

### Example C64 assembler program using the routine:

**Online demo**

**Code in ca65 syntax:**

```
.import oddfirst ; link with routine above

.segment "BHDR" ; BASIC header
                .word   $0801           ; load address
                .word   $080b           ; pointer next BASIC line
                .word   2018            ; line number
                .byte   $9e             ; BASIC token "SYS"
                .byte   "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes

.bss
linebuf:        .res    5               ; maximum length of a valid signed
                                        ; 8-bit number input
convbuf:        .res    3               ; 3 BCD digits for signed 8-bit
                                        ; number conversion
numbers:        .res    $100            ; maximum array size that can be
                                        ; directly handled with indexing
                                        ; instructions

.data
prompt:         .byte   "> ", $0
message:        .byte   $d, $d, "Enter one number per line.", $d
                .byte   "just press enter (empty line) when done.", $0
errmsg:         .byte   "Error parsing number, try again.", $d, $0

.code
                lda     #$17            ; set upper/lower mode
                sta     $d018

                lda     #0
                sta     $2a             ; index for number array
                sta     $52             ; flag that at least one number was
                                        ; entered

                lda     #<message       ; display message
                ldy     #>message
                jsr     $ab1e

inputloop:
                lda     #<prompt        ; display prompt
                ldy     #>prompt
                jsr     $ab1e

                lda     #<linebuf       ; read string into buffer
                ldy     #>linebuf
                ldx     #5
                jsr     readline

                lda     linebuf         ; empty line?
                beq     process         ; -> start processing

                lda     #<linebuf       ; convert input to int8
                ldy     #>linebuf
                jsr     toint8
                bcc     numok           ; successful -> store number
                lda     #<errmsg        ; else show error message and repeat
                ldy     #>errmsg
                jsr     $ab1e
                bcs     inputloop

numok:          ldx     #$ff            ; set flag that we have a number
                stx     $52
                ldx     $2a
                sta     numbers,x
                inc     $2a             ; next index
                bne     inputloop       ; if array not full, next input

process:        lda     $52             ; check we have some numbers
                beq     exit            ; otherwise exit program

                lda     #<numbers       ; address of array to $fb/fc
                sta     $fb
                lda     #>numbers
                sta     $fc
                lda     $2a             ; length of array to $fd
                sta     $fd
                jsr     oddfirst        ; call "sorting" function

                lda     #$0             ; index variable for output loop
                sta     $52
outloop:        ldy     $52             ; load current index
                lda     numbers,y       ; load current number
                jsr     printnum        ; -> output
                inc     $52             ; next index
                lda     $52             ; compare with ...
                cmp     $2a             ; ... array size
                bne     outloop         ; not reached yet -> repeat

exit:           rts                     ; done, exit program

; read a line of input from keyboard, terminate it with 0
; expects pointer to input buffer in A/Y, buffer length in X
.proc readline
                dex
                stx     $fb
                sta     $fc
                sty     $fd
                ldy     #$0
                sty     $cc             ; enable cursor blinking
                sty     $fe             ; temporary for loop variable
getkey:         jsr     $f142           ; get character from keyboard
                beq     getkey
                sta     $2              ; save to temporary
                and     #$7f
                cmp     #$20            ; check for control character
                bcs     checkout        ; no -> check buffer size
                cmp     #$d             ; was it enter/return?
                beq     prepout         ; -> normal flow
                cmp     #$14            ; was it backspace/delete?
                bne     getkey          ; if not, get next char
                lda     $fe             ; check current index
                beq     getkey          ; zero -> backspace not possible
                bne     prepout         ; skip checking buffer size for bs
checkout:       lda     $fe             ; buffer index
                cmp     $fb             ; check against buffer size
                beq     getkey          ; if it would overflow, loop again
prepout:        sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
output:         lda     $2              ; load character
                jsr     $e716           ;   and output
                ldx     $cf             ; check cursor phase
                beq     store           ; invisible -> to store
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and show
                ora     #$80            ;   cursor in
                sta     ($d1),y         ;   current row
                lda     $2              ; load character
store:          cli                     ; enable interrupts
                cmp     #$14            ; was it backspace/delete?
                beq     backspace       ; to backspace handling code
                cmp     #$d             ; was it enter/return?
                beq     done            ; then we're done.
                ldy     $fe             ; load buffer index
                sta     ($fc),y         ; store character in buffer
                iny                     ; advance buffer index
                sty     $fe
                bne     getkey          ; not zero -> ok
done:           lda     #$0             ; terminate string in buffer with zero
                ldy     $fe             ; get buffer index
                sta     ($fc),y         ; store terminator in buffer
                sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
                inc     $cc             ; disable cursor blinking
                cli                     ; enable interrupts
                rts                     ; return
backspace:      dec     $fe             ; decrement buffer index
                bcs     getkey          ; and get next key
.endproc

; print an int8 number to the screen
; input:
;   A - the number to print
; clobbers:
;   X, Y
.proc printnum
                bpl     doprint         ; positive? -> direct number output
                eor     #$ff            ; else invert,
                sta     $2              ; ...
                inc     $2              ; add one,
                lda     #'-'            ; output a minus sign
                jsr     $e716
                lda     $2
doprint:        tax                     ; number to X reg
                lda     #$0             ; set A to 0
                jsr     $bdcd           ; routine for uint16 in X/A output
                lda     #' '
                jmp     $e716           ; and print a space
.endproc

; parse / convert int8 number using a BCD representation and double-dabble,
; handle negative numbers.
.proc toint8
                sta     $fb
                sty     $fc
                ldy     #$0
                sty     $fd
                sty     $fe
                sty     convbuf
                sty     convbuf+1
                sty     convbuf+2
scanloop:       lda     ($fb),y
                beq     copy
                iny
                cmp     #$20
                beq     scanloop
                cmp     #$2d
                beq     minus
                cmp     #$30
                bcc     error
                cmp     #$3a
                bcs     error
                inc     $fd
                bcc     scanloop
minus:          lda     $fd
                bne     error
                lda     $fe
                bne     error
                inc     $fe
                bne     scanloop
error:          sec
                rts
copy:           dey
                bmi     error
                ldx     #$2
copyloop:       lda     ($fb),y
                cmp     #$30
                bcc     copynext
                cmp     #$3a
                bcs     copynext
                sec
                sbc     #$30
                sta     convbuf,x
                dex
copynext:       dey
                bpl     copyloop
                lda     #$0
                sta     $fb
                ldx     #$8
loop:           lsr     convbuf
                lda     convbuf+1
                bcc     skipbit1
                ora     #$10
skipbit1:       lsr     a
                sta     convbuf+1
                lda     convbuf+2
                bcc     skipbit2
                ora     #$10
skipbit2:       lsr     a
                sta     convbuf+2
                ror     $fb
                dex
                beq     done
                lda     convbuf
                cmp     #$8
                bmi     nosub1
                sbc     #$3
                sta     convbuf
nosub1:         lda     convbuf+1
                cmp     #$8
                bmi     nosub2
                sbc     #$3
                sta     convbuf+1
nosub2:         lda     convbuf+2
                cmp     #$8
                bmi     loop
                sbc     #$3
                sta     convbuf+2
                bcs     loop
done:           lda     $fe
                beq     positive
                lda     #$ff
                eor     $fb
                sta     $fb
                inc     $fb
positive:       lda     $fb
                clc
                rts
.endproc

```
> 3 votes

# Answer
# APL (Dyalog Extended), 9 bytes

-7 thanks to @rak1507.

```
{⍵[⍒2|⍵]}

```

Explanation:

```
{⍵[⍒2|⍵]}
    2|⍵      ⍝ ⍵ mod 2, return 1 for each odd element and 0 for each even element
   ⍒         ⍝ pick the indices that produce the array sorted in descending order
  [    ]     ⍝ pick elements corresponding to indices in provided order...
 ⍵           ⍝ from ⍵

```

For example:

```
2|6 7 8 9        => 0 1 0 1
⍒0 1 0 1         => 2 4 1 3
6 7 8 9[2 4 1 3] => 7 9 6 8

```

Try it online!
> 3 votes

# Answer
# C (gcc), 71 49 48 bytes

Many thanks to the commenters for the suggestions. Apparently gcc is happy with just a partial ordering of {equal, greater than} for `qsort` (just to check, clang seems to be happy with this as well.) Although I'm not happy with hardcoding type sizes, it does reduce 7 bytes from `sizeof b`: change `4` to `8` for systems with a 64-bit `int`.

```
q(int*a){a=1-*a&1;}f(a,b)int*a;{qsort(a,b,4,q);}

```

Try it online!

Alternative version using two passes through the array (79 bytes):

```
i,j;f(a,b)int*a;{for(i=2;~--i;)for(j=b;~--j;)!(a[j]%2)-i&&printf("%d\t",a[j]);}

```

Try it online!
> 2 votes

# Answer
# Elixir, ~~37~~ 35 bytes

Code:

```
fn x->Enum.sort_by x,&(-rem&1,2)end

```

Expanded version:

```
fn x -> Enum.sort_by(x, fn y -> -rem(y, 2) end) end

```

Try it online!
> 2 votes

# Answer
# Java 8, ~~46~~ ~~29~~ 27 bytes

```
l->l.sort((i,j)->1-(i&1)*2)

```

Uses Java 8's `List.sort()`, thanks to JollyJoker for making me aware of it and for saving me 19 bytes. Try it online here.

Ungolfed:

```
l -> // lambda taking a List of Integers and modifying it
        l.sort( // sort the List according to ...
        (i, j) ->                // ... a Comparator<Integer> with a compare() method ...
                 1 - (i & 1) * 2 // ... that finds a number smaller than another if it's odd, and greater otherwise

```
> 2 votes

# Answer
# C++, ~~174~~ ~~165~~ ~~164~~ ~~149~~ 129 bytes

* Replace the two include lines with a single include, regex, that happens to include both required headers

```
#include <regex>
int main(int c,char**v){std::sort(v+1,v+c,[](auto s,auto t){return atoi(s)%2>atoi(t)%2;});for(;*++v;)puts(*v);}

```

## 149 Bytes

* For loop trick for printing. This uses the fact that, on Linux at least, the argv array is null-terminated.
* replace `&1` with `%2` to remove need for some brackets. Thank you Toby Speight!

```
#include<algorithm>
#include<cstdio>
int main(int c,char**v){std::sort(v+1,v+c,[](auto s,auto t){return atoi(s)%2>atoi(t)%2;});for(;*++v;)puts(*v);}

```

## Older: 164 bytes

```
#include<algorithm>
#include<cstdio>
int main(int c,char**v){std::sort(v+1,v+c,[](auto s,auto t){return(atoi(s)&1)>(atoi(t)&1);});for(auto i=1;i<c;i++)puts(v[i]);}

```

Compile as C++14 or higher. Input is taken on the command line, and prints to standard output.

EDIT: removed un-needed `return 0;` statement

EDIT 2: Removed space after 'return'
> 2 votes

# Answer
# Clojure - 35 bytes

```
(defn o[c](sort(fn[p _](odd? p))c))

```

Ungolfed:

```
(defn oddsort [col]
  (sort (fn [p _] (odd? p)) col))

```
> 2 votes

# Answer
# Retina 0.8.2, 21 bytes

```
O$`.*(([02468])|.)
$2

```

Try it online! Link includes header that splits on commas for convenience. Explanation: The last digit of the number is captured if it is even, otherwise it is just matched (this avoids degenerate matches). The `$` option then uses the matched digit as the sort key. Odd numbers don't match and end up with an empty sort key, causing them to be sorted first (in their original order), then the even numbers are sorted in order of last digit.
> 2 votes

# Answer
# T-SQL, 33 bytes

```
SELECT*FROM t ORDER BY 1-ABS(i)%2

```

Per our IO standards, input is taken via pre-existing table **t** with integer column **i**.

The `ABS()` function is annoyingly necessary here because the T-SQL modulus operator `%` returns negative values for negative numbers, which in this case meant I was getting *three* possible results for `i%2`: -1, 0, and 1.

Subtracting from 1 is a couple bytes shorter than using `DESC`.

Note that per the question, I'm not doing any secondary sort, so the order of the odds and evens isn't predictable. If you want a secondary sort, add 2 bytes by adding `,i` to the end.
> 2 votes

# Answer
# sed 4.2.2, ~~51~~ 43 bytes

Includes +1 for `-r`

-8 Thanks to Toby Speight

```
:
s/([^,]*[02468]),([^,]*[13579])/\2,\1/
t

```

Try it online!
> 2 votes

# Answer
# Python 2, 34 bytes

```
lambda a:sorted(a,lambda x,y:x%-2)

```

Try it online!

This seems to work, but I don't actually understand why it works. If anyone can explain why my half-witted compare function (It returns -1 if the first argument is odd and 0 if the first argument is even, and that's it) works, I'd greatly appreciate it.
> 2 votes

# Answer
# \>\<\>, 40 bytes

```
l\ /nao01.
:<}\?%2:$-1/?(1
l0=?;naof2.\~

```

Try it online!

```
Filter through the list, printing odd numbers, keeping even numbers
l                  Get the length of the stack, use it as an iterator
:          /?(1    Check that there is at least one value left to process
        $-1        Decrement the iterator
    \?%2           Test if the next number is divisible by two
    /nao           Print it if so,
   }               Else, move it to the bottom of the stack
            ~      Delete the iterator after exiting the loop

Print the even numbers left on the stack
l0=?               If there are no values left on the stack,
    ;              Terminate
     nao           Print the next value

```
> 2 votes

# Answer
# Clojure, 18 bytes

```
#(sort-by even? %)

```

Try it online!
> 2 votes

# Answer
# Haskell, 44 bytes

Not as byte efficient as Laikoni's answer, but a different approach.

```
import Data.List
f=uncurry(++).partition odd

```

Try it online!

Using a sort instead, 47 bytes.

```
import Data.List
f=sortBy((.even).compare.even)

```

Try it online!
> 2 votes

# Answer
# \>\<\>, 25 bytes

```
l/!?:-1$v?%2:{~
$/<+2oan<

```

Try it online!

Input is via the `-v` flag. Ends with an error.

### Explanation:

```
l\            ~  Push length of stack as the counter
 \<

         ?%2:{   Pull a number from the bottom of the stack and check if it is odd

 /   -1$v  If even, subtract one from the counter
 /<+2oan<  If odd, print the number and a newline and add two to the counter

 /!?:      If the counter is 0, go down
$/+2oan<   Print the even number anyway, and set the counter to 2

```

For a non-erroring version, you can replace the last `~` on the first line with `;?=1`
> 2 votes

# Answer
# Go, 105 bytes

```
import."sort"
func f(I[]int)[]int{Slice(I,func(i,j int)bool{k:=I[i]
if k<0{k=-k}
return k%2>0})
return I}

```

Attempt This Online!
> 2 votes

# Answer
## Perl 5 with `-M5.010` \+ `-MList::MoreUtils+(sort_by)`, 21 bytes

```
sub{sort_by{$_%-2}@_}

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica),  ~~15~~  12 bytes

```
SortBy@EvenQ

```

Try it online!

(saved three bytes thanks to JungHwan Min)

---

Previous version:

```
#~SortBy~EvenQ&

```

Try it online!
> 1 votes

# Answer
# Awk: 50 bytes

```
{and($1,1)?(o=o $1 RS):(e=e $1 RS)}END{print o e}

```

Input on stdin, Output on stdout

I use RS, the record separator, as a stand-in for "\n", saving two characters each time.
> 1 votes

# Answer
# Ruby, ~~19~~ 20 bytes

Works on `ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]` from Arch Linux repos.

```
->a{a.sort{|i|~i%2}}

```
> 1 votes

# Answer
# Pyke, 4 bytes

```
.#t1.&

```

Try it here!

```
.#t1.& - sorted(input, key=lambda i: ↓)
  t    -   i-1
   1.& -  ↑ & 1

```

4 byte hexdump:

```
A3 74 31 A6

```

Try it here!
> 1 votes

# Answer
# Rust, 38 bytes

```
|l:&mut Vec<_>|l.sort_by_key(|e|1^e&1)

```

Try It Online
> 1 votes

# Answer
# Swift 4, 40 bytes

```
print(n.filter{$0%2>0}+n.filter{$0%2<1})

```

Try it online!

`n` is the input array

print will be like: `[1, 3, 2, 2, 2]`
> 1 votes

# Answer
# Mathematica 25 bytes

```
Flatten@GatherBy[#, OddQ] &

```
> 1 votes

# Answer
# Chip `-z`, 44 bytes

```
V z.
>~#<
|at|Bb
|A-}]~S
>vvv+Cc
DEFGH
defgh

```

Try it online!

Chip works in bytes, so this expects a sequence of byte-width values on stdin. I use `0x00` as a special delimiter, so that can't be one of the values. (This could be modified to use a different delimiter, at the expense of code size).

The TIO link above uses ASCII `"123456789"` as the input, corresponding to values `0x31`, `0x32`, `0x33`, ..., `0x39`.

This solution reads though the input twice (it knows it hit the end when it sees the `0x00` mentioned earlier, which is tacked onto the end by the flag `-z`). On the first pass, it prints the odd values, on the second the evens. It actually starts a third pass, but the termination logic kicks in before it does anything else.

Let's look at a rough overview of the code (Chip is 2D, so regions are described, each line on its own would do nothing useful):

```
           The V is a bookmarker of sorts. The mark is set at the start of a
V z.       pass, and then recalled when the input is exhausted. This does the
>~#<       looping (as opposed to using a stack or queue to hold the data).
|at|Bb     The # is a half-adder, it increments on each pass. When it
>A-}]~S    carries, the t is triggered, terminating the program. The S
>vvv+Cc    suppresses the values we don't want to print on this pass.
DEFGH      The remaining A-H letter pairs are a cat program, smooshed around
defgh      so that the input elements (capital letters) can do double duty,
           for things like detecting oddness, and the end of input.

```
> 1 votes

# Answer
# Lua, ~~142~~ 134 bytes

```
loadstring'p={...}n={}for i=1,#p*2 do n[#n+1]=i<=#p and p[i]%2==1 and p[i]or i>#p and p[i-#p]%2==0 and p[i-#p]or n[#n+1] end return n'

```

Try it online!
> 1 votes

# Answer
# , 8 bytes

```
{x@>2!x}

```

Try it online! Loosely based off of the J answer.

```
{      } /function
    2!x  /  modulo 2 (mapped through list)
   >     /  get indices to sort descending
 x@      /  return the original list at those indices

```
> 1 votes

# Answer
# Julia 1.0, 27 bytes

```
f(l)=l[sortperm(l.%2 .==0)]

```

Try it online!

This works too and is a lot more elegant:

```
f(l)=sort(l,lt=(a,b)->b%2==0)

```

But it's a few bytes longer :(
> 1 votes

# Answer
# Zsh, 31 bytes

```
grep [02468]$<i
grep [13579]$<i
```

Attempt This Online!

Takes input from a file called `i`.
> 1 votes

# Answer
# Vyxal, 2 bytes

```
µ₂

```

Try it Online!

```
µ  # Sort by...
 ₂ # Even?

```
> 1 votes

# Answer
# Fig, \\$3\log\_{256}(96)\approx\\$ 2.469 bytes

```
^@E

```

See the README to see how to run this

Aww loses to fancier languages.

```
^@E # Full program
^   # Sort...
 @  # by...
  E # Is even?

```
> 1 votes

# Answer
# Thunno 2, 2 bytes

```
ÞE

```

Attempt This Online!

#### Explanation

```
ÞE  # Implicit input
Þ   # Sort by:
 E  #  Is even?
    # Implicit output

```
> 1 votes

# Answer
# sed 4.2.2, 32 bytes

```
:
s/(<(!!)*>)(<(!!)*!>)/\3\1/g
t

```

Try it online!

Input is formatted as a exclamation marks surrounded by `<>`. Output is the same.

Ex: `<><!><!!><!!!><!!!!>` =\> `<!><!!!><><!!><!!!!>`
> 1 votes

# Answer
# x86-16 machine code, 25 bytes

```
00000000: e316 8bd7 03d1 4afc aca8 0174 03aa eb06  ......J....t....
00000010: 87d7 fdaa 87d7 e2ef c3                   .........

```

**Listing**

```
E3 16       JCXZ EXIT           ; handle empty input list
8B D7       MOV  DX, DI         ; DI = output list head
03 D1       ADD  DX, CX         ; DX = output list tail (1 past)
4A          DEC  DX             ; DX = output list tail
        INLOOP:
FC          CLD                 ; string direction forward
AC          LODSB               ; get next char
A8 01       TEST AL, 1          ; is even? NZ if odd, ZF if even
74 03       JZ   EVEN
        ODD:
AA          STOSB               ; write to list head
EB 06       JMP  DONE
        EVEN:
87 D7       XCHG DX, DI         ; DI = list tail
FD          STD                 ; string direction reverse
AA          STOSB               ; write to list tail
87 D7       XCHG DX, DI         ; DI = list head
        DONE:
E2 EF       LOOP INLOOP         ; continue looping input list
        EXIT:
C3          RET                 ; return to caller

```

Callable function, input list at `DS:SI`, length in `CX`. Output list buffer at `ES:DI`.

If input number is odd, is added to the beginning of output list. If even, is added to the end of the output list.

**Test cases:**

`[1, 2]``[1, 2]`

`[0, 0, -1]``[-1, 0, 0]`

`[-1, -2, 3, -4, -5]``[-1, 3, -5, -4, -4]`

`[3, 2, 2, 2, 1, 2]``[3, 1, 2, 2, 2, 2]`
> 1 votes

# Answer
# Kotlin, 33 bytes

```
{l:List<Int>->l.sortedBy{1-it%2}}

```

Try it online!
> 0 votes

# Answer
# Swift, 22 bytes

Two different answers with the same byte count!

## In-place

```
{$0.partition{$0&1<1}}

```

Argument type is any `MutableCollection` whose element type conforms to `BinaryInteger`. Technically this returns the index where it changes from odd to even numbers, but this can be made to return `Void` with a warning: SwiftFiddle link

~~C brain keeps telling me to do `~$0&1` but Swift doesn't do int-bool conversion~~

## New array

```
{$0.sorted{$0&1>$1&1}}

```

Argument type is any `Sequence` whose element type conforms to `BinaryInteger`. Returns an array with the same element type. SwiftFiddle link
> 0 votes

# Answer
# Arturo, 22 bytes

```
$=>[arrange&=>[^0-1&]]

```

Try it!

```
$=>[             ; a function where input is assigned to &
    arrange&=>[  ; sort input by
        ^0-1&    ; -1 to the (current element) power
    ]            ; end arrange
]                ; end function

```
> 0 votes

---
Tags: code-golf, number, array, sorting
---


title: Is it a pure word?

text:
# Question
Title: Is it a pure word?
# Introduction

A pure word (or perfect word), as defined by me, is a word where the sum of the position in the alphabet of each letter in the word is perfectly divisible by the total length of the word. For example, `abcb` is a perfect word because `1 + 2 + 3 + 2 = 8`, and `8 / 4 = 2`.

# Your task

Given a word as input, output whether or not it is a perfect word. The word may always be assumed to be lowercase.

## Scoring

This is code-golf, so shortest program in bytes wins.

## Examples

```
abcb: truthy
ccc: truthy
aaa: truthy
pure: truthy
word: truthy
bed: falsy
code: falsy
bode: falsy

```

# Answer
> 19 votes
# Factor, ~~37~~ 16 bytes

```
[ mean fixnum? ]

```

Try it online!

Is the mean of the input an integer?

#### Why does this work?

Four reasons.

* Strings in Factor are just sequences of code points.
* Because the question is asking for a sum divided by a length. Otherwise known as the mean.
* The `mean` word returns a ratio, not a float. In Factor, ratios automatically reduce to simplified form, which can be an integer. We can check for divisibility after taking the mean by checking whether the result is an integer or a ratio.
* It doesn't matter whether the input ranges from 1-26 or 97-122. It doesn't change whether the mean is an integer or not.

# Answer
> 13 votes
# Python 3, 33 bytes

```
lambda s:sum(map(ord,s))%len(s)<1

```

Try it online!

# Answer
> 12 votes
# , ~~42~~ ~~39~~ 33 bytes

```
function(w)!mean(utf8ToInt(w))%%1

```

Try it online!

-6 bytes thanks to m90.

# Answer
> 11 votes
# 05AB1E, 4 bytes

```
OIgÖ

```

Try it online! Takes input as a list of codepoints.

# Answer
> 10 votes
# Jelly, 5 bytes

```
OSḍ@L

```

Try It Online!

```
OSḍ@L    Main Link
O        ord (vectorizes)
 S       sum
  ḍ@     is this divisible by
    L    the length of the input?

```

If outputting inconsistent truthy/falsy values is allowed:

# Jelly, 4 bytes

```
OSọL

```

Try It Online!

```
OSọL    Main Link
O       ord (vectorizes)
 S      sum
  ọ     how many times is this divisible by
   L    the length?

```

This works using an observation made by caird coinheringaahing in chat that you do not need to account for the offset between A = 1 and A = 65 when you take the codepoint, since the codepoint offset will be added `len(X)` times and not affect the modulo.

Yes, caird also just straight up gave the algorithm, but to be fair, the observation was the only non-trivial part about this solution anyway.

# Answer
> 7 votes
# JavaScript (ES6), 58 bytes

```
w=>!([...w].reduce((s,c)=>s+parseInt(c,36)-10,0)%w.length)

```

# Answer
> 7 votes
# Vyxal, 5 bytes

```
C∑$LḊ

```

Try It Online!

Same thing as my Jelly solution.

```
C∑$LḊ    Full Program
C        ord (vectorizes)
 ∑       sum
  $      swap; bring the string back to the top
   L     length
    Ḋ    is the ord sum divisible by the length?

```

# Answer
> 7 votes
# Excel, ~~59~~ 54 bytes

Saved 5 bytes thanks to pajonk.

```
=MOD(SUM(CODE(MID(A1,SEQUENCE(LEN(A1)),1))),LEN(A1))=0

```

Input is in cell `A1`. Output is wherever the formula is.

* `SEQUENCE(LEN(A1))` creates an array with values 1 to the word length.
* `MID(A1,SEQUENCE(~),1)` pulls out each letter from the input one at a time.
* `CODE(MID(~))` finds the ASCII code for each letter. We don't have to convert this to 1-26 because it's 1 extra 96 for ever letter of the input so divisibility will be the same.
* `SUM(CODE(~))` adds all those values.
* `MOD(SUM(~),LEN(A1))` returns 0 if it's a whole number and a decimal if it isn't. If anything, this is the opposite of what we want because `0` is falsey and other numbers are truthy, at least in Excel.
* `MOD(~)=0` returns `TRUE` or `FALSE`.

---

I found an alternative with the same byte count. It works in reverse and exploits the fact that `CODE()` only pulls the left-most character if it's given a string of greater length. I almost like it more, though, because it has 5 closing parentheses in a row.

```
=MOD(SUM(CODE(RIGHT(A1,SEQUENCE(LEN(A1))))),LEN(A1))=0

```

# Answer
> 7 votes
# Haskell, 36 bytes

```
f w=sum(fromEnum<$>w)`mod`length w<1

```

Try it online!

# Answer
> 7 votes
# Vyxal 2.4.1 `K`, ~~4~~ 3 bytes

```
ṁ1Ḋ

```

Try it Online!

Ah yes classic pre-2.6 jank ftw. *-1 thanks to Dominic*

## Explained

```
ṁ1Ḋ
      # First, the input is converted to a list of corresponding ordinal values by the `K`(eg mode) flag:
ṁ     #   push the arithmetic mean of that list
 1Ḋ   #   is that divisible by 1? (i.e is it a whole number)

```

# Answer
> 7 votes
# Python, 24 bytes

```
lambda s:sum(s)%len(s)<1
```

Attempt This Online!

Takes input as a byte string. We don't need to subtract `95` from each element, because the sum will end up having `95 * length` added on, which has no effect on the result modulo `length`.

# Answer
> 7 votes
# Java, 31 bytes

```
s->s.chars().sum()%s.length()<1

```

Try it online!

# Answer
> 7 votes
# brainfuck, 162 bytes

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

```

Try It Online!

outputs `0` for **truthy** and `1` for **falsey**

This one was a lot of fun. Not necessary golf-optimal but hey, brainfuck solution :)

## Explanation

```
; 96 algorithm from esolangs constants
; initialise tape to (1)/96/0/0/0
>+[+[>+<+<]>]+[
    ; while(getchar())
    ,[>
        [>+<<->-]
        <[>>>+<<<-]>>>>+<<[<+>-]<<+>>
        ; 0/96/(0)/cumulative/length
    ]
    <<
]

; divmod algorithm from esolangs
>>>[-]>>[<+>-]
<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]

; prepare 0 for output
>[-]+++++++>[-]<[>+++++++<-]

; if(sum%length){print 1}else{print 0}
>>[<.[-]>[-]>[-]]<[-.[-]]

```

# Answer
> 6 votes
# Julia 1.0, 25 bytes

```
!x=sum(Int,x)%length(x)<1

```

Try it online!

# Answer
> 6 votes
# JavaScript (Node.js), 37 bytes

```
s=>eval(Buffer(s).join`+`)%s.length<1

```

Try it online!

# Answer
> 6 votes
# Wolfram Mathematica, ~~34~~ 24 bytes

```
1∣Mean@LetterNumber@#&

```

-10 bytes from @att

Try it online!

# Answer
> 6 votes
# Scala, 17 bytes

```
s=>s.sum%s.size<1

```

Try it online!

# Answer
> 5 votes
# APL+WIN, ~~22~~ 16 bytes

Prompts for string

```
0=(⍴s)|+/⎕av⍳s←⎕

```

Try it online!Thanks to Dyalog Classic

# Answer
> 5 votes
# Japt, 6 bytes

Takes input as an array of characters. The `c` can be removed by instead taking input as an array of codepoints.

```
xc vUl

```

Try it

```
xc vUl     :Implicit input of array U
x          :Sum of
 c         :  Codepoints
   v       :Is divisible by
    Ul     :  Length of U

```

# Answer
> 5 votes
# , 14 bytes

```
0=#|1#.96|3&u:

```

Try it online!

*-1 thanks to south*

# Answer
> 5 votes
# Husk, ~~5~~ 4 bytes

*Edit: -1 byte thanks to Razetime*

```
¦L¹Σ

```

Try it online!

Outputs truthy (non-zero) for perfect words, falsy (zero) for non-perfect words.

# Answer
> 5 votes
# BQN, ~~16~~ ~~12~~ ~~9~~ 8 bytes

*Edit: -3 bytes thanks to ovs, and -1 byte thanks to DLosc*

```
≠|·+´@-⊢

```

Try it at BQN online REPL

Outputs nonzero (truthy) for non-perfect words, zero (falsy) for perfect words.

# Answer
> 5 votes
# Ruby `-nl`, 17 bytes

```
p$_.sum%$_.size<1

```

Try it online!

# Answer
> 4 votes
# Vyxal , 11 10 bytes

-1 thanks to Neil

```
ƛkanḟ;∑?LḊ

```

Try it Online!

# Explanation

```
ƛkanḟ;∑?LḊ
ƛ            Start a mapping lambda for input
 ka          Lowercase alphabet
   n         Current letter
    ḟ        Find letter in the alphabet, return index
     ;       Close mapping lambda
      ∑      Sum the list of indices.
       ?L    Get Length of input
         Ḋ   Check if Sum is divisible by the length.

```

# Answer
> 4 votes
# SNOBOL4 (CSNOBOL4), ~~103~~ 98 bytes

```
	L =SIZE(W =INPUT)
N	W LEN(1) . X REM . W :F(O)
	S =S + ORD(X)	:(N)
O	OUTPUT =1	EQ(REMDR(S,L))
END

```

Try it online!

Prints `1` for truthy and nothing for falsey.

# Answer
> 4 votes
# Charcoal, 9 bytes

```
¬﹪ΣＥθ℅ιＬθ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a perfect word, nothing if not. Explanation:

```
    θ        Input string
   Ｅ         Map over characters
      ι      Current character
     ℅       Ordinal
  Σ          Sum
¬﹪           Is divisible by
        θ    Input string
       Ｌ     Length
             Implicitly print

```

# Answer
> 4 votes
# Python 3, 50 bytes

```
s=input();print(sum(ord(c)-95for c in s)%len(s)<1)

```

Try it online!

# Answer
> 4 votes
# Ly, 8 bytes

```
iys&+l%!

```

Try it online!

```
i         - read STDIN onto stack as codepoints
 ys       - push length of the stack, save to backup cell
   &+     - sum the codepoints on the stack (1)
     l    - load the number of chars from the backup cell
      %   - module math to push "0" if evenly divisble, ">0" otherwise
       !  - negate modulo result so that 0->1 and other->0

```

(1) The code includes the length of the original stack in the sum of the codepoints to save the `p` byte that would be needed to delete it. But it doesn't change the result of the modulo math to get the final result.

When the code exits, the only thing on the stack is the `0|1` result, which is printed as a number automatically.

# Answer
> 4 votes
# Retina 0.8.2, 46 bytes

```
.
$&26$*
+T`1l`_3l`\D.
^
2
O^`.
3
1
^(1+)2\1*$

```

Try it online! Link includes test cases. Explanation:

```
.
$&26$*

```

Append 26 `1`s to each letter.

```
+T`1l`_3l`\D.

```

Cycle the letters through the alphabet, removing a `1` each time. Once the letter reaches `a`, replace it with a `3`. (Note that this numbers the alphabet in reverse but this doesn't affect the divisibility check.)

```
^
2
O^`.

```

Insert a `2` and then sort the digits in reverse order, so you have the `3`s for each letter, the `2`, and then the `1`s representing the sum of the positions.

```
3
1

```

Change the `3`s into `1`s.

```
^(1+)2\1*$

```

Check that the leading `1`s divide the trailing `1`s.

# Answer
> 4 votes
# K (ngn/k), ~~14~~ 11 bytes

-3 bytes from @Dominic van Essen's improvement

```
{~(#x)!+/x}

```

Try it online!

* `+/x` take the sum of the ASCII codes of the (strictly lowercase) input
* `(#x)!` mod this sum by the length of the input
* `~` "not" the result, i.e. return `1` if the sum is evenly divisible by the length (i.e. the mod returns 0), and `0` otherwise

# Answer
> 3 votes
# Zsh, 31 bytes

```
a=(+\#\#${(s::)^1})
(((a)%$#1))

```

Try it online!

In Zsh, `##x` in arithmetic mode returns the codepoint of `'x'`.

```
        ${(s::) 1}    # split $1 into characters
   +\#\#${(s::)^1}    # append `+##` to each element
a=(+\#\#${(s::)^1})   # save as $a
(((a)%$#1))           # join $a on spaces, evaluate (+##a +##b ...) % $#1
                      # arithmetically

```

# Answer
> 3 votes
# Python, 125 bytes

Wow I feel like an idiot after reading all these other amazing answers.

```
j=[ord(k)-96 for k in str(input(""))]
l=len(j)
while len(j)>1:j[0]+=j[1];del j[1]
print("%sy"%("truth"if j[0]%l<1else"fals"))

```

I think how this works is pretty trivial.

# Answer
> 3 votes
# Pyth, 7 bytes

```
!%sCMQl

```

Test suite

##### Explanation:

```
!%sCMQl  | Full code
!%sCMQlQ | with implicit variables filled
---------+-------------------------------------------------------
   CMQ   | Replace each character in the input with its codepoint
  s      | Sum the resulting list
 %    lQ | Mod the sum with the length of the input
!        | Boolean negate (i.e. 0 -> True, other -> False)

```

# Answer
> 3 votes
# MathGolf, 5 bytes

```
$Σ\£÷

```

Input as a list of characters. Could be 1 byte less by taking the input as a list of codepoints.

Try it online.

**Explanation:**

```
$     # Map each character in the (implicit) input-list to a codepoint integer
 Σ    # Sum this list
  \   # Swap so the (implicit) input-list is at the top again
   £  # Pop and push its length
    ÷ # Check if the earlier sum is divisible by this length
      # (after which the entire stack is output implicitly as result)

```

# Answer
> 3 votes
# Whitespace, 113 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][S N
S _Duplicate_0][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][S N
S _Duplicate][T N
T   S _Read_STDIN_as_char][T    T   T   _Retrieve_input][S N
S _Duplicate][S S S T   S T S N
_Push_10][T S S T   _Subtract][N
T   S S N
_If_0_jump_to_Label_PRINT_RESULT][T S S S _Add][S N
T   _Swap_top_two][S S S T  N
_Push_1][T  S S S _Add][S N
T   _Swap_top_two][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT_RESULT][S N
N
_Discard_top][S N
T   _Swap_top_two][T    S T T   _Modulo][N
T   S T N
_If_0_Jump_to_Label_TRUTHY][S S T   T   N
_Push_-1][N
S S T   N
_Create_Label_TRUTHY][S S S T   N
_Push_1][T  S S S _Add][T   N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Since Whitespace can only read input one character at a time, the input must contain a trailing newline so we'll know when we're done reading characters.
Whitespace also lacks truthy/falsey values, so this program will output `1` for truthy and `0` for falsey (could be 28 bytes less with `0` as truthy and a positive integer as falsey).

**Try it online** (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer length = 0
Integer sum = 0
Start LOOP:
  Integer input = STDIN as character
  If(input == '\n'):
    Jump to PRINT_RESULT
  sum = sum + input
  length = length + 1
  Go to next iteration of LOOP

PRINT_RESULT:
  Integer result = 0
  Integer mod = sum modulo length
  If(mod == 0):
    Skip to TRUTHY
  Else:
    result = -1
  TRUTHY:
  result = result + 1
  Print result as integer to STDOUT

```

# Answer
> 3 votes
# C (clang), 49 bytes

```
i,l;f(*a){for(i=l=0;*a;i+=*a++)l++;return!(i%l);}

```

Try it online!

Takes input as a wide string; returns `1` for pure words and `0` for others.

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

```
{(#x)!+/x}

```

Try it online!

*Saves a byte by not using the Not operator (~)*

Quick and simple. Return `0` for true and any other value for false.

Explanation:

```
{(#x)!+/x}    Main function. Takes x as input
      +/x     Sum of all charcodes in x
     !        Modulo
 (#x)         Length of x

```

# Answer
> 3 votes
# Fig, \\$4\log\_{256}(96)\approx\\$ 3.292 bytes

```
%LxS

```

Try it online!

Port of K answer. Prints 0 for truthy and a positive number for falsey.

```
%LxS
   S # Sum of charcodes
%    # Modulo
 Lx  # Length of input

```

# Answer
> 3 votes
# \>\<\> (Fish), ~~26~~ ~~24~~ ~~23~~ ~~20~~ ~~19~~ 17 bytes

```
l&v
v+>l1-?!
>&%n

```

Try it

Exits with error, which is allowed by default.

This is my first answer in this language, so it can probably be golfed.

Input is assumed to be on the stack. Output is any non-zero number for falsy, `0` for truthy.

# Answer
> 3 votes
# Arturo, 41 bytes

```
$=>[=floor<=average map&=>[to :integer&]]

```

Try it

# Answer
> 3 votes
# Trilangle, 28 bytes

```
'0|2_~<.+!>S/>i,..<.@2\)/(%S

```

Prints "0" if the word is pure.

Try it on the online interpreter!

Roughly equivalent to this C code:

```
#include <stdio.h>

int main() {
    int total = 0, len = 0;
    int c;
    while ((c = getchar()) != EOF) {
        total += c;
        ++len;
    }
    if (total % len == 0) puts("0");
}

```

The code unfolds to this triangle:

```
      '
     0 |
    2 _ ~
   < . + !
  > S / > i
 , . . < . @
2 \ ) / ( % S

```

Control flow starts at the north corner heading southwest, on the red path:

* `'0`: push a zero to the stack
* `2`: duplicate the top of the stack, so it now contains two zeroes
* `<`: redirect control flow
* `i`: read a single character in and push it to the stack
* `>`: branch

If EOF was read, control flow continues on the blue path; otherwise, control flow continues on the green path.

The green path performs the necessary additions before looping:

* `+`: add the top two values on the stack
* `_`: redirect control flow
* `.`: no-op
* `S`: swap the top two values in the stack
* `.`: no-op
* `\`: redirect control flow
* `)`: increment the top of the stack
* `/`: redirect control flow
* `.`: no-op again
* `S`: swap the values back
* `<`: redirect control flow, merging with the red path

On the blue path (after EOF is read), the following instructions are seen:

* `<`: redirect control flow
* `..`: more no-ops
* `,`: pop the EOF off the stack
* `S`: swap the two values on the top of the stack
* `%`: pop two values off the stack and push `a % b`
* `(`: decrement the top of the stack
* `/`: redirect control flow
* `2`: duplicate the top of the stack
* `.`: another no-op
* `/`: redirect control flow
* `S`: "swap" the two values in the stack (effectively a no-op, since they're the same value)
* `>`: branch

If the word is pure, the stack contains two -1's, and the interpreter takes the magenta path. If the word is not pure, the stack contains two copies of some non-negative number, and the interpreter takes the yellow path.

On the magenta path, it prints a 0 before exiting:

* `,`: pop a value off the top of the stack
* `2`: duplicate the top of the stack (not necessary on this code path, but harmless)
* `|`: redirect control flow
* `~`: bitwise complement, changes -1 to 0
* `!`: print the top of the stack as a decimal integer
* `i`: attempt to read more input (always sees EOF)
* `@`: end program

The yellow path has a rather convoluted no-op before it exits:

* `\`: no-op when traversed in this direction
* `,`: pop from the stack
* `2`: duplicate the value on the stack (cancels out the `,`)
* `S`: "swap" the two identical values
* `@`: end program.

# Answer
> 2 votes
# Python 3, 55 bytes

```
lambda s:(sum(ord(c)-95for c in s)/len(s)).is_integer()

```

Try it online!

# Answer
> 2 votes
# C#, 101 83 bytes

```
bool P(string w){int i=0;foreach(var c in w){i+=(int)c%32;};return i%w.Length==0;};

```

Try it online

# Answer
> 2 votes
# Kotlin, 85 bytes

```
fun i(s:String):Int{var a=0;for(i in s)a+=i.code-96;return if(a%s.length==0)1 else 0}

```

Try it online!

### Ungolfed version:

```
fun isPure(s: String) : Int
{
    var acc = 0
    for(i in s) acc+= i.code-96
    return if(acc%s.length==0) 1 else 0
}

```

1 stands for Truthy and 0 stands for falsy, derived from this post Interpretation of Truthy/Falsey

# Answer
> 2 votes
# Vyxal, 7 bytes

```
C₆%₌∑LḊ

```

Try it Online!

# Answer
> 2 votes
# Nim, 52 bytes

```
import sequtils,sugar
t=>t.foldl(a+b.int,0)%%t.len<1

```

Try it online!

# Answer
> 2 votes
# D, 67 bytes

```
import std;int p(string w){return !(w.fold!"a+=b-96"(0)%w.length);}

```

ungolfed

```
import std;
int p(string w) {
    return !(w.fold!"a+=b-96"(0)%w.length);
}
// not much more readable, lol

```

takes a string `w`, and then performs a fold on it. The fold adds each char, minus 96, to the accumulator. 96 being the ascii value of the backtick character, one behind `a` (since this challenge specifies that the characters are 1-indexed). this effectively adds up all characters in the string. Then we perform a modulo for a divisibility check, and since we want 0 to be the true case, we invert it. Note how we return `int` from this function so that it takes up one less byte. `int`s can be implicitly cast to `bool` so it's fine.

Try it online!

# Answer
> 2 votes
# GolfScript, 9 bytes

```
.{+}*\,%!

```

Try it online!

# Explanation

```
.{+}*\,%! | whole program
 {+}*     | sum the codepoints of the string
.    \,   | push the length
       %  | modulo
        ! | logical negate

```

# Answer
> 2 votes
# Go, 73 bytes

```
func(R[]rune)bool{s:=0
for _,r:=range R{s+=int(r-'`')}
return s%len(R)<1}

```

Attempt This Online!

# Answer
> 1 votes
# Swift, 42 bytes

```
{$0.utf8.reduce(0){$0+Int($1)}%$0.count<1}

```

Try it online!

This uses the same algorithm as the current top answers for Python, Excel, Java, and Scala, and probably others. As for why I use `.utf8`, see my explanation here. As with that answer, the input type here can be `String` or `Substring`, and the output type is `Bool`.

It still surprises me that Swift has `.reduce(0, +)` rather than `.sum()` for collections of numbers.

# Answer
> 1 votes
# APOL, 32 bytes

`v(0 i);!(%(⊕(ƒ(⁰ ⌕(ⓛ ∋))) l(⁰)))`

Explanation:

```
v(            Set memory cell
  0
  i           to input
);
!(            Not
  %(          Modulo
    ⊕(       Sum
      ƒ(      List-builder for
        ⁰     Memory cell 0
        ⌕(    Find
          ⓛ  All ASCII lowercase characters
          ∋   Loop item
        )
      )
    )
    l(        Length of
      ⁰       Memory cell 0
    )
  )
)

```

# Answer
> 1 votes
# Thunno, \\$ 7\log\_{256}(96)\approx \\$ 5.76 bytes

```
OSz0L%!

```

Attempt This Online!

#### Explanation

```
OSz0L%!  # Implicit input
 S       # the sum of
O        # the ords of the input
     %!  # is divisible by
    L    # the length of
  z0     # the input?
         # Implicit output

```

# Answer
> 1 votes
# PHP, 67 bytes

```
fn($w)=>!(array_sum(array_map('ord',str_split($w)))%96%strlen($w));

```

Try it online!

**Ungolfed**

```
fn($w) => !(array_sum(
    array_map('ord', str_split($w))
  ) % 96 % strlen($w));

```

# Answer
> 1 votes
# Stax, 5 bytes

```
:VR1=

```

Run and debug it

This program's length is the same packed and unpacked, so I chose to use the unpacked version.

# Explanation

```
:V    # mean of array (returns a fraction)
  R   # denominator
    = # is equal to
   1  # 1

```

# Answer
> 1 votes
# PARI/GP, 40 bytes

Try it online!

```
f(w)=!(sum(i=1,#w,Vecsmall(w)[i]-96)%#w)

```

# Answer
> 1 votes
# Lua, ~~67~~ 59 bytes

```
s=...a=0s:gsub('.',load'a=a+(...):byte()-96')print(a%#s==0)

```

Try it online!

Ungolfed version:

```
s=...
a=0
s:gsub('.',load'a=a+(...):byte()-96')  -- Add up value of chars, store in a
print(a%#s==0)

```

# Answer
> 1 votes
# minigolf, 12 bytes

```
i+,ni#*i+=;+

```

Attempt This Online!

## Explanation

```
i+         sum of codepoints of input
,          map in [1..sum(i)]:
  n          push curr. item
  i#*        Multiply by input's length
  i+=        Is that equal to input's sum?
;          end map
+          Sum the list
           (we definitely have a 1 output for an integer quotient,
            and 0 with no integer output

Implicit output

```

# Answer
> 1 votes
# Thunno 2 `B`, 4 bytes

```
SslḊ

```

Attempt This Online!

#### Explanation

```
SslḊ  # Implicit input, converted
      # to ordinals by B flag
S     # Sum the ordinals
 sl   # Get the length of the input
   Ḋ  # Is divisible?
      # Implicit output

```

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


title: CodeGolf - Heads or Tails

text:
# Question
Title: CodeGolf - Heads or Tails
### Instructions

Given an unknown input string `i` with a value of either *heads* or *tails*, return `1` for *heads* or `-1` for *tails* with the shortest code.

### Sample not golfed code (55b):

```
if(i == "heads"){
    print(1);
}else{
    print(-1);
}

```

### Sample golfed code (16b):

```
print("t">i||-1)

```

---

*Javascript was used for the example but it's **not** a requirement*. Sorry if it's too simple for most users, it can be improved.

# Answer
> 11 votes
# CJam, 4 bytes

```
I'e#

```

Assumes that the variable `I` holds the input, since `i` isn't a valid identifier in CJam.

Try it online.

This is equivalent to the JavaScript code `I.indexOf('e')`.

# Answer
> 18 votes
## C, 18 bytes

Pretty easy, but let's do it just for fun...

```
puts("-1"+*i/8%2);

```

Given the string `char *i` it prints 1 for `heads` and -1 for `tails`, with trailing newline.

## Explanation

In C, `"-1" + 1` points to 1 character forward, so it is the same as `"1"`. Let's take a look at the first characters:

```
"heads"[0] = 'h' = 104 = 0b01101000
"tails"[0] = 't' = 116 = 0b01110100

```

If we count the bits from the rightmost one starting at zero, bit 3 is 1 in `heads` and 0 in `tails`: summing it to `"-1"` gives the right string. It looks like this:

```
"-1" + ((i[0] >> 3) & 1)

```

Now, substitute `i[0]` with `*i` and the right shift with the power-of-two division to save some bytes. Also remove useless parentheses:

```
"-1" + (*i / 8 & 1)

```

Now, `& 1` can be substituted with `% 2`. The character count is the same, but the modulus has higher priority, allowing to drop the parentheses. Remove the whitespace:

```
"-1"+*i/8%2

```

## Bonus

I think the shortest way to get an integer 1 or -1 (not a string) in C is:

```
18-*i/6

```

Explanation:

```
'h' = 104
't' = 116

('h' + 't') / 2 = 110
110 - 'h' =  6
110 - 't' = -6

(110 - 'h') / 6 =  1
(110 - 't') / 6 = -1

Apply distributive property (integer division):
18 - 'h' / 6 =  1
18 - 't' / 6 = -1

```

# Answer
> 12 votes
# Ruby, 8 (6 without output)

```
p ?t<=>i

```

Rocketship operator!

# Answer
> 9 votes
## PHP - 11 Bytes

```
<?=1-$i^=F;

```

This works because `'tails' ^ 'F'``'2'` and `'heads' ^ 'F'``'.'`, which when typed as an integer is `0`.

You may test this solution (or any of the below) in the following way:

```
<?php foreach(['heads', 'tails'] as $i): ?>
 <?=1-$i^=F;
endforeach; ?>

```

Ideone Link

---

**Alternatives**

*15*: `<?=1-md5($i)%3;`
*16*: `<?=md5($i)[5]-5;`
*16*: `<?=-crc32($i)%5;`

# Answer
> 6 votes
# TI-BASIC, 9-10 bytes

```
cos(πʳinString(Ans,"t

```

Straightforward. "t" is in position 1 of "tails", but "t" is not in the string "heads", so inString( returns 1 for tails and 0 for heads.

If your calculator is in radian mode (as any mathematician's should be), it takes only nine bytes:

```
cos(πinString(Ans,"t

```

Note that TI calculators do not have named strings, so the input is in the calculator's answer variable. Also note that lowercase letters are two bytes each, so this solution actually takes less memory than than the word "heads".

# Answer
> 5 votes
# Fission, ~~26~~ 21 Bytes

```
O/';'1
"S@]_"-
R? <tL

```

Martin (and his excellent answer here) convinced me to learn a new language, and what better place than a quick golf? This is almost certainly not optimal, but hey, it was fun! Once I feel good about it, I may provide some form of explanation if it is requested.

# Answer
> 5 votes
# x86-16 machine code, 8 bytes

As a callable function, input string at `DS:SI`, output in `AL`.

```
80 3C 74    CMP  BYTE PTR[SI], 't'      ; if 'h': CF = 1, if 't': CF = 0
1A C0       SBB  AL, AL                 ; AL = AL - AL - CF (AL = -CF)
                                        ;  if 't': AL = 0 and CF = 0
                                        ;  if 'h': AL = -1 and CF = 1
1C FF       SBB  AL, -1                 ; AL = AL - (-1) - CF
                                        ;  if 't': AL = AL + 1 = 1
                                        ;  if 'h': AL = AL + 0 = -1
C3          RET

```

### x86-16 machine code, IBM PC DOS, 17 bytes

Or as a standalone DOS COM executable. Input from command line, output to stdout.

```
00000000: b402 0826 8200 7a04 b22d cd21 b231 cd21  ...&..z..-.!.1.!
00000010: c3

```

**Unassembled:**

```
B4 02           MOV  AH, 02H        ; DOS API display char function
08 26 0082      OR   DS:[82H], AH   ; set parity flag from input
7A 04           JPE  HEADS          ; if even, heads - display just '1'
B2 2D           MOV  DL, '-'        ; otherwise first display a '-''
CD 21           INT  21H            ; output DL to console
            HEADS:
B2 31           MOV  DL, '1'        ; display the '1'
CD 21           INT  21H            ; output DL to console
C3              RET

```

**Explanation:**

Use the CPU's parity flag to determine if first char is an `'h'` (even number of binary `1`'s) or a `'t'` (odd number of binary `1`'s). This saves one byte over comparing the char in ASCII.

**Input/Output:**

# Answer
> 4 votes
# C, 22 bytes

```
puts(*i>'h'?"-1":"1");

```

Credits goes to @TheE for telling me about this!

Explanation:

If the first character of the string is greater than `'h'`, the string `"-1"` is printed. Otherwise, the string `"1"` gets printed. Note that this approach comes with a trailing newline character.

---

Old version (25 bytes):

```
printf("%d",*i>'h'?-1:1);

```

Explanation:

If the first character of the string is greater than `'h'`, -1 is printed. Otherwise, 1 is printed.

# Answer
> 4 votes
## Python 2, 16 bytes

```
print(i<'t')*2-1

```

# Answer
> 4 votes
# Pyth - 4 bytes

---

```
 xz"e

```

Run with heads or tails. As `i` is `int` in Pyth, this uses `z` as the variable name, which contains any user input. It is equivalent to the Python `print(z.find("e"))`, so uses @Dennis's method.

# Answer
> 4 votes
# VBA (Excel), 12 bytes

Not a fantastic bit of golfing, but it's fun to try with VBA to get anywhere near to a proper programming language...

```
?13-asc(i)/6

```

i is the string, and it just exploits the ASCII value of the first character, divided by 6 and substracted from 13 to give 1 or -1. Very simple.

Example run in immediate window (10 extra bytes to set the input variable) :

```
i="Heads":?13-asc(i)/6
 1

```

# Answer
> 4 votes
# Tr: ~~17~~ 13 characters

(Or ~~14~~ 10 if you count only the arguments…)

```
tr -s ta-s -1

```

Sample run:

```
bash-4.3$ tr -s ta-s -1 <<< heads
1

bash-4.3$ tr -s ta-s -1 <<< tails
-1

```

Brief explanation:

`tr` stands for transliterate, that means, replaces each character of the input found in the first argument with character at the same position in the second argument:

```
tr ta -1 <<< tails         # replaces t ⇢ -, a → 1
⇒ -1ils

```

If the first argument is longer, the characters without positional match in the second argument are replaced with second argument's last character:

```
tr tals -1 <<< tails       # replaces t ⇢ -, a → 1, l → 1, s → 1
⇒ -1i11

```

When `-s` (`--squeeze-repeats`) option is used, successive characters which would be replaced with the same character are replaced at once:

```
tr -s tals -1 <<< tails    # replaces t ⇢ -, a → 1, l+s → 1
⇒ -1i1

```

So if we enumerate all characters in “tails”, we get what we need:

```
tr -s tails -1 <<< tails    # replaces t ⇢ -, a+i+l+s → 1
⇒ -1

```

Same for “heads”, but wee need to keep the “t” in front to consume the minus (characters sorted alphabetically for creepiness):

```
tr -s taedhs -1 <<< heads   # replaces h+e+a+d+s → 1
⇒ 1

```

Merging all uniques characters of “tails” and “heads” in a single first argument, keeping “t” in front leads to final solution:

```
tr -s tadehils -1 <<< tails # replaces t → -, a+i+l+s → 1
⇒ -1

tr -s tadehils -1 <<< heads # replaces h+e+a+d+s → 1
⇒ 1

```

To avoid enumerating the characters, an interval in *from***-***to* format can be used instead.

# Answer
> 4 votes
# Japt, 2 bytes

```
ae

```

Try it online

# Answer
> 4 votes
# shell (portable/POSIX), 16 bytes

`expr $i : he - 1`

Try It Online!
Thanks to @StéphaneChazelas in unix.stackexchange.com

Other solutions tried:
`echo $[30#$i%7-1] # 17 bytes but only in bash, zsh.` Try It Online!
`echo $((30#$i%7-1)) # 19 bytes but only bash,ksh,zsh.` Try It Online!
`he=2;echo $[${i%a*}-1] # 22 bytes But only in bash,zsh .` Try It Online!
`a=${i%h*};echo ${a:+-}1 # 23 .` **portable .** Try It Online!
`he=2;echo $((${i%a*}-1)) # 24 bytes .` **portable .** Try It Online!
`IFS=h;set $i;echo ${1:+-}1 # 26 (change IFS) .` **portable .** Try It Online!
`(IFS=h;set $i;echo ${1:+-}1) # 28 (subshell) .` **portable .** Try It Online!
`(IFS=h;set $i;echo $(($#*2-3))) # 31 bytes .` **portable .** Try It Online!

Note: Using `dash` as a reasonable simile of a portable shell tester.

* `expr $i : he - 1` works by counting how many characters match `he` with `$i : he`. A `heads` match `2` and a `tails` match 0 (none).Then substracting `1` with `- 1`.
* `$[30#$i%7-1]` works by converting the string to an integer. The base 30 and the mod by 7 were selected to obtain a difference of 2 between `heads` and `tails`. Then subtracting 1 converts the numbers to `1` and `-1`.
Note that a `$[...]` is an archaic form of arithmetic expression `$((...))` valid only in some shells.
* `he=2;echo $[${i%a*}-1]` works by making a variable of some value and then using Arithmetic Expansion to expand that variable (from the text value). The `${i%a*}` converts `heads` to `he` and `tails` to `t` (that, as a variable, has a value of 0).
* `IFS=h;set $i;echo ${1:+-}1` works in two steps. Setting IFS to `h` breaks the unquoted `$i` in `set $i` into parts divided by the character `h`, `heads` is divided to `''` and `'eads'`, thus setting `$1` to null. `tail` is not divided by `h`, thus making `$1` equal to `tails`. Then, `${1:+-}` generates a `-` if the value of `$1` is non-null (as in `tails`) or nothing (as with a null `$1`). That sign (or nothing) is concatenated with `1`.
* `(IFS=h;set $i;echo $(($#*2-3)))` works in a similar way but use the number of parts (`$#`) that the string in `$i` got broken into.

# Answer
> 3 votes
# Python, 20 bytes

```
print(('h'in i)*2-1)

```

This returns `False` if it isn't, and `True` if it is. In python `False` and `0` are the same, and `True` and `1` are as well.

So:

```
True (1) * 2 -1 = 2-1 = 1
False (0) * 2 - 1 = 0-1 = -1

```

# Answer
> 3 votes
# Python 2, 17 bytes

```
print'-1'['t'>i:]

```

`'heads'` is less than `'t'`, so it evaluates to `True == 1`, and prints the string after the first character. `'tails'` is greater than `'t'`, so it evaluates to `False == 0` and the whole string is printed.

If we're doing this from the command line, with implicit printing, it just becomes:

```
'-1'['t'>i:]

```

...for 12 bytes, but it adds single quotes to the output.

# Answer
> 3 votes
# QBasic, 11 bytes

This has got to be the shortest piece of QBasic I've ever written.

```
c=i>"t
?c^c

```

**Explanation:**

The above is some pretty heavily golfed QBasic. Once the autoformatter gets through with it, it'll look like this:

```
c = i > "t"
PRINT c ^ c

```

The first line compares the string `i` with `"t"`. If `i` is `"heads"`, `i > "t"` is false and `c = 0`. If `i` is `"tails"`, `i > "t"` is true and `c = -1`. Yes, `-1` is the default value for boolean true in QBasic!

The second line maps `-1` to `-1` and `0` to `1` via a math trick: `(-1)^(-1) == 1/(-1) == -1`, and `0^0`, though technically mathematically undefined, returns `1`.

This code requires that `i` be explicitly declared as a string variable; otherwise, it would have to be `i$`. Full test program (tested on QB64):

```
DIM i AS STRING
DATA heads, tails

FOR x = 1 TO 2
READ i

c=i>"t
?c^c

NEXT x

```

# Answer
> 3 votes
# Gaia, ~~5~~ 4 bytes

```
'eI(

```

Similar to Dennis' CJam answer, finds the index of `e` in the input string

Saved one byte since I didn't realise input was automatically used as an argument if there isn't enough stack values

# How it works

```
'e  Push e
I   Index of e in the the input. 2 if heads, 0 if tails
(   Subtract One
Stack gets automatically outputted

```

Try it Online!

# Answer
> 3 votes
# Bash, 22

```
echo $[0x${1:1:1}/2-6]

```

Takes the 2nd letter (`e` or `a`) and interprets it as a hex digit (14 or 10), then divide by 2 and subtract 6 to get the right answers.

Try it online!

# Answer
> 3 votes
# ed, ~~27~~ ~~25~~ 21 bytes

**`ed`** gave me a headache. Finally figured it out with help from `@ed1conf` on twitter and some peeps on `unix.se`. You can't just match things with `s/re/newtext/`, you have to prefix it with `g` otherwise **`ed`** packs a sad. It's like a grumpy 50 year old unix program saying "get off my lawn".

```
g/t/s//-
,s/\w\+/1
w

```

Try it online!

***-2*** *bytes by dropping the final `/`s*
***-4*** *bytes thanks to @manatwork (& whose `sed` answer i plagiarised)*
*Old version:
`g/t/s//-
g/\w\+/s//1
wq
.`*

# Answer
> 2 votes
# golflua 25 20 18

```
w(I.r():f'h'&1|-1)

```

Probably could be golfed some more by using some tricks that I'm not thinking about at the moment. (see history for old version) Saved 5 chars by moving input to `write` and ignoring the `if` statement there. Two more chars were saved by ignoring the optional parenthesis on `find`. It does not check for failed conditions (i.e., input that isn't *heads* or *tails*).

A Lua equivalent would be

```
io.write(io.read():find('h') and 1 or -1)

```

# Answer
> 2 votes
# Haskell, 18 bytes

```
f('h':_)=1
f _= -1

```

Every string starting with the letter `h` is mapped to `1`, all others to `-1`.

# Answer
> 2 votes
# Sed: 16 characters

```
s/t/-/
s/\w\+/1/

```

Sample run:

```
bash-4.3$ sed 's/t/-/;s/\w\+/1/' <<< 'heads'
1

bash-4.3$ sed 's/t/-/;s/\w\+/1/' <<< 'tails'
-1

```

# Answer
> 2 votes
# APL (Dyalog Unicode), 5 bytes

```
3-3⊃⍋

```

Try it online!

# Answer
> 2 votes
# Stax, 3 bytes

```
'eI

```

Run and debug it

# Answer
> 2 votes
# Stax, 4 bytes

```
└0Y.

```

Run and debug it

It's the codepoint of the first character mod 7 minus 5.

# Answer
> 2 votes
## Keg, ~~8~~ ~~12~~ 8 bytes

```
_d=2*1-.

```

Try it online!

## Explanation (syntactically invalid)

```
_        Take input and discard the last item
 d=      If the top of the stack is d:
   2*    Re-set the top of the stack as 2
     1-  Decrement the top of the stack by 1
       . Explicitly output the top of the stack

```

> -4 bytes thanks to manatwork

# Answer
> 2 votes
# PowerShell, 15 bytes

```
($args[1]-99)/2

```

Try it online!

Takes input via splatting. Uses the `e` vs the `a` to do ASCII math

# Answer
> 2 votes
# dc, 8 bytes

```
?z2*1r-p

```

dc can't do anything meaningful with strings other than read them in and attempt to evaluate them. Doing this, "heads" outputs some warnings about unimplemented commands and empty stack, which we ignore, but importantly the stack remains empty. "tails" does almost the same with the important exception that the final "ls" loads a value from the s register to the stack.

We then use "z" to get the stack length and arithmetically fiddle to get the right answers.

Try it online!

# Answer
> 2 votes
# Triangular, 10 bytes

```
F.~%.7/-_<

```

Try it online!

Divides the ASCII value of a character input by 7. Subtracts the quotient from 15. Execution stops when the IP runs out of the program space. This works because Triangular can only manage integer division. Conveniently, "h" has a value of 104, which is 14 when integer divided by 7; "t" is 116, which is 16 when integer divided by 7.

Ungolfed/Explanation:

```
   F
  . ~
 % . 7
/ - _ <
---------------------------------------------------------------
F                 - Push 15 to Top of Stack
 ~                - Read a character from input, push its value to ToS
   7              - Push 7 to ToS
     <_           - Change directions, then pop ToS-1 and ToS, push their integer quotient
        -         - Pop ToS-1 and ToS, push their difference
          %       - Print ToS as an integer

```

---

**Previous version (14 bytes):**

```
~\81|m/,!<.>i%

```

Read a character from input; if that character's ASCII value divided by 8 has a remainder, print -1, otherwise print 1.

# Answer
> 2 votes
# Vyxal, 3 bytes

```
\eḟ

```

Try it Online!

Direct translation of the CJam answer (find the index of `e`, or -1 if not found).

Some more fun ones:

# Vyxal, 5 bytes

```
14βǒ‹

```

Try it Online!

```
14β     Convert given string from base 14 to integer
        (invalid digits are treated as -1)
   ǒ    Modulo 3
    ‹   Decrement

```

# Vyxal, 4 bytes

```
18β±

```

Try it Online!

```
18β     Convert from base 18 to integer
   ±    Sign
        "heads" is positive -> 1
        "tails" is negative (because leading digit is invalid) -> -1

```

# Answer
> 1 votes
# Vitsy, 13 bytes

So what, I'm late for the party. ¯\\\_(ツ)\_/¯

```
zv&v'h'=)i1rN
z             Grab all input.
 v            Capture the top item (h or t) as a temp variable.
  &           Generate new stack, move to it.
   v'h'=      Test if the variable is h.
        )i    If it isn't, push -1.
          1   Push 1.
           r  Reverse the stack.
            N Print out the top item as a number.
```

# Answer
> 1 votes
# SmileBASIC, 15 bytes

```
H=2?VAR(I[T])-1

```

Not the shortest possible solution, but I didn't want to post a boring program that's the same as all the others.

The `VAR` "function" converts a variable name into a variable. `VAR("X") = 1` is equivalent to `X = 1`, for example.

The program sets `H` to 2, then uses `VAR()` on the first character in the input string.
(`I[T]` is the same as `I[0]`, because `T` is `0`. I had to include `T` here because `VAR` is not allowed to create new variables).

If the input is `heads`, `VAR()` returns the variable `H`, which has a value of 2.
If the input is `tails`, `VAR()` returns the variable `T`, which has a value of 0.

Then, it subtracts 1 from this and outputs either `-1` or `1`.

Because variable names in SmileBASIC are not case sensitive, this program works for any capitalization of the input string.

Note:
Normally, string variables must have names ending in `$`, but there are several ways to avoid this restriction. The simplest is to put the code inside a function, because function arguments are not type checked:

```
TEST "heads"
TEST "tails"

DEF TEST I
 H=2?VAR(I[T])-1
END

```

# Answer
> 1 votes
# Homespring, 50 bytes

```
youth. fountain bear 1 pump heads    -1 pump tails

```

very simple, make the input salmon young, block him after he enters the right branch so he spawns early, then bear eats the downstream input salmon

# Answer
> 1 votes
# Commodore BASIC (PET, VIC-20, C64/128, C16/+4, TheC64Mini) 44 Tokenized and BASIC bytes

```
 0b$="heads":inputa$:?-1*(b$=a$)+1*(a$<>b$)

```

Commodore BASIC returns `-1` as `TRUE` and `0` as `FALSE`, so a bit of simple maths is required to output the right required answer here.

# Answer
> 1 votes
# Zsh, ~~25~~ 19 bytes

-5 bytes using @Digital Trauma's bash solution; get the second letter, either `e` or `a`. Then `0xe` and `0xa` are interpreted as hex, i.e. decimal `14` and `10`. Then we do a bit of arithmetic to output `1` or `-1`.

Try it Online!

```
<<<$[0x${1[2]}/2-6]

```

24 bytes: `<<<${1[1]:s/h//:s/t/-/}1`

25 bytes: `<<<${1[1]:s/h/1/:s/t/-1/}`

# Answer
> 1 votes
# Perl 5 `-p`, 10 bytes

```
$_=o cmp$_

```

Try it online!

# Answer
> 1 votes
## , 16 bytes

I will expand it later.

```
?-ň*8+94{1}{-1}

```

## Explanation

```
?               If statement
 -ň             Subtract input with
   *8+94        The ASCII code of h
        {1}     If true, return 1
           {-1} Otherwise, return -1

```

# Answer
> 1 votes
# 05AB1E, 3 bytes

```
'ek

```

Try it online or verify both test cases.

**Explanation:**

```
'ek '# Get the 0-based index of "e" in the (implicit) input-string
     # (or -1 if no "e" is present)
     # (and output the result implicitly)

```

# Answer
> 1 votes
# Gema, 7 characters

```
t=-
*=1

```

Generally the same thing as my Sed solution does, but there is a big difference: Sed executes all commands on the pattern space (so later commands act on previous command's result), while Gema handles each piece of input once and discards it.

So although in the 1st step Gema's `t=-` does the same as Sed's `s/t/-/`, in the 2nd step Gema's `*=1` will act either on “ails” or “heads”, while Sed's `s/\w\+/1/` has to handle either “-ails” or “heads”.

Sample run:

```
bash-5.0$ gema 't=-;*=1' <<< 'heads'
1

bash-5.0$ gema 't=-;*=1' <<< 'tails'
-1

```

Try it online!

# Answer
> 1 votes
# Zsh, ~~13~~ 12 bytes

*-1 from @Isaac*

```
<<<$[#1%7-5]

```

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

> `man zshmisc`, under *Arithmetic Evaluation*:
>
> > An expression of the form `##x` where x is any character sequence such as `a`, `^A`, or `\M-\C-x` gives the value of this character and **an expression of the form `#name` gives the value of the first character of the contents of the parameter name.**

# Answer
> 1 votes
# Brain-Flak, ~~52~~ 34 bytes

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

```

~~Output is the top element of the stack~~

-18 bytes thanks to Jo King

Try it with heads!

Try it with tails!

# Answer
> 1 votes
# C-INTERCAL, 177 bytes

This is my first, and hopefully last, INTERCAL program. INTERCAL is a truly remarkable language. Those who haven't heard of it should immediately investigate (here is the manual I used).

```
PLEASEDO,1<-#2PLEASEDOWRITEIN,1PLEASEDO.1<-',1SUB#1'~#4DO(2)NEXTDO,1SUB#1<-#76(1)DO,1SUB#2<-#40(2)DO(3)NEXTDO,1<-#1DO,1SUB#1<-#116DOCOMEFROM(1)DOREADOUT,1(3)DOFORGET.1DORESUME#1

```

The program reads from standard input and writes to standard output. After printing the appropriate string, the program crashes with one of two humorous error messages depending on the input.

Try It Online

## Ungolfed

```
    PLEASE DO ,1 <- #2
    PLEASE DO WRITE IN ,1
    PLEASE DO .1 <- ',1 SUB #1' ~ #4
    DO (2) NEXT
    DO ,1 SUB #1 <- #76
(1) DO ,1 SUB #2 <- #40
(2) DO (3) NEXT
    DO ,1 <- #1
    DO ,1 SUB #1 <- #116
    DO COME FROM (1)
    DO READ OUT ,1
(3) DO FORGET .1
    DO RESUME #1

```

Well, that didn't help much...

In the first three lines, we read 2 (`#2` in INTERCAL) characters from the input into array `,1` and store in variable `.1` whether the first character read has bit 2 set (mask of 4); in ASCII `h` is `0b1101000` and `t` is `0b1110100`, so this variable now indicates whether the input is `tails`. This uses the "select" operator `~`, which in this case performs both masking and shifting to select bit 2 as 0 or 1.

The rest of the program is an if/else conditional and a print statement. Unfortunately, control flow is very limited in INTERCAL. The only mechanism is a call stack that's pushed to when the program executes `DO (x) NEXT`. `DO RESUME #1` then operates like a return statement (but with no return value), popping the stack and jumping to the next statement after the most recent `DO (x) NEXT`. But the value passed to `DO RESUME` can be any number. `DO RESUME #3` pops the call stack three times and jumps to the third-from-last `DO NEXT`.

A similar construct is `DO FORGET`, which only pops the stack the specified number of times but does not jump. `DO RESUME` always jumps, so passing it 0 is a run-time error. But the instruction `DO FORGET #0` is valid, and doesn't do anything.

And so with the statements `DO (2) NEXT` and `DO (3) NEXT` I push two locations onto the call stack. At `(3)` I then discard `.1` frames, which has the effect of "forgetting" the call at `(2)` if and only if the input was `tails`. As a result, we end up just after either `DO (2) NEXT` or `DO (3) NEXT` after the return on the last line, depending on the input.

Each branch then loads the appropriate character data into `,1` (see here for why the values don't make any sense), and `COME FROM (1)`, an inverted `goto`, joins the two branches at the output statement `DO READ OUT`. Control then continues, but luckily in either case the program crashes before printing anything else.

# Answer
> 1 votes
# Java (JDK), 18 bytes

```
i->i=="heads"?1:-1

```

Try it online!

# Answer
> 1 votes
# JavaScript, 14 bytes

```
s=>s.search`e`

```

Try it online!

# Answer
> 1 votes
# , ~~8~~ 6 bytes

```
2-2{/:

```

Same approach as FrownyFrog's APL answer. -2 thanks to Bubbler

Attempt This Online!

```
2-2{/:
    /:  NB. grade up
  2{    NB. take the third item
2-      NB. subtract from 2

```

# Answer
> 1 votes
# Python 3, 18 bytes

```
print(i.find("e"))

```

`str.find` returns `-1` if it can't find the required character. In `heads`, `e` is in position 1 (Python is 0-indexed), whereas in `tails` it doesn't exist.

# Answer
> 0 votes
## Befunge, 28 bytes

28 bytes including whitespace and newlines:

```
<v"heads"
 >94+%v
,,"-1"_1.@

```

Assumes that either `heads` or `tails` is put into the string above (this is the equivalent of assuming the input is stored in `i`). Works by performing modulo 13 on the top character on the stack - `h` divides exactly, `t` does not.

I also made a 22 *character* version (excluding whitespace/newlines) but the input has to be backwards:

```
"sdaeh"v
       9
       4
       +
       %
@,,"-1"_1.

```

# Answer
> 0 votes
# Unefunge 98, 15 or 16 bytes

```
'h-4j@.-1_1.@

```

The above code assumes input is stored on top os the stack in **reverse order**. There are two 16-byte solutions that don't make this assumption:

```
$'d-4j@.-1_1.@

```

Assuming input is on top of the stack in normal order.

```
~'h-4j@.-1_1.@

```

Reading input from stdin

# Answer
> 0 votes
# , ~~58~~ 55 bytes

```
for(i in scan(,''))print(`if`(utf8ToInt(i)[1]%%8,-1,1))

```

Try it online!

Really poor attempt, but I the `utf8ToInt` values for `"h","H","t","T"` are 104, 72, 116, 84 respectively. As a result, `"h" and "H"` values are both evenly divisible by 8, while `"t" and "T"` are not. So a conversion and check for even divisibility yields the desired results.

This method compared to the following method takes different spellings of heads/Heads/HEADS/etc. and tails/Tails/TAILS/etc. As long as it starts with an h/H or t/T it will work properly.

EDIT: -3 bytes switching to a for loop. Prints each value on newline instead of a single array of 1's and -1's.

# , 49 bytes

```
for(i in scan(,''))print(ifelse(i=="heads",1,-1))

```

This method was suggested by @user5957401 and is much simpler. The difference here is that this method assumes that the user will input strictly "heads" or "tails" (technically anything but "heads").

Try it online!

# Answer
> 0 votes
# Whitespace, 40 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   S _Read_input_as_character][T   T   T   _Retrieve][S S S T  T   T   N
_Push_7][T  S T T   _Modulo][S S S T    S T N
_Push_5][T  S S T   _Subtract][T    N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Since Whitespace inputs one character at a time, I use that to my advantage here by only looking at the first character and porting *@recursive*'s Stax answer (so make sure to upvote him as well!)

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer c = STDIN as character code-point
c = c % 7
c = c - 5
Print c to STDOUT as integer

```

# Answer
> 0 votes
# 33, 12 bytes

```
P110mz6dzcmo

```

Try it online!

Requires `heads` or `tails` non-capitalised.

This only accepts the first character of the input. If it needs to accept all input, replace the `P` with `Ij`.

## Explanation

```
P            | Get the first character of input as its ASCII value
             |              ( h | t )
 110mz       | Subtract 110 (-6 | 6 )
      6dz    | Divide by 6  (-1 | 1 )
         cm  | Flip sign    ( 1 |-1 )
           o | Print it

```

# Answer
> 0 votes
# jq, 14 characters

```
index("e")//-1

```

That's searching character position in the string. Unfortunately on not found it returns `null`, so the `//` (alternative operator) has to be used. (Still shorter than an `.[:1]<"i"` check as that results boolean and there is no way to cast that to integer.)

Sample run:

```
bash-5.0$ jq -R 'index("e")//-1' <<< 'heads'
1

bash-5.0$ jq -R 'index("e")//-1' <<< 'tails'
-1

```

Try it online!

# Answer
> 0 votes
# \>\<\>, 9 bytes

```
ab*i-6,n;

```

Try it online!

I'm honestly surprised that there wasn't a fish answer yet.

Subtracts the ASCII value of the first character input from 110 and divides by 6.

# Answer
> 0 votes
# brainfuck, 42 bytes

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

```

Try it online!

Checks if it is heads or tails by checking if the ordinal values of first two characters are only three away from each other.

# Answer
> 0 votes
# MathGolf, 3 bytes

```
'e=

```

Try it online!

Basically identical to a lot of other solutions. Checks the index of `'e'`, and returns `-1` if not found.

# Answer
> 0 votes
# JavaScript (V8) - 19 Bytes

Since OPs solution returns 'true' and '-1' (see here), the following function:

```
f=i=>i[0]=='h'?1:-1

```

returns '1' and '-1' - see here. Just to be a smart-ass and so.

// Adaption of Java (SDK) version as a JS function.

# Answer
> 0 votes
# Runic Enchantments, 10 bytes

```
1i3%1C=?Z@

```

Try it online! (heads)
Try it online! (tails)

Works by determining if the 4th character is a `d` (compare to number literal 100) and if not, multiplies a `1` by `-1`, then prints and terminates.

```
1              Push 1 (the output)
  i            Read input string
   3%          Get 4th character (0-indexed)
     1C=?      Compare with 100 (decimal value of d)
         Z     If false, multiply TOS with -1
          @    Output entire stack (the only thing left with be a 1 or -1) and terminate

```

# Answer
> 0 votes
# Vyxal, 8 bytes

```
`e`c[1|u

```

Try it Online!

u is `-1`.

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