9
6

More than 5 years have passed since last update.

Ruby アルゴリ計算

Last updated at Posted at 2014-04-29

エラトステネスの篩

hello.rb
def eratosthenes(n)
  numbers = (0..n).to_a
  numbers[0],numbers[1] = nil
  numbers.each do |d|
    next if d == nil
    break if (Math.sqrt(n) < d)
    (2*d..n).step(d){|e| numbers[e] = nil}
  end
  numbers.compact!
  return numbers
end

p eratosthenes(100)

=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

1から9までの九九を計算する

hello.rb

[*1..9].each do |abc|
  [*1..9].each do |f|
    printf("%3d", abc * f)
  end
  print "\n"
end
 =>
  1  2  3  4  5  6  7  8  9
  2  4  6  8 10 12 14 16 18
  3  6  9 12 15 18 21 24 27
  4  8 12 16 20 24 28 32 36
  5 10 15 20 25 30 35 40 45
  6 12 18 24 30 36 42 48 54
  7 14 21 28 35 42 49 56 63
  8 16 24 32 40 48 56 64 72
  9 18 27 36 45 54 63 72 81

ジャンケンを実装する

hello.rb
def jankenn
  janken = { グー: 0, パー: 1, チョキ: 2 }
  puts("ジャンケン!!!")
  n = gets.chomp
  puts "わたし: #{n}!!!"
  m = janken.key(rand(3)).to_s
  puts "相手: #{m}!!!"

  if %w(グー チョキ パー).any?{ |abc| abc == n }
    if n == m
      puts "引き分け"
    elsif n == "グー" && m == "チョキ"
      puts "あなたの勝ち"
    elsif n == "チョキ" && m == "パー"
      puts "あなたの勝ち"
    elsif n == "パー" && m == "グー"
      puts "あなたの勝ち"
    else
      puts "あなたの負け"
    end
  else
    "グー・チョキ・パーのいずれかを入力して下さい!"
  end
end

好きな倍数を作る

hello.rb

def input_of_multiple
    puts "数値は1から始まります"
    puts "数値の終わりの範囲を入力して下さい"
    range = gets.chomp.to_i
    if range == 0
      raise "正の整数を入力してください"
    end
    puts "倍数を入力し下さい"
    x = gets.chomp.to_i
    if x == 0
      raise "正の整数を入力してください"
    end

  arr = []
  ->(range, x){
    (1..range).each do |abc|
      arr << abc if abc % x == 0
    end
  }.call(range, x)
  print arr
end

素因数分解

hello.rb
class Integer
  def prime_factors(n=self)
    list = []
    k = 2
    while n != 1
      if n % k == 0
        list.push(k)
        n = n / k
      else
        k = k + 1
      end
    end
    return list
  end
end

p 100.prime_factors
=> [2, 2, 5, 5]
9
6
0

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
9
6