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) {
} else {
return a + b;
}
}


Try this fiddle online.

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>

• So it gives the sum of two numbers plus a geometric random variable with failure probability 1/10?
– xnor
Dec 14, 2015 at 2:00
• @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) Dec 14, 2015 at 2:02
• Why was this sandboxed for 20 minutes? That seems to be missing the point of the sandbox. Dec 14, 2015 at 16:52
• @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. Dec 14, 2015 at 17:30
• 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. Dec 14, 2015 at 18:26

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

# 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

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

# APL (Dyalog Unicode), 10 bytes

+-{⌈10⍟?0}


Try it online!

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


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

# 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


# Tcl, 52 bytes

proc A n\ m {expr {rand()>.9?[A $n [incr m]]:$n+$m}}  Try it online! # 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  # 05AB1E, 151413 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  • +[TLΩ≠#> for 8 bytes May 9, 2018 at 11:04 • @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! May 9, 2018 at 11:59 # 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. # 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  # C (gcc), 33 bytes f(x,y){x=rand()%10?x+y:1+f(x,y);}  Try it online! # 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  # 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. • I think it should be rgeom(1,.9). Dec 14, 2015 at 6:37 # Perl 5-p, 23 bytes $_+=<>;$_++while.1>rand  Try it online! # Python 2, 63 bytes Returns the result as a string. from random import* f=lambda a,b:random()>.1anda+bor f(a,b+1)  Try it online! Test program showing probability distribution: Try it online! # λ-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 # Raku, 30 bytes {@_.sum+sum (.1>rand)xx*...!*}  Try it online! # PowerShell Core, 46 bytes param($a,$b)while(!(get-random 10)){++$a}$b+$a


Try it online!

• It is not full program or function. It is a code snippet. Full program for PS means "you can save the code to a standalone script file, run the script with optional parameters (not statements) and get a valid result". Oct 27, 2021 at 20:46
• From the msdn about Functions, A filter is a type of function that runs on each object in the pipeline. I think it does match? Oct 27, 2021 at 21:02
• I don't think the definition from MSDN matches the definition on this site. See comments from @AdmBorkBork and standard loopholes on this site and meta Oct 27, 2021 at 21:10

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