1

3つの数字を入力して合計をとるルビープログラムを作成しようとしていますが、同じ数字がある場合は合計にカウントされません。例(4,5,4)=5私の問題は私の表現にあります。同じ番号を入力すると、さまざまな組み合わせで複数の出力が得られます。例5,5,5=15,5,0と入力します

if a != b or c then
  puts a+b+c
elsif b != a or c then
  puts a+b+c
elsif c != a or b then 
  puts a+b+c
end

if a == b then
  puts c
elsif a == c then
  puts b
elsif b == c then
  puts a
end

if a == b and c then
  puts 0
elsif b == a and c then
  puts 0
elsif c == a and b then
  puts 0
end
4

1 に答える 1

2

2つの美しい自明のワンライナーでそれを解決する

array = [a,b,c]

array = array.keep_if {|item| array.count(item) == 1 }
array.inject(0){|sum,item| sum + item}

-最初の行は、パラメータを使用して配列を作成します。
-2行目は、カウントが1に等しいアイテムのみを保持し(複数回出現するアイテムを削除)、それを配列に格納します。
-3行目は、残りのすべての要素を合計します。

Voilà、ルビーの方法:)

于 2012-04-03T22:58:35.283 に答える