- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我很难理解如何在不引起内存分配问题的情况下解决这个问题。我很确定我的逻辑是合理的,但不幸的是,这似乎还不够好。有没有人对此有任何建议,以便我了解如何更有效地编写代码?
问题来了:示例输入: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/
双系统grub意外消失怎么办? 不用重装系统、不用去维修店、不会丢数据,教你一招,完美恢复grub! 。 背景 我的电脑是windows和linux双系统,启动项使用的grub。某天
我正在尝试构建一个表,该表将充当第三方服务的批量同步队列。 下面的方法应该不言自明;但需要明确的是,它的目的是向 delayed_syncs 表中添加一个具有 status: :queued 的新可更
我需要在特殊情况下捕获 NameError。但我不想捕获 NameError 的所有子类。有办法实现吗? # This shall be catched begin String::NotExis
我正在使用以下方法发送电子邮件: class Communicate msg end end bcc 包含 4 或 5 个电子邮件地址。 在我的测试中,我注意到两件事: 即使其中一封电子邮件不是
我想知道如何在使用 lib Linear 的 Java API 时挽救所有预测结果。 由于有详细记录,人们可以使用以下代码来挽救预测的准确性: Feature[] instance = new Fea
在我的 Rails 3 应用程序中,我通过以下方式获取 path_info: Rails.application.routes.recognize_path(url, { :method => req
当我将 IO::popen 与不存在的命令一起使用时,我在屏幕上打印了一条错误消息: irb> IO.popen "fakefake" #=> # irb> (irb):1: command
例如,如果我尝试删除一个不存在的表,我将收到以下错误: "# ex if ex.cause.is_a?(PG::UndefinedTable) # do something else
我负责使用 Cucumber 测试非 Rails 网络应用程序。我已经启动并运行了基本测试,I.E.我可以做类似的事情 Then /^the page should have a header$/ d
我有以下表演 Action : def show @name = params[:id] rescue ActiveRecord::RecordNotFound redirect_to :
我是一名优秀的程序员,十分优秀!