亚历克斯风格的加法

57

Alex风格的加法就是这样的-它有90％的机会简单地返回给定的两个数字的和，还有10％的机会递归Alex加上第一个数字和第二个数字+1。这意味着，潜在地，则相加可能相差1或更多。

参考实现（Groovy）

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

排行榜

``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>``

6

xnor 2015年

@xnor本质上是的。我对它进行了递归定义，以使其更容易理解，但您不必递归进行定义（例如，CJam解决方案无需这样做）
spaghetto

10

3
@PeterTaylor与此相关的一个小问题几乎立即得到解决，这个问题是如此简单，以至于我认为它不需要在沙盒中停留那么长时间（它已经被10个人研究过，我认为这已经足够了）回顾一下这样一个简单的挑战）。我在沙箱中拥有它的主要原因是看人们是否认为它太简单了。

2

40

珀斯8

``````u+G!OTsQ
``````

说明

``````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
``````

13

1

2015年

36

Python 2，55个字节

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

1

pppery

22

R，60 47 28字节

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

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

13

Minkolang 0.14，19个11 12字节

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

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

说明

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

El'endia Starman

2

1

El'endia Starman 2015年

12

CJam，12 11个字节

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

``````{         }
{     }h    Do-while that leaves the condition on the stack.
Amr!      ... but a `1` (i.e. increment) on future ones.
;   Pop the remaining 0.
``````

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

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

8

Javascript ES6，38个字节

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

`f=(a,b)=>new Date%10<1?f(a,b+1):a+b`35字节
WallyWest 2015年

2
@WallyWest不幸的是，使用`Date`时间戳的可能性并不准确，因为如果对其进行评估`true`，它将`1`在余下的毫秒内不断增加。
user81655

8

MATL，14 13 12字节

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

``````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
``````

``````iir10,2\$YlZo-+
``````

7

二进制编码的Golfical，32 29 + 1（`-x`标志）= 30字节

``````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
``````

2

2015年

7

Python，66 65 64 63字节

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

@@ only-ASCII，使用`.9>random()`量不是十分之九，因为浮点数分布不均
Mego

6

朱莉娅，30个字节

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

6

TI-BASIC，15字节

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

9字节的程序`sum(Ans)-int(log(10rand`不起作用，因为它`rand`只有14位精度，因此不能给出小于10 -14的数字

1

5

APL，17个字节

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

``````{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
``````

5

Pyth，14 12字节

``````KsQW!OT=hK;K
``````

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

5

Vitsy，12 10字节

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

4

Lisp，58个字节

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

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

`(- a(- -1 b))`工作吗？如果这样做，可为您节省2个字节。

@Neil，我不认为这工作，因为该功能应该是递归

4

认真地，10个字节

``````,Σ1±╤_G_\+
``````

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

3

Mathematica，32个字节

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

``````                               &   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.
``````

3

TeaScript，18字节21

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

3

糖果，11字节

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

``````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
``````

3

C，71 51 39 37字节

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

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

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

71字节解决方案：

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

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

3

MATL，12 13 14字节

``````r.1H\$YlY[ihs
``````

例

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

说明

``````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
``````

3

缩图，29 21字节

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

3

鼠标2002，41个39 38字节

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

``````&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
``````

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

``````&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
``````

3

果冻，7 个字节（无竞争）

``````‘⁵XỊ¤¿+
``````

这个怎么运作

``````‘⁵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.
``````

3

APL（Dyalog Unicode），13 12 字节SBCS

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

`+` 添加参数

`{``}⍣=` 应用以下功能，直到两个连续的应用程序具有相同的结果：

`?10` 1-10范围内的随机整数

`1=` 等于那个吗？（即1 / 10 机会）

`⍵+` 添加参数

@EriktheOutgolfer是的。

2

Perl 6、26个字节

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

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

（实际上可以接受任意数量的参数）

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

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

bb94

2

Pyth，11个字节

``````+sQ-18l`hO0
``````

``````+             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)
``````

2

八度，20字节

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

2

严重的是13个字节

``````,,1W+9uJYWDkΣ
``````

``````,,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
``````

while循环像这样离开堆栈：

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

`n`要运行while循环，必须上移1，因为它`0`是错误的。通过`n`在while循环后递减可以很容易地处理它，因此最终结果是`a + b + (n - 1)`

2

MATLAB，51字节

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