【问题标题】:Relational Algebra Homework (Arrays/Collection?)关系代数作业(数组/集合?)
【发布时间】:2014-07-15 21:32:32
【问题描述】:

我的作业叫做“关系代数”,它要求我对 .txt 文件中的两个表执行并集、差集、交集、连接、笛卡尔积和项目的运算:

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;
        }



    }
}

【问题讨论】:

  • 除了课堂上给你的东西,你自己尝试过什么?
  • 除了基本上什么都没有
  • 关系代数 rel = new RelationalAlgebra() ; ArrayList t1 = new ArrayList
    () ; ArrayList
    t2 = new ArrayList
    () ; ArrayList
    union = new ArrayList
    (); t1 =rel.getTable("C:\\Users\\Renny\\Documents\\T1.txt") ; t2 = rel.getTable("C:\\Users\\Renny\\Documents\\T2.txt") ; for (int i = 0; i
  • 1.将该代码放入您的问题中。 2.要考虑的事情:您正在实施的代数是否根据标题区分空关系,还是它的关系只是集合?可以有0个属性吗?你处理过空的关系吗?您是否防止无意义的联合、差异、交叉和产品? PS该代码不联合。
  • @JMMM "@" 仅适用于 cmets。 (但我检查了进度。)

标签: java relational-algebra


【解决方案1】:

看起来您的数据对应于地图,而不是数组或任何集合。 Java 已内置地图类,最有可能为您的目的是java.util.HashMap。有了这种形式的数据,您可以使用地图的keySets 和entrySets 做一些好事。您可以使用后者做的事情之一是遍历映射中的所有条目(键和值),或者通过它的iterator 或通过使用它是Iterable 的事实;您需要为您的连接(以及您的简单迭代)执行此操作,但您可以找到更简单的方法来进行交集、联合和差异操作。

请阅读 MapSet 的 Javadocs。

【讨论】:

  • 好的,我试试地图
  • @JIMM & JohnBollinger:有一个元组(数组切片)是一个 Map 并且有一个像 Set 这样的集合表示关系是合理的。然后 Map 迭代在属性名称-值对上,集合迭代在元组上。但是对于数组/关系集合使用 Map 是不合适的,因为 Map 键(以元组作为值)是不必要的;集合迭代器充当对元组的概念引用。
  • @JMMM 这些是给我的吗?唯一没有@ 通知的人是它的作者(问题或答案)和一个评论者,他是迄今为止唯一从作者那里得到评论的人。 (也就是说,我在最后一条评论中输错了您的用户名!)
  • @JMMM 和 JohnBollinger:我是说 JohnBollinger 的 table-as-map 提案并不简单,但是带有 row-as-map 的 table-as-set 很简单。 (关系=表,元组=行和属性=列。)
  • 嘿,谢谢大家的帮助,尤其是@philipxy。我现在将在我的原始帖子中发布我完成的代码。
猜你喜欢
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多