Skip to content

Instantly share code, notes, and snippets.

@incheon
Last active August 29, 2015 13:57
Show Gist options
  • Save incheon/9756034 to your computer and use it in GitHub Desktop.
Save incheon/9756034 to your computer and use it in GitHub Desktop.
情報論理及び演習サンプルプログラム 2012年度後期第1回
public class Existence {
public static void main(String[] args) {
String flag; // 検索結果
long startTime, endTime; // 検索の開始時間、終了時間
int size; // 配列のサイズ
int d; // 検索データ
int[] array; // 配列
CheckExist exist;
size = Integer.parseInt(args[0]); // コマンドライン引数の第一引数をint型に変換
d = Integer.parseInt(args[1]); // コマンドライン引数の第二引数をint型に変換
array = new int[size]; // 配列生成
exist = new CheckExist(); // CheckExistクラスのインスタンスを生成
exist.initArray(array); // 配列の各要素に値を代入
startTime = System.nanoTime(); // 現在の時間(ナノ秒)を取得
flag = exist.isExist(d, array); // データの検索
endTime = System.nanoTime();
System.out.println("検索データ:" + d);
System.out.print("データ集合:");
for (int i=0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
System.out.println("検索結果:" + flag);
System.out.println("実行時間:" + (endTime - startTime) + "ナノ秒");
}
}
class CheckExist {
public void initArray(int[] array) {
int len = array.length;
for (int i=0; i<len; i++) {
int n = (int)(Math.random()*len);
// 乱数を用いて、int型の値(0<=n<=len-1)を生成
array[i] = n;
}
}
public String isExist(int d, int[] array) {
for (int i=0; i<array.length; i++) {
if (d==array[i]) {
return "yes";
// 検索データが見つかれば文字列"yes"を返す
}
}
return "no";
// 検索データが見つからなければ文字列"no"を返す
}
}
# coding: utf-8
class CheckExist
def initArray(array)
len = array.length
for i in 0..len-1
n = Random.rand(len)
array[i] = n
end
end
def isExist(d, array)
for i in 0..array.length
return "yes" if d.to_s==array[i].to_s
end
"no"
end
end
size = ARGV[0].to_i
d = ARGV[1].to_i
array = Array.new(size)
exist = CheckExist.new
exist.initArray(array)
startTime = Time.now
flag = exist.isExist(d, array)
endTime = Time.now
puts "検索データ:" + d.to_s
puts "データ集合:"
for i in 0..array.length
printf array[i].to_s + " "
end
puts "\n\n"
puts "検索結果:" + flag
puts "実行時間:" + (endTime.nsec - startTime.nsec).to_s + "ナノ秒"
@incheon
Copy link
Author

incheon commented Mar 25, 2014

追加情報

  • Rubyで書きなおしたものを追加してあります。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment