我是新来的鲁比。当我通过Ruby,About_Scoring_Project工作时,我遇到了一些问题。.map方法根据短语的顺序而不是变量的名称返回值。我很困惑..。
def score(dice)
total_score = 0
side = 6
count = Array.new
side.times{count << 0} # [0, 0, 0, 0, 0, 0]
# Tell the occured time of each side
while i = dice.pop
count[i-1] += 1
end
# Calculating total score
i = 0
count.map! do |item|
i += 1
if item >= 3 && i != 1
total_score = i*100
item - 3
elsif item >= 3
total_score = 1000
item - 3
else
item
end
end
# Count the rest
total_score += ( count[0]*100 + count[4]*50 )
total_score # return the total score
end虽然这个可以用,但是当我最初写的时候:
elsif item >= 3
item - 3
total_score = 1000执行时,数组计数为1000、0、0、0、0、0、0。
score([1,1,1]) # score([1,1,1]) = 101000 which should be 1000也就是说,它给了item的值1000,而不是给total_value。但是,当我改变两个短语的顺序时,它是正确的,就像上面指出的那样。能帮我个忙吗。我是Ruby和编程方面的新手。原谅我破碎的英语..。
项目背景:
# Greed is a dice game where you roll up to five dice to accumulate
# points. The following "score" function will be used to calculate the
# score of a single roll of the dice.
#
# A greed roll is scored as follows:
#
# * A set of three ones is 1000 points
#
# * A set of three numbers (other than ones) is worth 100 times the
# number. (e.g. three fives is 500 points).
#
# * A one (that is not part of a set of three) is worth 100 points.
#
# * A five (that is not part of a set of three) is worth 50 points.
#
# * Everything else is worth 0 points.
#
#
# Examples:
#
# score([1,1,1,5,1]) => 1150 points
# score([2,3,4,6,2]) => 0 points
# score([3,4,5,3,3]) => 350 points
# score([1,5,1,2,4]) => 250 points
#
# More scoring examples are given in the tests below:
#
# Your goal is to write the score method.发布于 2017-01-31 13:01:16
.map方法根据短语的顺序而不是变量的名称返回值。我很困惑..。
或多或少,是的。一个块只返回最后一个表达式的值,非常类似于一个方法。
如果你有:
count.map! do |item|
item - 3
total_score = 1000
end然后,计算为total_score = 1000的1000是块的返回值。
如果你有:
count.map! do |item|
total_score = 1000
item - 3
end然后item - 3是块的返回值。
map!依次创建一个新数组,其中包含来自块的值。
发布于 2017-01-31 14:07:00
另一种方法是:
def three_of_a_kind(dice, count)
count * (dice == 1 ? 1000 : 100 * dice)
end
def no_set(dice, count)
case dice
when 1
count * 100
when 5
count * 50
else
0
end
end
def score(rolls)
rolls.group_by(&:itself).map do |dice, throws|
n = throws.size
three_of_a_kind(dice, n / 3) + no_set(dice, n % 3)
end.inject(:+)
end
p score([1, 1, 1, 5, 1]) == 1150
p score([2, 3, 4, 6, 2]) == 0
p score([3, 4, 5, 3, 3]) == 350
p score([1, 5, 1, 2, 4]) == 250顺便问一下:
side = 6
count = Array.new
side.times{count << 0}只是:
Array.new(6){ 0 }https://stackoverflow.com/questions/41956107
复制相似问题