title: Alex-style Addition

text:
# Question
Title: Alex-style Addition
Inspired by Alex's glorious Learn you an R for great good, we are going to humbly recreate Alex's "one true R program" -- but with a twist.

Alex-style Addition works like this -- it has a 90% chance of simply returning the sum of the two numbers given and a 10% chance of recursively Alex-adding the first number and the second number + 1. This means that, potentially, an addition could be off by 1 or more.

## Challenge

Write a full program or function that takes two integers and Alex-adds them as defined. You may assume that your program will not stack overflow if your language doesn't have tail recursion. (Note that you do not have to implement it recursively, as long as the probabilities are the same.)

## Reference Implementation (Groovy)

```
int alexAdd(int a, int b) {
  int i = new Random().nextInt(11);
  if(i == 1) {
    return alexAdd(a,b+1);
  } else {
    return a + b;
  }
}

```

Try this fiddle online.

## Leaderboard

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

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

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

# Answer
> 40 votes
# Pyth, 8

```
u+G!OTsQ

```

Try it online

This uses Pyth's second mode on reduce, that looks for repeated input then exits.

### Explanation

```
u+G!OTsQ  ##  Implicit: Q=eval(input())
u     sQ  ##  reduce with 2 arguments, which causes a loop until the reduce gets the
          ##  same argument twice
 +G       ##  lambda G,H: G + ...
   !OT    ##  boolean not of random value from 0 to 9 inclusive

```

If the extra alex-add occurs it will run again, but if not then it exits.

# Answer
> 22 votes
# R, ~~60~~ ~~47~~ 28 bytes

```
function(a,b)a+b+rgeom(1,.9)

```

This is an unnamed function object that accepts two numbers and returns a number. It does not use recursion.

As xnor pointed out in a comment, this problem can be viewed as simply adding two numbers plus a geometric random variable with failure probability 1/10.

Why is that true? Think about it in terms of recursion, as it's described in the post. In each iteration we have a 10% chance of adding 1 and recursing, and a 90% chance of exiting the function without further addition. Each iteration is its own independent Bernoulli trial with outcomes "add 1, recurse" (failure) and "exit" (success). Thus the probability of failure is 1/10 and the probability of success is 9/10.

When dealing with a series of independent Bernoulli trials, the number of trials needed to obtain a single success follows a geometric distribution. In our case, each recursion means adding 1, so when we do finally exit the function, we've essentially counted the number of failures that occurred before the first success. That means that the amount that the result will be off by is a random variate from a geometric distribution.

Here we can take advantage of R's expansive suite of probability distribution built-ins and use `rgeom`, which returns a random value from a geometric distribution.

Ungolfed:

```
f <- function(a, b) {
    a + b + rgeom(n = 1, prob = 0.9)
}

```

# Answer
> 13 votes
## Minkolang 0.14, ~~19~~ ~~11~~ 12 bytes

This is the "function" version; it assumes `a` and `b` are already on the stack, pops them off and pushes the modified version of `a+b`. The closest equivalent to functions in Minkolang is to use `F`, which pops off `b`,`a` and jumps to `(a,b)` in the codebox. Then when the program counter hits an `f`, it jumps back to where `F` was used.

```
(+$01$h`d)xf

```

This is the full program version, **15 bytes**. (`nn` takes two numbers from input and `N.` outputs the result and stops.)

```
nn(+$01$h`d)xN.

```

I stole the algorithm from Doorknob's answer; the while loop repeats so long as the generated random number is less than 0.1, adding 1 each time. Try it here (full program version) and run it 100 times here.

### Explanation

```
(              Open a while loop
 +             Adds the top two items of the stack
  $0           Pushes 0.1
    1$h        Pushes a random number between 0.0 and 1.0, inclusive
       `       Pops b,a and pushes a > b
        d      Duplicate the top of stack
         )     Close the while loop when the top of stack is 0
          x    Dump the extra, leading 0

```

The cleverest part here is `d`. The top of stack at that point in time will be either 0 or 1. If it's 0, the while loop exits. Otherwise, it continues. As I duplicate the top of stack, it will be `[a+b,1]` the second time through the loop, so the `+` at the beginning adds the 1 (and likewise for subsequent trips).

# Answer
> 12 votes
## CJam, ~~12~~ 11 bytes

```
{{+Amr!}h;}

```

Thanks to @MartinBütter for saving a byte with this super clever trick!

```
{         }
 {     }h    Do-while that leaves the condition on the stack.
  +          Add: this will add the numbers on the first iteration...
   Amr!      ... but a `1` (i.e. increment) on future ones.
         ;   Pop the remaining 0.

```

---

Old answer:

```
{+({)Amr!}g}

```

Try it online.

Explanation:

```
{          }  A "function."
 +            Add the input numbers.
  (           Decrement.
   {     }g   A while loop.
    )         Increment.
     Amr      Random number [0,9).
        !     Boolean NOT.

```

The basic algorithm is "while (0.1 chance), increment the number," which eliminates the need for the recursion.

# Answer
> 8 votes
# Javascript ES6, 38 bytes

```
f=(a,b)=>Math.random()<.1?f(a,b+1):a+b

```

# Answer
> 8 votes
## MATL, ~~14~~ ~~13~~ 12 bytes

```
is`r.1<tb+w]

```

This is just the loop method, add the inputs (entered as `[a b]`) then keep adding one while a uniform random number between 0 and 1 is less than 0.1. Full description below:

```
i         % input [a b]
s         % sum a and b
`         % do...while loop
  r       % get a uniformly distributed pseudorandom numbers between 0 and 1
  .1      % push 0.1 onto the stack
  <       % is the random number less than 0.1?
  t       % duplicate the T/F values
  b       % bubble a+b to the top of the stack
  +       % add the T/F to a+b
  w       % swap elements in stack to get the other T/F back to exit/continue the loop
]         % end

```

Took off 1 byte by changing input spec (from `ii+` to `is`).

---

The old way was based on taking the base-10 log of a random number between 0 and 1 to work out the amount to add to `a+b`, however it would only work up to 15 repetitions due to floating point accuracy.

```
iir10,2$YlZo-+

