实训GridWorld第二阶段问答题part4 and part5

版权声明:本文为博主原创文章,转载请标明出处 https://blog.csdn.net/C2681595858/article/details/80141375

都是按照自己的理解写的,若有错误,欢迎还请斧正

part4

1.

// @file: GridWorldCode\framework\info\gridworld\actor\Critter.java

 public void act();
 public ArrayList<Actor> getActors();
 public void processActors(ArrayList<Actor> actors);
 public ArrayList<Location> getMoveLocations();
 public Location selectMoveLocation(ArrayList<Location> locs);
 public void makeMove(Location loc);

2.

// @file: GridWorldCode\framework\info\gridworld\actor\Critter.java

 public ArrayList<Actor> getActors();
 public void processActors(ArrayList<Actor> actors);
 public ArrayList<Location> getMoveLocations();
 public Location selectMoveLocation(ArrayList<Location> locs);
 public void makeMove(Location loc);

3

It is usually not a good idea to override the act method in a Critter subclass. The Critter class was designed to represent actors that process other actors and then move. If you find the act method unsuitable for your actors, you should consider extending Actor, not Critter.

4

all methods implemented in Actor.java

getColor();
setColor(Color newColor);
getDirection();
setDirection(int newDirection);
getGrid();
getLocation();
putSelfInGrid(Grid<Actor> gr, Location loc)
removeSelfFromGrid();
moveTo(Location newLocation);

5

// @file: GridWorldCode\framework\info\gridworld\actor\Critter.java
//@line: 88~131

// Gets a list of possible locations for the next move.
public ArrayList<Location> getMoveLocations()
    {
        return getGrid().getEmptyAdjacentLocations(getLocation());
    }

//Selects the location for the next move.
    public Location selectMoveLocation(ArrayList<Location> locs)
    {
        int n = locs.size();
        if (n == 0)
            return getLocation();
        int r = (int) (Math.random() * n);
        return locs.get(r);
    }

  //Moves this critter to the given location <code>loc</code>, or removes this critter from its grid if <code>loc</code> is <code>null</code>.
    public void makeMove(Location loc)
    {
        if (loc == null)
            removeSelfFromGrid();
        else
            moveTo(loc);
    }

6

Because the Critter extend from Actor, and it has no particular attribute. so it use the default Construct;

7

Because the ChameleonCritter override the method used in act();;

// @file: GridWorldCode\projects\crittes\ ChameleonCritter.java
//@line: 36~54

public void processActors(ArrayList<Actor> actors)
    {
        int n = actors.size();
        if (n == 0)
            return;
        int r = (int) (Math.random() * n);

        Actor other = actors.get(r);
        setColor(other.getColor());
    }

    /**
     * Turns towards the new location as it moves.
     */
    public void makeMove(Location loc)
    {
        setDirection(getLocation().getDirectionToward(loc));
        super.makeMove(loc);
    }

8. Because compare to the parent(Critter), the ChameleonCritter only different in direction ,so after it change its direction, it can call the makeMove();method of its parent;

9.we can add following code in the makeMove(); method of ChameleonCritter.

10.Because it want to get the same Actors with Critter.

11.Actor

// @file: GridWorldCode\framework\info\gridworld\actor\Actor.java
//@line: 102~105
 public Location getLocation()
    {
        return location;
    }

12.By getGrid(); method.

// @file: GridWorldCode\framework\info\gridworld\actor\Actor.java
//@line: 92~95
 public Grid<Actor> getGrid()
    {
        return grid;
    }

13.Because it want to get the same processActors with Critter.

14.

A crab gets the actors in the three locations immediately in front, to its front-right and to its front-left “eat” (i.e. remove) selected actors that are not rocks or critters.

// @file: GridWorldCode\projects\critters\CrabCritter.java
//@line: 44~57
public ArrayList<Actor> getActors()
    {
        ArrayList<Actor> actors = new ArrayList<Actor>();
        int[] dirs =
            { Location.AHEAD, Location.HALF_LEFT, Location.HALF_RIGHT };
        for (Location loc : getLocationsInDirections(dirs))
        {
            Actor a = getGrid().get(loc);
            if (a != null)
                actors.add(a);
        }

        return actors;
    }
// @file: GridWorldCode\framework\info\gridworld\actor\Critter.java
//@line: 71~78
 public void processActors(ArrayList<Actor> actors)
    {
        for (Actor a : actors)
        {
            if (!(a instanceof Rock) && !(a instanceof Critter))
                a.removeSelfFromGrid();
        }
    }

15.

Because it want to Finds the valid adjacent locations of this critter in different directions.

// @file: GridWorldCode\projects\critters\CrabCritter.java
//@line: 101~114
public ArrayList<Location> getLocationsInDirections(int[] directions)
    {
        ArrayList<Location> locs = new ArrayList<Location>();
        Grid gr = getGrid();
        Location loc = getLocation();

        for (int d : directions)
        {
            Location neighborLoc = loc.getAdjacentLocation(getDirection() + d);
            if (gr.isValid(neighborLoc))
                locs.add(neighborLoc);
        }
        return locs;
    }    

