到目前为止我有这个代码:
def longest_awtz(n)
upto = n
series = []
for x in 2..upto
series << x
end
series.each do |num|
print num.to_s + " - "
while num != 1
if num % 2 == 0
num = num / 2
print num.to_s + " - "
else
num = (3 * num) + 1
print num.to_s + " - "
end
end
puts " "
end
end
longest_awtz(6)
并且该代码的输出是:
--------------------------------------------- helloworld 2 - 1 - 3 - 10 - 5 - 16 - 8 - 4 - 2 - 1 - 4 - 2 - 1 - 5 - 16 - 8 - 4 - 2 - 1 - 6 - 3 - 10 - 5 - 16 - 8 - 4 - 2 - 1 - ---------------------------------------------
现在,我想确定哪个起始编号产生最长的链,因此我必须将每个链放入一个数组中并对其进行计数以识别哪一个最长。我的最终输出必须如下所示:
--------------------------------------------- helloworld 2 - 1 - 3 - 10 - 5 - 16 - 8 - 4 - 2 - 1 - 4 - 2 - 1 - 5 - 16 - 8 - 4 - 2 - 1 - 6 - 3 - 10 - 5 - 16 - 8 - 4 - 2 - 1 - [2,1] # has 2 [3,10,5,16,8,4,2,1] # has 8 [4,2,1] # has 3 [5,16,8,4,2,1] # has 6 [6,3,10,5,16,8,4,2,1] # has 9 # identify and print the starting number that creates the longest chain. 6 is the starting number that creates the longest chain. ---------------------------------------------
到目前为止,我有上面的第一个输出,我仍然坚持如何将每个输出放入一个数组。你能帮我解决一下我的问题吗?
答案 0 :(得分:2)
如果你使用functional approach和适当的抽象,项目欧拉问题(以及所有这些问题的数学问题)会更简洁和声明:
collatz = proc { |n| n.even? ? n/2 : (3*n + 1) }
collatz_length = proc { |n| n > 1 ? 1 + collatz_length.(collatz.(n)) : 0 }
(1...1000).max_by(&collatz_length)
#=> 871
答案 1 :(得分:1)
我首先将序列的生成提取到自己的方法中:
def generate_sequence(num)
result = [num]
while num != 1
if num%2 == 0
num = num/2
else
num = (3*num)+1
end
result << num
end
result
end
这将返回包含序列的数组。然后,您可以编写一个方法,生成由1..n
:
def generate_sequences_upto(n)
1.upto(n).map do |num|
generate_sequence(num)
end
end
和另一个选择最长序列:
def longest_sequence(n)
generate_sequences_upto(n).max_by(&:length)
end
你可以这样使用它:
longest = longest_sequence(6)
puts "The longest sequence with length #{longest.length} is\n#{longest.inspect}"
将输出
The longest sequence with length 9 is
[6, 3, 10, 5, 16, 8, 4, 2, 1]
如果您想使用" - "
分隔数字,我建议您使用Array#join
:
longest.join(' - ')
#=> "6 - 3 - 10 - 5 - 16 - 8 - 4 - 2 - 1"
答案 2 :(得分:0)
您可能需要map
,如
array = series.map do |num|
但要正确使用此功能,您需要调整块,使其返回所需数组的值,而不是将其打印出来(puts
返回nil
,你不应该我想要这里。)
要将每个单独的数字收集到主要数字中的子数组中,而不是puts
,您需要subarray.push( num )
或类似的数据 - 这里有一些等效的语法。然后代替(或之后)puts " "
,在末尾只有subarray
变量(或任何你调用的变量),这将使它成为块的返回值,并将其添加到主数组中。最终会得到一组数组。
如果您想探索Ruby对象的可能性,我强烈建议您启动irb
并使用methods
命令查看您可以使用它执行的所有操作:
irb
1.9.3-p327 :001 > a = [1,2,3,4]
=> [1, 2, 3, 4]
1.9.3-p327 :002 > a.methods.sort
=> [:!, :!=, :!~, :&, :*, :+, :-, :<<, :<=>, :==, :===, :=~, :[], :[]=, :__id__, :__send__, :all?, :any?, :assoc, :at, :chunk, :class, :clear, :clone, :collect, :collect!, :collect_concat, :combination, :compact, :compact!, :concat, :count, :cycle, :define_singleton_method, :delete, :delete_at, :delete_if, :detect, :display, :drop, :drop_while, :dup, :each, :each_cons, :each_entry, :each_index, :each_slice, :each_with_index, :each_with_object, :empty?, :entries, :enum_for, :eql?, :equal?, :extend, :fetch, :fill, :find, :find_all, :find_index, :first, :flat_map, :flatten, :flatten!, :freeze, :frozen?, :grep, :group_by, :hash, :include?, :index, :initialize_clone, :initialize_dup, :inject, :insert, :inspect, :instance_eval, :instance_exec, :instance_of?, :instance_variable_defined?, :instance_variable_get, :instance_variable_set, :instance_variables, :is_a?, :join, :keep_if, :kind_of?, :last, :length, :map, :map!, :max, :max_by, :member?, :method, :methods, :min, :min_by, :minmax, :minmax_by, :nil?, :none?, :object_id, :one?, :pack, :partition, :permutation, :pop, :private_methods, :product, :protected_methods, :public_method, :public_methods, :public_send, :push, :rassoc, :reduce, :reject, :reject!, :repeated_combination, :repeated_permutation, :replace, :respond_to?, :respond_to_missing?, :reverse, :reverse!, :reverse_each, :rindex, :rotate, :rotate!, :sample, :select, :select!, :send, :shift, :shuffle, :shuffle!, :singleton_class, :singleton_methods, :size, :slice, :slice!, :slice_before, :sort, :sort!, :sort_by, :sort_by!, :taint, :tainted?, :take, :take_while, :tap, :to_a, :to_ary, :to_enum, :to_s, :transpose, :trust, :uniq, :uniq!, :unshift, :untaint, :untrust, :untrusted?, :values_at, :zip, :|]
这是要学习的方法的负载和负载!但如果你打字,例如Ruby Array map
进入Google,您通常会在第一个答案中获得有用的参考。
许多Ruby习语是基于你可以通过将数组方法与块组合起来做的事情,值得花时间进行探索。