Ruby 和数学问题
假设我必须有一辆小计为 1836.36 的购物车。我必须通过将具有一系列价格的列表中的几种产品相加来达到这个精确的金额。
假设我有一些价格为 9.99、29.99、59.99 的产品,我可以添加每种产品以满足所需的小计。如何使用 Ruby 解决这一问题?
我想过将价格列表输入脚本中,并以某种方式让脚本添加,直到达到小计,然后吐出达到小计所需的价格......只是不知道如何处理它。
欢迎任何建议,并提前致谢。期待想法。
Let's say I have to have a cart with a subtotal of 1836.36. I must achieve this exact amount by adding up several products from a list with a range of prices.
Say, I have a few products at 9.99, 29.99, 59.99 and I can add several of each to meet the desired subtotal. How would one approach this problem using Ruby?
I've thought of feeding the list of prices into a script and somehow getting the script to add until it reaches the subtotal and then spit out the prices required to reach the subtotal... just not sure how to approach it.
Any suggestions are welcome and thanks in advance. Looking forward to ideas.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
9.99*x + 29.99*y + 59.99*z = 1836.36
强力迭代整数范围内 x,y,z 的所有排列
例如:
丢弃总和不是 1835.36 的任何答案。
类似的东西……没测试过。您可能可以调整和优化它以忽略肯定无法通过的情况。
9.99*x + 29.99*y + 59.99*z = 1836.36
brute force iterate through all the permutations of x,y,z within a range of integers
For example:
discard any answer whose sum is not 1835.36.
Something like that... haven't tested it. You could probably tweak and optimize it to ignore cases that would certainly fail to pass.