# Question
Title: Enumerate each series of identical numbers in-place
Given a list of strictly positive integers, go through each distinct number and replace all occurrences of it with successive indices (zero or one based) of a new series.

## Examples

`[]``[]`/`[]`

`[42]``[0]`/`[1]`

`[7,7,7]``[0,1,2]`/`[1,2,3]`

`[10,20,30]``[0,0,0]`/`[1,1,1]`

`[5,12,10,12,12,10]``[0,0,0,1,2,1]`/`[1,1,1,2,3,2]`

`[2,7,1,8,2,8,1,8,2,8]``[0,0,0,0,1,1,1,2,2,3]`/`[1,1,1,1,2,2,2,3,3,4]`

`[3,1,4,1,5,9,2,6,5,3,5,9]``[0,0,0,1,0,0,0,0,1,1,2,1]`/`[1,1,1,2,1,1,1,1,2,2,3,2]`

# Answer
> 23 votes
# JavaScript (ES6), 26 bytes

1-indexed.

```
a=>a.map(o=x=>o[x]=-~o[x])

```

Try it online!

### Commented

```
a =>                // a[] = input array
  a.map(o =         // assign the callback function of map() to the variable o, so that
                    // we have an object that can be used to store the counters
    x =>            // for each value x in a[]:
      o[x] = -~o[x] //   increment o[x] and yield the result
                    //   the '-~' syntax allows to go from undefined to 1
  )                 // end of map()

```

# Answer
> 10 votes
# , 27 bytes

```
function(x)ave(x,x,FUN=seq)

```

Try it online!

**Explanation :**

`ave(x,x,FUN=seq)` splits vector `x` into sub-vectors using values of `x` as grouping keys. Then `seq` function is called for each group and each result is re-arranged back in the original group position.

Better see an example :

```
x <- c(5,7,5,5,7,6)
ave(x, x, FUN=seq) # returns 1,1,2,3,2

 ┌───┬───┬───┬───┬───┐
 │ 5 │ 7 │ 5 │ 5 │ 7 │
 └───┴───┴───┴───┴───┘
   |   |   |    |  |
   ▼   |   ▼    ▼  |
 GROUP A : seq(c(5,5,5)) = c(1,2,3)
   |   |   |    |  |
   ▼   |   ▼    ▼  |
 ┌───┐ | ┌───┬───┐ |
 │ 1 │ | │ 2 │ 3 │ |
 └───┘ | └───┴───┘ |
       ▼           ▼
 GROUP B : seq(c(7,7)) = c(1,2)
       |           |
       ▼           ▼
     ┌───┐       ┌───┐
     │ 1 │       │ 2 │
     └───┘       └───┘

   |   |   |   |   |
   ▼   ▼   ▼   ▼   ▼
 ┌───┬───┬───┬───┬───┐
 │ 1 │ 1 │ 2 │ 3 │ 2 │
 └───┴───┴───┴───┴───┘

```

Note :

`seq(y)` function returns a sequence `1:length(y)` in case `y` has `length(y) > 1`, but returns a sequence from `1:y[1]` if `y` contains only one element.
This is fortunately not a problem because in that case R *\- complaining with a lot of warnings -* selects only the first value which is incidentally what we want :)

# Answer
> 6 votes
# MATL, 4 bytes

```
&=Rs

```

This solution is 1-based

Try it out at MATL Online!

**Explanation**

Uses `[1,2,3,2]` as an example

```
    # Implicitly grab the input array of length N
    #
    #   [1,2,3,2]
    #
&=  # Create an N x N boolean matrix by performing an element-wise comparison
    # between the original array and its transpose:
    #
    #     1 2 3 2
    #     -------
    # 1 | 1 0 0 0
    # 2 | 0 1 0 1
    # 3 | 0 0 1 0
    # 2 | 0 1 0 1
    #
R   # Take the upper-triangular portion of this matrix (sets below-diagonal to 0)
    #
    #   [1 0 0 0
    #    0 1 0 1
    #    0 0 1 0
    #    0 0 0 1]
    #
s   # Compute the sum down the columns
    #
    #   [1,1,1,2]
    #
    # Implicitly display the result

```

# Answer
> 5 votes
# , 7 bytes

```
1#.]=]\

```

Try it online!

1-indexed.

## Explanation:

```
]\ all the prefixes (filled with zeros, but there won't be any 0s in the input):
   ]\ 5 12 10 12 12 10
5  0  0  0  0  0
5 12  0  0  0  0
5 12 10  0  0  0
5 12 10 12  0  0
5 12 10 12 12  0
5 12 10 12 12 10

]= is each number from the input equal to the prefix:
   (]=]\) 5 12 10 12 12 10
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 1 0 1 0 0
0 1 0 1 1 0
0 0 1 0 0 1

1#. sum each row:
   (1#.]=]\) 5 12 10 12 12 10
1 1 1 2 3 2

```

# K (oK), ~~11~~ 10 bytes

-1 byte thanks to ngn!

```
{+/'x=,\x}

```

Try it online!

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

Many, many thanks to H.PWiz, Adám and dzaima for all their help in debugging and correcting this.

```
+/¨⊢=,\

```

Try it online!

**Explanation**

The 10-byte non-tacit version will be easier to explain first

```
{+/¨⍵=,\⍵}

{         } A user-defined function, a dfn
      ,\⍵  The list of prefixes of our input list ⍵
           (⍵ more generally means the right argument of a dfn)
           \ is 'scan' which both gives us our prefixes
           and applies ,/ over each prefix, which keeps each prefix as-is
    ⍵=     Checks each element of ⍵ against its corresponding prefix
           This checks each prefix for occurrences of the last element of that prefix
           This gives us several lists of 0s and 1s
 +/¨       This sums over each list of 0s and 1s to give us the enumeration we are looking for

```

The tacit version does three things

* First, it removes the instance of  used in `,\⍵` as `,\` on the right by itself can implicitly figure out that it's supposed to operate on the right argument.
* Second, for `⍵=`, we replace the  with , which stands for right argument
* Third, now that we have no explicit arguments (in this case, ), we can remove the braces `{}` as tacit functions do not use them

# Answer
> 5 votes
# AWK, 14

* 1 byte saved thanks to @NahuelFouilleul

```
{print++a[$1]}

```

Try it online!

The above does one-based indexing. If you prefer zero-based indexing, its an extra byte:

```
{print a[$1]++}

```

Try it online!

# Answer
> 4 votes
# Python 2, 48 bytes

```
lambda a:[a[:i].count(v)for i,v in enumerate(a)]

```

Try it online!

# Answer
> 4 votes
# 05AB1E, 4 bytes

```
ηε¤¢

```

Try it online! or as a Test Suite

**Explanation**

```
ηε     # apply to each prefix of the input list
  ¤¢   # count occurrences of the last element

```

# Answer
> 4 votes
# BQN, 1 byte

Try it here!, All tests

I don't know much about BQN, but I learned from this answer that this is a built-in.

# Answer
> 3 votes
# C# (Visual C# Interactive Compiler), 44 bytes

```
x=>x.Select((y,i)=>x.Take(i).Count(z=>z==y))

```

Try it online!

# Answer
> 3 votes
# Ruby, 35 bytes

```
->a{f=Hash.new 0;a.map{|v|f[v]+=1}}

```

It's pretty mundane, unfortunately - build a hash that stores the total for each entry encountered so far.

Some other, fun options that unfortunately weren't quite short enough:

```
->a{a.dup.map{a.count a.pop}.reverse}   # 37
->a{i=-1;a.map{|v|a[0..i+=1].count v}}  # 38

```

# Answer
> 2 votes
# Perl 6, 15 bytes

```
*>>.&{%.{$_}++}

```

Try it online!

You can move the `++` to before the `%` for a one based index.

### Explanation:

```
*>>.&{        }  # Map the input to
      %          # An anonymous hash
       .{$_}     # The current element indexed
            ++   # Incremented

```

# Answer
> 2 votes
# Python 2, ~~47~~ 43 bytes

```
f=lambda a:a and f(a[:-1])+[a.count(a[-1])]

```

Try it online!

A recursive 'one-based' solution.

# Answer
> 2 votes
# Jelly, 4 bytes

```
ċṪ$Ƥ

```

Try it online!

For each prefix of the input list, it counts the number of occurrences of its last element in itself.

# Answer
> 2 votes
# , 41 bytes

```
function(x)diag(diffinv(outer(x,x,"==")))

```

Try it online!

Oddly, returning a zero-based index is shorter in R.

# Answer
> 2 votes
# , ~~62~~ 43 bytes

```
x=z=scan();for(i in x)z[y]=1:sum(y<-x==i);z

```

-19 bytes thanks to Giuseppe, by removing which, and table, and only slight changes to the implementation

**Original**

```
x=z=scan();for(i in names(r<-table(x)))z[which(x==i)]=1:r[i];z

