我正在为一个名为的学习网站编写一个函数 code wars我的主要问题是,当我遍历给定的数字时,我无法分配所需的5个整数。我从ruby-doc了解到我可以分配一个像
这样的数组arr = [1, 2, 3, 4, 5, 6]
arr[1..4] #=> [2, 3, 4, 5]
我适应了这样的循环
digits = 33333339999990000000
ray_a, ray_b = []
ray_a = digits[start_count, end_count]
ray_b = digits[start_count + 1, end_count+1]
但出于某种原因,因为它被循环,它为数组分配了太多的数字
问题的实际指示以及我的尝试如下......
在以下6位数字:283910
91是最大的2位数序列。
完成解决方案,使其返回给定数字中找到的最大五位数字。该数字将作为一个只有数字的字符串传入。它应该返回一个五位整数。传递的数字可能大到1000位。
我的带注释的代码......为了我的测试目的,我通过了33333339999990000000
def solution(digits)
ray_a = [] # ray_a & ray_b are to be compaired
ray_b = []
total_counter = 1
start_count = 0
end_count = 4
answer = 0
digits = digits.to_s.split('') #turns digits into an array of integers
digits.map!{|x| x.to_i }
while total_counter<=digits.length do #carries out as many loops as the variable "digits" has digits
ray_a = digits[start_count, end_count] #sets ray_a & ray_b to the numbers to be compaired
ray_b = digits[start_count + 1, end_count+1]
# the above block is where my problem is. At any time each array should have a maximum of 5 digits,
# instead using the example variable I am passing in as many as 13 digits are assigned
# I found the fatal flaw in my code with the debugging block
# puts "ray_a"
# print ray_a
ray_a.map{|x| x.to_s} #this block turns ray_a & ray_b into indivudal integers that are not arrays.
ray_a = ray_a.join('')
ray_b.map{|x| x.to_s}
ray_b = ray_b.join('')
ray_a = ray_a.to_i
ray_b = ray_b.to_i
if ray_a > ray_b # this block determines the answer
if ray_a > answer
answer = ray_a
end
end
start_count +=1 #incriments all the counters
end_count +=1
total_counter+=1
ray_a = []# resets both arrays to be redefined in the next loop
ray_b = []
end
return answer
end
solution(33333339999990000000)
答案 0 :(得分:2)
ray_a = digits[start_count, end_count]
ray_b = digits[start_count + 1, end_count+1]
您设置ray_a
和ray_b
的方式不正确。你在做什么
ray_a = digits[starting index, length]
这就是为什么你的数组长度不断变化,因为你正在递增end_count
。
您需要做的是
ray_a = digits[start_count..end_count]
或
ray_a = digits[start_count, 5]
您可以删除变量。