如果三元组的总和等于给定数字
,则以下代码返回trueclass triplet
def three_sum_fast(ary, sum)
ary.sort!
(0..ary.length - 3).each do |i|
front = ary[i]
start_index = i + 1
back_index = ary.length - 1
while(start_index < back_index) do
start = ary[start_index]
back = ary[back_index]
if (front + start + back) > 0
back_index -= 1
else
start_index += 1
end
if front + start + back == sum
return true
break
end
end
end
false
end
end
以下代码是测试文件
require "test/unit"
require "triplet.rb"
class Test < Test::Unit::TestCase
def test_trip
num=triplet.new
num.three_sum_fast({1,3,4,5,6,7},14)
assert_equal (expected,true)
end
end
发现的错误是:
syntax error, unexpected ',', expecting =>
num.three_sum_fast({1,3,4,5,6,7},14)
syntax error, unexpected ',', expecting ')'
assert_equal (expected,true)
答案 0 :(得分:1)
类名是常量,因此必须以大写字母开头:
class Triplet
# ...
end
在你的测试中:
num = Triplet.new
通过[
和]
创建数组,而通过{
和}
创建哈希,即
num.three_sum_fast([1, 3, 4, 5, 6, 7], 14)
下一行有一个错误的空间:
assert_equal (expected,true)
# ^
# that one is wrong
必须是:
assert_equal(expected, true)
# ^
# that one is okay
即使删除了错误的空间,该行也不起作用,因为expected
是未定义的变量。在使用之前,您必须分配:
expected = num.three_sum_fast([1, 3, 4, 5, 6, 7], 14)
assert_equal(expected, true)
这样可行,但expected
用词不当。 true
是预期的值,而方法的结果是实际值。所以它应该是:
actual = num.three_sum_fast([1, 3, 4, 5, 6, 7], 14)
assert_equal(true, actual)
或简单地说:
assert_equal(true, num.three_sum_fast([1, 3, 4, 5, 6, 7], 14))