16.

three locations in front, to its front-right and to its front-left(4,3)(4,4)(4,5)
int[] dirs =
{ Location.AHEAD, Location.HALF_LEFT, Location.HALF_RIGHT };

17.

similarities: when loc is null they will remove itself from grid.
different; CrabCritter only move to left or right.

18

if all three directions can’t move, it will randomly turns left or right.

// @file: GridWorldCode\projects\critters\CrabCritter.java
//@line: 62~72
int n = locs.size();
        if (n == 0)
            return getLocation();
        int r = (int) (Math.random() * n);
        return locs.get(r);
// @file: GridWorldCode\framework\info\gridworld\actor\Critter.java
//@line: 104~111
if (loc.equals(getLocation()))
        {
            double r = Math.random();
            int angle;
            if (r < 0.5)
                angle = Location.LEFT;
            else
                angle = Location.RIGHT;
            setDirection(getDirection() + angle);
        }

19

Because following code the condition

// @file: GridWorldCode\framework\info\gridworld\actor\Critter.java
//@line: 71~78
 public void processActors(ArrayList<Actor> actors)
    {
        for (Actor a : actors)
        {
            if (!(a instanceof Rock) && !(a instanceof Critter))
                a.removeSelfFromGrid();
        }
    }

part5

1

method isValid();specified at class Grid and implement at BoundedGrid and UnboundedGrid.

// @file: GridWorldCode\framework\info\gridworld\grid\BoundedGrid.java
//@line: 60~64
public boolean isValid(Location loc)
    {
        return 0 <= loc.getRow() && loc.getRow() < getNumRows()
                && 0 <= loc.getCol() && loc.getCol() < getNumCols();
    }
// @file: GridWorldCode\framework\info\gridworld\grid\UnboundedGrid.java
//@line: 53~56
public boolean isValid(Location loc)
    {
        return true;
    }

2

method getValidAdjacentLocations(Location loc); call the isValid method. Because other methods use the getValidAdjacentLocations(Location loc); method.

// @file: GridWorldCode\framework\info\gridworld\grid\AbstractGrid.java
//@line: 36~49
 public ArrayList<Location> getValidAdjacentLocations(Location loc)
    {
        ArrayList<Location> locs = new ArrayList<Location>();

        int d = Location.NORTH;
        for (int i = 0; i < Location.FULL_CIRCLE / Location.HALF_RIGHT; i++)
        {
            Location neighborLoc = loc.getAdjacentLocation(d);
            if (isValid(neighborLoc))
                locs.add(neighborLoc);
            d = d + Location.HALF_RIGHT;
        }
        return locs;
    }

3

the methods getOccupiedAdjacentLocations(loc)); and get(neighborLoc); used.

method getOccupiedAdjacentLocations(Location loc);implement in class AbstractGrid. and get(loc);implement in BoundedGrid and UnbounedeGrid.

// @file: GridWorldCode\framework\info\gridworld\grid\AbstractGrid.java
//@line: 62~71
public ArrayList<Location> getOccupiedAdjacentLocations(Location loc)
    {
        ArrayList<Location> locs = new ArrayList<Location>();
        for (Location neighborLoc : getValidAdjacentLocations(loc))
        {
            if (get(neighborLoc) != null)
                locs.add(neighborLoc);
        }
        return locs;
    }
// @file: GridWorldCode\framework\info\gridworld\grid\BoundedGrid.java
//@line: 85~91
 public E get(Location loc)
    {
        if (!isValid(loc))
            throw new IllegalArgumentException("Location " + loc
                    + " is not valid");
        return (E) occupantArray[loc.getRow()][loc.getCol()]; // unavoidable warning
    }
// @file: GridWorldCode\framework\info\gridworld\grid\UnboundedGrid.java
//@line: 66~71
public E get(Location loc)
    {
        if (loc == null)
            throw new NullPointerException("loc == null");
        return occupantMap.get(loc);
    }

4

Because we use get(loc); know whether at location loc has a object,if not , it must be null.so we can return the location.

// @file: GridWorldCode\framework\info\gridworld\grid\AbstractGrid.java
//@line: 56~57
if (get(neighborLoc) == null)
                locs.add(neighborLoc);

5

It will find only 4 directions(North, south, west, east) valid location;

// @file: GridWorldCode\framework\info\gridworld\grid\AbstractGrid.java
//@line: 41~47
for (int i = 0; i < Location.FULL_CIRCLE / Location.HALF_RIGHT; i++)
        {
            Location neighborLoc = loc.getAdjacentLocation(d);
            if (isValid(neighborLoc))
                locs.add(neighborLoc);
            d = d + Location.HALF_RIGHT;
        }

6

following code

// @file: GridWorldCode\framework\info\gridworld\grid\BoundedGrid.java
//@line: 41~44
if (rows <= 0)
            throw new IllegalArgumentException("rows <= 0");
        if (cols <= 0)
            throw new IllegalArgumentException("cols <= 0");

7

It determined By occupantArray[0].length;

