软件构造课程实验总结2

实验二

Abstract Data Type (ADT) and Object-Oriented Programming (OOP)

1.实验指导:

2.某些函数:

2.1.求两点之间的最短逻辑距离:

	/**
     * Get the distance of two vertex in the graph
     * 
     * @param p1 label for the source vertex
     * @param p2 label for the target vertex
     * @return the shortest distance (an int) between the people, or -1 if the two people are not
     *         connected(and this graph is not modified)
     */
    public int getDistance(Person p1, Person p2) {
        int count = 0;
        List<Person> friends = new ArrayList<Person>();
        int front = 0, rear = 1;
        boolean[] visited = new boolean[n];
        for (int i = 0; i < n; i++)
            visited[i] = false;
        friends.add(p1);
        visited[p1.getnumber()] = true;
        if (visited[p2.getnumber()]) {
            return count;
        }
        do {
            for (Person p : graph.targets(friends.get(front)).keySet()) {
                if (!visited[p.getnumber()]) {
                    friends.add(p);
                    visited[p.getnumber()] = true;
                }
            }
            front++;
            if (front == rear) {
                rear = friends.size();
                count++;
            }
        } while (visited[p2.getnumber()] != true && front < rear);
        if (visited[p2.getnumber()])
            return count;
        else
            return -1;
    }

2.2.根据图生成一首诗:

	/**
     * Generate a poem.
     * 
     * @param input string from which to create the poem
     * @return poem (as described above)
     */
    public String poem(String input) {
        String[] inputStrings = input.toLowerCase().split(" ");
        String[] addStrings = new String[inputStrings.length - 1];
        for (int i = 0; i < inputStrings.length - 1; i++) {
            int maxlen = 0;
            for (String s : graph.targets(inputStrings[i]).keySet()) {
                if (graph.sources(inputStrings[i + 1]).containsKey(s)) {
                    if (graph.targets(inputStrings[i]).get(s)
                            + graph.sources(inputStrings[i + 1]).get(s) > maxlen) {
                        maxlen = graph.targets(inputStrings[i]).get(s)
                                + graph.sources(inputStrings[i + 1]).get(s);
                        addStrings[i] = s;
                    }
                }
            }
        }
        String[] inputStrings1 = input.split(" ");
        String Poem = new String(inputStrings1[0]);
        for (int i = 0; i < addStrings.length; i++) {
            if (addStrings[i] != null)
                Poem += " " + addStrings[i];
            Poem += " " + inputStrings1[i + 1];
        }
        return Poem;
    }

3.实验报告:

你可能感兴趣的:(软件构造课程实验总结2)