有一副扑克牌,每次出示4张牌,怎样用四则运算求出其值为24的所有表达式,用ruby实现代码。
时间: 2023-02-23 13:09:39 浏览: 125
我不是很擅长编程,但是根据我的了解,可以用以下ruby代码来求出任意4张牌组合出24的表达式:cards = [1,2,3,4,5,6,7,8,9,10,11,12,13]def find_expressions(cards)
# 将4张牌的组合表达式存储在expressions数组中
expressions = []
# 循环遍历数组cards
cards.each_with_index do |c1, i1|
cards.each_with_index do |c2, i2|
cards.each_with_index do |c3, i3|
cards.each_with_index do |c4, i4|
# 如果每个元素都不相同,则求出24的表达式
if i1 != i2 && i1 != i3 && i1 != i4 && i2 != i3 && i2 != i4 && i3 != i4
expression = [c1, c2, c3, c4].permutation(4).to_a
expression.each do |e|
if e[0] + e[1] * e[2] / e[3] == 24
expressions << e
elsif e[0] - e[1] * e[2] / e[3] == 24
expressions << e
elsif e[0] * e[1] + e[2] / e[3] == 24
expressions << e
elsif e[0] * e[1] - e[2] / e[3] == 24
expressions << e
elsif e[0] * e[1] * e[2] / e[3] == 24
expressions << e
elsif e[0] + e[1] + e[2] + e[3] == 24
expressions << e
elsif e[0] + e[1] + e[2] - e[3] == 24
expressions << e
elsif e[0] + e[1] - e[2] + e[3] == 24
expressions << e
elsif e[0] - e[1] + e[2] + e[3] == 24
expressions << e
elsif e[0] - e[1] - e[2] + e[3] == 24
expressions << e
elsif e[0] - e[1] + e[2] - e[3] == 24
expressions << e
elsif e[0] - e[1] - e[2] - e[3] == 24
expressions << e
elsif e[0] + e[1] - e[2] - e[3] == 24
expressions << e
end
end
end
end
end
end
end
# 返回计算出的表达式
expressions
end# 调用find_expressions方法,传入4张牌
expressions = find_expressions(cards)# 打印出表达式
expressions.each do |e|
puts "#{e[0]} #{e[1]} #{e[2]} #{e[3]} = 24"
end
阅读全文