// @file: GridWorldCode\framework\info\gridworld\grid\BoundedGrid.java
//@line: 53~58
 public int getNumCols()
    {
        // Note: according to the constructor precondition, numRows() > 0, so
        // theGrid[0] is non-null.
        return occupantArray[0].length;
    }

8

Its row must more than zero and less than total rows. Its column must more than 0 and less than total columns.

// @file: GridWorldCode\framework\info\gridworld\grid\BoundedGrid.java
//@line: 60~64
public boolean isValid(Location loc)
    {
        return 0 <= loc.getRow() && loc.getRow() < getNumRows()
                && 0 <= loc.getCol() && loc.getCol() < getNumCols();
    }

9

Its return type is ArrayList<Location> .
Complexity is O(m*n), where m is total rows and n is total columns.

// @file: GridWorldCode\framework\info\gridworld\grid\BoundedGrid.java
//@line: 66~83
public ArrayList<Location> getOccupiedLocations();
// @file: GridWorldCode\framework\info\gridworld\grid\UnboundedGrid.java
//@line: 58~64
public ArrayList<Location> getOccupiedLocations();

10

It return a object at the location. Location is its parameter.
Its complexity is O(1);

// @file: GridWorldCode\framework\info\gridworld\grid\BoundedGrid.java
//@line: 85~91
 public E get(Location loc)
    {
        if (!isValid(loc))
            throw new IllegalArgumentException("Location " + loc
                    + " is not valid");
        return (E) occupantArray[loc.getRow()][loc.getCol()]; // unavoidable warning
    }

11

if the parameter E obj is NULL or the Location loc isn’t valid, it will throw a exception.
its complexity is O(1);

// @file: GridWorldCode\framework\info\gridworld\grid\BoundedGrid.java
//@line: 93~105
public E put(Location loc, E obj)
    {
        if (!isValid(loc))
            throw new IllegalArgumentException("Location " + loc
                    + " is not valid");
        if (obj == null)
            throw new NullPointerException("obj == null");

        // Add the object to the grid.
        E oldOccupant = get(loc);
        occupantArray[loc.getRow()][loc.getCol()] = obj;
        return oldOccupant;
    }

12

It return the object at the Location loc (parameter).
It will return a null object.
Complexity is O(1).

// @file: GridWorldCode\framework\info\gridworld\grid\BoundedGrid.java
//@line: 107~117
public E remove(Location loc)
    {
        if (!isValid(loc))
            throw new IllegalArgumentException("Location " + loc
                    + " is not valid");

        // Remove the object from the grid.
        E r = get(loc);
        occupantArray[loc.getRow()][loc.getCol()] = null;
        return r;
    }

13

It is an efficient implementation. In order to improve our code reuse , we use get();method in getEmptyAdjacentLocations() ,and it make our code more simple and in block.
HALF_RIGHT and RIGHT make our code more readable.
At least one valid location ensure us grid can use.

14

①the method equals(Object other); and hashCode(); must be implement.
②compareTo(Object other) and equals(Object other);must be overwrite.
③Yes.

// @file: GridWorldCode\framework\info\gridworld\grid\UnboundedGrid.java
//@line: 205~246
public boolean equals(Object other)
    {
        if (!(other instanceof Location))
            return false;

        Location otherLoc = (Location) other;
        return getRow() == otherLoc.getRow() && getCol() == otherLoc.getCol();
    }

    /**
     * Generates a hash code.
     * @return a hash code for this location
     */
    public int hashCode()
    {
        return getRow() * 3737 + getCol();
    }

    /**
     * Compares this location to <code>other</code> for ordering. Returns a
     * negative integer, zero, or a positive integer as this location is less
     * than, equal to, or greater than <code>other</code>. Locations are
     * ordered in row-major order. <br />
     * (Precondition: <code>other</code> is a <code>Location</code> object.)
     * @param other the other location to test
     * @return a negative integer if this location is less than
     * <code>other</code>, zero if the two locations are equal, or a positive
     * integer if this location is greater than <code>other</code>
     */
    public int compareTo(Object other)
    {
        Location otherLoc = (Location) other;
        if (getRow() < otherLoc.getRow())
            return -1;
        if (getRow() > otherLoc.getRow())
            return 1;
        if (getCol() < otherLoc.getCol())
            return -1;
        if (getCol() > otherLoc.getCol())
            return 1;
        return 0;
    }

15

Because the null value can be insert into HashMap, then it will occur many null key and occur error.
In BoundedGrid use isValid(); method to ensure it is not null.

16

HashMap complexity is O(n/2).
TreeMap complexity is O( log(n) ).

17

In method get ,put, and remove, we not need to check nulll. Because TreeMap can’t insert null value.

18

Yes.
If we use map , the method get,put,remove will have more than O(1) time complexity. But two dimensional array has O(1).

19

It has been implemented in code.
get method complexity is o(1).
put method when the row and column index values are within the current array bounds complexity is O(1).
else complexity is O(n*m). n and m is total rows and total columns of old array.

猜你喜欢

转载自blog.csdn.net/C2681595858/article/details/80141375
今日推荐