gpt4 book ai didi

for-loop - 我怎样才能改变:while condition on a Clojure for-loop while it is running?

转载 作者:行者123 更新时间:2023-12-02 08:36:22 25 4
gpt4 key购买 nike

我正在搜索所有三位数乘积的数字集中满足某些条件的最大数字。

最简单的方法是这样的:

(apply max (filter 
my-test?
(for [x (range 100 1000)
y (range x 1000)]
(* x y))))

但这涉及计算所有 900*900 产品的一半。例如,如果我发现 (* 380 455) 匹配我的 my-test? 谓词,我就不需要搜索任何一个因子小于 380 的产品。当然,如果我这样做,我也会想从最大到最小搜索列表。

在伪 Clojure 中,我想说这样的话:

(for [x (range 999 99 -1) :while (>= x P)
y (range x 99 -1) :while (>= y P)]
(* x y))

P 是我每次找到匹配项时神奇地设置为 (min x y) 的东西。

有没有办法在 Clojure 中做到这一点?

(考虑到我设置的这个特定问题,我意识到我可以以对角线方式搜索数字。但是,我现在正在尝试解决一般情况,即弄清楚如何告诉 for 循环它的一些分支需要修剪。)

最佳答案

@omeil 建议使用loop/recur 流程,这效果更好。 for 循环并不是为此而构建的。

(loop [x 999 y 999 min 99 candidates []]
(cond (<= x min) candidates ; exit condition
(<= y min) (recur (dec x) 999 min candidates) ; step x
(my-test? (* x y)) (recur x (dec y) (max min y) (conj candidates (* x y)))
:else (recur x (dec y) min candidates) ; step y
))

关于for-loop - 我怎样才能改变:while condition on a Clojure for-loop while it is running?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20927195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com