```

I can't compete with Giuseppe's knowledge, so my submission is somewhat longer than his, but using my basic knowledge, I felt that this solution was rather ingenious.

`r<-table(x)` counts the number of times each number appears and stores it in r, for future reference

`names()` gets the values of each unique entry in the table, and we iterate over these names with a for loop.

The remaining portion checks which entries are equal to the iterations and stores a sequence of values (from 1 to the number of entries of the iteration)

Try it online!

# Answer
> 2 votes
# Haskell, 44 bytes

```
([]#)
x#(y:z)=sum[1|a<-x,a==y]:(y:x)#z
_#e=e

```

Try it online!

## Explanation

Traverses the list from left to right keeping the list `x` of visited elements, initially `[]`:

For every encounter of a `y` count all equal elements in the list `x`.

# Answer
> 2 votes
# Haskell, ~~47~~ 46 bytes

```
(#(*0))
(x:r)#g=g x:r# \y->0^(y-x)^2+g y
e#g=e

```

Try it online!

A different approach than BMO's answer which turned out a bit longer. (And kindly borrows their nice test suit.)

The idea is to iterate over the input list and keep track of the number of times each element has occurred by updating a function `g`. Ungolfed:

```
f (const 0)
f g (x:r) = g x : f (\ y -> if x==y then 1 + g y else g y) r
f g []    = []

```

Two interesting golfing opportunities arose. First for the initial value of `g`, a constant function which disregards its argument and returns `0`:

```
const 0  -- the idiomatic way
(\_->0)  -- can be shorter if parenthesis are not needed
min 0    -- only works as inputs are guaranteed to be non-negative
(0*)     -- obvious in hindsight but took me a while to think of

```

And secondly an expression over variables `x` and `y` which yields `1` if `x` equals `y` and `0` otherwise:

```
if x==y then 1else 0  -- yes you don't need a space after the 1
fromEnum$x==y         -- works because Bool is an instance of Enum
sum[1|x==y]           -- uses that the sum of an empty list is zero
0^abs(x-y)            -- uses that 0^0=1 and 0^x=0 for any positive x
0^(x-y)^2             -- Thanks to  Christian Sievers!

```

There still might be shorter ways. Anyone got an idea?

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

```
a->{for(int l=a.length,i,c;l-->0;a[l]=c)for(c=i=0;i<l;)c+=a[l]==a[i++]?1:0;}

```

Try it online!

## Credits

# Answer
> 1 votes
# bash, ~~37~~ 24 bytes

```
f()(for x;{ r+=$[a[x]++]\ ;};echo $r)

```

TIO

if valid, there is also this variation, as suggested by DigitalTrauma

```
for x;{ echo $[a[x]++];}

```

TIO

# Answer
> 1 votes
# Tcl, 48 bytes

```
proc C L {lmap n $L {dict g [dict inc D $n] $n}}

```

Try it online!

# Answer
> 1 votes
# Ruby, 34 bytes

```
->a{r=[];a.map{|x|(r<<x).count x}}

```

Try it online!

# Answer
> 1 votes
# Perl 5, 11 bytes

```
$_=$h{$_}++

```

TIO

explanations following comment

* `$_` perl's special variable containing current line when looping over input (`-p` or `-n` switches)
* `$h{$_}++` autovivifies the map `%h` and creates an entry with key `$_` and increments and gives the value before increment
* the special variable is printed because of `-p` switch, `-l` switch removes end of line on input and adds end of line on output

# Answer
> 1 votes
# C (gcc), ~~65~~ 62 bytes

```
c,d;f(a,b)int*a;{for(;c=d=b--;a[b]=d)for(;c--;d-=a[c]!=a[b]);}

```

Try it online!

-2 bytes thanks to ASCII-only

---

This felt too straightforward, but I couldn't seem to get any shorter with a different approach.

# Answer
> 1 votes
# Pari/GP, 32 bytes

```
a->p=0;[polcoeff(p+=x^t,t)|t<-a]

```

The \\$k\\$-th element in the answer is the coefficient of the \\$x^{a\_k}\\$ term in the polynomial \\$\sum\_{i=1}^kx^{a\_i}\\$.

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), 21 bytes (@att)

```
_g=g/@#-(--g[#]&/@#)&

```

Try it online!

---

## Wolfram Language (Mathematica), 28 bytes

```
(Clear@g;g@a_=0;++g[#]&/@#)&

```

Based on @att's answer to another challenge.

Try it online!

---

## Wolfram Language (Mathematica), 32 bytes

-1 byte thanks to @att.

```
Accumulate[p=x^#]~Coefficient~p&

```

The \\$k\\$-th element in the answer is the coefficient of the \\$x^{a\_k}\\$ term in the polynomial \\$\sum\_{i=1}^kx^{a\_i}\\$.

Try it online!

# Answer
> 1 votes
# Attache, 23 bytes

```
{`~&>Zip[_,_[0:#_::0]]}

```

Try it online!

## Explanation

```
{`~&>Zip[_,_[0:#_::0]]}
{                     }    _: input (e.g., [5, 12, 10, 12, 12, 10])
             0:#_          range from 0 to length of input (inclusive)
                           e.g., [0, 1, 2, 3, 4, 5, 6]
                 ::0       descending range down to 0 for each element
                           e.g., [[0], [1, 0], [2, 1, 0], [3, 2, 1, 0], [4, 3, 2, 1, 0], [5, 4, 3, 2, 1, 0], [6, 5, 4, 3, 2, 1, 0]]
           _[       ]      get input elements at those indices
                           e.g., [[5], [12, 5], [10, 12, 5], [12, 10, 12, 5], [12, 12, 10, 12, 5], [10, 12, 12, 10, 12, 5], [nil, 10, 12, 12, 10, 12, 5]]
     Zip[_,          ]     concatenate each value with this array
                           e.g., [[5, [5]], [12, [12, 5]], [10, [10, 12, 5]], [12, [12, 10, 12, 5]], [12, [12, 12, 10, 12, 5]], [10, [10, 12, 12, 10, 12, 5]]]
   &>                      using each sub-array spread as arguments...
 `~                            count frequency
                               e.g. [12, [12, 10, 12, 5]] = 12 ~ [12, 10, 12, 5] = 2

```

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

```
(,/.!'#'=x)@<,/.=x

```

Try it online!

---

**OLD APPROACH**

# K (ngn/k), ~~27 23~~ 22 bytes

```
{x[,/.=x]:,/.!'#'=x;x}

```

Try it online!

---

this is not pretty... quick and dirty solution, i will be refining this later when i get the chance to think of a better approach

explanation:

* `=x` returns a dict where keys are items of x and values are their indices (`3 1 4 5 9 2 6!(0 9;1 3;,2;4 8 10;5 11;,6;,7)`)
* `i:` assign dict to `i`
* `#:'` count values for each key (`3 1 4 5 9 2 6!2 2 1 3 2 1 1`)
* `!:'` enumerate each value (`3 1 4 5 9 2 6!(0 1;0 1;,0;0 1 2;0 1;,0;,0)`)
* `,/.:` extract values and flatten list (`0 1 0 1 0 0 1 2 0 1 0 0`)
* `x[,/.:i]:` extract indices from i, flatten, and assign each value from the right-side list at these indices

annoyingly, the list is updated but a null value is returned by the assignment, so i need to return the list after the semicolon (`;x`)

**edit:** removed extraneous colons

**edit2:** removed unnecessary assignment

# Answer
> 1 votes
# Vyxal, 4 bytes

```
KƛtO

```

Try it Online!

`KƛṫO` is also valid for 4 bytes

Simply count the number of occurrences of the tail of each prefix in each prefix.

# Answer
> 1 votes
# Factor, 48 bytes

```
[ dup [ head [ = ] with count ] with map-index ]

```

Try it online!

# Answer
> 1 votes
# Husk, 4 bytes

```
z#ḣ¹

```

Try it online!

### Explanation

one-indexed

```
z#ḣ¹  transforms to z#ḣ⁰⁰
z     zip
  ḣ⁰  prefixes of input
    ⁰ and input
 #    with count

```

# Answer
> 1 votes
# PowerShell Core, 25 bytes

```
$t=@{}
$args|%{(++$t.$_)}

```

Try it online!

# Answer
> 0 votes
# Retina 0.8.2, 30 bytes

```
\b(\d+)\b(?<=(\b\1\b.*?)+)
$#2

```

Try it online! Link includes test cases. 1-indexed. Explanation: The first part of the regex matches each integer in the list in turn. The lookbehind's group matches each occurrence of that integer on that line up to and including the current integer. The integer is then substituted with the number of matches.

# Answer
> 0 votes
## Batch, 61 bytes

```
@setlocal
@for %%n in (%*)do @set/ac=c%%n+=1&call echo %%c%%

```

1-indexed. Because variable substitution happens before parsing, the `set/a` command ends up incrementing the variable name given by concatenating the letter `c` with the integer from the list (numeric variables default to zero in Batch). The result is then copied to another integer for ease of output (more precisely, it saves a byte).

# Answer
> 0 votes
# Japt, 8 bytes

```
£¯YÄ è¶X

```

Try it here

```
£¯YÄ è¶X
             :Implicit input of array U
£            :Map each X at 0-based index Y
 ¯           :  Slice U to index
  YÄ         :    Y+1
     è       :  Count the elements
      ¶X     :    Equal to X

```

# Answer
> 0 votes
# awk ~~46~~ 31 bytes

-15 bytes thanks to @Dennis

```
{for(;i++<NF;)$i=a[$i]++;print}

```

TIO

# Answer
> 0 votes
# Haxe, 58 bytes

```
l->{var x=[0=>0];l.map(e->++x[(x[e]==null?x[e]=0:0)+e]);};

```

(Requires arrow functions, so 4.0+)

`var x=[0=>0]` declares a new `IntMap`, with `0` as its only key (since the question say inputs are strictly positive). Unfortunately most targets throw when adding `null` to a number, hence the explicit check to make sure each key is in the map before incrementing.

Also a cheeky rip off based on the JS answer:

# Haxe (JS target), 41 bytes

```
l->{var x=[0=>0];l.map(e->x[e]=-~x[e]);};

```

Try both online

# Answer
> 0 votes
**GO 121 Bytes (Not included new lines and tabs)**

```
func cg(a []int) []int{
    var m = make(map[int]int)
    var r = make([]int, len(a))
    for i,v := range a{
        r[i] = m[v]
        m[v]++
    }
    return r
}

```

Accepts integer array and returns integer array.

# Answer
> 0 votes
# Python 2, 44 bytes

```
a=[]
for x in input():print a.count(x);a+=x,

```

Try it online!

The first thing I wrote tied Chas Brown's 43, so here's a different solution that's one byte longer.

# Answer
> 0 votes
# Reticular, 17 bytes

```
L[ddc@c~]~*$qlbo;

```

Try it online!

The input list of integers is assumed to already be pushed to the stack. Run the following code to test input:

```
'2''7''1''8''2''8''1''8''2''8'lbL[ddc@c~]~*$qlbo;

```

## Explanation

The pop instruction `c` which is supposed to: pop a list from the stack, pop the last element from that list and push this element to the stack. However, if the list occurs at more than 1 place in the stack (if it has been duplicated for example), **all of the duplicated lists** in the stack will also have their last element popped contrary to what one might think will happen. This is fortunately used in our favor in this puzzle.

```
L                 # Push length of input list to the stack.
 [      ]         # Push the following function:
  dd              # Duplicate top of stack twice.
    c             # Pop the list at top of the stack,
                    pop the last element in the list (which will pop the element of every list!)
                    and finally push it to the stack.
     @c           # Pop two items at the top of the stack (list + last element in that list).
                    then push the number of occurrences of that element in the list.
       ~          # Swap top two items in the stack (so that the popped list is on top again).
         ~        # Swap top two items in the stack.
          *       # Call the above function the same number of times as length of the input list.
           $      # Remove the item at the top of the stack (which by now is an empty list).
            q     # Reverse stack.
             lb   # Push size of stack and put that many items from the stack into a list.
               o; # Output resulting list and exit.

```

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), 63 bytes

```
 T =TABLE()
R I =INPUT :F(END)
 T<I> =OUTPUT =T<I> + 1 :(R)
END

```

Try it online!

# Answer
> 0 votes
# C++ (gcc), 122 bytes

```
#import<vector>
using V=std::vector<int>;V f(V x){for(int i,t,z=x.size();t=i=z--;x[z]=t)for(;i--;)t-=x[z]!=x[i];return x;}

```

Try it online!

Saved 2 more bytes thanks to @ceilingcat

# Answer
> 0 votes
# C# (.NET Core), 172 bytes

Without LINQ. `0` indexed `int[]` arrays.

```
p=>{int h=0,m=0,l=p.Length,j;var k=new int[l];if(l>0){foreach(int z in p){h=z>h?z:h;m=z<m?z:m;}for(j=m;j<=h;j++,m=0)for(int z=0;z<l;z++)k[z]=p[z]==j?m++:k[z];}return k;}

```

Try it online!

# Answer
> 0 votes
# Pyth, 7 bytes

```
.e/<Qkb

```

Try it online!

```
.e     Q # enumerated map over (implicit) Q (input): lambda k,b: (k=index, b=element)
  /   b  # number of occurences of b in
   <Qk   # Q[:k]

```

## Alternative 1-based solution (7 bytes)

```
m/ded._

```

Try it online!

```
m    ._ # map over all prefixes of (implicit) Q (input): lambda d:
 / ed   # Number of occurences of d[-1] in
  d     #                                  d

```

# Answer
> 0 votes
# SAP ABAP, 174 bytes

```
FORM f TABLES t.DATA r TYPE int_tab1.LOOP AT t.DATA(i) = 0.DATA(x) = sy-tabix.LOOP AT t.CHECK:sy-tabix < x,t = t[ x ].i = i + 1.ENDLOOP.APPEND i TO r.ENDLOOP.t[] = r.ENDFORM.

```

Subroutine which takes a table of integers and replaces all values with zero-based indices. ABAP has no array type, so a table of integers is the closest thing we have. It uses the builtin table type `int_tab1` to save some bytes over declaring `TYPE TABLE OF i` and abuses obsolete (but still functional) internal tables with header lines, which allows us to use `LOOP AT t` and read `t` at the implicit index `sy-tabix` without declaring additional variables for keeping the value.

---

Full program with some test cases from OP can be found here. Output below:

Forgot to add the two edge cases of `[ ]` and `[42]`, but they work, too:
`[ ]` =\> An empty input table stays empty as the outer loop gets skipped completely
`[42]` =\> A single value in the table means table line 1 in the inner loop is skipped, since `sy-tabix` is equal to `x` \- therefore `i` stays `0` and the output is `[0]`.

---

### Explanation:

```
FORM f TABLES t.              "Subroutine, TABLES parameters are references
  DATA r TYPE int_tab1.       "A temporary internal table for results
  LOOP AT t.                  "Go over each line in table t
    DATA(i) = 0.              "Set count to 0            (inline declaration)
    DATA(x) = sy-tabix.       "Set x to current index    (inline declaration)
    LOOP AT t.                "Go over each line in table t again
      CHECK:                  "Check whether... (works like a CONTINUE if not true)
        sy-tabix < x,         "1) ...inner LOOP index is smaller than outer index (= only check lines up to outer index - 1)
        t = t[ x ].           "2) ...value of t at inner index (implicit) is equal to value of t at outer index (x)
      i = i + 1.              "If both are true, increase the counter by 1
    ENDLOOP.
    APPEND i TO r.            "Add the count for this value to temporary results table
  ENDLOOP.
  t[] = r.                    "Fill referenced table t with the values in r.
ENDFORM.

```

# Answer
> 0 votes
# Gema, 32 characters

```
<D>=@set{$1;@add{${$1;};1}}${$1}

```

Outputs 1 based indexes.

Sample run:

```
bash-5.0$ gema '<D>=@set{$1;@add{${$1;};1}}${$1}' <<< '[5,12,10,12,12,10]'
[1,1,1,2,3,2]

```

Try it online!

## Gema, 34 characters

```
<D>=${$1;0}@set{$1;@add{${$1;};1}}

```

Outputs 0 based indexes.

Sample run:

```
bash-5.0$ gema '<D>=${$1;0}@set{$1;@add{${$1;};1}}' <<< '[5,12,10,12,12,10]'
[0,0,0,1,2,1]

```

Try it online!

# Answer
> 0 votes
# Go, 85 bytes

```
package main
func main(){
m:=make(map[int]int)
for i,n:=range a{
a[i]=m[n]
m[n]++
}
}

```

Create a map to store the count, loop through input list (a), replacing each item with the count for that item before incrementing.

# Answer
> 0 votes
# \[APL (Dyalog Unicode)\], 13 bytes

```
(+/⊃⍷⊢)⍤⌽¨,\⎕

```

# Answer
> 0 votes
# Thunno 2, 4 bytes

```
ƒıṪc

```

Try it online!

#### Explanation

```
ƒıṪc  # Implicit input
ƒ     # Get the prefixes of the input list
 ı    # Map over this list of lists:
  Ṫ   #  Remove the last item and push it separately
   c  #  Count the occurrences of this letter
      # Implicit output

```

---
Tags: code-golf, number, integer, sorting, substitution
---


title: Compare the averages of my lists

text:
# Question
Title: Compare the averages of my lists
## Getting the average of a list (e.g `[2,6,7]`)

* Get the length of the list: `[2,6,7] -> 3`
* Sum the numbers in the list: `2 + 6 + 7 = 15`.
* Divide the sum by their count: `15 / 3 = 5`.

You should compare the averages of two lists of *positive* integers **N** and **M**, by returning a value if **N** has a higher average, another value if **M** has a higher average, and another one in case of a tie.

---

# I/O rules

All the standard Input and Output methods are allowed.

### Input

You may take input as two separate lists, a nested list, or anything else you consider suitable for the task. Please specify the format.

### Output

The values provided have to be distinct and must consist of at least one non-whitespace character. Also, they *must* be consistent between runs (a single value for **N**, a single value for **M**, a single value for **Tie**). Please specify those in your answer. The values can be non-empty Strings, Bool values, Integers, or anything you consider suitable.

---

# Specs

* The lists will not necessarily have equal length.
* You are guaranteed that the lists are non-empty.

---

# Test Cases

I chose the values `N wins`, `M wins` and `Tie`, which are pretty much self-evident.

```
N, M                     ->   Output     (Averages)

[7], [6]                 -> N wins  (N has 7, M has 6 )
[4,5], [4,4]             -> N wins  (N has 4.5, M has 4)
[2,3,4], [4,5,6]         -> M wins  (N has 3, M has 5)
[4,1,3], [7,3,2,1,1,2]   -> Tie     (both have 2.666...)
[100,390,1], [89,82,89]  -> N wins  (N has 163.666..., M has 86.666...)
[92,892], [892,92]       -> Tie     (lists are basically identical)
[10,182], [12,78,203,91] -> Tie     (both have 96)

```

---

Default Loopholes apply. Explanations are encouraged! This is , so the shortest code in bytes wins!

# Answer
> 4 votes
# Actually, 5 bytes

```
♂æi-s

```

Try it online!

`1` for `N > M`, `0` for `N = M`, `-1` for `N < M`.

Explanation:

```
♂æi-s Takes input in format [N, M]
♂æ    Map average
  i   Dump to stack in reverse
   -  Subtract
    s Get sign

```

# Answer
> 15 votes
## Mathematica, 15 bytes

```
Order@@Mean/@#&

```

Try it online!

`Function` which expects a list of two lists. `Mean/@#` takes the arithmetic mean of each list in the input, then those means are passed into `Order`, which returns `-1` if the first list wins, `0` if there is a tie, and `1` if the second list wins.

# Answer
> 7 votes
# JavaScript (ES6), ~~52~~ 50 bytes

*(Saved 2 bytes thanks to @Shaggy.)*

Here are two 50-byte solutions:

```
f=(N,M,a=eval(N.join`+`)/N.length)=>M?(a-f(M))/0:a

(N,M,A=a=>eval(a.join`+`)/a.length)=>(A(N)-A(M))/0

```

Returns **Infinity** for N, **-Infinity** for M, and **NaN** for a tie.

The first solution may require a bit of explanation due to the recursion:

On the first call to the function, `a` is initialized as the average of the `N` array:

```
a=eval(N.join`+`)/N.length

```

`M` has a value at this point, so the first part of the conditional expression is called:

`M ? (a-f(M))/0 : **a**
 ----------`

The function is called within this expression, this time substituting `M` for `N`.

On this second call to the function, `a` is initialized as the average of `N` –– which was `M` in the previous call.

Since there is no second parameter during this call to the function, the second part of the conditional expression is triggered, which returns the average:

`M ? (a-f(M))/0 : **a**
 --`

We can now understand the expression better:

```
(a - f(M)) / 0

```

It's:

```
(the average of N  minus  the average of M) divided by 0

```

The difference between the averages will be a positive number, a negative number, or 0.

Dividing the difference by 0 results in **Infinity**, **-Infinity**, or **NaN** – providing the three distinct values as required.

**Test Cases:**

```
f=(N,M,a=eval(N.join`+`)/N.length)=>M?(a-f(M))/0:a

console.log(f([7], [6]                 )) // N wins  (N has 7, M has 6 )
console.log(f([4,5], [4,4]             )) // N wins  (N has 4.5, M has 4)
console.log(f([2,3,4], [4,5,6]         )) // M wins  (N has 3, M has 5)
console.log(f([4,1,3], [7,3,2,1,1,2]   )) // Tie     (both have 2.666...)
console.log(f([100,390,1], [89,82,89]  )) // N wins  (N has 163.666..., M has 86.666...)
console.log(f([92,892], [892,92]       )) // Tie     (lists are basically identical)
console.log(f([10,182], [12,78,203,91] )) // Tie     (both have 96)
```

# Answer
> 5 votes
# Mathematica, 21 bytes

```
Sign[Mean@#-Mean@#2]&

```

1 for `#` wins, -1 for `#2` wins, 0 for tie.

# Answer
> 5 votes
# MATL, 8 bytes

Soooo many modifiers (`Y` and `Z`). I can't find a way to make it shorter. `sum / number_of_elements` is three bytes. It might be a better way to do `-ZS`, but I can't find one.

```
YmiYm-ZS

```

Try it online!

```
           % Take first input implicitly
Ym         % Mean of that input
  i        % Grab second input
   Ym      % Mean of that input
     -     % Subtract
      ZS   % Sign

```

Returns `1` if the first input is larger, `0` if they tie, and `-1` if the second input is larger.

# Answer
> 5 votes
# Julia, 27 bytes

```
(x,y)->cmp(mean(x),mean(y))

```

Try it online!

Returns `1` if the first average is larger, `-1` if second is, and `0` if they tie.

# Answer
> 5 votes
# 05AB1E, 9 bytes

**1** if `M` wins, **-1** if `N` wins and **0** for a tie.

```
vyOyg/}.S

```

Try it online!

**Explanation**

```
v           # for each y in list of lists
 yO         # sum y
   yg       # get length of y
     /      # divide
      }     # end loop
       .S   # compare

```

# Answer
> 4 votes
# Python 2, 43 bytes

```
lambda p:cmp(*[sum(l)*1./len(l)for l in p])

```

Try it online!

# Answer
> 3 votes
# Octave, 27 bytes

```
@(x,y)sign(mean(x)-mean(y))

```

Try it online!

Takes two vectors `x.y` as input, takes the `mean` of both vectors, and subtract one from the other. Get the sign of this, to get `1`, `0` and `-1` for the three different alternatives.

# Answer
> 3 votes
# Python 2, 49 bytes

```
lambda N,M:cmp(1.*sum(N)/len(N),1.*sum(M)/len(M))

```

**Try it online**

# Answer
> 3 votes
# APL (Dyalog), 11 bytes

Prompts for a list of two lists. Prints `1` if the left has higher average, 0 if they have the same average, and `¯1` if the right has higher average.

```
×-/(+/÷≢)¨⎕

```

Try it online!

prompt

`(` apply the following tacit function to each:

`+/` the sum

`÷` divided by

the tally

`-/` insert (and evaluate) a minus between them

`×` signum

# Answer
> 3 votes
# Javascript, ~~81~~ ~~66~~ ~~58~~ 56 bytes

*saved 15 bytes thanks to Luke*

*saved 2 bytes thanks to Justin Mariner*

```
n=>m=>Math.sign((a=b=>eval(b.join`+`)/b.length)(m)-a(n))

```

Tie is 0, M is 1 and N is -1. Called using currying syntax, eg. `f([7])([6])`

# Answer
> 3 votes
# **Pyth, ~~10~~ ~~8~~ ~~7~~ 6 bytes**

Thanks @isaacg for saving a byte

```
._-F.O

```

Input is taken as a nested list, `[N, M]`. Outputs `-1` if `N < M`, `1` if `N > M` and `0` if they are equal.

Try It Online

# Answer
> 3 votes
# PHP, 68 bytes

```
<?foreach($_GET as$v)$r[]=array_sum($v)/count($v);echo$r[0]<=>$r[1];

```

Try it online!

# PHP, 69 bytes

```
<?=($s=array_sum)($a=$_GET[0])/count($a)<=>$s($b=$_GET[1])/count($b);

```

Try it online!

spaceship operator -1 less then , 0 tie , 1 greater then

# Answer
> 3 votes
# Haskell, ~~65~~ 43 Bytes

*Saved 22 bytes thanks to nimi!*

```
a x=sum x/sum[1|_<-x]
x#y=compare(a x)$a y

```

~~There has to be a much better way... But type conversions screwed me.~~

**Usage**

```
(#) [7] [6]

```

Returns `GT` if the first argument wins, `LT` if the second argument wins, and `EQ` if they tie.

Try it online!

# Answer
> 3 votes
## TI-Basic, ~~25~~ ~~21~~ ~~13~~ ~~12~~ 10 bytes

-2 bytes thanks to lirtosiast

```
:tanh(ᴇ9mean(L₁-mean(L₂

```

# Answer
> 3 votes
# J, 10 bytes

```
*@-&(+/%#)

```

One list given on the left, one on the right. Will return \_1 if the left average is smaller, 1 if it's bigger, and 0 if they're equal

* `(+/%#)` is a standard J fork for calculating the average of a list
* `&` provides a variation on the dyadic fork. it applies the right side (the average verb, in this case) to both arguments, and then passes them along to the verb on the left side, which in this case is...
* `*@-` subtract followed by "sign of": so the right avg is subtracted from the left, and we are given the sign of the result -- \_1, 1, or 0

# Answer
> 2 votes
# Jelly, 7 bytes

```
S÷Lµ€IṠ

```

A monadic link accepting a list of the two lists, `N,M` which returns:
`[-1]` for `N`;
`[1]` for `M`; and
`[0]` for a tie.
As a full program it prints the result (single item lists print their content only, so `-1`, `1`, or `0`).

**Try it online!**

### How?

```
S÷Lµ€IṠ - Link: list of lists, [N,M]
   µ€   - perform the chain to the left for €ach (of N, M)
S       -   sum
  L     -   length
 ÷      -   divide (yields the average)
     I  - incremental differences (yields [avg(M) - avg(N)])
      Ṡ - sign (yields: [1] if avg(M)>avg(N); [-1] if avg(N)>avg(M); or [0] if equal)

```

# Answer
> 2 votes
# C (gcc), 91 ~~98~~ bytes

```
u,v,j;f(x,y,a,b)int*a,*b;{for(u=v=0;x--;u+=a[x])for(j=0;j<y;)v+=b[j++];j=u*y-v;x=j>0?2:!j;}

```

Wrong place for C and probably the only answer that doesn't need division. At least the code is displayed without a slider.

Return 0,1,2 for `M>N`, `M=N`, `M<N` respectively. Takes input as `length of M`, `length of N`, `M`, `N`.

# Answer
> 2 votes
# Perl 6, 25 bytes

```
{sign [-] .map:{.sum/$_}}

```

Try it online!

Takes a single argument, a two-element list of lists of numbers. Returns `1` if the first list has a greater average, `-1` if the second list does, and `0` if the averages are equal.

# Answer
> 2 votes
# JavaScript (ES6), ~~60~~ 54 bytes

*-6 bytes thanks to @Luke and @Neil*

```
(i,[x,y]=i.map(v=>eval(v.join`+`)/v.length))=>y-x&&x>y

```

Takes input as a 2-element array `[N, M]`. Outputs `true`, `0`, or `false` for `N`, `Tie`, or `M`, respectively.

## Explanation

```
(i,                 // input array: [N, M]
    [x,y] =         // destructure assignment: set x and y to...
    i.map(v=>       // the input values mapped as...
        eval(v.join`+`) // the sum, by joining the array with +
        / v.length      // divided by the length
    )
) => y-x && x>y     // return 0 for tie, or the result of avg(N) > avg(M)

```

## Test Snippet

Input numbers separated by spaces/commas.

```
f=
(i,[x,y]=i.map(v=>eval(v.join`+`)/v.length))=>y-x&&x>y
```

```
<div oninput="O.value=f([N.value,M.value].map(x=>x.split(/[ ,]+/)))">N <input id=N> M <input id=M></div>
Out: <input id=O disabled>
```

# Answer
> 2 votes
# JavaScript (ES6), 60 bytes

```
a=>(b=(c=a.map(d=>eval(d.join`+`)/d.length))[0])-c[1])?b>0:0

```

Outputs `0` for `Tie`, `true` for `N` and `false` for `M`.

# Answer
> 2 votes
# Pip, 13 bytes

```
{$CM$+*a/#*a}

```

This is a function that takes a list of lists. Returns `1` if the first average is bigger, `-1` if the second is bigger, `0` if tied. Run all test cases here.

### Background

This solution makes heavy use of two of Pip's metaoperators:

* `$`, fold. Take a binary operator and apply it between the elements of a list. For instance, `+` is addition, but `$+` sums a list. Note that `$` makes a binary operator into a unary operator.
* `*`, map. Take a unary operator and apply it to each element of a list. For instance, `#` gives the length of a list, but `#*` gives (a list of) the lengths of the list's items.
* These two metaoperators can be combined: `$+*` maps fold/plus over a list, summing each of the list's elements.

The other thing to know about Pip is that a lot of operators work item-wise on lists by default. For instance, `[1 2 3] * 5` gives `[5 10 15]`; `[1 2 3] * [2 3 4]` gives `[2 6 12]`; and `[[1 2] [3 4]] * [5 6]` gives `[[5 10] [18 24]]`.

### Explanation

We'll use an example input of `[[2 3 4] [2 3 4 6]]`:

* `{...}`
Defines a function. The (first) argument is bound to the local variable `a`.
* `#*a`
Map `#` to the function's argument, getting the lengths of the sublists. Result: `[3 4]`
* `a/#*a`
Divide (the elements of) the sublists of `a` by their respective lengths. Result: `[[0.667 1 1.333] [0.5 0.75 1 1.5]]`
* `$+*a/#*a`
Map `$+` (fold on addition) to that result, summing the sublists. Result: `[3 3.75]`
* `$CM$+*a/#*a`
Fold on `CM`, which gives `-1`, `0`, or `1` depending on the comparison of its two operands (like Python's `cmp`). Result: `-1` (because `3` is smaller than `3.75`).

---

You can also define functions in Pip by writing expressions containing the identity function `_`. For example, `_*_` is a function that squares its argument--syntactic sugar for `{a*a}`, and fewer bytes. However, there's a bug in the current version of the interpreter that prevents `_` from working with the `*` metaoperator. Once that's fixed, this solution can be **11 bytes**: `$CM$+*_/#*_`.

# Answer
> 2 votes
# Brachylog, 8 bytes

```
⟨+/l⟩ᵐ-ṡ

```

Try it online!

Outputs `1` if the first list has a bigger average, `-1` is the second list has a bigger average, and `0` if they are tied.

### Explanation

```
     ᵐ        Map:
⟨   ⟩           Fork:
 +                Sum…
  /               …divided by…
   l              …length
       -      Subtract
        ṡ     Sign

```

# Answer
> 2 votes
# Java, 105 bytes

```
s->s.stream().map(l->l.stream().reduce((i,j)->i+j).get()/l.size()).reduce((i,j)->Math.signum(i-j)).get();

```

Lambda that takes a nested list, as per allowable inputs.

Streams the list of lists, converts both to their averages, then returns the sign of the difference. `1` if the first list is larger, `-1` if the second list is larger, `0` for a tie.

# Answer
> 2 votes
# R 38 34 bytes

```
function(a,b)sign(mean(a)-mean(b))

```

Function that takes as input two numeric vectors. Returns 1 if first list average is higher, 0 if they are the same and -1 if second list average is higher.

# Answer
> 2 votes
# MATL, 6 bytes

Don't be so mean!\*

```
!-ssZS

```

Input stack order:

```
M
N

```

Output:

```
 1 = N wins
-1 = M wins
 0 = tie

```

Try it online!

```
!-ssZS
========
!           % transpose M
 -          % N - M^T using elementwise subtraction and implicit expansion
  s         % sum columns of the result
   s        % sum the resulting row vector
    ZS      % sign of the sum

```

\*This answer was golfed without being mean to any poor, defenseless numbers.

# Answer
> 2 votes
# Java (OpenJDK 8), ~~76~~ 62 bytes

```
a->b->Math.signum(a.average().orElse(0)-b.average().orElse(0))

```

Try it online!

Since the input can be anything, I decided to take `IntStream`s as input. You can get such an input from a standard `int[]` with `Arrays.stream(array)`.

The output is `1` for "N wins", `-1` for "M wins", and `0` for tie.

### Saves

* -14 bytes from insights of both @Zircon and @Xanderhall!

# Answer
> 1 votes
# Japt v2.0a0, ~~12~~ ~~11~~ ~~10~~ 8 bytes

Takes input as a 2D array. Returns `-1` for M, `1` for N or `0` for tie.

```
®x÷ZÊÃrg

```

Try it

```
®x÷ZÊÃrg     :Implicit input of 2D array
®            :Map each Z
 x           :  Reduce by addition
  ÷          :  Divide by
   ZÊ        :  Length of Z
     Ã       :End map
      r      :Reduce by
       g     :  Sign of difference

```

# Answer
> 1 votes
# Dyalog APL, 14 bytes

```
×(-/(+/÷≢)¨∘⊢)

```

`1` if the left is greater, `¯1` if the right is and `0` on tie.

**How?**

`¨∘⊢` for each list

`+/÷≢` calculate average (`+/` sum `÷` divide by  length)

`-/` subtract the averages

`×` sign of the result

# Answer
> 1 votes
# Tcl, 93 bytes

```
proc C A\ B {proc M L {expr ([join $L +])/[llength $L].}
expr [set n [M $A]-[M $B]]<0?2:$n>0}

```

Try it online!

I saved 1 byte returning 2 instead of -1.

# Answer
> 1 votes
## CJam, ~~18~~ ~~16~~ 15 bytes

-1 thanks to @ErikTheOutgolfer

```
q~{_:+\,d/}%~-g

```

Input is given as `[[1 2 3] [4 5 6]]`. Output is -1, 0, or 1.

### Explanation:

```
q    e# Read input: "[[1 2 3] [4 5 6]]"
~    e# Eval:       [[1 2 3] [4 5 6]]
{    e# For each:     [1 2 3]
 _   e#   Duplicate:  [1 2 3] [1 2 3]
 :+  e#   Sum:        [1 2 3] 6
 \   e#   Swap:       6 [1 2 3]
 ,   e#   Length:     6 3
 d/  e#   Float div:  2.0
}%   e# End:        [2.0 5.0]
~    e# Unpack:     2.0 5.0
-    e# Subtract:   -3.0
g    e# Signum:     -1

```

# Answer
> 1 votes
# Retina, ~~69~~ 66 bytes

```
\d+
$*
1(?=.*;(1+,)+)
1$#1$*
1(?<=(,1+)+;.*)
1$#1$*
,

+`1;1
;
D`1

```

Try it online! Link includes test cases. Edit: Saved 3 bytes thanks to @MartinEnder. Takes two comma-separated lists joined with a semicolon and returns `;` for a tie, `1;` if the first list's average is larger and `;1` if the second list's average is. Explanation: The first stage converts to unary. The second stage multiplies each element of the first list by the length of the second list, while the third stage multiplies each element of the second line by the length of the first. The totals on both sides are now the averages multiplied by the product of the length of the lists, so they are directly comparable. The fourth stage totals the values together and the fifth stage subtracts the totals from each other, while the final stage takes the sign of the result.

# Answer
> 1 votes
# Common Lisp, ~~74~~ 71 bytes

```
(defun g(x)(/(apply'+ x)(length x)))(defun f(x y)(signum(-(g x)(g y))))

```

Try it online!

# Answer
> 1 votes
## Haskell, 40 bytes

```
f x=sum x/sum(1<$x)
x!y=compare(f x)$f y

```

# Answer
> 1 votes
# C#, 75 bytes

```
using System.Linq;n=>m=>n.Average()>m.Average?1:m.Average()>n.Average()?2:0

```

# Answer
> 1 votes
# Gallina, 103 bytes

```
Definition a l := Z.div (fold_left Z.add l 0) (Zlength l).
Definition g l l' := Z.compare (a l) (a l').

```

# Answer
> 1 votes
# SQL (MS T-SQL), 99 bytes

```
select SIGN((x.a)-(y.a))from(select avg(a) a from(values<list1>)a(a))x,(select avg(a) a from(values<list2>)a(a))y

```

This returns `1` if the first list has a higher average, `0` for ties and `-1` for a heavier second list. Input uses this format: `(1),(2),(3)`, which I have substituted with the placeholders `<list1>` and `<list2>` in the code above.

# Answer
> 1 votes
# PowerShell 69 Bytes

```
param($n,$m)(($n|measure -A|% A*)-($m|measure -A|% A*))|% T*g "N;M;T"

```

Outputs `N` when 'N' is bigger, `M` for 'M', and `T` for a Tie.

gets the average using the builtin `Measure-Object -Average` command.

```
PS C:\Users\sweeneyc\Desktop> $t = @((7),(6)
(4,5),(4,4)
(2,3,4),(4,5,6)
(4,1,3),(7,3,2,1,1,2)
(100,390,1),(89,82,89)
(92,892),(892,92)
(10,182),(12,78,203,91))

for ($a=0;$a-lt14;$a+=2){
    .\avg.ps1 -a $t[$a] -b $t[$a+1]
}
A
A
B
T
A
T
T

```

# Answer
> 1 votes
# C# (.NET Core), 40 + 18 = 58 bytes

```
using System.Linq;n=>m=>n.Average().CompareTo(m.Average())

```

Try it online!

# Answer
> 1 votes
# Braingolf, 20 bytes

```
VRlm&+vlM&+vmc/v/c-s

```

Try it online!

Takes input multiplied by 1000. This can be increased to a higher power of 10 for better accuracy.

Takes first input as individual integers, and second input as an array of integers.

Outputs `1` if first array's average is larger

Outputs `-1` if second array's average is larger

Outputs `0` for tie

Only accurate for averages up to 3 decimal places (so if the average of the first list is `3.5554`, and the average of the second list is `3.5557`, this will output `0` for a tie)

## Explanation

```
VRlm&+vlM&+vmc/v/c-s  Implicit input from command-line args
                      2nd input as array is inputted to separate stack
VR                    Create stack3, return to stack1
  lm                  Push length of stack, move it to previous stack (wrap to stack3)
    &+                Sum entire stack
      v               Switch to stack2
       lM             Push length of stack, move it to next stack (stack3)
         &+           Sum entire stack
           v          Switch to stack3
            m         Move last item back to stack2
             c        Collapse stack3 into stack1
              /       Divide
               v      Switch to stack2
                /     Divide
                 c    Collapse into stack1
                  -   Subtract
                   s  Sign, positive becomes 1, negative becomes -1, 0 is not affected.
                      Implicit output of last item on stack

```

# Answer
> 1 votes
# Husk, 4 bytes

```
±¤-A

```

Try it online! Outputs -1 if **N** wins, 1 if **M** wins, and 0 if they are tied. Just takes the sign (`±`) of the difference (`-`) between the averages (`¤..A`) of the two lists.

# Answer
> 0 votes
# Python 3, 44 bytes

Takes two lists `n` and `m`. Returns `True` if the average of `n` is larger, `False` if that of `m` is, and throws a `ZeroDivisionError` if they are equal.

```
lambda n,m:1/(sum(n)/len(n)-sum(m)/len(m))>0

```

Try it online!

# Answer
> 0 votes
# Python 3, 87 101 84 Bytes

```
def c(M,N):
  j=sum(N)/len(N)-sum(M)/len(M);print('N')if j>0else print('MT'[j==0])

```

input is standard Python lists called `M` and `N` Output is name of larger list or `T` for tie.

Try it online!

## Explanation

Get an int to represent the comparison.

Compare in nested ternary.

Thank you @Morgan Thrapp for the improvements!

# Answer
> 0 votes
# Perl 5, 44 + 1 (`-a`) = 45bytes

```
push@a,eval(join'+',@F)/@F}{say$a[1]<=>$a[0]

```

Try it online!

Outputs `-1` if the first has a greater average, `1` if the second has the greater average, or `0` if the averages are equal.

# Answer
> 0 votes
# AWK, 69 bytes

```
{for(i=0;i++<NF;)d=M[NR-1]-(M[NR]+=$i/NF)}z=(NR-1)%2{$0=(d<0)-(d>0)}z

```

Try it online!

Input is by rows with odd row line numbers corresponding to `N` and even rows corresponding to `M`. Output is -1 if `N` is greater than `M`. 0 if they are equal, and 1 if `M` \> `N`. Output only occurs on even rows.

# Answer
> 0 votes
# J-uby, 24 bytes

Returns `1` if the first list has the greater average, `-1` if the second list, or `0` for a tie.

```
:*&:/%[:sum|Q,:+@]|+:<=>

```

Attempt This Online!

## Explanation

```
:* & :/ % [:sum | Q, :+@] | +:<=>

:* &                               # Map arguments with...
     :/ % [        ,    ]          #   Quotient of...
           :sum | Q                #     Sum of list converted to float and
                     :+@           #     Length of list
                          | +:<=>  # Then compare

```

# Answer
> 0 votes
# Arturo, 29 bytes

```
$=>[compare average&average&]

```

Try it

# Answer
> 0 votes
# Thunno 2, 4 bytes

```
€mẸṛ

```

Attempt This Online!

Gives `1` for N wins, `0` for tie, and `-1` for M wins.

#### Explanation

```
€mẸṛ  # Implicit input
€m    # Mean of each
  Ẹṛ  # Compare them
      # Implicit output

```

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


title: Determining Yes or No?

text:
# Question
Title: Determining Yes or No?
After inputting a string \[length 1-20\], only containing the chars **y** for yes and **n** for no, your program should output the result (y or n). Example input: `yynynynny` would output y.

The result is determined by combining the y's and n's in the following way:

* **y**es and **n**o equals **n**o
* **y**es and **y**es equals **y**es
* **n**o and **n**o equals **y**es

If the string contains more than 2 characters (likely...), the calculation would look the same. Examples:

* **y**es and **y**es and **n**o equals **n**o (because the no merges with the first yes to no. then there are no and yes left and the same thing happens again)
* **n**o and **n**o and **n**o equals **n**o (the first two no's merge to yes, then there are yes and no left, which emerge to no)

Example input with output:

* `yynynynynyyn` = n

Tip: have in mind that the order of the chars your program works off doesn't care. (for example you can read the input from back, or from behind, mix the letters, sort it, whatever. What counts is the correct ouptput) have fun!

Winning criteria: this is , so shortest code in byte wins.

# Answer
# Charcoal, 6 bytes

```
§yn№Ｓn

```

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

```
    Ｓ   Input string
   № n  Count number of `n`s
§yn     Circularly index into string `yn`
        Implicitly print appropriate character

```
> 10 votes

# Answer
# Octave, ~~29~~ 27 bytes

*Thanks to @RickHithcock for pointing out a mistake, now corrected. Also, 2 bytes off thanks to @StewieGriffin!*

```
@(s)'yn'(mod(sum(s+1),2)+1)

```

**Try it online!**

### Explanation

The ASCII code point of `'y'` is odd, and that of `'n'` is even. The code

1. adds `1` to each char in the input string to make `'y'` even and `'n'` odd;
2. computes the sum;
3. reduces the result to `1` if even, `2` if odd;
4. indexes (1-based) into the string `'yn'`.
> 15 votes

# Answer
# JavaScript (ES6), 28 bytes

Takes input as a string.

```
s=>'ny'[s.split`n`.length&1]

```

Try it online!

---

# JavaScript (ES6), 30 bytes

Takes input as an array of characters.

```
y=>'yn'[n=1,~~eval(y.join`^`)]

```

Try it online!
> 10 votes

# Answer
# Haskell, ~~33~~ 28 bytes

```
f a=cycle"yn"!!sum[1|'n'<-a]

```

Indexes the count of n's into the infinite list "ynynynyn…". Previous approach (33 bytes) was folding pairs of different elements to n, otherwise y:

```
f=foldl1(\a b->last$'y':['n'|a/=b])

```

Try it online!
> 9 votes

# Answer
# Jelly, 7 bytes

```
ċ”nị⁾ny

```

Try it online!

**ċ**ount number of **”n**, ndex into the string **⁾ny**. (with modulo 2)

---

```
ċḢịɗ⁾ny

```

Try it online!

{**ċ**ount number of, take the ead, then ndex into} string **⁾ny**.

---

```
OCSị⁾ny

```

Try it online!

Similar to the Octave answer above. Calculate **O**rd value, take the **C**omplement (for each ord value *x* calculate *1-x*), **S**um, then ndex into string **⁾ny**.
> 8 votes

# Answer
# APL (Dyalog Unicode), 15 bytes

```
'ny'[1+=/'y'=⍞]

```

Try it online!

Note: TIO defaults to `⎕IO = 1`. If run with `⎕IO←0`,

# APL (Dyalog Unicode), 13 bytes

```
'ny'[=/'y'=⍞]

```

Try it online!

This is the XNOR function (sometimes called EQV, especially in old BASICs.

### Decomposition/Analysis:

```
             ⍞  - Accept string input
         'y'=   - Compare it to the letter `y`. This "converts" the input
                  string into a vector of 1s and 0s where the 1s correspond
                  to 'y' and the 0s to 'n'.
       =/       - XNOR/EQV/equality reduction - converts the vector into a
                  single boolean value by evaluating e.g., 1 xnor 0 xnor 0
                  xnor 1 ...
     1+         - adds one for subscripting in ⎕IO = 1 environment. In
                  ⎕IO = 0, should be omitted (save 2 bytes)
    [         ] - subscript indicator - the expression, which should be
                  either a 1 or 2 (0 or 1 in `⎕IO = 0`), is now going to be
                  interpreted as a subscript of...
'ny'            - The string of possible results - a 0/1 is 'n', a 1/2 is 'y'

```
> 8 votes

# Answer
# Python 2, 29 bytes

```
lambda s:'yn'[s.count('n')%2]

```

Try it online!
> 7 votes

# Answer
# Pyth, 9 bytes

```
@"yn"l@\n

```

Try it here

### Explanation

```
@"yn"l@\n
     l@\nQ   Get the length of the intersection of the (implicit) input and "n".
@"yn"        Modular index into "yn".

```
> 6 votes

# Answer
# Japt, 8 bytes

```
"yn"gUèn

```

Try it online!

## Explanation:

```
"yn"gUèn
"yn"       String literal - "yn"
    g      Return the char at index:
      è      Number of matches where:
       n       "n" is found in
     U         Input

```

Japt uses index-wrapping, so if `Uèn` returns `2`, it will return `y` when getting the char from `"yn"`.
> 6 votes

# Answer
# dc, 39

```
?dsiZdsl[[]r1-d0<m]dsmxklixzll-2%B*C1+P

```

Input string is read from STDIN and should be in the form `[yynynynynyyn]`.

dc is not known for its string handling, but we have just enough here to get this to work. The approach here is to count the `n`s, and output `y` if even or `n` if odd. This is done by executing the input string as a macro. `dc` will output `'y' (0171) unimplemented` errors for all the `y`s and attempt to pop strings and print them for all the `n`s. So first we make sure we have plenty (total input string length) of empty strings `[]` on the stack to pop. Then we execute the input string and see how many `[]` are left on the stack. The original string length is subtracted from this to give the (-ve) total number of `n`s. The rest is arithmetic to do mod 2 and have the output come out right as ASCII `y` or `n`.

```
?dsi                                    # Read input string, duplicate, store in register i
    Zdsl                                # Get input length, duplicate, store in register l
        [         ]                     # define macro to:
         []                             #   push empty string
           r                            #   swap empty string and remaining length
            1-                          #   subtract 1 from length
              d0                        #   duplicate and compare with 0
                <m                      #   if >0 recursively call this macro again
                   dsmx                 # duplicate macro, store in register m and execute
                       k                # discard left-over 0
                        lix             # load input string and execute as macro
                           z            # get stack length
                            ll-         # load string length and subract
                               2%       # mod 2 (result is -ve because difference is -ve)
                                 B*     # multiply by 11 ('y' - 'n')
                                   C1+  # add 121 ('y')
                                      P # print result as ASCII char

```

Try it online!
> 6 votes

# Answer
# Perl 6, 21 bytes

```
{<y n>[.comb('n')%2]}

```

Try it

## Expanded:

```
{  # bare block lambda with implicit parameter $_

  # index into the list ('y', 'n')
  <y n>[

    .comb('n') # get every instance of 'n' (implicit method call on $_)
    % 2        # turn it into a count and get the modulus

  ]
}

```
> 5 votes

# Answer
# , ~~10~~ 9 bytes

```
{&'ny'@=/

```

Try it online!
> 5 votes

# Answer
# Java 8, 35 bytes

A decider for a regular language! I can do that.

```
s->s.matches("y*(ny*ny*)*")?'y':'n'

```

Try It Online
> 5 votes

# Answer
# Jelly,  ~~8~~  7 bytes

```
O‘Sị⁾ny

```

**Try it online!**
> 3 votes

# Answer
# , ~~46~~ 44 bytes

```
"if"(sum(1+utf8ToInt(scan(,"")))%%2,"n","y")

```

Try it online!

Down 2 bytes thanks to Giuseppe and ngm. Port of the Octave answer by Luis Mendo.
> 3 votes

# Answer
# Japt, 9 bytes

Oliver beat me to the shortest solution so here are a couple that are just a byte longer.

```
B*aUèÍu¹d

```

Try it

```
#ndB*UèÍv

```

Try it

---

## Explanations

```
              :Implicit input of string U
B             :11
 *            :Mutiplied by
  a           :  The absolute difference of 11 and
   UèÍ        :    The count of "n" in U
      u       :    Mod 2
       ¹d     :Get the character at that codepoint

```

```
              :Implicit input of string U
#n            :110
   B*         :Add 11 multiplied by
        v     :  The parity of
     UèÍ      :    The count of "n" in U
  d           :Get the character at that codepoint

```
> 3 votes

# Answer
# Perl 5, ~~19~~ 18 bytes

```
s/y|ny*n//g;s;^$;y

```

Try it online!

Similar to the Retina solution.
> 3 votes

# Answer
# ///, 24 bytes

```
/ny/n//nn/y//yy/y//yn/n/<input>

```

Try it online!

I believe this is the shortest possible /// program, as making a one character substitution either is useless (if you insert something in its place) or prevents it from being an output (if you insert nothing). However, since the program must deal with the two character cases, this should be minimal.

First removes all `y`s right of an `n`. Then replaces double `n`s with `y`s, taking advantage of LTR substitution. At this stage there are many `y`s followed by at most one `n`; we deduplicate the `y`s and if there is an `n` use it to mop the last `y` up.
> 3 votes

# Answer
# MATL, 8 bytes

```
Qs'ny'w)

```

Try it online!

Saved 2 bytes thanks to Luis Mendo! I previously used the explicit modulus command to get the index into the range `1,2`.

### Explanation

This uses the fact that MATL have modular indexing, which means that the 1st, 3rd, 5th ... element of the string `ny` are the same (`n`). So are the 2nd, 4th, 6th ... element of the string (`y`).

```
Q          % Grab input implicitly, and increment each ASCII-value by 1
           % This makes 'n' odd, and 'y' even
 s         % Take the sum of all elements
  'ny'     % Push the string `ny`
      w    % Swap the stack to facilitate the indexing
       )   % Take the n'th element of 'yn' and output it.

```
> 3 votes

# Answer
# Python 2, 26 bytes

```
lambda s:'yn'[int(s,35)%2]

```

Try it online!
> 3 votes

# Answer
# Retina, 11 bytes

```
y

nn

^$
y

```

Try it online!
> 2 votes

# Answer
# CJam, ~~20~~ 11 bytes

```
q~'ne="yn"=

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 8 bytes

```
'n¢„ynsè

```

Try it online!
> 2 votes

# Answer
# Java (OpenJDK 8), 143 bytes

```
a->{char[] u=a.toCharArray();if(u.length==1)return u[0];else{char b=(u[0]==u[1])?'y':'n',i=2;for(;i<u.length;b=(b==u[i++])?'y':'n');return b;}}

```

Try it online!

And if we take the input as a list:

# Java (OpenJDK 8), 118 bytes

```
u->{if(u.length==1)return u[0];else{char b=(u[0]==u[1])?'y':'n',i=2;for(;i<u.length;b=(b==u[i++])?'y':'n');return b;}}

```

Try it online!

### Explanation:

(input as string)

```
char[] u=a.toCharArray();  //turn string into char array
if(u.length==1){
    return u[0];      //if single letter, return it
}else{
    char b=(u[0]==u[1])?'y':'n';     //first two XNOR
    for(char i=2;i<u.length;b=(b==u[i++])?'y':'n');   //XNOR each remaining character
return b;    //return final result
}

```
> 2 votes

# Answer
## F#, ~~54~~ 50 bytes

-4 bytes thanks to Laikoni.

```
let c=Seq.reduce(fun a x->if a=x then 'y'else 'n')

```

Try it online!

`Seq.reduce` applies a function with an accumulator (`a`) to each element (`x`) in the string. For the first call, `a` is the first element in the string and `x` is the second element.
> 2 votes

# Answer
# Ruby, 24 bytes

```
->s{"yn"[s.count(?n)%2]}

```

Try it online!

A lambda taking a string and returning a string.
> 2 votes

# Answer
# Chip `-z`, 24 bytes

```
B}Zvv~vedSD~t
 `'bc af*g

```

Try it online!

### Explanation

This prints `'h'`, which is `'n' & 'y'`:

```
        d
       f*g

```

This converts the `'h'` to either an `'n'` or a `'y'`, according to whether the top-left wire is powered:

```
   vv~ve
   bc a

```

This is the xor counter, it powers the part described above as necessary:

```
B}Z
 `'

```

Finally, this causes the program to only print the last output and terminate when the input is exhausted (the `-z` flag adds a null terminator for this purpose):

```
         SD~t

```

Try replacing the `S` with a space to see the running result (the first `'y'` is extraneous, the second char matches the first input, and the third is the result of the first nontrivial calculation).
> 2 votes

# Answer
# Cubix, ~~24~~ 20 bytes

Been a while since I played with Cubix, so ...

```
i;iwW-?;o@..!'yv.n'|

```

Try it online!

Fairly naive implementation that steps through the string and compares the character against current result.

Interactive Demo

This unwraps onto the cube as follows

```
    i ;
    i w
W - ? ; o @ . .
! ' y v . n ' |
    . .
    . .

```
* `W` shift ip left
* `i` get the initial character
* `i?` get character and test for EOI (-1), also start of the loop
    + if EOI `;o@` remove TOS, output TOS as character and exit.
* else `-W!` subtract, shift ip left, test for truthy
    + if truthy `'n` push character n to TOS
    + if falsey `|!'y` reflect, test and push character y to TOS
* `v'.;w` redirect around the cube pushing and removing a . character and shifting right back into the loop
> 2 votes

# Answer
# Scala, 50 Bytes

```
def?(b:String)=b.reduce((r,l)=>if(r==l)'y'else'n')

```
> 2 votes

# Answer
# C (gcc), 52 50 bytes

Thanks to @Neil for the suggestions.

I borrowed the solution of counting `n`s, but instead of keeping a count, I just flip between the initial state and its inverse on an `n`.

```
i;f(char*a){for(i=*a;*++a;i^=*a&1?0:23);return i;}

```

Try it online!
> 2 votes

# Answer
# Befunge-98, 13 bytes

```
~k!aj@,+n'*b!

```

Try it online!

Basically inverts a 0 for every `n` in the input, and once more for good measure, then outputs `y` for `1` and `n` for `0`

```
~     Get inputted character
 k!   Invert the current value 110 (n) or 121 (y) + 1 times
   aj Jump past the rest of the code
~     Get input again. If no more input, reverse direction
            ! Invert the value once again
       +n'*b  Convert 0/1 to n/y
     @,       Output letter

```
> 2 votes

# Answer
# JavaScript, 3937 Bytes

```
s=>[...s].reduce((x,y)=>x==y?'y':'n')

```

Simple reduce function after splitting the input string.
> 2 votes

# Answer
# Clean, ~~26~~ 23 bytes

```
foldr1\a b|a==b='y'='n'

```

Try it online!
> 2 votes

# Answer
# Kotlin, 32 Bytes

```
"yn"[s.filter{it=='n'}.length%2]

```

Try it online!
> 2 votes

# Answer
## PHP, 77 70 Bytes

Try it online

**Code, recursive function**

```
function f($p){echo($p[1])?f(strtr($p,[yy=>y,yn=>n,ny=>n,nn=>y])):$p;}

```

**Explanation**

Why use `strtr` with a replace array like `[yy=>y,yn=>n,ny=>n,nn=>y]`, as the string the function takes can be shown like (example with test case `"yynynynynyyn"`)

```
  (y and y) and (n and y) and (n and y) and (n and y) and (n and y) and (y and n)

```

What does the function do?

```
  function f($p){
      echo($p[1])
           //The function will replace yy yn ny nn while strlen>1
           ?f(strtr($p,[yy=>y,yn=>n,ny=>n,nn=>y]))
           //Length greater than one, apply strtr
           :$p;
           //ok, just one letter left, "echo" it
     }

```

**With a loop, 83 Bytes**

Try it online

Simulates "run as pipe"

**Code**

```
<?php $p=$argv; while(strlen($p)>1){$p=strtr($p,[yy=>y,yn=>n,ny=>n,nn=>y]);}echo$p;

```

**Explanation**

It does the exact same thing as the recursive function

```
$p=$argv; //Accepting value from the script variable
while(strlen($p)>1){ //the loop ends when string length is one
   $p=strtr($p,[yy=>y,yn=>n,ny=>n,nn=>y]); //replace
}
echo$p; //echo the result.

```
> 1 votes

# Answer
# JavaScript, 44 bytes

```
(prompt()+"n").match(/n/gi).length%2?"y":"n"

```

Try it out on developer console.
> 1 votes

# Answer
# Husk, 8 bytes

```
!"ny"#'n

```

Try it online!
> 1 votes

# Answer
# Stax, ~~9~~ 7 bytes

```
Å8Dq↨W<

```

Run and debug it
> 1 votes

# Answer
# Mathematica, 59 bytes

Not the shortest but anyway

```
f[s_]:=Times@@StringCases[s,a={"y"->1,"n"->-1}]/.Reverse/@a

```

Call if `s` is your string of `y` and `n` (included between ".."), call `f[s]`.

All it does is to replace `y` by 1 and `n` by -1, then multiply them and replace the numbers back to strings.
> 1 votes

# Answer
# GolfScript, 14 bytes

```
'n'/,2%'ny'1/=

```

Try it online!
> 1 votes

# Answer
# PowerShell Core, ~~48~~ 43 bytes

```
"$args"|% t*y|%{$z=$z-xor$_-eq'n'};'yn'[$z]

```

Try it online!

Not the best method. Split into char array, use `-xor`, invert it implicitly at the end with the array lookup to get back a char.
> 1 votes

# Answer
# Go, 91 bytes

```
package main;import ."strings";type s=string;func f(S s)(s){return s("yn"[Count(S,"n")%2])}

```

105 bytes if `;func main(){}` is added; unsure of Gode Golf golang norms.
> 1 votes

# Answer
# Clojure, 40 bytes

```
(if(even?(count(filter #(= %\n)s)))\y\n)

```

Try it online!
> 1 votes

# Answer
C (GCC) **42 bytes**

```
g(char*a){return*a?"yn"[(g(a+1)^*a)&1]:1;}

```

Try in online!

Solution is simply based on XNOR operation.
> 1 votes

# Answer
# JavaScript (ES6), 71 bytes

```
f=a=>(a.split("").map(b=>(b=="y")?1:-1).reduce((b,c)=>b*c)==1)?"y":"n";

```
> 1 votes

# Answer
# Prolog (SWI), 56 bytes

```
[H,H]-121.
[_,_]-110.
[A]-A.
[A,B|T]-S:-[A,B]-C,[C|T]-S.

```

Try it online!
> 1 votes

# Answer
# Common Lisp, 52 bytes

```
(lambda(s)(reduce(lambda(a b)(if(eq a b)#\y #\n))s))

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 7 bytes

```
'n¢„ynè

```

Try it online!

```
'n¢„ynè  # full program
      è  # character in...
         # (implicit) commutative indèx...
   „yn   # literal...
      è  # at 0-based index...
         # (implicit) commutative, modular indèx...
  ¢      # number of...
'n       # literal...
  ¢      # s in...
         # implicit input
         # implicit output

```
> 0 votes

# Answer
# Thunno 2, 8 bytes

```
'nc`ynsi

```

Try it online!

Same as all the other answers

```
'nc`ynsi  # Implicit input
'nc       # Count of "n"s
      si  # modularly indexed
   `yn    # into the string "yn"
          # Implicit output

```
> 0 votes

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


title: Magic the Gathering: Friends or Foes?

text:
# Question
Title: Magic the Gathering: Friends or Foes?
In the card game Magic: the Gathering there are five different colours, which represent loose affiliations of cards, White (`W`), Blue (`U`), Black (`B`), Red (`R`) and Green (`G`). These are often arranged in a pentagon as follows:

```
  W
G   U
 R B

```

Both in the lore of MtG as well as in many card mechanics, adjacent colours in this pentagon are usually considered allies, and non-adjacent (sort of opposite) colours are considered enemies.

In this challenge, you'll be given two colours and should determine their relationship.

## The Challenge

You're given any two distinct characters from the set `BGRUW`. You may take these as a two-character string, a string with a delimiter between the characters, two separate character values, two singleton strings, two integers representing their code points, or a list or set type containing two characters/strings/integers.

Your output should be one of two distinct and consistent values of your choice, one which indicates that the two colours are allies and one which indicates that they are enemies. One of those two values may be no output at all.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is , so the shortest valid answer – measured in *bytes* – wins.

## Test Cases

There are only 20 possible inputs, so I'll list them all.

**Friends:**

```
WU   UB   BR   RG   GW   UW   BU   RB   GR   WG

```

**Foes:**

```
WB   UR   BG   RW   GU   BW   RU   GB   WR   UG

```

# Answer
> 81 votes
# JavaScript (ES6),  ~~26 23 17 15~~  14 bytes

Takes input as two ASCII codes in currying syntax `(a)(b)`. Returns `4` for friends or `0` for foes.

```
a=>b=>a*b/.6&4

```

Try it online!

### How?

*NB: only the integer quotient of the division by 0.6 is shown below.*

```
Combo | a  | b  | a*b  | / 0.6 | AND 4
------+----+----+------+-------+------
  WU  | 87 | 85 | 7395 | 12325 |   4
  UB  | 85 | 66 | 5610 |  9350 |   4
  BR  | 66 | 82 | 5412 |  9020 |   4
  RG  | 82 | 71 | 5822 |  9703 |   4
  GW  | 71 | 87 | 6177 | 10295 |   4
  UW  | 85 | 87 | 7395 | 12325 |   4
  BU  | 66 | 85 | 5610 |  9350 |   4
  RB  | 82 | 66 | 5412 |  9020 |   4
  GR  | 71 | 82 | 5822 |  9703 |   4
  WG  | 87 | 71 | 6177 | 10295 |   4
------+----+----+------+-------+------
  WB  | 87 | 66 | 5742 |  9570 |   0
  UR  | 85 | 82 | 6970 | 11616 |   0
  BG  | 66 | 71 | 4686 |  7810 |   0
  RW  | 82 | 87 | 7134 | 11890 |   0
  GU  | 71 | 85 | 6035 | 10058 |   0
  BW  | 66 | 87 | 5742 |  9570 |   0
  RU  | 82 | 85 | 6970 | 11616 |   0
  GB  | 71 | 66 | 4686 |  7810 |   0
  WR  | 87 | 82 | 7134 | 11890 |   0
  UG  | 85 | 71 | 6035 | 10058 |   0

```

# Previous approach, 15 bytes

Takes input as two ASCII codes in currying syntax `(a)(b)`. Returns `0` for friends or `1` for foes.

```
a=>b=>a*b%103%2

```

Try it online!

### How?

```
Combo | a  | b  | a*b  | MOD 103 | MOD 2
------+----+----+------+---------+------
  WU  | 87 | 85 | 7395 |    82   |   0
  UB  | 85 | 66 | 5610 |    48   |   0
  BR  | 66 | 82 | 5412 |    56   |   0
  RG  | 82 | 71 | 5822 |    54   |   0
  GW  | 71 | 87 | 6177 |   100   |   0
  UW  | 85 | 87 | 7395 |    82   |   0
  BU  | 66 | 85 | 5610 |    48   |   0
  RB  | 82 | 66 | 5412 |    56   |   0
  GR  | 71 | 82 | 5822 |    54   |   0
  WG  | 87 | 71 | 6177 |   100   |   0
------+----+----+------+---------+------
  WB  | 87 | 66 | 5742 |    77   |   1
  UR  | 85 | 82 | 6970 |    69   |   1
  BG  | 66 | 71 | 4686 |    51   |   1
  RW  | 82 | 87 | 7134 |    27   |   1
  GU  | 71 | 85 | 6035 |    61   |   1
  BW  | 66 | 87 | 5742 |    77   |   1
  RU  | 82 | 85 | 6970 |    69   |   1
  GB  | 71 | 66 | 4686 |    51   |   1
  WR  | 87 | 82 | 7134 |    27   |   1
  UG  | 85 | 71 | 6035 |    61   |   1

```

# Initial approach, 23 bytes

Takes input as a 2-character string. Returns `true` for friends or `false` for foes.

```
s=>parseInt(s,35)%9%7<3

```

Try it online!

# Answer
> 36 votes
# Python 2, 19 bytes

```
"WUBRGWGRBUW".count

```

Try it online!

An anonymous function: returns `1` for friends and `0` for foes.

# Answer
> 36 votes
# Jelly, 6 bytes

```
ạg105Ị

```

Takes two code points as argument. Yields **1** for friends, **0** for foes.

Try it online!

### Background

Let **n** and **m** be the code points of two input characters. By taking **|n - m|**, we need to concern ourselves only with all 2-combinations of characters. The following table shows all 2-combinations of characters the the corresponding absolute differences.

```
WU  2
UB 19
BR 16
RG 11
GW 16

WB 21
UR  3
BG  5
RW  5
GU 14

```

All *foe* combinations are divisible by **3**, **5**, or **7**, but none of the *friend* combinations this, so friends are exactly those that are co-prime with **3 × 5 × 7 = 105**.

### How it works

```
ạg105Ị  Main link. Left argument: n (code point). Right argument: m (code point)

ạ       Yield the absolute difference of n and m.
 g105   Compute the GCD of the result and 105.
     Ị  Insignificant; return 1 if the GCD is 1, 0 if not.

```

# Answer
> 21 votes
# Befunge-98, ~~13~~ 12 bytes

```
~~-9%5%3%!.@

```

Try it online!

Prints `0` for friends and `1` for foes

This uses the difference between the ASCII values of the letters.

If we take the `(((ASCII difference % 9) % 5) % 3)`, the values for the foes will be 0. Then, we not the value and print it.

Thanks to @Martin for the golf

# Answer
> 17 votes
# Jelly, ~~8~~ 7 bytes

Piggybacks off of Mistah Figgins's fabulous Befunge answer!

```
Iị390B¤

```

**Try it online!**

### How?

As Mistah Figgins noted the decision may be made by taking the absolute difference between the ASCII values mod 9 mod 5 mod 3 - 0s are then friends and 1s and 2s are enemies.

If we instead take the (plain) difference mod 9 we find that friends are 1s, 2s, 7s, and 8s while enemies are 3s, 4s, 5s, and 6s.

The code takes the difference with `I` and then indexes into the length 9 list `[1,1,0,0,0,0,1,1,0]`, which is 390 in binary, `390B`. The indexing is both modular (so effectively the indexing performs the mod 9 for free) and 1-based (hence the 1 on the very left).

# Answer
> 16 votes
# C++ template metaprogramming, 85 bytes

```
template<int A,int B,int=(A-B)%9%5%3>struct f;template<int A,int B>struct f<A,B,0>{};

```

less golfed:

```
template<int A, int B,int Unused=(((A-B)%9)%5)%3>
struct foe;
template<int A, int B>
struct foe<A,B,0>{};

```

As this is a metaprogramming language, a construct compiling or not is one possible output.

An instance of `f<'W','B'>` compiles if and only if `'W'` and `'B'` are foes.

Math based off Befunge answer.

Live example.

As C++ template metaprogramming is one of the worst golfing languages, anyone who is worse than this should feel shame. ;)

# Answer
> 14 votes
## Ruby, ~~22~~ 19 bytes

```
->x,y{390[(x-y)%9]}

```

Input: ASCII code of the 2 characters. Output: 1 for allies, 0 for enemies.

### How it works:

Get the difference between the 2 numbers modulo 9, use a bitmask (390 is binary 110000110) and get a single bit using the `[]` operator.

# Answer
> 10 votes
## CJam, 8 bytes

```
{*51%9>}

```

An unnamed block that expects two character codes on top of the stack and replaces them with `0` (friends) or `1` (foes).

Try it online!

### Explanation

Well, we've seen a lot of fun arithmetic solutions now, so I guess it's fine if I present my own one now. The closest to this I've seen so far is Steadybox's C solution. This one was found with the help of a GolfScript brute forcer I wrote some time ago for anarchy golf.

Here is what this one does to the various inputs (ignoring the order, because the initial multiplication is commutative):

```
xy   x    y    x*y   %51  >9

WU   87   85   7395    0   0
UB   85   66   5610    0   0
BR   66   82   5412    6   0
RG   82   71   5822    8   0
GW   71   87   6177    6   0
WB   87   66   5742   30   1
UR   85   82   6970   34   1
BG   66   71   4686   45   1
RW   82   87   7134   45   1
GU   71   85   6035   17   1

```

We can see how taking the product of the inputs modulo 51 nicely separates the inputs into large and small results, and we can use any of the values in between to distinguish between the two cases.

# Answer
> 9 votes
# Röda, ~~30~~ ~~22~~ 21 bytes

*Bytes saved thanks to @fergusq by using `_` to take the values on the stream as input*

```
{[_ in"WUBRGWGRBUW"]}

```

Try it online!

The function is run like `push "WU" | f` after assigning a name to the function

### Explanation

```
{                      /* Declares an anonymous function */
 [                 ]   /* Push */
  _ in                 /* the boolean value of the value on the stream is in */
      "WUBRGWGRBUW"    /* this string */
}

```

# Answer
> 9 votes
# 05AB1E, 10 bytes

Returns **0** for friend and **1** for foe.

```
‘Û‹BWR‘ûIå

```

Try it online! or as a Test suite

**Explanation**

```
‘Û‹BWR‘     # push the string "RUGBWR"
       û    # palendromize (append the reverse minus the first char)
        Iå  # check if input is in this string

```

# Answer
> 9 votes
# C, ~~33~~ ~~32~~ ~~29~~ ~~24~~ 22 bytes

```
#define f(k,l)k*l%51<9

```

Returns 1 if friends, 0 if foes.

# Answer
> 8 votes
# Vim, ~~22~~ 21 bytes

```
CWUBRGWGRBUW<esc>:g/<c-r>"/d<cr>

```

Input: a single line containing the two characters.

Output: empty buffer if friends, buffer containing `WUBRGWGRBUW` if enemies.

## Explanation

```
C                                 # [C]hange line (deletes line into " register and enters insert mode)
 WUBRGWGRBUW<esc>                 # insert this text and exit insert mode
                 :g/      /d<cr>  # delete all lines containing...
                    <c-r>"        # ... the previously deleted input

```

# Answer
> 8 votes
# Japt, 6 bytes

Inspired by @Martin Ender's solution.

Takes an array of two char codes as input.

```
×%51<9

```

Try it online! | Test Suite

Returns `true` for friends, `false` for foes.

**14-byte solution:**

Takes two char codes as input

```
nV a /3%3 f ¦1

```

Try it online! | Test Suite

### Explanation:

```
nV a /3%3 f ¦1
nV a             // Absolute value of: First input (implicit) - Second input
      /3%3 f     // Divide by 3, mod 3, then floor the result
             ¦1  // Return true if the result does not equals 1, otherwise return false

```

**12-byte solution:**

```
"WUBRGW"ê èU

```

Try it online! | Test Suite

### Explanation:

```
"WUBRGW"ê èU
"WUBRGW"ê     // "WUBRGW" mirrored = "WUBRGWGRBUW"
          èU  // Returns the number of times U (input) is found

```

Returns `1` for friends and `0` for foes.

**9-byte solution**:

Inspired by @Arnauld's solution.

```
*V%24%B%2

```

Test Suite

Returns `1` for friends, `0` for foes.

**11-byte solution:**

inspired by @Mistah Figgins's solution.

```
nV %9%5%3¦0

```

Test Suite

# Answer
> 8 votes
# Brain-Flak, ~~155, 147~~, 135 bytes

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

```

Try it online!

This is 134 bytes of code plus one byte penalty for the `-a` flag which enables ASCII input.

This works by finding the absolute difference between the inputs, and checking if they equal 2, 11, 16, or 19. If it does, the input is a friend, and it prints a 1. If it's not, it prints nothing. Since *nothing* in brain-flak corresponds to an empty stack, which is falsy, no output is a falsy value. (meta)

One thing I particularly like about this answer, is that the "absolute difference" snippet (that is, `(([(({}[{}]))<>])){({}())<>}{}{}<>{}`) is not stack clean, but it can still be used in this answer since we don't care which stack we end up on before encoding the possible differences.

On a later edit, I took advantage of this even more by abusing the leftovers on the stack that *doesn't* end up with the absolute difference on it. On the first revision, I popped both of them off to keep it slightly more sane. *Not* doing this gives two major golfs:

1. Obviously, it removes the code to pop them: `{}{}`, but more importantly:
2. It allows us to compress the `2, 11, 16, 19` sequence from

```
(((((()()))[][][](){})[][]())[])

```

to

```
(((([])[][][])[]())()()())

```

Fortunately, there is no extra code needed to handle these leftovers later, so they are just left on the alternate stack.

Since brain-flak is notoriously difficult to understand, here is a readable/commented version:

```
#Push the absolute difference of the two input characters. It is unknown which stack the result will end on
(([(({}[{}]))<>])){({}())<>}

#Push 2, 11, 16, 19, while abusing the values left on the stack from our "Absolute value" calculation
(((([])[][][])[]())()()())

#Pop a zero from the other stack and toggle back
<>{}<>

#While True
{

    #Move top over and duplicate the other top
    ({}<><(({}))>)

    #Equals?
    ({}[{}]<(())>){((<{}{}>))}{}

    #If so:
    {

        #Increment the number under the stack
        {}({}<({}())>)
        #Push a zero
        (<()>)

    }

    #Pop the zero
    {}

    #Go back to the other stack
    <>

#Endwhile
}

#Toggle back
<>

#Pop a zero
{}

```

# Answer
> 7 votes
# Jelly, 14 bytes

```
“WUBRG”wÐ€IAÆP

```

Returns `1` for enemies and `0` for friends.

Test suite at **Try it online!**

### How?

```
“WUBRG”wÐ€IAÆP - Main link                                   e.g. WG
“WUBRG”        - ['W','U','B','R','G']
       wÐ€     - first index of sublist mapped over the input     [1,5]
          I    - incremental differences                           -4
           A   - absolute value                                     4
            ÆP - is prime?                                          0

```

# Answer
> 6 votes
# CJam, ~~16~~ ~~12~~ ~~11~~ 10 bytes

*Golfed 4 bytes by using Mistah Figgins's algorithm*

*Saved 1 byte thanks to Lynn*

```
l:m9%5%3%!

```

Outputs `1` for enemy colours, `0` for ally colours.

Try it online! (Or verify all test cases)

**Explanation**

```
l           e# Push a line of input as a string
 :m         e# Reduce the string by subtraction (using the ASCII values)
   9%5%3%   e# Mod by 9, then by 5, then by 3. By doing this, enemy
            e#  pairs go to 0, and allies go to 1, 2, -1, or -2.
         !  e# Boolean negation

```

# Answer
> 6 votes
# 05AB1E, 7 bytes

```
$Æ105¿Ö

```

This is a port of my Jelly answer. Takes a list of code points as input. Prints **1** for friends, **0** for foes.

Try it online!

### How it works

```
$        Push 1 and [n, m] (the input).
 Æ       Reduce [n, m] by subtraction, pushing n - m.
  105¿   Take the GCD of n - m and 105.
      Ö  Test if 1 is divisible by the GCD (true iff the GCD is ±1).

```

# Answer
> 4 votes
# Java (OpenJDK 8), ~~28~~ 23 bytes

*-5 bytes thanks to fergusq*

```
"WUBRGWGRBUW"::contains

```

Try it online!

# Answer
> 4 votes
## Retina, 18 bytes

```
O`.
BR|BU|GR|GW|UW

```

Try it online!

Quite straight-forward: sorts the input and tries to match any of the sorted ally pairs against it. Unfortunately, I don't think that Retina's string-based nature allows for any of the more interesting approaches to be competitive.

As a sneak peek for the next Retina version, I'm planning to add an option which swaps regex and target string (so the current string will be used as the regex and you give it a string to check), in which case this shorter solution will work (or something along those lines):

```
?`WUBRGWGRBUW

```

# Answer
> 4 votes
# Brachylog, 10 bytes

A straightforward solution, no tricks involved.

```
p~s"WUBRGW

```

Try it online!

### Explanation

```
p               A permutation of the input
 ~s             is a substring of
   "WUBRGW      this string

```

# Answer
> 4 votes
# Jelly, 6 bytes

```
ạ:3%3Ḃ

```

For completeness's sake. Takes two code points as argument. Yields **0** for friends, **1** for foes.

Try it online!

### Background

Let **n** and **m** be the code points of two input characters. By taking **|n - m|**, we need to concern ourselves only with all 2-combinations of characters. The following table shows all 2-combinations of characters the the corresponding absolute differences.

```
WU UB BR RG GW  WB UR BG RW GU
 2 19 16 11 16  21  3  5  5 14

```

If we divide these integers by **3**, we get the following quotients.

```
WU UB BR RG GW  WB UR BG RW GU
 0  6  5  3  5   7  1  1  1  4

```

**1**, **4**, and **7** can be mapped to **1** by taking the results modulo **3**.

```
WU UB BR RG GW  WB UR BG RW GU
 0  0  2  0  2   1  1  1  1  1

```

Now we just have to look at the parity.

### How it works

```
ạ:3%3Ḃ  Main link. Left argument: n (code point). Right argument: m (code point)

ạ       Absolute difference; yield |n - m|.
 :3     Integer division by 3, yielding |n - m| / 3.
   %3   Modulo 3, yielding |n - m| / 3 % 3.
     Ḃ  Parity bit; yield |n - m| / 3 % 3 & 1.

```

# Answer
> 4 votes
# Cubix, 11 bytes

A Cubix implementation of Arnauld's solution.

```
U%O@A*'g%2W

```

# Usage

Input the two characters, and it outputs `0` for friends and `1` for foes. Try it here.

# Explanation

The code can be expanded like this.

```
    U %
    O @
A * ' g % 2 W .
. . . . . . . .
    . .
    . .

```

The characters are executed in this order (excluding control flow):

```
A*'g%2%O@
A         # Read all input as character codes
 *        # Multiply the last two character codes
    %     # Modulo the result by
  'g      #     103
      %   # And modulo that by
     2    #     2
       O  # Output the result ...
        @ # ... and terminate

```

# Answer
> 3 votes
# Python 2, 26 bytes

```
lambda a:a in"GWUBRGRBUWG"

```

Try it online!

# Answer
> 2 votes
# Python 2, ~~56~~ ~~46~~ 28 Bytes

```
print input()in"WUBRGWGRBUW"

```

Takes input as a string and returns `True` or `False` if it is in the string `b`. Try it here! Thanks to @Григорий Перельман for removing 10 bytes! Thanks @SparklePony for removing another 18 bytes!

# Answer
> 2 votes
## AWK, 23 Bytes

```
{$0="WUBRGWGRBUW"~$1}1

```

Example usage: awk '{$0="WUBRGWGRBUW"~$1}1' \<\<\< UB

This prints `1` if the pair is a friend, `0` otherwise. I wanted to do something clever, but everything I thought of would be longer.

# Answer
> 2 votes
# Jelly, 12 bytes

```
“WUBRGW”ŒBẇ@

```

Outputs `1` for allies, `0` for enemies.

Try it online!

**Explanation**

```
“WUBRGW”ŒBẇ@   Main link

“WUBRGW”       The string "WUBRGW"
        ŒB     Bounce; yields "WUBRGWGRBUW"
          ẇ@   Check if the input exists in that string

```

# Answer
> 2 votes
# Ruby, 28 bytes

Outputs true for friend, false for foe:

```
p'WUBRGWGRBUW'.include?$**''

```

The ungolfed version isn't much different:

```
p 'WUBRGWGRBUW'.include?(ARGV.join(''))

```

# Answer
> 2 votes
# 05AB1E, 7 bytes

Adaptation of the mod-trick from Jonathan's Jelly answer

```
Æ451bsè

```

Try it online! or as a Test suite

**Explanation**

```
 Æ        # reduced subtraction
  451b    # 451 to binary (111000011)
      sè  # index into this with the result of the reduced subtraction

```

# Answer
> 2 votes
# ///, 40 bytes

```
//i//R///G///W///U///B///i/1/WUBRGWGRBUW

```

Try it online!

Since /// has no other way of taking input, you need to put your input after the first /. An example of checking WG:

```
/WG/i//R///G///W///U///B///i/1/WUBRGWGRBUW

```

# Itflabtijtslwi, 52 bytes

```
GGjGGGGkGG/jk/i//R///G///W///U///B///i/1/WUBRGWGRBUW

```

Try it online!

Outputs a 1 if they are allies, otherwise outputs nothing.

The funny part is that it is actually a shorter answer than some "real" languages have.

You may be thinking, "You're not allowed to code the input in the program!" But you are allowed to do so if the language has no other way of getting input, as said here: meta.codegolf.stackexchange.com/a/10553/64159.

Thanks to Ørjan Johansen for the help with the Itflabtijtslwi port and making the interpreter. Very much.

# Answer
> 2 votes
## GolfScript, 7 bytes

```
~*51%9>

```

Takes two code points as input.

Try it online! (Test suite which converts the input format for convenience.)

A GolfScript port of my CJam answer (which technically, is a CJam port of the result of my GolfScript brute forcer... uhhh...).

However, since GolfScript gets modulo with negative inputs right, there's a fun alternative solution at the same byte count which uses `4` for foes instead of `1`:

```
~-)9%4&

```

Try it online!

```
xy   x    y    x-y    +1  %9  &4

WU   87   85     2     3   3   0
UB   85   66    19    20   2   0
BR   66   82   -16   -15   3   0
RG   82   71    11    12   3   0
GW   71   87   -16   -15   3   0
WB   87   66    21    22   4   4
UR   85   82     3     4   4   4
BG   66   71    -5    -4   5   4
RW   82   87    -5    -4   5   4
GU   71   85   -14   -13   5   4

```

# Answer
> 2 votes
# Java 7, 38 bytes

```
int b(int a,int b){return(a-b)%9%5%3;}

```

Port from *@Mistah Figgins*' Befunge-98 answer is the shortest in Java 7 from the answers posted so far.
As for the others:

**39 bytes:** Port from *@Arnauld*'s JavaScript (ES6) answer.

```
int a(int a,int b){return a*b%24%11%2;}

```

**39 bytes:** Port from *@MartinEnder*'s CJam answer

```
Object e(int a,int b){return a*b%51>9;}

```

**47 bytes:** Port from *@Steadybox*' C answer

```
Object d(int a,int b){return(a=a*b%18)>7|a==3;}

```

**52 bytes:** Port from *@Lynn*'s Python 2 answer

```
Object c(String s){return"WUBRGWGRBUW".contains(s);}

```

*NOTE: Skipped answers which uses primes / palindromes and alike, because those are nowhere near short in Java. ;)<br>~~TODO: Coming up with my own answer.. Although I doubt it's shorter than most of these.~~*

**Try all here.**

---

*EDIT: Ok, came up with something myself that isn't too bad:*

# 50 bytes:

```
Object c(int a,int b){return(a=a*b%18)>3&a<7|a<1;}

```

**Explanation:**

```
ab  a   b   a*b     %18

WU  87  85  7395    15
UB  85  66  5610    12
BR  66  82  5412    12
RG  82  71  5822    8
GW  71  87  6177    3
UW  85  87  7395    15
BU  66  85  5610    12
RB  82  66  5412    12
GR  71  82  5822    8
WG  87  71  6177    3

WB  87  66  5742    0
UR  85  82  6970    4
BG  66  71  4686    6
RW  82  87  7134    6
GU  71  85  6035    5
BW  66  87  5742    0
RU  82  85  6970    4
GB  71  66  4686    6
WR  87  82  7134    6
UG  85  71  6035    5

```

All enemies are either in the range 4-6 (inclusive) or 0.
EDIT2: Hmm.. I just noticed it's very similar to *@Steadybox*' answer.. :(

# Answer
> 2 votes
# PHP, 31 bytes

```
echo!strstr(WBGURWRUGBW,$argn);

```

Run with `echo AB | php -nR '<code>`, where `A` and `B` are the two colors.

`strtr` returns the string from the position where the input is found;
with `WBGURWRUGBW` as haystack this returns a truthy string if the colors are foes; empty string if not.

`!` turns the truthy string to `false`, resulting in empty output
and the empty string to `true`, resulting in output `1`.

# Answer
> 2 votes
# Brain-Flak, 78 bytes

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

```

Try it online!

This improves on DJMcMayhem's answer by streamlining the comparisons. It also uses the negative absolute value directly instead of using extra instructions to reach the positive absolute value.

# Answer
> 1 votes
# PowerShell, ~~42~~ ~~34~~ 32 bytes

```
'WUBRGWGRBUW'.indexof($args)-ge0

```

Try it online!

Input is as a single string (e.g., `RG`), that is stringified `$args` and used as the `.indexof()` parameter for the color string. If the substring is not found, `-1` is returned, so testing whether the result is `-g`reater-than-or-`e`qual to `0` suffices for a truthy/falsey output.

*Saved two more bytes thanks to Philipp Leiß.*

# Answer
> 1 votes
## Batch, 62 bytes

```
@set s=WUBRGWGRBUW
@call set t=%%s:%1=%%
@if %s%==%t% echo 1

```

Outputs `1` for foes, nothing for friends.

# Answer
> 1 votes
# PHP, 45 Bytes

I know if I use a mod solution from someone else, that I can do it much shorter.

the absolute difference mod 17 mod 5 is 1 or 2

```
<?=abs(ord($t=$argv[1])-ord($t[1]))%17%5+1&2;

```

golfed down by @Titus from 64 Bytes

```
<?=in_array((abs(ord(($t=$argv[1])[0])-ord($t[1]))%17)%5,[1,2]);

```

## PHP, 72 Bytes

the absolute difference mod 17 foes contains a digit between 3 and 5

```
<?=preg_match("#^[^3-5]+$#",(abs(ord(($t=$argv[1])[0])-ord($t[1]))%17));

```

## PHP, 88 Bytes

the absolute difference mod 17 friends have a digit sum of 2 or 7

```
<?=in_array(array_sum(str_split((abs(ord(($t=$argv[1])[0])-ord($t[1]))%17))),[2,7])?1:0;

```

# PHP \>= 7.1, 81 Bytes

```
$p=strpos($s=WUBRG,($i=$argv[1])[0]);echo$i[1]==$s[$p!=4?$p+1:0]|$i[1]==$s[$p-1];

```

http://sandbox.onlinephpfunctions.com/code/9136a36084ecb5b397466e839210b50a88d8fe98

# Answer
> 1 votes
# Java 8, ~~17~~ ~~16~~ 14 bytes

This is simply a Java lambda version of the same arithmetic solution everyone else is using. Takes two integral/character arguments containing the color codes as ASCII. Returns true if they are friends, false if foes.

Golfed:

```
a->b->a*b%51<9

```

Ungolfed:

```
import java.util.function.*;

public class MagicTheGatheringFriendsOrFoes {

  private static final char[][] FRIENDS = new char[][] { { 'W', 'U' }, { 'U', 'B' }, { 'B', 'R' }, { 'R', 'G' },
      { 'G', 'W' }, { 'U', 'W' }, { 'B', 'U' }, { 'R', 'B' }, { 'G', 'R' }, { 'W', 'G' } };

  private static final char[][] FOES = new char[][] { { 'W', 'B' }, { 'U', 'R' }, { 'B', 'G' }, { 'R', 'W' },
      { 'G', 'U' }, { 'B', 'W' }, { 'R', 'U' }, { 'G', 'B' }, { 'W', 'R' }, { 'U', 'G' } };

  public static void main(String[] args) {
    System.out.println("Friends: expect true");
    for (char[] friends : FRIENDS) {
      boolean result = f().apply(Integer.valueOf(friends[0])).apply(Integer.valueOf(friends[1]));
      System.out.println("(" + friends[0] + "," + friends[1] + ") = " + result);
    }

    System.out.println();
    System.out.println("Foes: expect false");
    for (char[] foes : FOES) {
      boolean result = f().apply(Integer.valueOf(foes[0])).apply(Integer.valueOf(foes[1]));
      System.out.println("(" + foes[0] + "," + foes[1] + ") = " + result);
    }
  }

  private static Function<Integer, IntFunction<Boolean>> f() {
    return a -> b -> a * b % 51 < 9;
  }
}

```

# Answer
> 1 votes
# S.I.L.O.S, 53 bytes

```
loadLine
a=get 256
b=get 257
a*b
a%103
a%2
printInt a

```

Try it online!

Input as a commmand line argument Please do note that this uses the method from the most upvoted answer

# Answer
> 1 votes
# bash, 23 bytes

```
[[ WUBRGWGRBUW =~ $1 ]]

```

Exits/returns 0 (success/true) if friends, 1 (failure/false) if enemies.

This works by using the input string (for example, `WU`) as a regular expression using bash's builtin `[[`, which tests various things, in this case, the `=~` operator of `[[` is used to see if the first string `WUBRGWGRBUW` matches the regex (input string). Since the regex is not anchored by default, so long as the input string occurs anywhere in the "checked" string, `[[` returns the status code 0, meaning the test result was true. If the input character pair did not occur anywhere in the string, it returns status code 1, meaning the test result was false. The tested string is a concatenation of all possible adjacent friend characters, so it's matched only by the friend-pair inputs.

Test:

```
for pair in WU UB BR RG GW UW BU RB GR WG WB UR BG RW GU BW RU GB WR UG
do
  bash -c '[[ WUBRGWGRBUW =~ $1 ]]' - $pair
  echo $pair $?
done

```

# Answer
> 1 votes
# OIL, 77 bytes

Third-worst answer, but hey, it's OIL. Commented for clarity (remove spaces and C++-style comments for execution)

```
WU //storage, this just nops
UB
BR
RG
GW
UW
BU
RB
GR
WG
5  // read user input into line 10 (overwriting this line)
10
10 // test if what's in line 10 (the user input) &
10
0  // is identical to what's in line 0 (the first string) *
26 // if so, jump to line 26 (marked with %)
17 // else, jump to the next line
8  // increment line 14 (marked with *)
14
10 // test if line 14 is identical to
14
11 // what's in line 11 (a "10")
27 // if so, we checked all strings; so jump to line 27 (marked with $)
24 // else jump to the next line
6  // jump to line 12 (marked with &)
12
4  // print what's in line 4 ("GW" ≙ friend) %
4  // print what's in line 0 ("WU" ≙ foe) $

```

Prints `GW` if the colours are allies, `WU` otherwise (and if any unexpected input occurs).

# Answer
> 1 votes
# Brain-Flak, 90 bytes

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

```

Try it online!

This beats the previous Brain-Flak answer by swapping getting the absolute value of the difference with creating negative copies of the differences to check. It also has slightly better number generation and difference checking

# Answer
> 1 votes
# Whitespace, 60 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   S _Read_input_as_character][T   T   T   _Retrieve_first_input][S N
S _Duplicate_first_input][S N
S _Duplicate_first_input][T N
T   S _Read_input_as_character][T   T   T   _Retrieve_second_input][T   S S N
_Multiply][S S S T  T   S S T   T   T   N
_Push_103][T    S T T   _Modulo][S S S T    S N
_Push_2][T  S T T   _Modulo][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.

Port of *@Arnauld*'s 15-bytes JavaScript answer, so also outputs `0` for friends and `1` for foes.

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

**Explanation in pseudo-code:**

```
Integer a = read STDIN as character
Integer b = read STDIN as character
Integer t = a * b
t = t % 103
t = t % 2
Print t as integer to STDOUT

```

# Answer
> 0 votes
# Pyth, 16 bytes

```
gx+J"WUBRGW"_JzZ

```

Test suite available online.

## Explanation

```
gx+J"WUBRGW"_JzZ
   J"WUBRGW"      store string in variable J
  +         _J    concat J and reversed J
 x            z   get index of input in this string
g              Z  return if index >= 0 (will be -1 if not found)

```

# Answer
> 0 votes
# JavaScript (ES6), 20 bytes

```
a=>b=>(a-b)%9%5%3!=0

```

```
let F = a=>b=>(a-b)%9%5%3!=0
let ch = [87, 85, 66, 82, 71];

console.log('Friends:');
console.log('WU/UW', F(ch[0])(ch[1]), F(ch[1])(ch[0]));
console.log('UB/BU', F(ch[1])(ch[2]), F(ch[2])(ch[1]));
console.log('BR/RB', F(ch[2])(ch[3]), F(ch[3])(ch[2]));
console.log('RG/GR', F(ch[3])(ch[4]), F(ch[4])(ch[3]));
console.log('GW/WG', F(ch[4])(ch[0]), F(ch[0])(ch[4]));

console.log('Foes:');
console.log('WB/BW', F(ch[0])(ch[2]), F(ch[2])(ch[0]));
console.log('UR/RU', F(ch[1])(ch[3]), F(ch[3])(ch[1]));
console.log('BG/GB', F(ch[2])(ch[4]), F(ch[4])(ch[2]));
console.log('RW/WR', F(ch[3])(ch[0]), F(ch[0])(ch[3]));
console.log('GU/UG', F(ch[4])(ch[1]), F(ch[1])(ch[4]));
```

Takes input as ascii character codes, passed in as `F(a)(b)` (one character each). Returns `true` for friends, `false` for foes.

Thanks to Mistah Figgins for the modulo idea.

# Answer
> 0 votes
## QBIC, 29 bytes

```
;?instr(@WUBRG`+@W`+_fB|,A)>0

```

Explanation:

```
;       Gets the color combination as one strintg, "UG"
?       Print --> will eventually yield -1 for allies and 0 otherwise
instr(  Get the index of one string in antother.
@WUBRG` The string to be searced is all allies, (@...` creates a string called B$)
+@W`      and an extra 'W' that we don't want to flip (prevents 'WW')
+_fB|    and all allies flipped --> WUBRGWGRBUW
,A)    The string to look for: "UG"
>0     If A is found in B+G+fB, this is >0, and PRINT will show -1 (QBasic's TRUE value)
       It prints 0 in all other cases.

```

This would be two bytes shorter if we could say that any positive value is true, and 0 is false...

# Answer
> 0 votes
## C#, 37 Bytes

```
(string s)=>"GWUBRGRBUWG".Contains(s)

```

# Answer
> 0 votes
# Perl 5, 18 bytes

```
$_=WUBRGWGRBUW=~$_

```

Try it online!

Takes input as a two letter string, upper case. Outputs 1 (true) for allies, nothing (false) for enemies.

# Answer
> 0 votes
# Thunno 2, 7 bytes

```
×.6/4Æ&

```

Try it online!

Link is to verify all test cases. Port of Arnauld's JS answer.

#### Explanation

```
×.6/4Æ&  # Implicit input as charcodes
×        # Multiply the two charcodes together
 .6/     # Divide this result by 0.6
    4Æ&  # Bitwise AND with 4
         # Implicit output

```

---
Tags: code-golf, game, decision-problem, card-games
---