```

In this code, `10,2$YlZo-` does base-10 logarithm of the random number and rounds up to the nearest integer.

# Answer
> 8 votes
## TI-BASIC, 15 bytes

```
While rand<.1
Ans+.5
End
sum(Ans

```

This takes the input as a two-element list from `Ans`. While a random number is less than `0.1`, it does vectorized addition to `0.5` on the list. Increasing each element by `0.5` increases the sum by 1. I believe this is the shortest TI-BASIC solution.

The 9-byte program `sum(Ans)-int(log(10rand` doesn't work, because `rand` only has 14 digits of precision, and thus it can't give a number less than 10-14.

# Answer
> 7 votes
## Python, ~~66~~ ~~65~~ ~~64~~ 63 bytes

```
from random import*
g=lambda*s:randint(0,9)and sum(s)or g(1,*s)

```

Try it online

Thanks to Sherlock9 for the corrections and the byte saved.

Thanks to Mathias Ettinger for another byte.

Thanks to mbomb007 for a byte.

# Answer
> 7 votes
# Binary-Encoded Golfical, ~~32~~ 29+1 (`-x` flag) = 30 bytes

Hexdump (manually edited to correct for a bug in the image-to-binary part of the transpiler, which has since been fixed):

```
00 B0 02 15 14 0C 01 14 15 14 1B 1E 3A 14 0C 01
14 00 0A 14 38 00 01 23 1D 4C 14 17 14

```

This encoding can be converted back into the original graphical representation using the included Encoder utility, or run directly using the `-x` flag.

Original image:

Magnified 50x:

Explanation: The top row is the main block. It reads a number, copies it to the right, reads another number, adds them, copies the result to the right, does some RNG stuff, and, with probability 90%, prints the result of the addition. The rest of the time, it is sent to the bottom row, where it puts a one in the first cell and goes back to the main row just before the addition instruction (using a north turn then an east turn).

# Answer
> 6 votes
# Julia, 30 bytes

```
f(a,b)=rand()>0.9?f(a,b+1):a+b

```

This is a recursive function `f` that accepts two numbers and returns a number of the same type. It should work fine for any numeric type.

First we check whether a random float between 0 and 1 is greater than 0.9. If so, we recurse with a little extra somethin' somethin', otherwise we just add.

# Answer
> 6 votes
# Vitsy, ~~12~~ 10 bytes

```
aR)[1+0m]+
aR          Get a random number in [0,10)
  )[    ]   If its truncated int is 0, do the stuff in brackets.
    1+0m    Add 1 to one of the items and execute the 0th index of code.
         +  Add the numbers together.
```

Try it online!

Note that this has a *tiny* chance of a stack overflow error. We're talking `(.1)^400` chance. It also exits on error due to how I caused recursion.

# Answer
> 5 votes
# APL, 17 bytes

```
{1=?10:⍺∇⍵+1⋄⍺+⍵}

```

This is an unnamed dyadic function.

Ungolfed:

```
{1=?10:            ⍝ If a random number between 1 and 10 is 1,
       ⍺∇⍵+1       ⍝ Recurse on the inputs with one incremented
            ⋄⍺+⍵}  ⍝ Otherwise return the sum of the inputs

```

# Answer
> 5 votes
## Pyth, ~~14~~ 12 bytes

```
KsQW!OT=hK;K

```

My first real Pyth golf!

Takes input on STDIN in the format `a,b`.

Explanation:

```
KsQ       read STDIN, assign sum to variable K
W         while...
  !OT       not rand(10)
  =hK;      increment K
K         implicit-output of K

```

Thanks to @FryAmTheEggman for shaving off two chars by giving me a shorter way to increment a variable!

# Answer
> 4 votes
## Seriously, 10 bytes

```
,Σ1±╤_G_\+

```

This program generates a random variable from a geometric distribution by transforming a uniform distribution. It takes input as a list: `[2,3]` (braces optional). Try it online.

Explanation:

```
,Σ1±╤_G_\+
,Σ          get sum of input
  1±╤_      push ln(0.1)
      G_    push ln(random(0,1))
        \   floored division
         +  add

```

Given a random variable `X ~ Uniform(0, 1)`, it can be transformed to a random variable `Y ~ Geometric(p)` with the formula `Y = floor(log(X)/log(p))`.

# Answer
> 4 votes
# Lisp, 58 bytes

My first time writing Lisp!

```
(defun +(a b)(if(<(random 10)9)(- a(- b))(- a(-(+ b 1)))))

```

You can use this special addition exactly as you would usually add in Lisp:

```
> (+ 1 3)
4
> (+ 1 3)
5

```

I would love to hear suggestions as I am brand new to the language.

# Answer
> 3 votes
# Microscript, ~~29~~ 21 bytes

```
isi+vzr10!{l1vzr10!}l

```

I tried to make a Microscript II answer but for some reason I couldn't get the addition loop to work right :(

# Answer
> 3 votes
## Mathematica, 32 bytes

```
If[RandomReal[]<.1,+##,#0@##+1]&

```

Explanation:

```
                               &   A function returning
If[                           ]     if
   RandomReal[]                       a random number in [0,1)
               <                     is less than
                .1                    .1
                  ,                 , then
                   +                 the sum of
                    ##                all arguments
                      ,             , otherwise,
                       #0@            this function applied to
                          ##           all arguments
                            +        plus
                             1        one.

```

Note that this function works for any number of inputs.

# Answer
> 3 votes
# Mouse-2002, ~~41~~ ~~39~~ 38 bytes

No recursion.

```
&TIME &SEED ??&RAND k*&INT 9=[+1+!|+!]

```

Explained:

```
&TIME &SEED               ~ painfully obvious

? ?                       ~ get some input
&RAND 10 * &INT 8 >       ~ get a random number 0-1 * 10, make it an int & check if >8
[                         ~ if true
  + 1 + !                 ~ add the input then add 1 and print
|                         ~ else
  + !                     ~ add and print
]                         ~ endif
$                         ~ (implicit) end of program

```

---

Or, if you're a functional programming fanboy, and recursion is your deal then **57 bytes**:

```
&TIME &SEED #A,?,?;!$A&RAND k*&INT 9=[#A,1%,2%1+;|1%2%+]@

```

Explained:

```
&TIME &SEED            ~ painfully obvious

#A, ?, ?; !            ~ call with input & print

$A                     ~ begin a definition of a function A

  &RAND 10 * &INT 8 >  ~ same as above
  [
    #A, 1%, 2% 1 +;    ~ call with args and add 1
  |
    1% 2% +            ~ else just add
  ]
@                      ~ end func
$                      ~ as above

```

# Answer
> 3 votes
# TeaScript, 18 bytes ~~21~~

```
#$r<.1?f(l,i¬):l+i

```

This is a TeaScript function. Assign it to a variable or just run it directly.

Try it online

# Answer
> 3 votes
# Candy, 11 bytes

```
+#10H{.}10g

```

The long form is:

```
add          # add two numbers on the stack
number digit1 digit0 rand  # random int from 0 to 9
if           # if non-zero
  retSub     # terminate loop
endif
digit1       # push 1 to stack
digit0 goto  # loop to start

```

# Answer
> 3 votes
# APL (Dyalog Unicode), ~~13~~ 12 bytesSBCS

Basically the same as FryAmTheEggman's Pyth solution. -1 thanks to Erik the Outgolfer.

Anonymous tacit infix function.

```
{⍵+1=?10}⍣=+

```

Try it online!

`+` add the arguments

`{``}⍣=` apply the following function until two successive applications have the same result:

`?10` random integer in the range 1–10

`1=` is one equal to that? (i.e. 110th chance)

`⍵+` add the argument to that

# Answer
> 3 votes
# C, ~~71~~ ~~51~~ ~~39~~ 37 bytes

First code-golf, done in C... I don't think it will beat anything, and may be golfed down a lot

EDIT 3: cuted 2 bytes thanks to @Mego , by writing .1 instead of 0.1 and rewriting the ternary operator

```
a(x,y){return(rand()<.1?a(1,y):y)+x;}

```

EDIT 2: cuted 12 bytes, following gnu99, every variable is an int if not stated otherwise. Same goes for the return type of function

```
a(x,y){return rand()<0.1?a(x,y+1):x+y;}

```

EDIT : cuted 20 bytes, forgot that basic .h aren't necessary in C99 (using gcc for instance). It will produce a warning :)

```
int a(int x,int y){return rand()<0.1?a(x,y+1):x+y;}

```

71 Bytes solution :

```
#include <stdlib.h>
int a(int x,int y){return rand()<0.1?a(x,y+1):x+y;}

```

If you want to see lots of output, you can use the following code

```
#include <stdio.h>
#include <stdlib.h>
int a(int x,int y){return rand()<0.1?a(x,y+1):x+y;}

int main(void)
{
    int i,j;
    for(i=0;i<10;i++)
        for(j=0;j<10;j++)
            printf("%d + %d = %d\n",i,j,a(i,j));
    return 0;
}

```

# Answer
> 3 votes
# MATL, 12 ~~13~~ ~~14~~ bytes

```
r.1H$YlY[ihs

```

Input is of the form `[3 4]`, that is, a row vector with the two numbers.

### Example

```
>> matl r.1H$YlY[ihs
> [3 4]
7

```

### Explanation

This generates the geometric random variable without loops, by directly applying a a transformation to a uniform random variable. Note that log0.1 *a* is used instead of log *a* / log 0.1 to save 1 byte.

```
r        % random number with uniform distribution in (0,1)
.1       % number 0.1
H$       % specify two inputs for next function
Yl       % logarithm in specified base (0.1)
Y[       % floor. This produces the geometric random variable with parameter 0.1
i        % input vector of two numbers
h        % concatenate horizontally with the previously generated random value
s        % sum of vector elements

```

# Answer
> 3 votes
# Jelly, 7 bytes

```
‘⁵XỊ¤¿+

```

Try it online!

### How it works

```
‘⁵XỊ¤¿+  Main link. Arguments: n, m (integers)

    ¤    Combine the three atoms to the left into a niladic chain.
 ⁵       Yield 10.
  X      Pseudo-randomly generate a positive integer not greater than 10.
   Ị     Insignificant; test if the generated integer is 1 (or less).
     ¿   While chain yields 1:
‘          Increment n.
      +  Add m to the result.

```

# Answer
> 3 votes
# Java 8, ~~57~~ 56 bytes

4 years and no Java answer? Shame.

```
int a(int a,int b){return.1>Math.random()?a(a,b+1):a+b;}

```

Try it online!
-1 byte thanks to ceilingcat

# Answer
> 3 votes
# Vyxal `RṀ`, 7 bytes

```
+{₀℅¬|›

```

Try it Online!

# Vyxal, 8 bytes

```
+{₀ʁ℅¬|›

```

Try it Online!

```
+        # Add the two (implicitly input) numbers
 {       # While...
    ℅    # Random choice of...
   ʁ     # range 0 to...     (Unnecessary in flagged version)
  ₀      # 10 (exclusive)
     ¬   # Is 0
      |› # Increment

```

# Answer
> 3 votes
# Julia 1.0, 27 bytes

```
a\b=rand()<.1 ? 1+a\b : a+b

```

Try it online!

**Bonus: for 2 additionnal bytes, we can overwrite the `+` function for even more fun:**

```
a+b=rand()<.1 ? -~a+b : a- -b

```

Try it online!

# Answer
> 2 votes
## Seriously, 13 bytes

```
,,1W+9uJYWDkΣ

```

Uses a similar strategy to Doorknob's CJam answer (increment number while random float is less than 0.1), except it uses integers, and increments while random integer in `[0,9]` is less than 1. The lack of easy recursion hurts.

Try it online (needs manual input)

Explanation:

```
,,1W+9uJYWDkΣ
,,1            get input, push 1
   W     W     while loop:
    +            add top two elements
     9uJ         push a random integer in [0, 9]
        Y        push 1 if random value is falsey (0) else 0
          DkΣ  decrement top value and add everything together

```

The while loop leaves the stack like this:

```
n: the # of times the random value was < 0.1, plus 1
b: the second input
a: the first input

```

Shifting `n` up by 1 is necessary to get the while loop to run, since `0` is falsey. It's easily dealt with by decrementing `n` after the while loop, so the final result is `a + b + (n - 1)`.

# Answer
> 2 votes
# Perl 6, 26 bytes

Actually doing it recursively:

```
sub f{.1>rand??f |@_,1!![+] @_} # 31 bytes

```

---

Create a possibly empty sequence of `1`s followed by the arguments, then sum them all together.

```
{[+] {1}...^{rand>.1},|@_} # 26 bytes

```

( it can actually take any number of arguments )

usage:

```
# give the lambda a name
my &f = {...}

say f 1,2; # one of 3,4,5 ... *

```

# Answer
> 2 votes
## Pyth, 11 bytes

```
+sQ-18l`hO0

```

A direct Pyth port of my Python answer.

```
+             Add up
 sQ            the sum of the input and
   -           the difference of
    18          18 and
      l`         the string length of
        hO0       one plus a random number in [0,1)

```

# Answer
> 2 votes
# Octave, 20 bytes

```
@(a,b)a+b+geornd(.9)

```

Sum of the inputs, plus a random sample from the geometric distribution with parameter `0.9`.

# Answer
> 2 votes
# MATLAB , 51 bytes

```
function f(a,b)
if rand > .1;a+b;else;f(a,b+1);end

```

Result is found in the 'ans' automatic variable

# Answer
> 2 votes
# F#, 66 bytes

```
let rec a x y=(if(System.Random()).Next(10)=9 then a x 1 else x)+y

```

Try it online!

The `if` statement is like a function itself. If the random number is 9 (in the range \[0, 10)) then perform Alex-addition on `x` and 1 and return that value. Otherwise return just `x`.

Then add the result of the `if` statement to `y`, and return it.

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

```
+-{⌈10⍟?0}

```

Try it online!

# Answer
> 2 votes
# Brachylog, 10 bytes

```
∧9ṙ9&↰+₁|+

```

Try it online!

Takes input as a list of numbers. The TIO header runs the predicate on the input infinitely and prints the results.

```
  ṙ           A random integer from zero to
 9            nine
∧             which is not necessarily the input
   9          is nine,
    &         and the input
     ↰        passed through this predicate again
      +₁      plus one
        |     is the output, or, the input
         +    summed
              is the output.

```

# Answer
> 2 votes
# Factor, 41 bytes

```
: a ( x y -- z ) .1 [ 1 + a ] [ + ] ifp ;

```

Try it online!

`ifp` is a version of `if` that takes a probability instead of a boolean. Otherwise, it's just a simple recursive definition (which is verbose in Factor because of the mandatory stack effect declaration).

# Answer
> 1 votes
# Ruby, 32 bytes

Can't believe there was no Ruby answer. Here's a pretty basic lambda function:

```
f=->a,b{rand(10)<1?f[a,b+1]:a+b}

```

But why not do it properly? Here's some ungolfed meta-Alexification:

```
module Alex
  def +(other)
    other += 1 if rand(10) == 7
    super
  end
end

[Fixnum, Bignum, Float].each { |klass| klass.prepend(Alex) }

# testing
p 1000.times.count { 1 + 1 == 3 } #=> 87
p 1000.times.count { 1 + 1 == 4 } #=> 19
p 1000.times.count { 1 + 1.3 == 5.3 } #=> 1

```

# Answer
> 1 votes
# Tcl, 52 bytes

```
proc A n\ m {expr {rand()>.9?[A $n [incr m]]:$n+$m}}

```

Try it online!

# Answer
> 1 votes
# SmileBASIC 3, 54 bytes

Recursive function that takes two numbers.

```
DEF A(B,C)IF RND(10)THEN RETURN B+C
RETURN A(B,C+1)END

```

# Answer
> 1 votes
# Kotlin (1.3+), 60 bytes

```
fun a(b:Int,c:Int):Int=if((0..9).random()<1)a(b,c+1)else b+c

```

A solution that uses the new cross-platform random features added in Kotlin 1.3.

Try it online!

---

# Kotlin (JVM), 59 bytes

```
fun a(b:Int,c:Int):Int=if(Math.random()<.1)a(b,c+1)else b+c

```

Try it online!

Works on the JVM version because `java.lang.Math` is automatically imported.

---

# Kotlin (\<1.3), 65 bytes

This version is "cross-platform" Kotlin since it doesn't depend on any Java features.

```
fun a(b:Int,c:Int):Int=if((0..9).shuffled()[0]<1)a(b,c+1)else b+c

```

Try it online!

The "randomness" is obtained by shuffling the inclusive range `0..9`, which generates a `List<Int>`, and then checking the first element of that list. Assuming `shuffled()` is perfectly random (I have no idea how random it actually is) there is a 10% chance of the first element being 0.

# Answer
> 1 votes
# 05AB1E, ~~15~~ ~~14~~ ~~13~~ 8 bytes

```
+[TLΩ≠#>

```

-5 bytes thanks to *@Emigna* by placing the `>` (increment by 1) after the `#` (break loop).

Try it online.

**Explanation:**

```
            # Implicit inputs `a` and `b`
+           # Sum of these two inputs
 [          # Start an infinite loop
    Ω       #  Random integer
  TL        #   in the range [1, 10]
     ≠      #  If this integer isn't exactly 1:
      #     #   Stop the loop
       >    #  Increase the result by 1
            # Implicitly output the result

```

# Answer
> 1 votes
# Thunno 2, 7 bytes

```
+(Tɼḅ;⁺

```

Try it online!

#### Explanation

```
+(Tɼḅ;⁺  # implicit input
+        # add the two inputs together
 (       # (while)
  Tɼ     #   random item from [1..10]
    ḅ    #   is equal to 1
     ;   # (do)
      ⁺  #   increment
         # implicit output

```

# Answer
> 1 votes
# C (gcc), 33 bytes

```
f(x,y){x=rand()%10?x+y:1+f(x,y);}

```

Try it online!

# Answer
> 1 votes
# INTERCAL, 91 bytes

```
DOWRITEIN.1+.2PLEASE(1000)NEXTDO.1<-.3DO%10COMEFROM(1)(1)DON'T(1020)NEXTONCEPLEASEREADOUT.1

```

Try it online!

Explanation:

```
DO WRITE IN .1 + .2        // Get input numbers
PLEASE (1000) NEXT         // Add them together
DO .1 <- .3                // Copy the result into .1
DO %10 COME FROM (1)       // Loop back 10% of the time
(1) DON'T (1020) NEXT ONCE // Increment .1 every loop iteration except the first
PLEASE READ OUT .1         // Output result
                           // Fallthrough to stdlib syntax error/exit

```

# Answer
> 0 votes
# R 33 bytes

```
f=function(a,b)a+b+rbinom(b,b,.1)

```

Edit: now simulates recursive application of +1 for each 1 in b.

# Answer
> 0 votes
# Perl 5 `-p`, 23 bytes

```
$_+=<>;$_++while.1>rand

```

Try it online!

# Answer
> 0 votes
# Python 2, 63 bytes

Returns the result as a string.

```
from random import*
f=lambda a,b:random()>.1and`a+b`or f(a,b+1)

```

**Try it online!**

Test program showing probability distribution: **Try it online!**

# Answer
> 0 votes
# PowerShell Core, 46 bytes

```
param($a,$b)while(!(get-random 10)){++$a}$b+$a

```

Try it online!

# Answer
> 0 votes
# λ-2d, 100 squares

Found this language on Hackernews yesterday and I wanted to try it at a small program
You can test it by going to this page and going to "file" -\> "load JSON" with a file containing this content

```
{"22,6":"func_def","24,6":"func_def","23,6":"end_s","25,6":"end_s","26,6":"end_s","24,8":"func_call","24,11":"func_call","25,7":"wire_nw","24,7":"wire_se","25,8":"wire_sw","25,9":"wire_ns","24,10":"wire_sw","25,10":"func_call","23,9":"wire_ns","23,8":"wire_ns","23,7":"wire_ns","23,10":"wire_ne","25,11":"wire_nw","26,9":"wire_ns","26,8":"wire_ns","26,7":"wire_ns","26,10":"wire_nw","24,12":"op_plus","22,5":"wire_se","23,5":"label","24,5":[0,0,1,0,0,0,1,0,1,0,0,1,1,1,0,1,0,0,0,1,1,0,0,0,1],"32,8":"func_call","33,9":"func_call","33,8":"wire_sw","34,9":"wire_nw","34,8":"func_call","34,7":"func_def","35,7":"end_s","36,7":"end_e","35,8":"wire_sw","36,9":"func_call","35,9":"wire_ns","35,10":"wire_ne","36,10":"wire_nw","36,8":"func_def","37,8":"end_s","37,7":"wire_nw","37,6":"wire_ns","37,5":"joint_nse","38,6":"func_call","38,7":"op_plus","38,5":"wire_sw","39,6":"wire_sw","39,7":"wire_ne","40,7":"wire_nw","40,6":"func_call","40,5":"num_1","41,6":"wire_sw","38,8":"end_e","37,9":"wire_we","42,4":"wire_sw","39,4":"wire_we","40,4":"wire_we","41,4":"wire_we","36,4":"func_def","37,4":"end_s","38,4":"end_e","36,3":"wire_se","37,3":"label","38,3":[0,0,1,1,0,0,0,0,0,1,0,1,0,1,0,1,1,1,0,0,0,1,0,1,0],"24,9":[0,0,1,1,0,0,0,0,0,1,0,1,0,1,0,1,1,1,0,0,0,1,0,1,0],"33,16":"entry","34,16":"end_s","35,16":"end_e","36,16":"frame_tl","47,16":"wire_sw","47,18":"wire_nw","36,18":"wire_ne","36,17":"wire_ns","47,17":"wire_ns","37,16":"wire_we","38,16":"wire_we","39,16":"wire_we","40,16":"wire_we","41,16":"wire_we","42,16":"wire_we","43,16":"wire_we","44,16":"wire_we","45,16":"wire_we","46,16":"wire_we","46,18":"wire_we","45,18":"wire_we","44,18":"wire_we","43,18":"wire_we","41,18":"wire_we","40,18":"wire_we","38,18":"wire_we","37,18":"wire_we","39,18":"wire_we","42,18":"wire_we","35,20":"func_call","34,17":"wire_ns","34,18":"wire_ns","34,19":"wire_ns","34,20":"wire_ns","36,20":"wire_sw","36,21":"wire_nw","35,21":"wire_nswe","34,21":"wire_ne","35,22":"wire_nw","34,22":"wire_se","34,23":"wire_ns","34,24":"wire_ns","34,25":"wire_ne","35,25":"wire_nswe","35,24":"func_call","36,25":"wire_nw","36,24":"wire_sw","35,26":[0,0,1,0,0,0,1,0,1,0,0,1,1,1,0,1,0,0,0,1,1,0,0,0,1],"35,19":"num_1","35,23":"num_1","19,3":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"30,7":"func_call","31,9":"func_call","33,10":"op_if","30,8":"op_rand","30,6":"num_1","31,6":"num_1","32,7":"num_1","31,7":"wire_sw","31,8":"wire_ns","32,9":"wire_nw","31,10":"op_gt","41,7":"func_call","41,8":[0,0,1,1,0,0,0,0,0,1,0,1,0,1,0,1,1,1,0,0,0,1,0,1,0],"42,7":"wire_sw","42,8":"wire_ns","42,9":"wire_nw","41,9":"wire_we","39,8":"wire_we","40,8":"wire_sw","40,9":"wire_ne","39,9":"wire_sw","43,6":"wire_sw","42,6":"wire_ne","39,10":"wire_ne","43,10":"wire_nw","42,5":"wire_ns","43,7":"wire_ns","43,8":"wire_ns","43,9":"wire_ns","38,9":"wire_we","40,10":"wire_we","41,10":"wire_we","42,10":"wire_we"}

```

---

The screenshot and square count only show the function, the full program also have a call to the function using this structure

where you can replace both **42** by the input you want

---

## pseudo code using a jslike syntax

```
alexAdd = a => b => a + maybeInc(b)
maybeInc = c => random(11) > 1 ? c : maybeInc(c + 1)

```

---

You can get knowledge of how to read the program by reading the *cheatsheet* sample in the editor and the release blog post

# Answer
> 0 votes
# Raku, 30 bytes

```
{@_.sum+sum (.1>rand)xx*...!*}

```

Try it online!

# Answer
> 0 votes
# Swift, 64 bytes

```
func f(a:Int,b:Int)->Int{.random(in:0...9)==0 ?f(a:a,b:b+1):a+b}

```

SwiftFiddle link to try it yourself. The code should be fairly straightforward.

---
Tags: code-golf, arithmetic, random, recursion
---


title: Detect rotated strings

text:
# Question
Title: Detect rotated strings
Read two strings from `stdin`.
Output `Yes` if one string is a rotated version of the other.
Otherwise output `No`

**Testcases**

Input

```
CodeGolf GolfCode

```

Output

```
Yes

```

Input

```
stackexchange changestackex

```

Output

```
Yes

```

Input

```
stackexchange changestack

```

Output

```
No

```

Input

```
Hello World

```

Output

```
No

```

# Answer
## APL (28)

Takes input on two lines.

```
'No' 'Yes'[1+(⊂⍞)∊⌽∘A¨⍳⍴A←⍞]

```

Explanation:

* `A←⍞`: read a line of input and store it in A
* `⌽∘A¨⍳⍴A`: Rotate A by x, for each x in \[1..length A\]. Gives a list, i.e. `estT stTe tTes Test`
* `(⊂⍞)∊`: read another line of input, and see if it is in this list.
* `1+`: add one to this, giving 1 if the strings were not rotated and 2 if they were
* `'No' 'Yes'[`...`]`: Select either the first or second element from the list `'No' 'Yes'` depending on whether the strings were rotated or not.
* This value is output automatically.
> 7 votes

# Answer
## Ruby 49 41

```
a,b=$*;puts (a*2).sub(b,'')==a ?:yes: :no

```

Edit: replaced gets.split by $\*
> 19 votes

# Answer
## Python, 70 bytes

```
a,b=raw_input().split()
print ['No','Yes'][a in b*2and len(a)==len(b)]

```

Testing ...
> 7 votes

# Answer
**Python 70 Characters**

```
a,b=raw_input().split()
print'YNeos'[len(a)<>len(b)or a not in 2*b::2]

```

Thanks to gnibbler for the slice trick.
> 6 votes

# Answer
## J, 47

```
y=:>2{ARGV
(>1{ARGV e.1|.^:(i.#y)y){'No',:'Yes'

```
> 5 votes

# Answer
According to the spec (same string lengths):

### Perl, 42 43 chars

```
$.=pop;$_=(pop)x2;print+(qw'yes no')[!/$./]

```

If different sized strings are allowed, the solution would be:

### Perl, 47 chars

```
$.=(pop)x8;$_=(pop)x9;print+(qw'yes no')[!/$./]

```

rbo
> 5 votes

# Answer
## Golfscript, 31

```
' '/:)~,\,=)~.+\/,(&'Yes''No'if

```

This one check length first, so it should work as expected.
> 5 votes

# Answer
## J, 57

```
{&('No';'Yes')@-:/@:((/:~@(|."0 _~i.&$))&.>)&.(;:&stdin)_

```

Sample use:

```
$ echo -n CodeGolf GolfCode | jconsole rotate.ijs
Yes
$ echo -n stackexchange changestackex | jconsole rotate.ijs
Yes
$ echo -n stackexchange changestack | jconsole rotate.ijs
No
$ echo -n Hello World | jconsole rotate.ijs
No

```
> 4 votes

# Answer
## Windows PowerShell, 76

```
$a,$b=-split$input
('No','Yes')[+!($a.length-$b.length)*"$b$b".contains($a)]

```
> 3 votes

# Answer
## JavaScript, 51

```
function f(a,b)a&&(a+a).replace(b,"")==a?"Yes":"No"

```

JavaScript doesn't have a canonical host, so this answer is written as a function of two arguments. The score goes up to 60 if we disallow JS 1.7 features (expression closures).

In the SpiderMonkey shell this would be (for a score of 71):

```
[a,b]=readline().split(" ");print(a&&(a+a).replace(b,"")==a?"Yes":"No")

```
> 3 votes

# Answer
## Python, 66 63

```
a,b=raw_input().split()
print'YNeos'[a!=(2*a).replace(b,"")::2]

```

**Another solution in 69 char**

```
a,b=raw_input().split()
print['No','Yes'][a in b*2and len(a)==len(b)]

```
> 3 votes

# Answer
## J, 84

```
y=:(>1{ARGV),:(>2{ARGV)
((0{y)e.(y&((]$0{[),(]-~[:}.[:$[)$1{[)/.i.}.$y)){'No',:'Yes'

```
> 2 votes

# Answer
## Python, 71

```
a,b=raw_input().split()
print'Yes'if a in b*2and len(a)==len(b)else'No'

```
> 2 votes

# Answer
**JavaScript (120 chars)**

```
function f(a,b) {for (i=0,A=a.split("");A.join("")!=b&&i++<a.length;A.push(A.shift()));return A.join("")==b?'Yes':'No';}

```

Output:

```
f('CodeGolf','GolfCode'); //Yes
f('stackexchange','changestackex'); //Yes
f('stackexchange','changestack'); //No
f('Hello','World'); //No
f('nn','nBn'); //No

```
> 2 votes

# Answer
## Ruby, 58 (62) characters

```
a,b=gets.split;$><<(a.size==b.size&&/#{a}/=~b*2?:Yes: :No)

```

This solution assumes the input contains only alphanumeric characters (actually everything that doesn't have a special meaning inside a regular expression is ok).

A solution that doesn't have this constraint is 4 characters longer

```
a,b=gets.split;$><<(a.size==b.size&&(b*2).index(a)?:Yes: :No)

```
> 2 votes

# Answer
## Haskell (98 96 chars)

```
g x y@(t:r)(z:w)|x==y="Yes"|1>0=g x(r++[t])w
g _ _[]="No"
f(x:y:_)=g x y y
main=interact$f.words

```
> 2 votes

# Answer
## PHP, 61

```
<?echo preg_match('/^(.+)(.*) \\2\\1$/',fgets(STDIN))?Yes:No;

```
> 2 votes

# Answer
## Ruby, 41

```
puts gets =~ /^(.+)(.*) \2\1$/ ?:Yes: :No

```
> 2 votes

# Answer
# Q (~~50~~ 43 chars)

```
{`No`Yes x in((!)(#)y)rotate\:y}." "vs(0:)0

```
> 2 votes

# Answer
## bash 56

```
read a b
[[ $a$a =~ $b&&$b$b =~ $a ]]&&echo Yes||echo No

```
> 2 votes

# Answer
**Scala 78**

```
val b=readLine split " "
print(b(0).size==b(1).size&&(b(0)+b(0)contains b(1)))

```

It's a shame about the size check, without it the count drops to **54**

```
val a=readLine split " "
print(a(0)+a(0)contains a(1))

```
> 2 votes

# Answer
# GolfScript, 25 bytes

```
' '/~.2*@/''+='Yes''No'if

```

### How it works

```
             # STACK: "CodeGolf GolfCode"
' '/         # Split input string by spaces.
             # STACK: [ "CodeGolf" "GolfCode" ]
~            # Dump the array.
             # STACK: "CodeGolf" "GolfCode"
.            # Duplicate the topmost string.
             # STACK: "CodeGolf" "GolfCode" "GolfCode"
2*           # Repeat the topmost string.
             # STACK: "CodeGolf" "GolfCode" "GolfCodeGolfCode"
@            # Rotate the three topmost strings.
             # STACK: "GolfCode" "GolfCodeGolfCode" "CodeGolf"
/            # Split the second topmost string around the topmost one.
             # STACK: "GolfCode" [ "Golf" "Code" ]
''+          # Flatten the array of strings.
             # STACK: "GolfCode" "GolfCode"
=            # Check for equality.
             # STACK: 1
'Yes''No'if  # Push 'Yes' for 1, 'No' for 0.
             # STACK: "Yes"

```
> 2 votes

# Answer
# CJam, 21 bytes

```
r]r_,,\f{\{(+}*}_@+^!

```

Try it online!
> 2 votes

# Answer
# Jelly, ~~17~~ 13 bytes

```
ɠṙJɠeị“Yes“No

```

Try it online!

## How it works

```
ɠṙJɠeị“Yes“No - Main link. Takes no arguments
ɠ             - Read a line from STDIN
  J           - Indices; [1, 2, ..., len(S)]
 ṙ            - All rotations of S
   ɠe         - Read a line from STDIN; is that in the rotations?
     ị“Yes“No - Index that into ["Yes", "No"]

```
> 2 votes

# Answer
# Husk, 14 bytes

Not sure about the rules here, Husk doesn't do IO at all. The closest alternative is a function:

```
!w¨Ye∫No¨€U¡ṙ1

```

Try it online!

### Explanation

```
!w¨Ye∫No¨€U¡ṙ1
           ¡    -- iterate the following for ever:
            ṙ1  --   rotate string by 1
          U     -- only keep the longest prefix with unique elements
         €      -- is the argument in that list?
  ¨Ye∫No¨       -- compressed string: "Yes No"
 w              -- split on space
!               -- modular index (1-based)

```
> 2 votes

# Answer
**Lua 115 chars**

```
a,b=io.read():match"(%w+) (%w+)"c=b repeat c=c:sub(2,-1)..c:sub(1,1) s=s or a==c until b==c print(s and"Yes"or"No")

```
> 1 votes

# Answer
## C program - 146

```
char b[99],c[99],*p,*q;main(n){q=(p=b+(n=strlen(gets(c))))+n;sprintf(b,"%s%s"
,c,c);for(gets(c);p>b&&strcmp(p,c);--p,*--q=0);puts(p>b?"Yes":"No");}

```
> 1 votes

# Answer
## PHP, 82 characters

```
<?$s=split(" ",fgets(STDIN));echo str_replace($s[1],"",$s[0].$s[0])==$s[0]?Yes:No;

```
> 1 votes

# Answer
**perl, 123 chars**

```
@s1=split(//,shift);
$s2=shift;
$i=0;
while($i<=@s1){
    if(join("",@s1) eq $s2){die "yes";}
    unshift @s1,pop @s1;
    $i++;
}
die "no";

```
> 1 votes

# Answer
## Ruby, 30 37

```
gets
puts~/^(.+)(.*) \2\1$/?:Yes: :No

```

A version that prints "true" and "false" instead of "yes" and "no":

```
gets
p !! ~/^(.+)(.*) \2\1$/

```

Both of these work with different-length strings (unlike the old one)
> 1 votes

# Answer
## Python 2, 86 Characters

```
a,b=raw_input().split()
print"Yes"if any(a==b[n:]+b[:n]for n in range(len(a)))else"No"

```
> 1 votes

# Answer
Fixed to say Yes/No and improved (91 chars)

```
import List;f[a,b]|a`elem`[x++y|x<-tails b|y<-inits b]="Yes";f _="No";main=interact$f.words

```

original Haskell (92 chars) that says True/False

```
import Data.List;f(a:b:_)=any(a==)$zipWith(++)(tails b)(inits b);main=interact(show.f.words)

```
> 1 votes

# Answer
## Perl (just a quick fix)

A fix to rubber boots' solution, being a new user that I am I can't comment yet so I'll just post a new answer.

As the mentioned method uses a regular expression constructed from user input, it is possible to perform a small regex injection, as follows:

```
> perl -le '$.=pop;$_=(pop)x2;print+(qw/yes no/)[!/$./]' anything '.*'
yes

```

The fix is to use \Q (known also as quotemeta):

```
> perl -le '$.=pop;$_=(pop)x2;print+(qw/yes no/)[!/\Q$./]' anything '.*'
no

```

The code itself could be further shortened using 'say' but this is left as an exercise to the reader :)
> 1 votes

# Answer
# Clojure, 95

The function `rotated?` simply tests one string against all possible rotations of the other. Brute force.

```
(defn rotated?
  [a b]
  (let[l (count a)
       b (seq b)]
    (->> a cycle (partition l 1) (take l) (some #{b}))))

```

I personally don't care where the input strings come from, but if it has to be stdin...

```
(apply rotated? (.split (read-line) " "))

```

This would add 38 to character count, if strings were whitespace separated.

```
(rotated? (read-line) (read-line))

```

This would add 32 to character count, if strings were newline separated. The function `rotated?` works with any characters in the strings.
> 1 votes

# Answer
# Bash, 70 65 59 55 characters

new approach:

```
read a b;c=$a$a;[[ ${c/$b/} == $a ]]&&echo yes||echo no

```
> 1 votes

# Answer
## JavaScript - 66

```
p=prompt,a=p(),b=p();alert(!b.match(a)&&!!b+b.match(a)?'Yes':'No')

```
> 1 votes

# Answer
# 05AB1E, 20 bytes

Code:

```
DgFÀD²Qi"Yes",q}}"No

```

Uses **CP-1252** encoding. Try it online!
> 1 votes

# Answer
# Jelly, 16 bytes

```
ɠJṙ@€ɠe@ị“Yes“No

```

Try it online!

Many thanks to @cairdcoinheringaahing and @MrXcoder for helping me out in chat.

Explanation:

```
ɠ                   # The first string
  ṙ@€               # Rotated by...
 J                  #   The indexes of each element in the string
     ɠ              # The second string
      e@            # Exists in that list of strings.
                    # (either '0' or '1')
        ị           # Indexed into the list...
         “Yes“No    # ["yes", "no"]

```
> 1 votes

# Answer
# C (gcc), ~~118~~ ~~113~~ 111 bytes

-5 bytes thanks to ceilingcat

```
i,l,r;f(s,t)char*s,*t;{for(l=r=0,i=strlen(s);i--;)r=strncmp(s+i,t,++l)|strncmp(s,t+l,i)?r:3;puts(r+"No\0Yes");}

```

Try it online!
> 1 votes

# Answer
# jq -Rn, 62 + 4 = 65 bytes

```
len('if[inputs|explode|sort|implode]|.[0]==.[1]then"Yes"else"No"end')

```

As in the accepted answer, the two strings should be on separate lines. `-R` is used to avoid having to quote the input strings, and `-n` is used to disable the default input processing because `inputs` takes care of that.
> 1 votes

# Answer
# Stax, 11 bytes

```
Ä:∩ö┌┘/YJTI

```

Run and debug it

This program takes input on two lines.

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

```
:(      get all rotations
s|#     other input is a member of rotations?
`n!`    "Yes"
.No     "No"
?       (a ? b : c)

```

Run this one
> 1 votes

# Answer
# 05AB1E, 13 bytes

```
ā._Êßi„Noë”…Ü

```

Try it online or verify all test cases.

**Explanation:**

```
ā         # Push a list in the range [0, length] for the (implicit) input-string,
          # without popping this input-string itself
          #  i.e. "CodeGolf" → [1,2,3,4,5,6,7,8]
 ._       # Rotate the string that many times towards the left (vectorized)
          #  "CodeGolf" and [1,2,3,4,5,6,7,8] → ["olfCodeG","lfCodeGo","fCodeGol","CodeGolf",
          #                                      "odeGolfC","deGolfCo","eGolfCod","GolfCode"]
   Ê      # Check for each whether it's NOT equal to the second (implicit) input-string
          #  "GolfCode" → [1,1,1,0,1,1,1,1]
    ß     # Pop and push the minimum (to check if any are falsey)
          #  [1,1,1,0,1,1,1,1] → 0 (falsey)
     i    # If this minimum is truthy (so all rotations were unequal to the second input):
      „No #  Push string "No"
     ë    # Else:
      ”…Ü #  Push dictionary string "Yes"
          # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `”…Ü` is `"Yes"`.
> 1 votes

# Answer
# PHP, 57 bytes

Input via space-delimited string on `STDIN`, output to `STDOUT` is `"Yes"` or `"No"` string.

```
<?=strpos(($a=explode(' ',$argn))[1].$a[1],$a[0])?Yes:No;

```

Try it online!

Or with Default I/O input via command line args and output `truthy`/`falsey`.

# PHP, 37 bytes

```
<?=strpos(($a=$argv)[2].$a[2],$a[1]);

```

Try it online!

Or as a function:

# PHP, 41 bytes

```
function($a,$b){return strpos($b.$b,$a);}

```

Try it online!
> 1 votes

# Answer
# K3 / Kona, 28

```
{:[y _in![;x]'!#x;`Yes;`No]}

```
> 0 votes

# Answer
# Pyth, 18 bytes

```
?}zm.<QdlQ"YES""NO

```

Try it online

### Explanation

```
?}zm.<QdlQ"YES""NO
   m   dlQ            For each number in [1, ..., len(first input)]...
    .<Q               ... rotate the first input that many characters.
 }z                   Check if the second input is in that list.
?         "YES""NO    Return "YES" or "NO" appropriately.

```
> 0 votes

# Answer
# Brachylog, 17 bytes

```
~c₂ᵐ↔ᵈ∧"Yes"|∧"No

```

Try it online!

(If the input strictly has to be whitespace-separated, add two bytes to prepend `ṇ₁`, but note that the input still has to be quoted. Brachylog does not have any sort of direct access to stdin.)

Takes input as a list of two strings, and outputs through the output variable. The actual logic is all in the first six bytes, which succeed if the elements of the input are rotations of each other, and fail if they are not:

```
   ᵐ      Both strings in the input
~c₂       can be split into two pieces each
    ↔ᵈ    such that one string's two chunks are the other's swapped.

```

(`↔ᵈ` could just as well be `pᵈ`, `pᵛ`, or `oᵛ` which is what it was originally before I decided that `↔ᵈ` is more to the point.)

Although it would be possible to brute force rotating one of them until it matches, the number of rotations would need to be explicitly bounded, and on top of that just the effort required to separate out the two elements of the input list would be fairly costly. Since it's very easy to brute force partitions in Brachylog, the fact that a rotation is just as much taking one chunk off one end and moving it to the other as it is doing that to single characters however many times saves a lot of bytes.

With very flexible I/O, this could be as short as 5 bytes, taking one string through the input variable and the other through the output variable: `~c₂↔c`
> 0 votes

# Answer
# Thunno 2, 14 bytes

```
ż€ẒQM"YesNo"½i

```

Try it online!

#### Explanation

```
ż€ẒQM"YesNo"½i  # Implicit input
ż€Ẓ             # All rotations of the first input
   QM           # Is the second input NOT in it?
     "YesNo"½   # Push the list ["Yes", "No"]
             i  # Index the result into it
                # Implicit output

```
> 0 votes

# Answer
# Raku, 55 bytes

```
->\a,\b {my@a=a.comb;grep {b eq@a.rotate($_).join},^@a}

```

Returns a list of rotate positions that produce a match, which is truthy when non-empty.

If you have to output `Yes` or `No`, then the following takes 66 bytes:

```
->\a,\b {my@a=a.comb;<No Yes>[?grep {b eq@a.rotate($_).join},^@a]}

```

Try it online!
> 0 votes

# Answer
# , 28 bytes

```
(;:'No Yes'){::~[e.#\@]|."{]

```

Takes in input via function arguments.

Attempt This Online!

```
(;:'No Yes'){::~[e.#\@]|."{]
                           ]  NB. right arg
                   #\@]       NB. take the right arg then get the length of each prefix [1..len(y)]
                       |."{   NB. rotate the right by each element of the left, obtain all rotations
                [e.           NB. is the left arg a member of the resulting table?
(;:'No Yes')                  NB. split the string, returns an array of boxed strings
            {::~              NB. fetch using the boolen result of e., unlike {, this unboxes the result

```
> 0 votes

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


title: Tips for golfing in (,) in-paren-comma

text:
# Question
Title: Tips for golfing in (,) in-paren-comma
What tips do you have for golfing in (,)? I've found that there are so many ways to make code shorter, and I want more ways. I doubt there even are any tips for (,) that are applicable in the majority of programming languages, but if there are, feel free to include them.

Please, one tip per answer.

# Answer
# Nest Variables

When you have a variable (lets say A) with a index at least two more than a constant, fairly large variable B (or at least constant while you use A), you can usually instead have A be var\[B\]. Or, you can nest it more deeply.

For an example of how this can help, first assume all variables are constant, sufficiantly large, and sufficiantly distinct. Then, with only one set of parentheses characters you can only make one variable: `()`. With 2, `()()` and `(())`. With 3, `()()()`, `(())()`, `(()())`, `((()))`. With 4, `()()()()`, `(())()()`, `(()())()`, `((()))()`, `(()()())`, `((())())`, `((()()))`, `(((())))`, `(())(())`.

As you can see, it more than doubles for each new set of parentheses. However, since you usually don't have all constant variables, you should try out each reasonable combination of variable orderings to see which is smallest, and also keep in mind that constant variables greatly increase total accessable variables.
> 4 votes

# Answer
# Take advantage of flags

There are a ton of flags currently existing. 'D' is only useful for debugging, but all others can be useful. The 's'/'S' flags are only useful for golfing, and can help cut down on commas used. 'i' is useful when input is an integer, 'm' is useful for multiplication of negative numbers, 'n' and 'N' are useful for different output formats, and 'd' is useful only rarely.
> 2 votes

# Answer
# Nest print statements

When you are printing values of variables you could have a situation like this:

```
(,,(()))(,,(()()))

```

Where we are printing var1 followed by var2. Thanks to the fact that referring to a variable in the first argument does not require surrounding the variable address in parentheses, we could do this instead:

```
(,,(()(),,(())))

```

Where the inner statement prints var1 and returns the value of var2, to be printed by the outer statement for two less bytes.

With this approach it is still possible to do sums before printing, and this saved me lots of bytes in my (,) quine.
> 2 votes

# Answer
# Edit variables when you use them

Title is fairly self-explanatory. Instead of going `[something](var)[something](var,[something])`, you can usually shorten it to `[something](var,[something])[something]`, because var access happens before var setting (aka return value += vars\[var\_to\_access\] happens before vars\[var\_to\_access\] = value\_to\_set\_var\_to).

## An example

To output then increment variable one, instead of writing `(,,(()))((),(())())` write `(,,((),(())))`.
> 1 votes

---
Tags: code-golf, tips
---


title: How happy is this emoticon?

text:
# Question
Title: How happy is this emoticon?
In this challenge, submissions will be programs or function which, when given an emoticon such as `:-)`, `:(`, or `:D`, will rate their happiness from 0 to 3.

An emoticon will be one of the following:

* `:(`: 0
* `:|`: 1
* `:)`: 2
* `:D`: 3

Emoticons may also have noses (a `-` after the `:`).

Test cases:

```
:(  -> 0
:-| -> 1
:D  -> 3
:-) -> 2
:|  -> 1

```

This is a code golf challenge, shortest answer per language wins.

# Answer
> 18 votes
# Python 3, 26 bytes

```
lambda s:ord(s[-1])*2%19%4

```

Try it online!

$$ f(x) = (2x \bmod 19) \bmod 4 $$

# Answer
> 13 votes
# Ruby, 20 bytes

`s[-1].ord` will give us the codepoint of the last character in the string, which we can then plug into this formula: $$(160 \bmod c) \bmod 7 $$

```
->s{160%s[-1].ord%7}

```

Try it online!

# Answer
> 12 votes
# APL (Dyalog), ~~11~~ 8 bytes

*3 bytes saved thanks to @Bubbler!*

```
⊃'(|)'⍳⌽

```

Try it online!

```
       ⌽  reverse the string
⊃         take the last (now first) byte
 '(|)'⍳    index inside '(|)' (if not found ('D') returns the length (3))

```

# Answer
> 10 votes
# Python 3, ~~28~~ 27 bytes

```
lambda e:"(|)D".find(e[-1])

```

Try it online!

Because we don't care about the eyes/nose, we can just look at the mouth (the last character) and find its index in a string with all the mouths, ordered from saddest to happiest :) Thanks @Surculose Sputum!

# Answer
> 6 votes
# Python 3, 25 bytes

```
lambda s:160%ord(s[-1])%7

```

Try it online!

Math taken from @dingledooper

# Answer
> 5 votes
# C (gcc),  ~~37~~  33 bytes

*Saved 4 bytes on both versions thanks to @ceilingcat and @dingledooper*

I overlooked the rule about the optional nose, so this is not as effective as expected.

```
f(char*s){s=390%~-s[*++s%9<1]&3;}

```

Try it online!

### How?

Among the characters that we have to deal with, the hyphen is the only one whose ASCII code is congruent to \\$0\\$ modulo \\$9\\$. We use this property to decide whether we need to work on the second or the third character.

Given the ASCII code \\$n\\$ of the relevant smiley character, we apply the following formula to get the happiness:

$$h(n)=(390\bmod (n-1))\bmod 4$$

---

# C (gcc),  ~~36~~  32 bytes

Using Uriel's formula is 1 byte shorter.

```
f(char*s){s=s[*++s%9<1]*2%19&3;}

```

Try it online!

# Answer
> 5 votes
## Excel, 25 bytes

```
=FIND(RIGHT(A1),"(|)D")-1

```

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

```
⁽$9,4ḥ’

```

A monadic Link accepting a list of characters which yields an integer in \\$\[0,3\]\\$.

**Try it online!**

### How?

```
⁽$9,4ḥ’ - Link: list of characters, A
⁽$9     - base 250 literal = 10058
   ,4   - pair with four
     ḥ  - Jelly hash A using 10058 as a salt and [1,2,3,4] as the domain
      ’ - decrement

```

---

Previous **8** byter:

```
“|)D”iⱮS

```

Try it online!

### How?

```
“|)D”iⱮS - Link: list of characters, A             e.g. ":-)"     OR  ":-("
      Ɱ  - map across c in A with:
     i   -   first index of c in (or 0 if not found):
“|)D”    -     list of characters = "|)D"               [0,0,2]       [0,0,0]
       S - sum                                          2             0

```

# Answer
> 4 votes
# Bash \+ GNU utilities, 17 bytes

```
tr '(|)D:-' 0-3\

```

Try it online!

*Note: There's a space character after the backslash.*

Input on stdin, output on stdout.

The challenge doesn't specify the format of the output. Depending on the input, this program may print the output in either %2d or %3d format (that is, with one or two spaces before the 0, 1, 2, or 3).

If that's not acceptable, then

`tr -s '(|)D:-' 0-3\`

**(20 bytes)** always prints the digit in %2d format. (There's a space after the backslash here too.)

Or

`tr '(|)D:-' 0-4|tr -d 4`

**(23 bytes)** prints just the digit (with no spaces).

# Answer
> 4 votes
# Raku, 19 bytes

```
{TR:d/(|)D:-/0123/}

```

Try it online!

# Answer
> 4 votes
# Mornington Crescent, 1820 bytes

Try it online!

A port of @dingledooper's fantastic Ruby answer, which just so happens to work seamlessly in Mornington Crescent because of a convenient `7` in it. Props to them!

```
Take Northern Line to Leicester Square
Take Northern Line to Leicester Square
Take Piccadilly Line to Turnpike Lane
Take Piccadilly Line to Turnpike Lane
Take Piccadilly Line to Leicester Square
Take Northern Line to Leicester Square
Take Northern Line to Charing Cross
Take Northern Line to Charing Cross
Take Bakerloo Line to Baker Street
Take Bakerloo Line to Paddington
Take Bakerloo Line to Charing Cross
Take Bakerloo Line to Charing Cross
Take Northern Line to Moorgate
Take Circle Line to Moorgate
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to King's Cross St. Pancras
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Aldgate
Take Circle Line to Aldgate
Take Metropolitan Line to Chalfont & Latimer
Take Metropolitan Line to Preston Road
Take Metropolitan Line to Baker Street
Take Metropolitan Line to Preston Road
Take Metropolitan Line to Pinner
Take Metropolitan Line to Preston Road
Take Metropolitan Line to King's Cross St. Pancras
Take Victoria Line to Seven Sisters
Take Victoria Line to King's Cross St. Pancras
Take Circle Line to King's Cross St. Pancras
Take Metropolitan Line to Pinner
Take Metropolitan Line to Preston Road
Take Metropolitan Line to Pinner
Take Metropolitan Line to Preston Road
Take Metropolitan Line to King's Cross St. Pancras
Take Circle Line to King's Cross St. Pancras
Take Northern Line to Mornington Crescent

```

The only major thing I feel I need to point out is how I got `160` in the program. To do this, I took the first letter of `Paddington`, which gives an ASCII value of `80` when run through Charing Cross, then multiplied it by `2` in Chalfont & Latimer to get `160`. Subsequently, the program computes `160 % (ASCII of last character) % 7` via Preston Road, the formula found by @dingledooper.

# Answer
> 3 votes
# Retina 0.8.2, ~~16~~ 12 bytes

```
T`-:(|)D`__d

```

Try it online!

```
T`

```

Enter transliteration mode

```
(|)D`d

```

Replace the mouth character with the corresponding digit (0 to 3)

```
-:`__

```

Remove each of `-` and `:` from the string.

Implicitly output the result, which will be a single digit.

# Answer
> 3 votes
# MATL, 9 bytes

```
'|)D'jmfs

```

Try it online!

### Explanation

```
'|)D' % Push this string
j     % Read input as unevaluated string
m     % ismember: true for chars of the first string that are present in the second
f     % find: (1-based) indices of true entries. The result will have length 0 or 1
s     % sum. This is needed to transform an empty array into 0
      % Implicitly display

```

# Answer
> 3 votes
# Keg, `-hr`, 18 bytes

```
?^⑵¦P0|\1|R2|\¦3™

```

Try it online!

The same switch statement format, but with a different character checking criteria.

# Answer
> 3 votes
# 05AB1E, 8 bytes

```
θÇx19%4%

```

Try it online!

### Explanation

I used Uriel's formula.

```
θ        # Get mouth (last char)
 Ç       # ASCII value
  x      # Multiply by 2
   19%   # Modulo 19
      4% # Modulo 4

```

# Answer
> 2 votes
# Perl 5 `-p`, 24 bytes

```
s/.*(.)/ord($1)*2%19%4/e

```

Try it online!

Steals the math from @Uriel's Python answer

# Answer
> 2 votes
# Charcoal, 10 bytes

```
Ｉ⌕(|)D§Ｓ±¹

```

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

```
       Ｓ    Input string
      §     Cyclically indexed by
         ¹  Literal 1
        ±   Negated
 ⌕          Find index in
  (|)D      Literal string of mouths
Ｉ           Cast to string
            Implicitly print

```

# Answer
> 2 votes
# Io, 31 bytes

Io's strings are made of integers, so character-converting is unneccecary. Although Io doesn't allow us to index the last item of a sequence using `last()`...

```
method(x,160%x reverse at(0)%7)

```

Try it online!

# Answer
> 2 votes
# naz, 120 bytes

```
8a5m2x1v1a2x2v4a2x3v9a9a5a2x4v1x1f2r3x3v1e2f0x1x2f3x1v3e3x2v5e3x4v6e4f0x1x3f0m1o0x1x4f0m1a1o0x1x5f0m2a1o0x1x6f0m3a1o0x1f

```

**Explanation** (with `0x` commands removed)

```
8a5m2x1v                 # Set variable 1 equal to 40 ("(")
1a2x2v                   # Set variable 2 equal to 41 (")")
4a2x3v                   # Set variable 3 equal to 45 ("-")
9a9a5a2x4v               # Set variable 4 equal to 68 ("D")
1x1f                     # Function 1
    2r                   # Read the second byte in the input string, removing it
      3x3v1e             # Jump back to the start of the function if it equals variable 3
            2f           # Otherwise, jump to function 2
1x2f                     # Function 2
    3x1v3e               # Jump to function 3 if the register equals variable 1
          3x2v5e         # Jump to function 5 if the register equals variable 2
                3x4v6e   # Jump to function 6 if the register equals variable 4
                      4f # Otherwise, jump to function 4
1x3f                     # Function 3
    0m1o                 # Output 0
1x4f                     # Function 4
    0m1a1o               # Output 1
1x5f                     # Function 5
    0m2a1o               # Output 2
1x6f                     # Function 6
    0m3a1o               # Output 3
1f                       # Call function 1

```

# Answer
> 2 votes
# Pyth, 8 bytes

```
x"(|)D"e

```

Try it online!

### Exalanation

```
x"(|)D"e
          : Implicit evaluated input
       e  : Last element of input
 "(|)D"   : The string "(|)D"
x         : First occurrence of the last element of input in "(|)D"

```

# Answer
> 2 votes
# Red, 32 bytes

```
func[s][select"(0|1)2D3"last s]

```

Try it online!

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), ~~17~~ 14 bytes

Turns out Ranges finally started to actually exist and work! Thanks to an anonymous user for pointing this out (by proposing an edit, but anonymous users cannot comment...)

```
s=>160%s[^1]%7

```

Try it online!

# Answer
> 2 votes
# batch, ~~109 bytes~~ 99 bytes

```
@For %%G in ("(=0",")=2","D=3","|=1")Do @Set %%G
@Set "T=%~1"
@<Nul Call Call Set/P"=%%%T:~-1%%%"

```

# Answer
> 2 votes
# JavaScript, ~~35~~ ~~32~~ 29 bytes

I based the logic off of the Java solution submitted April 2 and edited April 8, by branboyer. I suppose it would be referred to as a port of their answer, but I don’t know exactly how that’s supposed to be marked.

```
a=>"(|)D".indexOf(a[2]||a[1])

```

An anonymous function, taking a string and returning an integer. Please help me shorten it further, I’m new to golfing code. Just the code, without the way of inputting (no idea how to get input in try it online) is at this Try it online link

# Answer
> 2 votes
# International Phonetic Esoteric Language, 11 bytes

```
iʁ2f{J}ⱱ4ⱱo

```

Based on Uriel's formula.

```
iʁ2f{J}ⱱ4ⱱo
iʁ          (split the face into it's ord values)
  2f        (mouth * 2)
    {J}ⱱ    (mod 19) (base 26)
        4ⱱ  (mod 4)
          o (print)

```

# Answer
> 2 votes
# sed, 20 bytes

```
y/(|)D/0123/;s/:-*//

```

Pretty self explanatory. Replaces the the "mouth" characters with numbers using the `y///` transform command and then strips off the eyes and the nose if they exist.

Try it online!

This is one byte longer, but perhaps it gets bonus points for having an emoticon in the code itself? `:-\`

```
y/(|)D/0123/;s/:-\?//

```

The shorter solution (16 bytes)

```
y/(|)D:-/0123  /

```

also works, but adds extra whitespace to each line of output. It also has two emoticons `D:` and `:-/`. :)

Try it online!

# Answer
> 1 votes
# Japt, 9 bytes

```
"(|)D"bUÌ

```

Try it

# Answer
> 1 votes
# Erlang (escript), 32 bytes

The verbosity offseted the bytecount.

```
h(I)->160rem lists:last(I)rem 7.

```

Try it online!

# Answer
> 1 votes
# , 7 bytes

```
☻M:ù·±♥

```

Uncompressed:

```
(|)D"azx

```

## Explanation

```
         % Implicit quote
(|)D"    % The string "(|)D"
     az  % The last item of the input
       x % Where is ^ in the above string?

```

# Answer
> 1 votes
# , ~~10~~ 9 bytes

-1 byte thanks to FrownyFrog ang Bubbler

```
'(|)'i.{:

```

Try it online!

# Answer
> 1 votes
# GolfScript, 11 bytes

```
)3?11%2/(p;

```

I'm convinced my method is the smallest possible, but this isn't the best possible one - just one of the earliest low-value ones.

```
)3?11%2/(p;
)           #Pop the last element of the string (as ascii value)
 3?         #Cube the number
   11%      #Modulo 11
      2/    #Divide by 2 (round down)
        (   #Decrement by one (gotta be 0 1 2 3, not 1 2 3 4)
         p; #Print the value we want, and shunt the rest of the stack

```

I used the following TIO to search for answers, and 11 popped up quite early. I also tried squares and higher powers, but they weren't as clean and short.

Try it online!

Every case!

# Answer
> 1 votes
# Raku `-p` 23 Bytes -\> 19 Bytes

```
$_=(4-.ords[*-1]*2%5)%4

$_=160%.ords[*-1]%7      #(with @dingledooper's formula)

```

# Answer
> 1 votes
# PowerShell, 16 bytes

```
2*$args[-1]%19%4

```

Try it online!

PowerShell port of the modulo formula going around. Takes input via splatting

# Answer
> 1 votes
# Wolfram Language (Mathematica), 38 bytes

```
Mod[2Last@ToCharacterCode@#,19]~Mod~4&

```

Try it online!

This borrows Uriel's formula, which happens to be the same length as dingledooper's, but I can't help but wonder if another formula would be shorter. I will investigate.

For comparison, here's the string indexing solution (51 bytes):

```
("(|)D"~StringPosition~Last@Characters@#)[[1, 1]]-1&

```

Try it online!

# Answer
> 1 votes
# MAWP, 27 bytes

```
|2W!!92W1MP92W1MWA!!4P4WA:.

```

Try it!

# Answer
> 1 votes
## JavaScript, 2335

`(・・?` Did somebody say emoticons?

```
a =
// The function:
(w)=>{(笑)=(w);ﾟωﾟﾉ= /｀ｍ´）ﾉ ~┻━┻   //*´∇｀*/ ['_']; o=(ﾟｰﾟ)  =_=3; c=(ﾟΘﾟ) =(ﾟｰﾟ)-(ﾟｰﾟ); (ﾟДﾟ) =(ﾟΘﾟ)= (o^_^o)/ (o^_^o);(ﾟДﾟ)={ﾟΘﾟ: '_' ,ﾟωﾟﾉ : ((ﾟωﾟﾉ==3) +'_') [ﾟΘﾟ] ,ﾟｰﾟﾉ :(ﾟωﾟﾉ+ '_')[o^_^o -(ﾟΘﾟ)] ,ﾟДﾟﾉ:((ﾟｰﾟ==3) +'_')[ﾟｰﾟ] }; (ﾟДﾟ) [ﾟΘﾟ] =((ﾟωﾟﾉ==3) +'_') [c^_^o];(ﾟДﾟ) ['c'] = ((ﾟДﾟ)+'_') [ (ﾟｰﾟ)+(ﾟｰﾟ)-(ﾟΘﾟ) ];(ﾟДﾟ) ['o'] = ((ﾟДﾟ)+'_') [ﾟΘﾟ];(ﾟoﾟ)=(ﾟДﾟ) ['c']+(ﾟДﾟ) ['o']+(ﾟωﾟﾉ +'_')[ﾟΘﾟ]+ ((ﾟωﾟﾉ==3) +'_') [ﾟｰﾟ] + ((ﾟДﾟ) +'_') [(ﾟｰﾟ)+(ﾟｰﾟ)]+ ((ﾟｰﾟ==3) +'_') [ﾟΘﾟ]+((ﾟｰﾟ==3) +'_') [(ﾟｰﾟ) - (ﾟΘﾟ)]+(ﾟДﾟ) ['c']+((ﾟДﾟ)+'_') [(ﾟｰﾟ)+(ﾟｰﾟ)]+ (ﾟДﾟ) ['o']+((ﾟｰﾟ==3) +'_') [ﾟΘﾟ];(ﾟДﾟ) ['_'] =(o^_^o) [ﾟoﾟ] [ﾟoﾟ];(ﾟεﾟ)=((ﾟｰﾟ==3) +'_') [ﾟΘﾟ]+ (ﾟДﾟ) .ﾟДﾟﾉ+((ﾟДﾟ)+'_') [(ﾟｰﾟ) + (ﾟｰﾟ)]+((ﾟｰﾟ==3) +'_') [o^_^o -ﾟΘﾟ]+((ﾟｰﾟ==3) +'_') [ﾟΘﾟ]+ (ﾟωﾟﾉ +'_') [ﾟΘﾟ]; (ﾟｰﾟ)+=(ﾟΘﾟ); (ﾟДﾟ)[ﾟεﾟ]='\\'; (ﾟДﾟ).ﾟΘﾟﾉ=(ﾟДﾟ+ ﾟｰﾟ)[o^_^o -(ﾟΘﾟ)];(oﾟｰﾟo)=(ﾟωﾟﾉ +'_')[c^_^o];(ﾟДﾟ) [ﾟoﾟ]='\"';(ﾟДﾟ) ['_'] ( (ﾟДﾟ) ['_'] (ﾟεﾟ+(ﾟДﾟ)[ﾟoﾟ]+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ (ﾟｰﾟ)+ (ﾟΘﾟ)+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ ((ﾟｰﾟ) + (ﾟΘﾟ))+ (ﾟｰﾟ)+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ (ﾟｰﾟ)+ ((ﾟｰﾟ) + (ﾟΘﾟ))+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ ((o^_^o) +(o^_^o))+ ((o^_^o) - (ﾟΘﾟ))+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ ((o^_^o) +(o^_^o))+ (ﾟｰﾟ)+ (ﾟДﾟ)[ﾟεﾟ]+((ﾟｰﾟ) + (ﾟΘﾟ))+ (c^_^o)+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟｰﾟ)+ ((ﾟｰﾟ) + (o^_^o))+ (ﾟДﾟ)[ﾟεﾟ]+((ﾟｰﾟ) + (ﾟΘﾟ))+ (c^_^o)+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ ((ﾟｰﾟ) + (o^_^o))+ (ﾟｰﾟ)+ (ﾟДﾟ)[ﾟεﾟ]+((ﾟｰﾟ) + (ﾟΘﾟ))+ (ﾟΘﾟ)+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ (c^_^o)+ (ﾟｰﾟ)+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟｰﾟ)+ ((ﾟｰﾟ) + (o^_^o))+ (ﾟДﾟ)[ﾟεﾟ]+((ﾟｰﾟ) + (ﾟΘﾟ))+ ((o^_^o) +(o^_^o))+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ ((ﾟｰﾟ) + (ﾟΘﾟ))+ (ﾟΘﾟ)+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ ((ﾟｰﾟ) + (ﾟΘﾟ))+ ((o^_^o) +(o^_^o))+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ (ﾟｰﾟ)+ (ﾟｰﾟ)+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ (ﾟｰﾟ)+ ((ﾟｰﾟ) + (ﾟΘﾟ))+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ ((ﾟｰﾟ) + (o^_^o))+ (c^_^o)+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ (ﾟΘﾟ)+ ((ﾟｰﾟ) + (o^_^o))+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ (ﾟｰﾟ)+ ((o^_^o) +(o^_^o))+ (ﾟДﾟ)[ﾟεﾟ]+((ﾟｰﾟ) + (ﾟΘﾟ))+ (c^_^o)+ (ﾟДﾟ)[ﾟεﾟ]+(oﾟｰﾟo)+ ((ﾟｰﾟ) + (o^_^o))+ (ﾟДﾟ) .ﾟΘﾟﾉ+ (ﾟΘﾟ)+ (ﾟΘﾟ)+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ (o^_^o)+ (o^_^o)+ (ﾟДﾟ)[ﾟεﾟ]+((o^_^o) +(o^_^o))+ ((o^_^o) - (ﾟΘﾟ))+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ (o^_^o)+ ((ﾟｰﾟ) + (ﾟΘﾟ))+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ ((ﾟｰﾟ) + (o^_^o))+ (ﾟｰﾟ)+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ ((ﾟｰﾟ) + (o^_^o))+ (ﾟｰﾟ)+ (ﾟДﾟ)[ﾟεﾟ]+(oﾟｰﾟo)+ ((ﾟｰﾟ) + (o^_^o))+ (ﾟДﾟ) .ﾟΘﾟﾉ+ (ﾟΘﾟ)+ (ﾟΘﾟ)+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ (o^_^o)+ (o^_^o)+ (ﾟДﾟ)[ﾟεﾟ]+((o^_^o) +(o^_^o))+ (ﾟΘﾟ)+ (ﾟДﾟ)[ﾟεﾟ]+(ﾟΘﾟ)+ (o^_^o)+ ((ﾟｰﾟ) + (ﾟΘﾟ))+ (ﾟДﾟ)[ﾟεﾟ]+((ﾟｰﾟ) + (ﾟΘﾟ))+ (ﾟΘﾟ)+ (ﾟДﾟ)[ﾟεﾟ]+((ﾟｰﾟ) + (ﾟΘﾟ))+ (ﾟΘﾟ)+ (ﾟДﾟ)[ﾟoﾟ]) (ﾟΘﾟ)) ('_');}
// Execute function:
a(':D');
```

I took it from this answer, encoded it with aaencode, and wrapped it an the arrow function.

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

```
y/(|)D:-/0-3/d

```

Try it online!

Basically a port of my sed answer, but the `y///` command in perl has the additional utilities of deleting extra characters and specifying ranges of characters, so this manages to be shorter and still contain `:-/` and `D:` as essential parts of the code.

# Answer
> 1 votes
# Factor, 20 bytes

```
[ last "(|)D"index ]

```

Try it online!

## Explanation:

If `":)"` is on the data stack when this quotation is called...

* `last` Take the last element of the input.

**Stack:** `41` (code point for `)`)
* `"(|)D"` Push a string to the stack.

**Stack:** `41 "(|)D"`
* `index` Find the index of `41` in `"(|)D"`.

**Stack:** `2`

# Answer
> 1 votes
# Vyxal `K`, 7 bytes

```
td19%4%

```

Try it Online! -1 thanks to exedraj.

# Answer
> 1 votes
# brainfuck, 94 bytes

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

```

Try it online!

Uses Uriel's formula. Here's how it works:

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

```

A nifty input loop that handles the optional nose and doubling the characters. It gets a character, doubles it into the next cell, then moves two cells over and tries to get another character. At the end, the tape looks something like

```
0 2*c1 0 2*c2 0 2*c3 0 ...
                     ^

```

This requires an implementation with EOF=0 or no change (which accounts for most of them including TIO).

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

```

Put 16 after the last doubled input. Now on to the main loop:

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

```

This loop will

* add 3 to the dividend (current cell). I do this because it's 2 bytes shorter to get 16 rather than 19, and these can be reused to construct 4 for the second dividend.
* compute the modulus of the previous%current cell.
* clear out a temporary variable
* check if the value of the cell 3 indices back is non-zero (which is only true on the first iteration since the loop ends 2 indices to the right of where it started). If it is, increment the cell where the next dividend will be (this sets up the second modulo 4).

For clarity, here's what the tape looks like during the first iteration, before the tempvar is cleaned:

```
0 2*c1 0 2*c2 0 0 tmp 2*c3%19 0 ...
                  ^

```

And the same for the second:

```
0 2*c1 0 2*c2 0 0 0 0 tmp 2*c3%19%4 0 ...
                      ^

```

So checking the cell 3 indices back is an easy way to see which iteration we're on without using a counter.

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

```

And finally, a bit of wrapping abuse to add 48 to the result so it can be outputted.

There's probably room for improvement, particularly in the input loop or the memory layout, but this is the best I could come up with.

# Answer
> 1 votes
# Thunno 2 `tB`, 5 bytes

```
ṇ;Œ7%

```

Try it online!

Uses dingledooper's formula.

#### Explanation

```
ṇ;Œ7%  # Implicit input
       # Convert to codepoints
ṇ;     # Push compressed integer 160
  Œ    # Take 160 mod each codepoint
   7%  # Mod each by 7
       # Implicit output of last item

```

# Answer
> 0 votes
# Kotlin,  ~~27~~  24 bytes

-3 Refactor to remove `it.`

```
{"(|)D".indexOf(last())}

```

Try it online!

# Answer
> 0 votes
# T-SQL, 34 bytes

```
SELECT CHARINDEX(RIGHT(@,1),'|)D')-1

```

Requires the variable `@` to be declared and assigned the input.

This code takes the right most character, and searches an indexed list of the possible mouthes. `CHARINDEX` returns a 1-based index. *But*, failing to find anything returns 0. So we leave the frown out of the search string (making the sad face even sadder).

Try it online! (SQL Fiddle)

# Answer
> 0 votes
## Hy, 33 bytes

```
(fn[s](%(%(*(ord(last s))2)19)4))

```

Try it online!

It's a basic port of Uriel's answer. I might be able to shorten it by getting rid of a `%` but I need to play around with the syntax.

# Answer
> 0 votes
# MAWP 0.1, 27 bytes

```
|2W!!99M1MP99M1MWA!!4P4WA:.

```

Uses the modulo formula from @Uriel 's answer

# Answer
> 0 votes
# Golfscript, 10 bytes

```
-1='(|)D'?

```

Try It Online!

## Explanation:

```
-1=        # Gets the ASCII value of the final character.
   '(|)D'? # Finds the index of that ASCII value, in the string '(|)D'.

```

And then, the index value is implicitly printed.

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


title: Mode (most common element) of a list

text:
# Question
Title: Mode (most common element) of a list
Write a snippet to calculate the mode (most common number) of a list of positive integers.

For example, the mode of

```
d = [4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]

```

is `1`, because it occurs the maximum of 5 times.

You may assume that the list is stored in a variable such as `d` and has a unique mode.

e.g.: Python, 49

```
max(((i,d.count(i))for i in set(d)), key=lambda x:x[1])

```

This is , so the shortest solution in bytes wins.

# Answer
> 8 votes
# K5, 6 bytes

```
*>#:'=

```

The first (`*`) of the descending elements (`>`) of the count of each (`#:'`) of the group (`=`). Step by step:

```
  i
4 3 1 0 6 1 6 4 4 0 3 1 7 7 3 4 1 1 2 8

  =i
4 3 1 0 6 7 2 8!(0 7 8 15
 1 10 14
 2 5 11 16 17
 3 9
 4 6
 12 13
 ,18
 ,19)

  #:'=i
4 3 1 0 6 7 2 8!4 3 5 2 2 2 1 1

  >#:'=i
1 4 3 7 6 0 8 2

  *>#:'=i
1

```

try it in your browser!

# Answer
> 29 votes
## Python 2 - 18

```
max(d,key=d.count)

```

Since your python answer doesn't seem to print, I expect this is what you want.

Add 6 bytes for `print`  normally.

# Answer
> 27 votes
# Matlab/Octave, ~~7~~ 5 bytes

Unsurprisingly there's a built-in function for finding modes. As an anonymous function:

```
@mode

```

This returns the most commonly occuring element in the input vector with ties going to the smaller value.

Saved 2 bytes thanks to Dennis!

# Answer
> 16 votes
## Pyth \- 6

```
eo/QNQ

```

Try it online.

Expects input on stdin like `[4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]`. Ties are resolved by last occurrence because Python performs stable sorts.

Sorts the list by count the value in the list, then prints the last number of the list.

`Q` could be replaced with `d` if you initialized `d` to contain the value before e.g. `=d[4 3 1 0 6 4 4 0 1 7 7 3 4 1 1 2 8)`

Python-esque pseudo-code:

```
Q=eval(input());print(sorted(Q,key=Q.count)[-1])

```

Full Explanation:

```
            : Q=eval(input()) (implicit)
e           : ... [-1]
 o   Q      : orderby(lambda N: ...,Q)
  /QN       : count(Q,N)

```

Pyth's `orderby` runs exactly like Python's `sorted` with `orderby`'s first argument being the `key` argument.

# Answer
> 12 votes
# Mathematica, 25 bytes

```
Last@SortBy[d,d~Count~#&]

```

or

```
#&@@SortBy[d,-d~Count~#&]

```

As in the challenge, this expects the list to be stored in `d`.

## or... 15 bytes

Of course, Mathematica wouldn't be Mathematica if it didn't have a built-in:

```
#&@@Commonest@d

```

`Commonest` returns a list of all most common elements (in case of a tie), and `#&@@` is a golfed `First@`.

# Answer
> 9 votes
# CJam, ~~11~~ 10 bytes

```
A{A\-,}$0=

```

Assumes the array in a variable called `A`. This is basically sorting the array based on the occurrence of each number in the array and then picks the last element of the array.

Example usage

```
[1 2 3 4 4 2 6 6 6 6]:A;A{aA\/,}$W=

```

Output

```
6

```

1 byte saved thanks to Dennis!

Try it online here

# Answer
> 9 votes
# Ruby, 22 bytes

```
d.max_by{|i|d.count i}

```

Basically a port of my Mathematica answer, except Ruby has a direct `max_by` so I don't need to sort first.

# Answer
> 9 votes
# R, ~~33~~ 25 bytes

Thanks @Hugh for the help shortening:

```
names(sort(-table(d))[1])

```

---

The original:

```
v=table(d);names(v[which.max(v)])

```

This calculates the frequency of each element in the vector `d`, then returns the name of the column containing the largest value. The value returned is actually a character string containing the number. It didn't say anywhere that that wasn't okay, so...

Any suggestions to shorten this are welcome!

# Answer
> 8 votes
# Powershell 19

```
($d|group)[0].Count

```

(this asumes the array is already on `$d`)

# Answer
> 8 votes
# J - 12 char

Anonymous function. Sorts list from most to least common, taking first item.

```
(0{~.\:#/.~)

```
* `0{` First of
* `~.` Unique items
* `\:` Downsorted by
* `#/.~` Frequencies

Try it for yourself.

# Answer
> 6 votes
# JavaScript (ES6) 51

Just a single line expression using the preloaded variable d. Sort the array by frequency then get the first element.
Nasty side effect, the original array is altered

```
d.sort((a,b)=>d.map(w=>t+=(w==b)-(w==a),t=0)&&t)[0]

```

As usual, using .map instead of .reduce because it's 1 char shorter overall. With .reduce it' almost a clean, non-golfed solution.

```
d.sort((a,b)=>d.reduce((t,w)=>t+(w==b)-(w==a),0))[0]

```

At last, a solution using a function, not changing the original array and without globals (62 bytes):

```
F=d=>[...d].sort((a,b)=>d.reduce((t,w)=>t+(w==b)-(w==a),0))[0]

```

**Test** In FireFox/FireBug console

```
d=[4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]
d.sort((a,b)=>x.map(w=>t+=(w==b)-(w==a),t=0)&&t)[0]

```

*Output* 1

The d array becomes:

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

```

# Answer
> 6 votes
# Perl 6, 21 bytes

```
.Bag.invert.max.value

```

### Example:

```
$_ = < 4 3 1 0 6 1 6 4 4 0 3 1 7 7 3 4 1 1 2 8 >».Int;

say .Bag.invert.max.value; # implicitly calls $_.Bag…

```

If there is a tie it will print the larger of the ones that tied.

---

The `.Bag` method on a List or an Array creates a quantified hash that associates the total count of how many times a given value was seen with that value.

```
bag(4(4), 3(3), 1(5), 0(2), 6(2), 7(2), 2, 8)

```

The `.invert` method creates a List of the pairs in the bag with the key and the value swapped. ( The reason we call this is for the next method to do what we want )

```
4 => 4,  3 => 3,  5 => 1,  2 => 0,  2 => 6,  2 => 7,  1 => 2,  1 => 8

```

The `.max` method on a List of Pairs returns the biggest Pair comparing the keys first and in the case of a tie comparing the values.
( This is because that is how `multi infix:<cmp>(Pair:D \a, Pair:D \b)` determines which is larger )

```
5 => 1

```

The `.value` method returns the value from the Pair. ( It would have been the key we were after if it wasn't for the `.invert` call earlier )

```
1

```

---

If you want to return all of the values that tied in the case of a tie:

```
say @list.Bag.classify(*.value).max.value».key

```

The `.classify` method returns a list of pairs where the keys are from calling the Whatever lambda `*.value` with each of the Pairs.

```
1 => [2 => 1, 8 => 1],
2 => [0 => 2, 6 => 2, 7 => 2],
3 => [3 => 3],
4 => [4 => 4],
5 => [1 => 5]

```

Then we call `.max` to get the largest Pair.

```
"5" => [1 => 5]

```

A call to `.value` gets us the original Pairs from the Bag ( just one in this case )

```
1 => 5

```

Then we use `>>.key` to call the `.key` method on every Pair in the list, so that we end up with a list of the values that were seen the most.

```
1

```

# Answer
> 5 votes
# Python - 32

```
max((x.count(i),i)for i in x)[1]

```

Don't see an 18 character solution anywhere in the future to be honest.

EDIT: I stand corrected, and impressed.

# Answer
> 5 votes
# 05AB1E, 3 bytes

```
.MJ

```

Explanation:

```
.M  # Gets the most frequent element in the [implicit] input
  J # Converts to a string, needed as the program would output "[1]" instead of "1" without this.

```

If you want to store the array in a variable instead of using input, just push the array to the stack at the start of the program.

Try it online!

# Answer
> 4 votes
# JavaScript, ES6, 71 bytes

A bit long, can be golfed a lot.

```
f=a=>(c=b=[],a.map(x=>b[x]?b[x]++:b[x]=1),b.map((x,i)=>c[x]=i),c.pop())

```

This creates a function `f` which can be called like `f([1,1,1,2,1,2,3,4,1,5])` and will return `1`.

Try it on your latest Firefox's Console.

# Answer
> 4 votes
# Dyalog APL, 12 characters

`d[⊃⍒+/∘.=⍨d]`

`∘.=⍨d` is the same as `d∘.=d`, reflexive outer product of `=`. It creates a boolean matrix comparing every pair of elements in `d`.

`+/` sums that matrix along one of the axes and produces a vector.

grades the vector, i.e. sorts it by indices. (As the glyphs suggest,  grades in descending order and  would grade in ascending order.)

takes the first index from the grading—the index of the largest element of `d`.

`d[...]` returns that element.

# Answer
> 4 votes
# Jelly, 2 bytes

```
Æṃ

```

Try it online!

Jelly finally got a mode builtin! A non-builtin version however is 5 bytes:

```
ċ@Þ`Ṫ

```

Try it online!

## How they work

```
Æṃ - Main link. Takes a list d on the left
Æṃ - Return the mode of d

```

Well that was unimpressive. How about the 5 byte, non-builtin version?

```
ċ@Þ`Ṫ - Main link. Takes d on the left
   `  - Use d as both the left and right argument to:
  Þ   -   Sort d by:
ċ@    -     Count occurrences in d
    Ṫ - Take the last element (i.e. the element with a maximal count in d)

```

# Answer
> 3 votes
# C# - 49

Can't really compete using C# but oh well:

Assuming `d` is the array

`d.GroupBy(i=>i).OrderBy(a=>a.Count()).Last().Key;`

# Answer
> 3 votes
# bash - ~~29~~ 27 characters

```
sort|uniq -c|sort -nr|sed q

```

Using it:

```
sort|uniq -c|sort -nr|sed q
4
3
1
0
6
1
6
4
4
0
3
1
7
7
3
4
1
1
2
8
[ctrl-D]
5 1

```

i.e. "1" is the mode, and it appears five times.

# Answer
> 3 votes
# GolfScript, 10 bytes

```
a{a\-,}$0=

```

From this answer I wrote to Tips for golfing in GolfScript. Expects the input in an array named `a`, returns result on stack. (To read input from an array on the stack, prepend `:` for 11 bytes; to read input from stdin (in the format `[1 2 1 3 7]`), also prepend `~` for 12 bytes.)

This code works by iterating over the input array, subtracting each element from the original array, and counting the number of elements left. This is then used as a key to sort the original array by, and the first element of the sorted array is returned.

Online demo.

*Ps.* Thanks to Peter Taylor for pointing out this challenge to me.

# Answer
> 3 votes
# Java 8, 83 Bytes

```
d.stream().max((x,y)->Collections.frequency(d,x)-Collections.frequency(d,y)).get();

```

`d` must be a `Collection<Integer>`.

---

If `Collections` can be statically imported:
**59 Bytes**

```
d.stream().max((x,y)->frequency(d,x)-frequency(d,y)).get();

```

# Answer
> 3 votes
# Jelly, 7 bytes

```
ṢŒrṪÞṪṪ

```

Try it online!

Longer than K :(

Assumes the first argument has the array. There are no variables in Jelly.

# Answer
> 3 votes
# Haskell, ~~42~~ 39 bytes

```
f s=snd$maximum[([1|y<-s,y==x],x)|x<-s]

```

Try it online!

*Edit: Thans to Zgarb for -3 bytes*

# Answer
> 3 votes
# JavaScript (Node.js), 45 bytes

```
x=>x.map(a=t=>a[t]=0+a[t]||[1+t]).sort()[0]-1

```

Try it online!

42 without 0 support

# Answer
> 2 votes
# Bash + unix tools, 62 bytes

Expects the array in the STDIN. The input format does not count, as long as the numbers are non-negative integers.

```
grep -o [0-9]\*|sort|uniq -c|sort -n|awk 'END{print $2}'

```

Edited: escaped wildcard in grep argument. Now it can be run safely in non-empty directories. Thanks to manatwork.

# Answer
> 2 votes
## Java 8 : 184 bytes

```
Stream.of(A).collect(Collectors.groupingBy(i -> i, Collectors.counting())).entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).findFirst().get().getKey();

```

Input **A** must be of type `Integer[]`. Note `java.util.*` and `java.util.stream.*` need to be imported, however in the spirit oneliner they are left out.

# Answer
> 2 votes
# Haskell 78

```
import Data.List
import Data.Ord
g=head.maximumBy(comparing length).group.sort

```

If the imports are ignored, it's **45**.

# Answer
> 2 votes
# Perl, 27 bytes

```
$Q[$a{$_}++]=$_ for@F;pop@Q

```

Returns the last most common value in case of a tie.

# Answer
> 2 votes
# jq, 29 characters

```
group_by(.)|max_by(length)[0]

```

Sample run:

```
bash-4.3$ jq 'group_by(.)|max_by(length)[0]' <<< '[4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]'
1

```

On-line test

# Answer
> 2 votes
# PHP, ~~53~~ 50 bytes

```
<?=array_flip($c=array_count_values($d))[max($c)];

```

Run like this:

```
echo '<?php $d=$argv;?><?=array_flip($c=array_count_values($d))[max($c)]; echo"\n";' | php -- 4 3 1 0 6 1 6 4 4 0 3 1 7 7 3 4 1 1 2 8

```

## Tweaks

* Saved 3 bytes by making use of the freedom to assume the input is assigned to a variable `d`

# Answer
> 2 votes
# Brachylog, 5 bytes

```
ọtᵒth

```

Try it online!

This isn't really a snippet, but I'm not sure what would be...

```
         The output is
    h    the first element of
   t     the last element of
ọ        a list of [value, number of occurrences] pairs corresponding to
         the input,
  ᵒ      sorted ascending by
 t       their last elements (the numbers of occurrences).

```

# Answer
> 2 votes
## Clojure, 32 bytes

```
#(apply max-key(frequencies %)%)

```

`(frequencies %)` returns a hash-map, which can be used as a function. Given a key it returns the corresponding value :)

Equal length:

```
#(last(sort-by(frequencies %)%))

```

# Answer
> 2 votes
# 05AB1E, 2 bytes

```
.M

```

Try it online!

# Answer
> 2 votes
# Zsh (builtins only), 55 ~~57~~ ~~62~~ bytes

```
for i ({0..9})c=${#${(M)A#$i}}&&((c>d?(d=c,m=i)));<<<$m

```

Try it online! ~~57B~~

No utils like `sort`, `uniq`, `sed`. Uses data from array `A`. The expression `${#${(M)A#$i}}` counts elements of A, matching pattern `$i`. Then we just keep track of the biggest `$c` and matching `$i`. (note, Zsh is triggered by `c>d?...`, just ignore the guff on stderr)

---

Alternate, regex-ified solution, for 80B.

`B+=(${(Mj::)A#$i})` constructs an array B with all `i`th elements joined, so in the given example the element `11111` is the longest.

```
for i ({0..9})B+=(${(Mj::)A#$i})
<<<${B[(r)${(l.${#${(O@)B//?/X}[1]}..?.)}]:1:1}

```

Sample code taken from the Zsh User Guide. Quote: *"This chapter will appeal above all to people who are excited by the fact that `print ${array[(r)${(l.${#${(O@)array//?/X}[1]}..?.)}]` prints out the longest element of the array `$array` \[...\] This is for advanced students only (nutcases, if you ask me)."*
PS: Here's a slightly more sensible way for 69B

# Answer
> 2 votes
# Arturo, 32 bytes

```
$=>[m:maximum tally&[k,v][v]m\0]

```

Try it

# Answer
> 2 votes
# Julia 1.0, ~~39~~ 37 bytes

```
~d=argmax(@.sum(==(1:max(d...)),[d]))

```

Try it online!

The solution above works for positive integers. It can be adapted to handle `0`:

# Julia 1.0, ~~41~~ 39 bytes

```
~d=argmax(@.sum(==(0:max(d...)),[d]))-1

```

Try it online!

-2 bytes thanks to MarcMush: use `sum` instead of `count`

# Answer
> 2 votes
# Japt `-h`, 5 bytes

```
ü ñÊÌ

```

Try it

```
ñ@è¶X

```

Try it

```
ü ñÊÌ     :Implicit input of array
ü         :Group & sort
  ñ       :Sort by
   Ê      :  Length
    Ì     :Last element
          :Implicit output of last element

```

```
ñ@è¶X     :Implicit input of array
ñ         :Sort by
 @        :Passing each X through the following function
  è       :  Count the elements in U
   ¶X     :    Equal to X
          :Implicit output of last element

```

# Answer
> 2 votes
# Nekomata, 2 bytes

```
ŢṂ

```

Attempt This Online!

```
Ţ   Tally
 Ṃ  Maximum by

```

Let's take the input `[4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]` as an example.

`Ţ` returns two lists `[4,3,1,0,6,7,2,8]` and `[4,3,5,2,2,2,1,1]`, where the first list contains the unique elements of the input, and the second list contains the number of occurrences of each element.

finds an element in the first list with the largest corresponding element in the second list, and returns that element. In this case, the maximum of the second list is `5`, and the corresponding element in the first list is `1`, so  returns `1`.

# Answer
> 1 votes
# Scala, 32

```
d.groupBy(a=>a).maxBy(_._2.size)

```

# Answer
> 1 votes
## C++ 119

```
int *a=std::max_element(x,x+n);int z=0,b=0,c=0;for(int i=0;i<=*a;i++){c=std::count(x,x+n,i);if(c>b){b=c;z=i;}}return z;

```

Full code and test:

```
#include <iostream>
#include <algorithm>
#include <vector>

int m(int *x,int n)
{
int *a=std::max_element(x,x+n);int z=0,b=0,c=0;for(int i=0;i<=*a;i++){c=std::count(x,x+n,i);if(c>b){b=c;z=i;}}return z;
}

int main()
{
int d[] = {4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8};
std::cout<<m(d,20);
return 0;
}

```

# Answer
> 1 votes
## Ceylon, 67

```
E m<E>(E+l)=>(l.frequencies().max(increasingItem)else nothing).key;

```

This function works on any type of element, including Integers (though `null` elements are ignored). (And it is shorter than the same function for just integers.)

Formatted:

```
E m<E>(E+ l) =>
        (l
        .frequencies()
        .max(increasingItem)
            else nothing)
    .key;

```

The `else nothing` is needed, because the Ceylon compiler can't figure out that `l.frequencies` always is non-empty if `l` is nonempty (because in general, all elements of `l` could be `null`, and therefore discarded).

You can call this function like this:

```
print(m(4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8));

```

If you already have a list `list`, call it like this:

```
print(m(*list));

```

(This will unpack the list into arguments, and pass them to the function.)

# Answer
> 1 votes
# Hassium, 94 Bytes

This example assumes that the array is stored in `d`

```
func main(){t,b=0;foreach(e in d){c=0;foreach(n in d)if(e==n)c++;if(c>b){b=c;t=e;}}println(t)}

```

See expanded and run online with test case here

# Answer
> 1 votes
## Pyke, 10 bytes

```
D3m/DSe@R@

```

Try it here!

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

```
ztcZZz;AJAK

```

Attempt This Online!

Thunno doesn't have a `mode` built-in so we have to implement it ourselves:

```
ztcZZz;AJAK  # Implicit input
zt           # Triplicate the (implicit) input
  c          # And get the count of each element
   ZZ        # Zip with the input
             # So we have a nested list of the form
             # [[count, element], [count, element], ...]
     z;      # And reverse-sort this list of lists
             # (so the first pair will be the mode)
       AJ    # Get the first pair
         AK  # And get the last item
             # Implicit output

```

# Answer
> 1 votes
# Nibbles, 5 bytes (10 nibbles)

```
/+=~$,+`%@

```

```
  =~        # group and sort
    $       # the input
            # by
     ,      #   length of
      +     #   flattened
       `%   #   split
         @  #   the input
            #   by
            #   (implicitly) each element
 +          # then flatten this
/           # and output the first element
            # (by folding over list returning left-hand
            # argument at each step)

```

# Answer
> 1 votes
# Thunno 2, 1 byte

Try it online!

Built-in.

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