58
\$\begingroup\$

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>

\$\endgroup\$
  • 6
    \$\begingroup\$ So it gives the sum of two numbers plus a geometric random variable with failure probability 1/10? \$\endgroup\$ – xnor Dec 14 '15 at 2:00
  • \$\begingroup\$ @xnor Essentially, yes. I defined it recursively so that it is easier to understand, but you don't have to do it recursively (CJam solution does not, for instance) \$\endgroup\$ – a spaghetto Dec 14 '15 at 2:02
  • 10
    \$\begingroup\$ Why was this sandboxed for 20 minutes? That seems to be missing the point of the sandbox. \$\endgroup\$ – Peter Taylor Dec 14 '15 at 16:52
  • 3
    \$\begingroup\$ @PeterTaylor The one minor issue with it was fixed almost immediately, and the question was so simple I didn't think it needed to stay in the sandbox for that long (it had already been looked at by 10 people which I thought was sufficient peer review for such a simple challenge). The main reason I had it in the sandbox was to see if people thought it was too simple. \$\endgroup\$ – a spaghetto Dec 14 '15 at 17:30
  • 2
    \$\begingroup\$ I would say it still has a major issue, in that it's not clear whether you insist on implementations being written as recursive functions or just on giving the right distribution, but it's far too late to do anything about clarifying that now. \$\endgroup\$ – Peter Taylor Dec 14 '15 at 18:26

42 Answers 42

40
\$\begingroup\$

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.

\$\endgroup\$
  • 13
    \$\begingroup\$ This... is pure black magic. O_o \$\endgroup\$ – Doorknob Dec 14 '15 at 2:23
  • 1
    \$\begingroup\$ This... is ridiculous. \$\endgroup\$ – cat Dec 14 '15 at 2:23
36
\$\begingroup\$

Python 2, 55 bytes

from random import*
lambda a,b:a+b+18-len(`1+random()`)

This is an absolutely bizarre way to do it.

The function random gives a float in [0,1), and its string representation by default has 16 digits after the decimal point, for 18 characters total. But, because trailing 0's are omitted, it might be shorter. Reading digits from the end, each one has a 1/10 chance of being 0, and we stop when we hit a nonzero digit. So the number of trailing zeroes is distributed just like the number of recursions Alex makes, so we can sample from this distribution by 18 minus the string length.

Actually, Python will display more than 18 digits for small numbers, sometimes even scientific notation, so we add 1 to fix this.

This will never give more than 15 more than the sum, but that's OK because 10^15 is much less than the chance a cosmic ray disrupts the computation.

\$\endgroup\$
22
\$\begingroup\$

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)
}
\$\endgroup\$
13
\$\begingroup\$

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).

\$\endgroup\$
  • \$\begingroup\$ Is this really a function? I quickly scanned through the language documentation, and couldn't find anything describing function definitions. Based on the explanation, it looks more like a code fragment. \$\endgroup\$ – Reto Koradi Dec 14 '15 at 2:00
  • \$\begingroup\$ @RetoKoradi: I can put such a "code fragment" on it's own line, jump to it with 0kF (where k is some number), and jump back with f at the end. That's the closest you'll get to a function in Minkolang. \$\endgroup\$ – El'endia Starman Dec 14 '15 at 2:07
  • 2
    \$\begingroup\$ Isn't that technically like saying "my CJam code fragment is a function; you just have to surround it with curly braces"? At the very least, you should probably include the f at the end in the char count (and technically the preceding newline if you're feeling extra-pedantic, but I don't think that's necessary). \$\endgroup\$ – Doorknob Dec 14 '15 at 2:10
  • 1
    \$\begingroup\$ If the language doesn't have functions, you can always post full programs. My understanding is that when it says "function", it either has to be a named function, or an anonymous function (which is typically an expression that can be assigned to a function variable). I once posted something similar to this in CJam, and Martin quickly called me out on it, saying that it was a code fragment, and not a function. \$\endgroup\$ – Reto Koradi Dec 14 '15 at 2:11
  • \$\begingroup\$ @RetoKoradi: Alright, that's understandable. What do you think of Doorknob's suggestion? \$\endgroup\$ – El'endia Starman Dec 14 '15 at 2:12
