功能以创建具有随机数和胜利条件的简化飞镖游戏
我设法用代码创建了一对数字
(defn dart-throwing []
[(- (* 2 (rand-int 2)) 1) (- (* 2 (rand-int 2)) 1)])
(def onetrial (dart-throwing))
,但我不知道如何创建我的获胜条件,该条件将是x^2 + y^2< 1
我尝试写作,
(defn won? [x y]
(< (+ (* x x) (* y y)) 1))
(won? onetrial)
希望它会检查对[]
从刺激的情况
我 , 谢谢
I managed to create a pair of numbers with code
(defn dart-throwing []
[(- (* 2 (rand-int 2)) 1) (- (* 2 (rand-int 2)) 1)])
(def onetrial (dart-throwing))
But I do not know how to create my win condition which would be x^2 + y^2 < 1
I tried writing
(defn won? [x y]
(< (+ (* x x) (* y y)) 1))
(won? onetrial)
I expected it to check the pair []
from dart-throwing and check if it was less than 1 giving a true or false
I would appreciate it if I had some help, thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码执行的操作与以下相同:
rand-nth
从给定的集合中有意选择 - 在本例中为-1
和1
。问题是:-1 的平方是 1 - 所以
(+ (* xx) (* yy))
永远不会<
小于 1。所以:什么是
won?
函数的意义是什么?或者飞镖不应该返回 -1 和 1 之间的一些浮点数?从范围内进行选择?在这种情况下,
rand-int
是错误的。那么它一定是rand
。因此,应该是
(- (* 2 (rand)) 1) ,而不是
(- (* 2 (rand-int 2)) 1)
。但是,rand
不包括上限 - 在本例中为1
。可以将上限发送到1 + Float/MIN_VALUE
以包含 1。或者保留它,但在 -1 和 1 之间随机选择,然后将它们与结果相乘 - 然后会得到包含 1 的值。 - 但它不会是均匀分布的......Your code does the same like:
rand-nth
chooses deliberately from the given collection - in this case-1
and1
.And here is the problem: -1 squared is 1 - so
(+ (* x x) (* y y))
will never be<
than 1.So: What is the point of the
won?
function?Or shouldn't dart-throwing return some float between -1 and 1? a selection from the range? In this case
rand-int
is wrong. It must be thenrand
.so, instead of
(- (* 2 (rand-int 2)) 1)
it should be then(- (* 2 (rand)) 1)
. However,rand
excludes the upper limit - in this case1
. One could send the upper limit to1 + Float/MIN_VALUE
to include 1. Or one keeps it but randomly choose between -1 and 1 and multiply them with the result - then one would get 1 included ... - but it wouldn't be a even distribution ...据我所知,您的投掷实现不正确,返回组件
-1 | 1
而不是-1 | 0 | 1
。我建议的是这样的:
然后,您只是在尝试函数中使用它:
won?
似乎是如下:检查:
此外,因为唯一的获胜情况是<代码> [0 0] ,
won?
counld是这样的:或像这样:
甚至是这样:
as far as i can see, you've got an incorrect throwing implementation, returning components
-1 | 1
instead of-1 | 0 | 1
.what i would propose, is something like this:
then you just use it in an attempt function:
and the
won?
seems to be like the following:check it:
moreover, since the only winning situation is
[0 0]
,won?
counld be like this:or like this:
or even like this:
您的
won?
函数期望两个参数,一个x
和y
。您的onortrial
是两个元素的向量,但是这里是一个参数。您有几个选择:
您可以使用 apply 将vector传播到参数中列表。
(申请won?oneTrial)
或
您可以重写
won?
稍微使用破坏Your
won?
function expects two arguments, anx
and ay
. Youronetrial
is a vector of two elements, but it is a single argument here.You have a couple of options:
You can use apply to 'spread' the vector into the argument list.
(apply won? onetrial)
OR
You can rewrite
won?
slightly using destructuring