2013-02-14

『アルゴリズムとデータ構造』学習ノート:リニアサーチ

書籍にはJavaで書かれていたのでrubyでリニアサーチを実装しなおしてみた。

# -*- coding: utf-8 -*-
def linear_search(numbers, target)
  i = 1
  # リニアサーチの実行。対象が見つかった場合にはそのインデックスを返す
  numbers.each do |number|
    if number == target.to_i
      return i
    end
    i = i + 1
  end
  # 見つからない場合には-1を返す
  return -1
end

# 乱数を格納する配列を生成
numbers = []
20.times { numbers << rand(100) }

# 配列の出力
j = 0
numbers.each do |number|
  puts "#{j} : #{number}"
  j = j + 1
end

# 検索対象の問いかけ
puts "What is searching for?"

# コマンドラインからの入力の受け取り
target = STDIN.gets
target = target.chomp

# リニアサーチの実行
search_result = linear_search(numbers, target)

# 検索結果の出力
if search_result == -1
  puts "Could not found anything that matches \"#{target}\""
else
  puts "#{target} is found at #{search_result}"
end