2010-09-15 97 views
0

所以,我通過http://www.rubykoans.com/努力工作,我卡在about_scoring_project.rb。這是我刺傷得分的方法。爲什麼Ruby包含?評估爲零?

def score(dice) 
    score = 0; 
    if dice.respond_to?("include?") then 
    # add 1000 points if rolled 3 ones 
    score += 1000 if dice.include?([1, 1, 1]) 

    # add 100 points times die face value if rolled 3 of a number between 2 and 6 
    (2...6).each do |die| 
     score += die*100 if dice.include?([die, die, die]) 

     # award points for each 1 or 5 not a part of a set of 3 
     leftovers = dice - [1,1,1] 
     leftovers -= [5,5,5] 
     leftovers.each do |leftover| 
     score += 100 if leftover == 1 
     score += 50 if leftover == 5 
     end 
    end 
    end 
    score 
end 

class AboutScoringAssignment < EdgeCase::Koan 
    def test_score_examples 
    assert_equal 1150, score([1,1,1,5,1]) 
    assert_equal 0, score([2,3,4,6,2]) 
    assert_equal 350, score([3,4,5,3,3]) 
    assert_equal 250, score([1,5,1,2,4]) 
    end 
end 

在呼叫從第一assert_equal進球,我希望dice.include?([1,1,1]),以評估爲真,但它評估爲零(和得分返回0,而不是的1150)。

這個我試過單獨...

require 'test/unit' 

class EnumerableTests < Test::Unit::TestCase 
    def test_include 
    my_enumerable = [1,1,1,5,1] 
    assert true, my_enumerable.include?([1,1,1])  
    end 
end 

...並測試通過,所以我不知道爲什麼我在我的得分方法越來越爲零。

有人看到我做錯了什麼?

+0

好問題,但重複的[確定一個數組是否包含另一個數組在紅寶石](http://stackoverflow.com/questions/2855174/determining-whether-one-array-contains-the-contents-另一陣列在紅寶石) – 2010-09-17 00:14:09

回答

2

小挑點:Array#include?總是返回truefalse,從不nil

回答你的問題:x.include?(y)測試y是否是x的元素,而不是它是否是子數組。

[1,1,1,5,1].include?([1,1,1])返回false,因爲[1,1,1]不是數組[1,1,1,5,1]的元素。 [[1,1,1],[5,1]].include?([1,1,1]))將返回true

ruby​​中沒有檢查數組是否是另一個數組的子數組的方法,但是您可以很容易地將其編寫爲arr1.each_cons(arr2.size).include?(arr2)(需要1.8.6中的require 'enumerator')。不過,這是O(arr1.size*arr2.size)

如果你想在O(arr1.size + arr2.size),你可以實現Knuth-Morris-Pratt algorithm(這是爲了找到子字符串,但尋找子陣列,因爲它們本質上是相同的東西同樣適用)。

+0

謝謝...我得到的想法,它從RubyMine調試器返回零。也許我不明白調試器,或者它可能是一個RubyMine錯誤。 – Marvin 2010-09-15 20:15:51

+0

感謝arr1.each_cons(arr2.size).include?(arr2)建議 - 對我很好! – Marvin 2010-09-15 20:36:32

0

我想你誤解了Array#include?的功能。它將其參數搜索爲數組的一個元素,而不是作爲子序列。您的test_include將始終通過,因爲您將assert函數true作爲其第一個參數。你應該使用assert_equal這些參數或(最好)只是擺脫第一個參數。

+0

感謝您爲我澄清。 – Marvin 2010-09-15 20:36:59

相關問題