-2
숙제는 "관계형 대수학"이라고하며, 읽기, 쓰기, 읽기, 쓰기 등 두 테이블에서 Union, Difference, Intersection, Join, Cartesian Product 및 Project 작업을 수행하도록 요청합니다. :관계 대수학 숙제 (배열/컬렉션?)
a 1 a 1
b 2 and z 26
c 3 c 3
기본적으로이 프로젝트에 어떻게 접근합니까?
다음은 제가 완료 한 프로젝트입니다. 실수가 있으면 알려 주시기 바랍니다. 제안과 비평도 환영합니다.
import javax.swing.JOptionPane;
import java.util.*;
import java.io.*;
/**
* ----------------------------------------------------------------------------
* ------------------------- Purpose : This class is used to create a row for a
* two dimensional data
*
* @since 06/17/2014
* @author abass.alamnehe
* --------------------------------------------------------
* ---------------------------------------------
*/
class Table { //Class Table
public String getID() { //getters and setters
return ID;
}
public void setID(String iD) {
this.ID = iD;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
String ID = "";
String name = "";
Table(String ID, String name) { //Table constructor
this.ID = ID;
this.name = name;
}
}
public class RelationalAlgebra {
/**
* It reads a two columns table into a two dimensional array
*
* @return ArrayList
* <Table>
* @throws IOException
*/
ArrayList<Table> getTable(String fileName) throws IOException {
ArrayList<Table> T1 = new ArrayList<Table>(); // creates an array list
File inFile = new File(fileName); // creates a file object
Scanner scanner = new Scanner(inFile); // Scanner is a reader class
int repetition = 1; // used to skip the 1st line from input file
while (scanner.hasNext()) { // reads until not data
if (repetition == 1) { // if 1st line, skips
scanner.next();
scanner.next();
repetition = 2;
} else { // else reads each column
String ID = scanner.next();
String name = scanner.next();
T1.add(new Table(ID, name));
}
}
scanner.close(); // close input stream
return T1; // returns the new table in the form of ArrayList
}
/**
* It prints the content of an ArrayList
* <Table>
*
* @param t
*/
void printTable(ArrayList<Table> t) {
for (int i = 0; i < t.size(); i++) {
System.out.println(t.get(i).ID + "\t" + t.get(i).name);
}
}
/**
* It prints the content of an ArrayList into a Cartesian Product
* <Table>
*
* @param t
*/
void printCartProdTable(ArrayList<Table> t) {
for (int i = 0; i < t.size() - 3; i++) {
System.out.print(t.get(i).ID + " " + t.get(i).name + "\t");
System.out.print(t.get(i + 1).ID + " " + t.get(i + 1).name + "\t");
System.out.print(t.get(i + 2).ID + " " + t.get(i + 2).name + "\t");
System.out.println(t.get(i + 3).ID + " " + t.get(i + 3).name + "\t");
}
}
/**
* It prints the content of an ArrayList
* <String>
*
* @param t
*/
void printProj(ArrayList<String> t) {
for (int i = 0; i < t.size(); i++) {
System.out.println(t.get(i));
}
}
ArrayList<Table> intersect(ArrayList<Table> t1, ArrayList<Table> t2) { // method intersect, accepts Arraylists of Tables (t1,t2)
ArrayList<Table> res = new ArrayList<Table>(); // creates an instance of ArrayList, result
/* Checks each object, "Table", in both ArrayLists (t1 against t2)
* for equality at both ID and Name , ignores case,
* adds matches to res
*/
for (int i = 0; i < t1.size(); i++) {
for (int j = 0; j < t2.size(); j++)
if (t1.get(i).ID.toString().equalsIgnoreCase(
t2.get(j).ID.toString())
&& t1.get(i).name.toString().equalsIgnoreCase(
t2.get(j).name.toString()))
res.add(t2.get(j));
}
printTable(res); //prints table. printTable method
return res; //returns result (ArrayList)
}
ArrayList<Table> join(ArrayList<Table> t1, ArrayList<Table> t2) { // method join, accepts Arraylists of Tables (t1,t2)
ArrayList<Table> res = new ArrayList<Table>(); // creates an instance of ArrayList, result
/* Checks each, "Table", at corresponding key (t1 against t2)
* for equality at both ID and Name, ignores case,
* adds matches to res
*/
for (int i = 0; i < t1.size(); i++) {
if (t1.get(i).ID.toString().equalsIgnoreCase(
t2.get(i).ID.toString())
&& t1.get(i).name.toString().equalsIgnoreCase(
t2.get(i).name.toString())) {
res.add(t2.get(i));
}
}
printTable(res);
return res; //returns result (ArrayList)
}
ArrayList<Table> union(ArrayList<Table> t1, ArrayList<Table> t2) { // method union, accepts Arraylists of Tables (t1,t2)
ArrayList<Table> res = new ArrayList<Table>(); // creates an instance of ArrayList, result
/* Adds all of t1 to res. Checks each object
* in both ArrayLists (t1 against t2) for equality at
* both ID and Name , ignores case, adds non-matches
* to res at corresponding key
*/
res.addAll(t1);
int c = 0;
for (int j = 0; j < t1.size(); j++) {
for (int i = 0; i < t2.size(); i++) {
if (t1.get(i).ID.toString().equalsIgnoreCase(
t2.get(j).ID.toString())
&& t1.get(i).name.toString().equalsIgnoreCase(
t2.get(j).name.toString()))
break;
else if (i == t2.size() - 1) {
res.add(j + c, t2.get(j));
c++;
}
}
}
printTable(res); //prints table. printTable method
return res; //returns result (ArrayList)
}
ArrayList<Table> differenceAB(ArrayList<Table> t1, ArrayList<Table> t2) { // method differenceAB, accepts Arraylists of Tables (t1,t2)
ArrayList<Table> res = new ArrayList<Table>(); // creates an instance of ArrayList, result
/* Checks each object
* in both ArrayLists (t1 against t2) for equality at
* both ID and Name , ignores case, adds t1's non-matches
* to res
*/
for (int i = 0; i < t1.size(); i++) {
for (int j = 0; j < t2.size(); j++) {
if (t1.get(i).ID.toString().equalsIgnoreCase(
t2.get(j).ID.toString())
&& t1.get(i).name.toString().equalsIgnoreCase(
t2.get(j).name.toString()))
break;
else if (j == t2.size() - 1) {
res.add(t1.get(i));
}
}
}
printTable(res); //prints table. printTable method
return res; //returns result (ArrayList)
}
ArrayList<Table> differenceBA(ArrayList<Table> t1, ArrayList<Table> t2) { // method differenceBA, accepts Arraylists of Tables (t1,t2)
ArrayList<Table> res = new ArrayList<Table>(); // creates an instance of ArrayList, result
/* Alternate for above method.
* Checks each object
* in both ArrayLists (t1 against t2) for equality at
* both ID and Name , ignores case, adds t2's non-matches
* to res
*/
for (int j = 0; j < t1.size(); j++) {
for (int i = 0; i < t2.size(); i++) {
if (t1.get(i).ID.toString().equalsIgnoreCase(
t2.get(j).ID.toString())
&& t1.get(i).name.toString().equalsIgnoreCase(
t2.get(j).name.toString()))
break;
else if (i == t1.size() - 1) {
res.add(t2.get(j));
}
}
}
printTable(res); //prints table. printTable method
return res; //returns result (ArrayList)
}
ArrayList<Table> cartProdBA(ArrayList<Table> t1, ArrayList<Table> t2) { // method cartProdBA, accepts Arraylists of Tables (t1,t2)
ArrayList<Table> res = new ArrayList<Table>(); // creates an instance of ArrayList, result
for (int j = 0; j < t1.size(); j++) {
for (int i = 0; i < t2.size(); i++) {
/* Distributes ID and name of each table t2,
* across each table t1. ((Adds new table to
* res; each name and ID from t2 with each t1 name and ID))
*/
res.add(new Table(t2.get(j).ID, t1.get(i).ID));
res.add(new Table(t2.get(j).ID, t1.get(i).name));
res.add(new Table(t2.get(j).name, t1.get(i).ID));
res.add(new Table(t2.get(j).name, t1.get(i).name));
}
}
printCartProdTable(res); //prints table. printCartProdTable method
return res; //returns result (ArrayList)
}
ArrayList<Table> cartProdAB(ArrayList<Table> t1, ArrayList<Table> t2) { // method cartProdAB, accepts Arraylists of Tables (t1,t2)
ArrayList<Table> res = new ArrayList<Table>(); // creates an instance of ArrayList, result
for (int j = 0; j < t1.size(); j++) {
for (int i = 0; i < t2.size(); i++) {
/* Alternate for above method.
* Distributes ID and name of each table t2,
* across each table t1. ((Adds new table to
* res; each name and ID from t2 with each t1 name and ID))
*/
res.add(new Table(t1.get(j).ID, t2.get(i).ID));
res.add(new Table(t1.get(j).ID, t2.get(i).name));
res.add(new Table(t1.get(j).name, t2.get(i).ID));
res.add(new Table(t1.get(j).name, t2.get(i).name));
}
}
printCartProdTable(res); //prints table. printCartProdTable method
return res; //returns result (ArrayList)
}
ArrayList<String> projectID(ArrayList<Table> t1, ArrayList<Table> t2) { // method projectID, accepts Arraylists of Tables (t1,t2)
ArrayList<Table> res = new ArrayList<Table>(); // creates an instance of ArrayList, result
ArrayList<String> proj = new ArrayList<String>(); // creates an instance of ArrayList, proj
/* Makes union of t1 and t2 in res.
* Adds each ID from res to proj.
*/
res.addAll(t1);
int c = 0;
for (int j = 0; j < t1.size(); j++) {
for (int i = 0; i < t2.size(); i++) {
if (t1.get(i).ID.toString().equalsIgnoreCase(
t2.get(j).ID.toString())
&& t1.get(i).name.toString().equalsIgnoreCase(
t2.get(j).name.toString()))
break;
else if (i == t2.size() - 1) {
res.add(j + c, t2.get(j));
c++;
}
}
}
for (int i = 0; i < res.size(); i++) {
proj.add(res.get(i).ID);
}
printProj(proj); //prints table. printProj method
return proj; //returns proj (ArrayList)
}
ArrayList<String> projectName(ArrayList<Table> t1, ArrayList<Table> t2) { // method projectName, accepts Arraylists of Tables (t1,t2)
ArrayList<Table> res = new ArrayList<Table>(); // creates an instance of ArrayList, result
ArrayList<String> proj = new ArrayList<String>(); // creates an instance of ArrayList, proj
/* Alternate for above method.
* Makes union of t1 and t2 in res.
* Adds each Name from res to proj.
*/
res.addAll(t1);
int c = 0;
for (int j = 0; j < t1.size(); j++) {
for (int i = 0; i < t2.size(); i++) {
if (t1.get(i).ID.toString().equalsIgnoreCase(
t2.get(j).ID.toString())
&& t1.get(i).name.toString().equalsIgnoreCase(
t2.get(j).name.toString()))
break;
else if (i == t2.size() - 1) {
res.add(j + c, t2.get(j));
c++;
}
}
}
for (int i = 0; i < res.size(); i++) {
proj.add(res.get(i).name);
}
printProj(proj); //prints table. printProj method
return proj; //returns proj (ArrayList)
}
/**
* An entry point for program execution
*
* @param args
*/
public static void main(String[] args) throws IOException {
RelationalAlgebra rel = new RelationalAlgebra(); // creates an object of
// this class
ArrayList<Table> t1 = new ArrayList<Table>();
ArrayList<Table> t2 = new ArrayList<Table>(); // creates an instance of ArrayList, t1
// creates an instance of ArrayList, t2
String t1file = JOptionPane.showInputDialog(
"Enter Table 1 (.txt) file location with double backslahes") //user input to string file location, t1
.toString();
String t2file = JOptionPane.showInputDialog(
"Enter Table 2 (.txt) file location with double backslahes") //user input to string file location, t2
.toString();
t1 = rel.getTable(t1file); // creates an object based on the input file
t2 = rel.getTable(t2file); // creates an object based on the input file
boolean input = false; //creates exit for while loop
String select = null; // initializes variable for switch statement
while (!input) { //while loop to prevent crash with invalid input
select = JOptionPane
.showInputDialog(
"Enter a number (1-9) corresponding to desired operation: \n"
+ " 1 = Intersection of Table 1 and Table 2 \n"
+ " 2 = Union of Table 1 and Table 2 \n"
+ " 3 = Join of Table 1 and Table 2 \n"
+ " 4 = Difference (Table 1 - Table 2) \n"
+ " 5 = Difference (Table 2 - Table 1) \n"
+ " 6 = Cartesian Product (Table 1 x Table 2) \n"
+ " 7 = Cartesian Product (Table 2 x Table 1) \n"
+ " 8 = Project 'ID' from the Union of Table 1 and Table 2 \n"
+ " 9 = Project 'Name' from the Union of Table 1 and Table 2 \n")
.toString(); // takes user input for selection of operation 1-9, as string
if (select.matches("1") || select.matches("2") // tests for valid input
|| select.matches("3") || select.matches("4")
|| select.matches("5") || select.matches("6")
|| select.matches("7") || select.matches("8")
|| select.matches("9"))
input = true; // exits while loop, if valid input
}
switch (select) { //switches between all 9 operation methods
// according to user input, which print final results of operation
case "1":
rel.intersect(t1, t2);
break;
case "2":
rel.union(t1, t2);
break;
case "3":
rel.join(t1, t2);
break;
case "4":
rel.differenceAB(t1, t2);
break;
case "5":
rel.differenceBA(t1, t2);
break;
case "6":
rel.cartProdAB(t1, t2);
break;
case "7":
rel.cartProdBA(t1, t2);
break;
case "8":
rel.projectID(t1, t2);
break;
case "9":
rel.projectName(t1, t2);
break;
}
}
}
수업 시간에받은 것과는 별도로 무엇을 시도 했습니까? – drum
기본적으로 아무것도 아니라, – JMMM
RelationalAlgebra rel = new RelationalAlgebra(); \t \t \t ArrayList
답변
귀하의 데이터가지도가 아니라 배열이 아닌 것처럼 보입니다. 자바는지도 클래스를 내장하고 있는데, 가장 가능성이 높은 곳은
java.util.HashMap
입니다. 이 형식의 데이터를 사용하면 'keySet
'및entrySet
'맵으로 멋진 작업을 수행 할 수 있습니다. 후자를 사용하여 수행 할 수있는 작업 중에는iterator
을 통해 또는Iterable
이라는 사실을 사용하여지도의 모든 항목 (키 및 값)에 대해 반복됩니다. 당신은 당신의 조인 (그리고 당신의 간단한 반복)을 위해 그렇게 할 필요가있을 것이다. 그러나 당신은 교차, 결합 및 차 집합 연산에 대한 더 간단한 접근법을 발견 할 수있다.Map
및Set
에 대한 Javadocs를 읽으십시오.출처
2014-07-15 22:21:04
좋아요, 맵을 사용해 보겠습니다. – JMMM
@JIMM & JohnBollinger : 튜플 (배열 슬라이스)을 Map으로하고 Set과 같은 콜렉션에 관계를 나타내는 것이 합리적입니다. 그런 다음 Map 반복은 속성 이름 - 값 쌍을 넘고 컬렉션 반복은 튜플을 넘습니다. 그러나 맵/키 컬렉션 (값으로 터플을 사용)은 불필요하므로 배열/관계 컬렉션에 Map을 사용하는 것은 적절하지 않습니다. 콜렉션 반복자는 튜플에 대한 개념적 참조로 작동합니다. – philipxy
롤, 내 머리 바로 위에 :) – JMMM
관련 문제