Alex-style Addition

57

2

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>

a spaghetto

Posted 2015-12-14T01:19:26.387

Reputation: 10 647

6So it gives the sum of two numbers plus a geometric random variable with failure probability 1/10? – xnor – 2015-12-14T02:00:48.860

@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) – a spaghetto – 2015-12-14T02:02:08.173

Can the two integers be taken as a two-element array? (input [3 4] instead of inputs 3 and 4) – Luis Mendo – 2015-12-14T15:10:05.387

@LuisMendo This is fine. I'm not too picky about the input format. – a spaghetto – 2015-12-14T15:29:07.437

11Why was this sandboxed for 20 minutes? That seems to be missing the point of the sandbox. – Peter Taylor – 2015-12-14T16:52:56.277

3@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. – a spaghetto – 2015-12-14T17:30:34.040

3I 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. – Peter Taylor – 2015-12-14T18:26:59.010

I didn't mean for it to come off as requiring recursion. Fixed. – a spaghetto – 2015-12-14T18:30:15.403

Is it required for submissions to have some chance (assuming true randomness) of giving an answer >15, even if the float precision is 15 digits? – lirtosiast – 2015-12-14T19:59:31.323

I'm not sure I understand. Do you mean "to have some chance of adding 15 or more to the number?" – a spaghetto – 2015-12-14T20:12:37.473

So depending on the size of your stack, there could potentially be a fairly large chance of a stack overflow... just by adding. – ArtOfCode – 2015-12-15T16:25:49.523

In your reference implementation, I would use the clearer b+1 instead of ++b. – Paŭlo Ebermann – 2015-12-15T20:49:31.697

@PaŭloEbermann I'm not sure why I had ++b there... Fixing – a spaghetto – 2015-12-15T20:50:14.320

The leader board appears to be borked. – dfeuer – 2019-04-16T02:19:24.807

Answers

40

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.

FryAmTheEggman

Posted 2015-12-14T01:19:26.387

Reputation: 16 206

13This... is pure black magic. O_o – Doorknob – 2015-12-14T02:23:12.387

1This... is ridiculous. – cat – 2015-12-14T02:23:48.220

36

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.

xnor

Posted 2015-12-14T01:19:26.387

Reputation: 115 687

1

Sorry, this answer is invalid, as it has a 10^-15 chance of not functioning properly, which is explicitly prohibited by the linked meta post.

– pppery – 2018-08-02T18:27:52.173

22

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

Alex A.

Posted 2015-12-14T01:19:26.387

Reputation: 23 761

13

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

El'endia Starman

Posted 2015-12-14T01:19:26.387

Reputation: 14 504

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. – Reto Koradi – 2015-12-14T02:00:00.877

@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. – El'endia Starman – 2015-12-14T02:07:58.887

2Isn'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). – Doorknob – 2015-12-14T02:10:35.793

1If 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. – Reto Koradi – 2015-12-14T02:11:27.857

@RetoKoradi: Alright, that's understandable. What do you think of Doorknob's suggestion? – El'endia Starman – 2015-12-14T02:12:08.797

@RetoKoradi: Is my edit satisfactory? – El'endia Starman – 2015-12-14T02:25:57.270

12

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.

Doorknob

Posted 2015-12-14T01:19:26.387

Reputation: 68 138

8

Javascript ES6, 38 bytes

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

SuperJedi224

Posted 2015-12-14T01:19:26.387

Reputation: 11 342

f=(a,b)=>new Date%10<1?f(a,b+1):a+b for 35 bytes – WallyWest – 2015-12-14T11:00:08.947

2@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. – user81655 – 2015-12-14T11:51:08.063

I tried the geometric distribution f=(a,b)=>a+b-~~Math.log10(Math.random()) but it is 2 bytes longer. – Neil – 2015-12-16T00:36:28.663

8

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.

David

Posted 2015-12-14T01:19:26.387

Reputation: 1 316

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. – David – 2015-12-14T04:38:48.957

Actually I can amke the loop shorter! Thanks @ThomasKwa! – David – 2015-12-14T04:47:19.763

Very nicely done! – Luis Mendo – 2015-12-14T10:11:55.990

7

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.

Mego

Posted 2015-12-14T01:19:26.387

Reputation: 32 998

62? – ASCII-only – 2018-05-10T00:23:46.013

the smart way is 76 :( – ASCII-only – 2018-05-10T00:31:43.730

@ASCII-only Using .9>random() isn't quite 9-out-of-10, because of uneven distribution of floats – Mego – 2018-05-10T21:43:11.307

7

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

SuperJedi224

Posted 2015-12-14T01:19:26.387

Reputation: 11 342

2Can you add an explanation? This is super cool. – cat – 2015-12-14T03:57:42.987

6

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.

Alex A.

Posted 2015-12-14T01:19:26.387

Reputation: 23 761

6

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.

lirtosiast

Posted 2015-12-14T01:19:26.387

Reputation: 20 331

1Worth 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. – Fund Monica's Lawsuit – 2015-12-15T03:18:03.523

5

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

Alex A.

Posted 2015-12-14T01:19:26.387

Reputation: 23 761

5

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!

Doorknob

Posted 2015-12-14T01:19:26.387

Reputation: 68 138

5

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.

Addison Crump

Posted 2015-12-14T01:19:26.387

Reputation: 10 763

4

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

Mego

Posted 2015-12-14T01:19:26.387

Reputation: 32 998

4

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.

sudo rm -rf slash

Posted 2015-12-14T01:19:26.387

Reputation: 1 076

Would (- a(- -1 b)) work? Saves you 2 bytes if it does. – Neil – 2015-12-16T00:31:43.763

@Neil, I don't think that works because the function should be recursive – sudo rm -rf slash – 2015-12-16T06:25:18.320

Thanks for explaining why the expression looks so cumbersome. – Neil – 2015-12-16T22:56:37.630

3

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

SuperJedi224

Posted 2015-12-14T01:19:26.387

Reputation: 11 342

3

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.

LegionMammal978

Posted 2015-12-14T01:19:26.387

Reputation: 15 731

3

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

cat

Posted 2015-12-14T01:19:26.387

Reputation: 4 989

3

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

Downgoat

Posted 2015-12-14T01:19:26.387

Reputation: 27 116

3

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

Dale Johnson

Posted 2015-12-14T01:19:26.387

Reputation: 509

3

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

Adám

Posted 2015-12-14T01:19:26.387

Reputation: 37 779

You can take two integers as two arguments and remove the /. – Erik the Outgolfer – 2018-05-09T12:27:43.343

@EriktheOutgolfer Yeah. – Adám – 2018-05-09T14:26:44.517

3

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;
}

Katenkyo

Posted 2015-12-14T01:19:26.387

Reputation: 2 857

3

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

Luis Mendo

Posted 2015-12-14T01:19:26.387

Reputation: 87 464

3

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.

Dennis

Posted 2015-12-14T01:19:26.387

Reputation: 196 637

2

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

Mego

Posted 2015-12-14T01:19:26.387

Reputation: 32 998

2

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

Brad Gilbert b2gills

Posted 2015-12-14T01:19:26.387

Reputation: 12 713

23 bytes – bb94 – 2019-04-14T06:08:10.853

2

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)

xnor

Posted 2015-12-14T01:19:26.387

Reputation: 115 687

2

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.

alephalpha

Posted 2015-12-14T01:19:26.387

Reputation: 23 988

2

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

costrom

Posted 2015-12-14T01:19:26.387

Reputation: 478

1

Tcl, 52 bytes

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

Try it online!

sergiol

Posted 2015-12-14T01:19:26.387

Reputation: 3 055

1

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

snail_

Posted 2015-12-14T01:19:26.387

Reputation: 1 982

1

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.

snail_

Posted 2015-12-14T01:19:26.387

Reputation: 1 982

1

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

Kevin Cruijssen

Posted 2015-12-14T01:19:26.387

Reputation: 67 575

1+[TLΩ≠#> for 8 bytes – Emigna – 2018-05-09T11:04:17.027

@Emigna Ah, smart.. I guess I'm too used to languages like C and JS were 0 == false and anything else == true. In 05AB1E 1 == true, and anything else == false. Also, placing the increment > after the break is pretty obvious (now that I see it ;p). Thanks! – Kevin Cruijssen – 2018-05-09T11:59:10.303

1

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.

Ciaran_McCarthy

Posted 2015-12-14T01:19:26.387

Reputation: 689

1

APL (Dyalog Unicode), 10 bytes

+-{⌈10⍟?0}

Try it online!

ngn

Posted 2015-12-14T01:19:26.387

Reputation: 11 449

1

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.

Unrelated String

Posted 2015-12-14T01:19:26.387

Reputation: 5 300

1

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

Benjamin Urquhart

Posted 2015-12-14T01:19:26.387

Reputation: 1 262

@ceilingcat thanks – Benjamin Urquhart – 2019-04-16T02:03:53.663

1

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

daniero

Posted 2015-12-14T01:19:26.387

Reputation: 17 193

0

Perl 5 -p, 23 bytes

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

Try it online!

Xcali

Posted 2015-12-14T01:19:26.387

Reputation: 7 671

0

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!

mbomb007

Posted 2015-12-14T01:19:26.387

Reputation: 21 944

0

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.

mnel

Posted 2015-12-14T01:19:26.387

Reputation: 826

1I think it should be rgeom(1,.9). – alephalpha – 2015-12-14T06:37:53.517