1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

任意の3つの数字を、同じ値を除外して合計を出力する方法

1
Posted at

【概要】

1.結論

2.どのようにコーディングするのか

1.結論

配列、eachメソッド、if文を使う!


2.どのようにコーディングするのか ----------------------------------------
def any_three_sum(array)
  unique_nums = [] #---❶
  array.each do |num| #---❷
    count = 0
    array.each do |i| #---❸
      if num == i
        count += 1
      end
    end
    if count < 2 #---❹
      unique_nums << num
    end
  end

  three_sum = 0 #---❺
  unique_nums.each do |unique_num|
    three_sum += unique_num
  end

  puts three_sum

end

まず被らない数字を取り出すプログラムをコーディングしています。例えばany_three_sum([4,3,4])で考えてみます。
❶:重複しない数字を配列に入れ込む箱を用意しています。❺で再度使用します。
❷:num=4,num=3,num=4として、eachで取り出しています。
❸:❷で取り出した数字と❸i=[4,3,4]の数字が一緒の場合はcountが+1になるようにしています。❹に重複した際の重要なコーディングをしています。
❹:count < 2の時はunique_numsに配列に含めるようにしています。count は重複の数字をカウントしているので、num=4の場合は、count=2になるのでunique_sumsに追加しないようになっています。なのでnum=3 が unique_sumsに追加されます。
❺:unique_sums = [3]のみなので、puts three_sum は”3”になります。unique_sumsの値をそれぞれ取り出し(=each)全てを合計(three_sum +=により1回目・2回目の数字も反映する)したものをthree_sum変数に代入しています。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?