2016-12-05 74 views
0

我有这样的代码:如何解决类型错误无不能强迫Fixnum对象

require 'set' 

N, K = gets.split().map{ |v| v.to_i } 
set = Set.new 
numbers = gets.split().map{ |v| v.to_i } 
pairs = 0 

N.times do |i| 
    set.add(numbers[i]) 
end 

set.each{ |value| pairs += set.include?(value+K) ? 1 : 0 } 

puts pairs 

但是当我把N和K,返回此错误:

`+': nil can't be coerced into Fixnum (TypeError) 

我应该转换或其他事情?谢谢!

+0

所以,我做什么?对我来说没有意义 –

+0

我认为这里的问题是'数字[i]'在某些情况下是零,所以'set'被'nil'推到它。然后当你迭代集合时,'value'在某些情况下是零,所以'value + K'失败。你可以用'.compact'从数组中删除nil元素,但我不确定这是否解决了你的问题,因为我没有完全理解这个代码的目标是什么。 –

+0

紧凑没有工作 –

回答

1

你想计算你的集合中由K分隔的对的数量吗? 当您输入3 1后跟1 2 3时,您的代码将起作用。它回答了2

  • 首先,你真的应该多描述一下你的目标是什么。
  • 然后,不需要输入N.它应该是你的设置的大小。
  • 写调用gets

这里是一个可能实现之前所需的输入的例子:

require 'set' 

puts 'Please type the integers of your set, separated by a space. Example : 1 2 3' 
numbers = Set.new(gets.split.map{ |v| v.to_i}) 

# N=numbers.size # But you don't need it 

puts 'Which pair difference are you looking for? Example : 1' 
k = gets.to_i 

pairs = numbers.select{|value| numbers.include?(value+k)} 

count = pairs.size 

puts "#{count} pair(s) found :" 

pairs.each{|first_value| 
    puts format("(%d, %d)",first_value,first_value+k) 
} 

# Please type the integers of your set, separated by a space. Example : 1 2 3 
# 1 2 3 
# Which pair difference are you looking for? Example : 1 
# 1 
# 2 pair(s) found : 
# (1, 2) 
# (2, 3) 
相关问题