12
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

Javascript ES6, 38 bytes

f=(a,b)=>Math.random()<.1?f(a,b+1):a+b
\$\endgroup\$
  • \$\begingroup\$ f=(a,b)=>new Date%10<1?f(a,b+1):a+b for 35 bytes \$\endgroup\$ – WallyWest Dec 14 '15 at 11:00
  • 2
    \$\begingroup\$ @WallyWest Unfortunately the probability when using the Date timestamp won't be accurate because if it evaluates true it will keep adding 1 for the rest of the millisecond. \$\endgroup\$ – user81655 Dec 14 '15 at 11:51
  • \$\begingroup\$ I tried the geometric distribution f=(a,b)=>a+b-~~Math.log10(Math.random()) but it is 2 bytes longer. \$\endgroup\$ – Neil Dec 16 '15 at 0:36
8
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Fair comment, although I'd like to see you generate 15 with any other solution presented :P Another way, for 15 bytes, is the simple looping version: ii+`10Yr1=tb+w], not golfed yet. \$\endgroup\$ – David Dec 14 '15 at 4:38
  • \$\begingroup\$ Actually I can amke the loop shorter! Thanks @ThomasKwa! \$\endgroup\$ – David Dec 14 '15 at 4:47
  • \$\begingroup\$ Very nicely done! \$\endgroup\$ – Luis Mendo Dec 14 '15 at 10:11
7
\$\begingroup\$

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: enter image description here

Magnified 50x:

enter image description here

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).

\$\endgroup\$
  • 2
    \$\begingroup\$ Can you add an explanation? This is super cool. \$\endgroup\$ – cat Dec 14 '15 at 3:57
7
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 62? \$\endgroup\$ – ASCII-only May 10 '18 at 0:23
  • \$\begingroup\$ the smart way is 76 :( \$\endgroup\$ – ASCII-only May 10 '18 at 0:31
  • \$\begingroup\$ @ASCII-only Using .9>random() isn't quite 9-out-of-10, because of uneven distribution of floats \$\endgroup\$ – Mego May 10 '18 at 21:43
6
\$\begingroup\$

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.

\$\endgroup\$
6
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Worth noting that for it to add 14, you'll also have to watch pigs fly and Hell freeze over. And by the time you add 14, I'll have done something with my life. \$\endgroup\$ – Fund Monica's Lawsuit Dec 15 '15 at 3:18
5
\$\begingroup\$

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
\$\endgroup\$
5
\$\begingroup\$

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!

\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Would (- a(- -1 b)) work? Saves you 2 bytes if it does. \$\endgroup\$ – Neil Dec 16 '15 at 0:31
  • \$\begingroup\$ @Neil, I don't think that works because the function should be recursive \$\endgroup\$ – sudo rm -rf slash Dec 16 '15 at 6:25
  • \$\begingroup\$ Thanks for explaining why the expression looks so cumbersome. \$\endgroup\$ – Neil Dec 16 '15 at 22:56
4
\$\begingroup\$

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)).

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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;
}
\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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 :(

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

Jelly, 7 bytes (non-competing)

‘⁵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.
\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ You can take two integers as two arguments and remove the /. \$\endgroup\$ – Erik the Outgolfer May 9 '18 at 12:27
  • \$\begingroup\$ @EriktheOutgolfer Yeah. \$\endgroup\$ – Adám May 9 '18 at 14:26
2
\$\begingroup\$

Perl 6, 26 bytes

Actually doing it recursively:

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

Create a possibly empty sequence of 1s 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 ... *
\$\endgroup\$
  • \$\begingroup\$ 23 bytes \$\endgroup\$ – bb94 Apr 14 at 6:08
2
\$\begingroup\$

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)
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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).

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.