gpt4 book ai didi

Ruby - Hackerrank 谜题 - 拯救囚犯

转载 作者:数据小太阳 更新时间:2023-10-29 08:59:58 26 4
gpt4 key购买 nike

我很难理解如何在不引起内存分配问题的情况下解决这个问题。我很确定我的逻辑是合理的,但不幸的是,这似乎还不够好。有没有人对此有任何建议,以便我了解如何更有效地编写代码?

问题来了:示例输入:1个5 2 1示例输出2个有 N = 5 个囚犯和 M = 2 个糖果。分配从 ID 号 S = 1 开始,因此囚犯 1 获得第一个糖果,囚犯 2 获得第二个(最后一个)糖果。因此,我们必须警告囚犯有毒,所以我们在新行上打印 2。

# Enter your code here. Read input from STDIN. Print output to STDOUT
n = gets.strip.to_i
n.times do

arr = gets.strip.split(" ").map { |s| s.to_i}
prisoners = arr[0].to_i
sweets = arr[1].to_i
position = arr[2].to_i
prisoners_array = (1..prisoners).map { |p| p.to_i}
starting_position = prisoners_array[position - 1]
end_position = prisoners_array.size

awesome_array = (starting_position..end_position).map { |p| p.to_i}
awesomer_array = (prisoners_array[0]...starting_position).map { |p| p.to_i}
awesomest_array = awesome_array + awesomer_array

warning = 0

if sweets > prisoners
sweets = sweets % prisoners
end
for i in awesomest_array

warning += 1
if warning === sweets
puts prisoners_array[i - 1]
end
end
end

最佳答案

This appears to be有问题的练习。这里的关键是管理您对问题(使用 1 索引位置)的模数(计算 0 索引位置)的使用。

在示例中,我们有 5 个人 (n) 并希望从 人 #1 (s ) 。 Person #1 是索引位置 0,我们通过从 s 中减去一个来计算它.我们还必须从行进的距离中减去一个 t因为到达起始位置被认为是第一步。所以我们有 s+m-2 .

通过取这个结果数,对 % 取模总人数,我们将计算出我们最终到达的 0 索引位置。我们需要将此数字加一以转换回 1 索引系统。

虽然可以采用长格式方法来解决练习题(例如通过填充数组并实际迭代它们),但也可以按如下方式解决此问题:

# Enter your code here. Read input from STDIN. Print output to STDOUT
gets.strip.to_i.times do
# n - number of prisoners
# m - number of sweets
# s - starting id
n, m, s = gets.split.map &:to_i
puts ((m+s-2) % n) + 1
end

关于Ruby - Hackerrank 谜题 - 拯救囚犯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38215749/

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