Monday, 28 February 2011

Barons

I forgot my Baron's book at school, I will do it tomorrow in my free block.

Tuesday, 22 February 2011

Barons 357-374 Multiple Choice

How did you do on the multiple choice questions?
I did pretty well, I got only a few mistakes, and most were not conceptual.

Did you understand your errors?
Not all...

What do you not understand?
 In the turning questions, I was confused. E.g. question 2 stated that when a bug turns it takes its direction and adds 45 degrees to it. So if it was South, it would be 180 + 45 = 225. Mathematically speaking, 225 degrees is South East not South West as the book said it was.

Grid World Part 4 Part 2

        

Gridworld: Part 4: Interacting Objects: Set 9: Page 35





1
Why doesn’t CrabCritter override the processActors() method?  
 It doesn't override the processActors() method because the implementation of the method in the critter class is to eat other actors, and the crab does the same with movement restrictions and eating restrictions.
2
Describe the process a CrabCritter uses to find and eat other actors.

Does it always eat all neighboring actors?

Explain.  
 After moving either left or right (depending on the random value) it will check if a neighbor which is not a rock and is a critter is in front, front left, or front right of it and remove it. It won't eat all neighboring actors if they aren't critters, or if they're a rock. This because of the implementation of the processActors() in the critter class.
3
Why is the getLocationsInDirections() method used in CrabCritter?  
 I am not sure about this question. I can't really understand the getLocationsInDirections() method.
4
If a CrabCritter has location (3, 4) and faces south, what are the possible locations for actors that are returned by a call to the getActors()  method?  
 I was under the impression that getActors() returns all actors in the grid, but I assume it is only the locations around the critter, therefore they would be (2,3), (3,3), (4, 3), (2,4), (4,4), (2,5), (3, 5), (4, 5).
5
What are the similarities and differences between the movements of a CrabCritter and a Critter?  
 CrabCritter moves in each call of act(), just as critter does; however, it can only move right, left, or turn 90 degrees either left or right, and relies on random values in order to determine its movement.
6
How does a CrabCritter determine when it turns instead of moving?  
 It checks whether it's movement is blocked in any direction. If it is, then it turns instead of moving.
7
Why don’t the CrabCritter objects eat each other?  
 I thought CrabCritter objects can eat each other... there seems to be no part of the code which suggests otherwise.















Grid World Part 4 part 1

1
page 30
What methods are implemented in Critter?
The act(), getActors(), processActors(), getMoveLocations(), and selectMoveLocation() methods are implemented in Critter, although it still contains methods from it's superclass Actor.


2
What are the five basic actions common to all critters when they act?  
 The actors are collected from the grid, they all invoke the processActors() method, they get their moves through getMoveLocations(), they select a location through selectMoveLocation(), and finally make a move through makeMove().


3
Should subclasses of Critter override the getActors()   method?
Explain
No, because the getActors() method is used to collect all actors on the grid, and if a subclass of critter overrides it, it might not even get to act because it won't be collected into the list of actors.
 

4
Describe three ways that a critter could process actors. 
  It could change the state of the critter and the actor, it could change the state of the critter based on the actor, or change the actor (i.e. removing it).


5
What three methods must be invoked to make a critter move?
 Explain each of  these methods. 
processActors(), getMoveLocations(), and selectedMoveLocation() must be implemented in order for the critter to move. 


6
Why is there no Critter constructor?
This is because the critter class is an abstract class. Furthermore, it implements methods for its subclasses to use, but can't make any objects.
 
page 33
1
Why does act() cause a ChameleonCritter to act differently from a Critter even though ChameleonCritter does not override act()?
ChameleonCritter acts differently from a Critter even though it doesn't override act() because it has a different implementation of the processActors() method which it does override to make it's color that of its neighbors.


2
Why does the makeMove() method of ChameleonCritter call super.makeMove?
ChameleonCritter calls super.makeMove() because it wants to override the makeMove method but at the same time implement the previous implementation of the method as part of the new method.
 

3
How would you make the ChameleonCritter drop flowers in its old location when it moves?
You would put an implementation of dropping flowers in the beginning of the makeMove() method, so that for each call to the makeMove() method it would drop a flower thereby putting a flower where it was.
 

4
Why doesn’t ChameleonCritter override the getActors() method? 
The ChameleonCritter class doesn't override the getActors() method because it wants to use the same implementation that the critter class used in order to find the actors currently on the grid.


5
Which class contains the getLocation() method? 
Actor contains the getLocation() method.


6
How can a Critter access its own grid?
If by grid, what is meant is location, then the critter can simply call the getLocation() method since it is implemented in the Actor class.

Wednesday, 16 February 2011

Barron's Polymorphism Multiple Choice

How did you do on the multiple choice questions?
I got most of them right, apart from one or two.
Did you understand your errors?
Yes. They were errors in understanding the question, but not conceptual.

What do you not understand?
I couldn't really understand the difference between polymorphism and overriding methods. From what I could understand, it seems overriding a method is simply redefining a method in a subclass, and polymorphism is using the correct overridden method in run-time. Is that precise?

Monday, 14 February 2011

Gridworld Part 3

Assume the following statements when answering the following questions.
Location loc1 = new Location(4, 3);
Location loc2 = new Location(3, 4);

1. How would you access the row value for loc1?  


1. loc1.getRow() would return the row value of loc1.

2. What is the value of  b  after the following statement is executed?
boolean b = loc1.equals(loc2);

2. The value of b will be false because loc1 does not have the same values for row and column as loc2.

3. What is the value of loc3  after the following statement is executed?
Location loc3 = loc2.getAdjacentLocation(Location.SOUTH); 

3. loc3 will have the values (4, 4).

4. What is the value of dir  after the following statement is executed?
 int dir = loc1.getDirectionToward(new Location(6, 5));

4. dir will have the value 135 because Location(6, 5) is directly South East from loc1.


5. How does the getAdjacentLocation()   method know which adjacent location to return?

5. It knows which adjacent location to return by taking a direction as a parameter, which will direct it towards the requested location.


pg. 21
1. How can you obtain a count of the objects in a grid? How can you obtain a count of the empty locations in a bounded grid?

1. You can make a loop to go through the grid incrementing rows and collumns by 2 in order to not count the same object twice, and increment a counter value by the getNeighbors() method for each of the locations. You can do the same but with incrementing the counter value by the getEmptyAdjacentLocations() method to find the empty locations in a bounded grid.


2. How can you check if location (10,10) is in a grid?

2. You can call the isValid() method and put the location (10, 10) as a parameter. If it returns true it is valid, otherwise it is false.

3. Grid contains method declarations, but no code is supplied in the methods.
Why? Where can you find the implementations of these methods? 

3. 3. Because some might be labeled as abstract and to be implemented by its subclasses. In the subclasses you can find implementations of these methods.
 

4. All methods that return multiple objects return them in an ArrayList.  
Do you think it would be a better design to return the objects in an array?
Explain your answer.  

4. No, because an ArrayList can grow infinitely while an array has a set size. It could be that we would want to mess with the size of the ArrayList, and therefore, it serves as a better holder of the objects.

pg. 23
1. Name three properties of every actor.

1. They all have a color, a direction, and an implementation of the act() method.

2. When an actor is constructed, what is its direction and color?

2. When an actor is constructed its direction is north and its color is blue.

3. Why do you think the Actor class was created as a class instead of an interface?

3. It was probably made as a class instead of an interface because it is a general rule for all objects on the grid, and not necessarily something they implement. The Actor class also defines fields which an interface cannot do, which apply to its subclasses.

4. Can an actor put itself into a grid twice without first removing itself? Can an actor remove itself from a grid twice? Can an actor be placed into a grid, remove itself, and then put itself back? Try it out. What happens?

4. No, it can't put itself into a grid twice without first removing itself. No it also can't remove itself twice. It also can't place itself, then remove itself, and then put itself back, because as soon as it is removed it disappears.

5. How can an actor turn 90 degrees to the right?

5. It can call its setDirection() method and place the direction + 90 as the parameter of the method thus turning it 90 degrees to the right.

pg. 25-26
1
Which statement(s) in the canMove()  method ensures that a bug does not try to move out of its grid?  
The statement "if(!gr.isValid(next))
    return false;
else ... ensures the bug doesn't try to move out of the grid.


2
Which statement(s) in the canMove() method determines that a bug will not walk into a rock? 
 The statement "return (neighbor == null) || (neighbor instanceof Flower)" determines that a bug will not walk into a walk because it evaluates to false if the neighbor object is a rock, which will cause the canMove() method to be false as a whole and not let the bug walk into a rock.


3
Which methods of the Grid  interface are invoked by the canMove()  method and why?
The isValid() method of the Grid interface is invoked by the canMove method to check whether the location chosen by the bug is still in grid.


4
Which method of the Location  class is invoked by the canMove() method and why?
The Location class is invoked in order to find a new location for the bug to move to invoking its getAdjacentLocation() method.

5
Which methods inherited from the Actor class are invoked in the canMove() method?
None are invoked in the canMove() method.
 

6
What happens in the move() method when the location immediately in front of the bug is out of the grid?
When the location immediately in front of the bug is out of the grid it removes itself from the grid.


7
Is the variable loc needed in the move() method, or could it be avoided by calling getLocation() multiple times?
It is not needed in the move() method because the loc variable is only referred to once, and therefore is redundant.
 

8
Why do you think the flowers that are dropped by a bug have the same color as the bug?
Because it calls the getColor() method when constructed which will return the bug's color, and construct a flower with that color.
 

9
When a bug removes itself from the grid, will it place a flower into its previous location?
Depends when. If it simply calls the removeSelfFromGrid() method then it won't. However, there is one case where it will. In the move() method, if the bug finds no valid place to go to, it will remove itself from the grid, but at the same time place a flower in its place.
 

10
Which statement(s) in the  move() method places the flower into the grid at the bug’s previous location?
"Flower flower = new Flower(getColor());
flower.putSlefInGrid(gr, loc);" puts a flower in the bug's previous location.
 

11
If a bug needs to turn 180 degrees, how many times should it call the turn() method?
It will have to call the turn() method 4 times, because each one call moves the but 45 degrees to the right.



Tuesday, 8 February 2011

APQ

My APQ Coding:
import java.util.*;

public class APQ implements Queue
{

   private ArrayList <ArrayList<Message> > messageQueues;
   private int total;//total number of message in the system
  
   public APQ ()//constructor
   {
         messageQueues = new ArrayList <ArrayList<Message>>();
         for(int i=0;i<10;i++)
         {
               messageQueues.add(new ArrayList <Message>());
            }
          total = 0; 
    }
  
   public  boolean isEmpty()//returns true if there are no messages
     {
         for(int i = 9; i>= 0; i--)
         {
             if(messageQueues.get(i) != null)
                 return false;
            }
         return true;
     }
     
       
       public  int size()//returns the total number of messages
        {
           int count = 0;
           for(int i = 0; i<10; i++)
           {
               count += messageQueues.get(i).size();
        }
        return count;
    }

        public void add (Message msg)
        {
            messageQueues.get(msg.getPriority()).add(msg);
        }

     public Message remove()
        {
            int i = 9;
            while(messageQueues.get(i).size() == 0 && i>= 0)
            {
                i--;
            }
            total--;
            return messageQueues.get(i).remove(0);
        }
    }

Credit to Amit Maor for help with the last method.

Sunday, 6 February 2011

Multiple Choice pages 103-117

1. Barron’s Review
How did you do on the multiple choice questions?
I got most of them correct, a little more mistakes than the last one.

Did you understand your errors?
Yes I do, they mostly had to do with scope, and me messing up how far something's scope reaches.

What do you not understand?
I think I understood it all.

Multiple Choice Pages 70-80

How did you do on the multiple choice questions?
I got most of them correct, these seemed substantially easier than the others.

Did you understand your errors?
Yeah, I had a few arithmetic mistakes.

What do you not understand?
I'm not so sure as to how the hexadecimal numbers work, and how float is different from binary.

Can you convert between hexadecimal and decimal (and binary)?
Yes and no. I can't see the logic behind converting hexadecimal numbers, or their purpose, but I seem to see the same numbers appear when the book goes through it. I'll ask about it in class.

Tuesday, 1 February 2011

Gridworld Problems

 Page 6 Questions
1. Does the bug always move to a new location? Explain.
    No, it can turn.

2. In which direction does the bug move?
    Straight if it can, unless it hits a rock or a wall and must turn clockwise.

3. What does the bug do if it does not move?
    It turns it's direction (if something is in its path).

4. What does a bug leave behind when it moves?
    It leaves behind a big flower that takes up the cell.

5. What happens when the bug is at an edge of the grid? (Consider whether the bug is facing the edge as well as whether the bug is facing some other direction when answering this question.)
    It turns 90 degrees clockwise.

6. What happens when a bug has a rock in the location immediately in front of it?
    It turns 45 degrees clockwise (that's to say it turns diagonally).

7. Does a flower move?
    Nope it's position is static.

8. What behavior does a flower have?
    It doesn't move, but for each step it's color becomes darker until it's pitch black.

9. Does a rock move or have any other behavior?
    No it doesn't move or act, it simply remains in its place and acts as a block to the bugs.

10. Can more than one actor (bug, flower, rock) be in the same location in the grid at the same time?
    No, only one object can take up a cell on the grid.

Page 8 Questions
1. Test the setDirection method with the following inputs and complete the table, giving the compass direction each input represents.
0 - North
45 - NE
90 - East
135 - SE
180 - South
225 - SW
270 - West
315 - NW
360 - North

2. Move a bug to a different location using the moveTo method. In which directions can you move it? How far can you move it? What happens if you try to move the bug outside the grid?
2. You can place it on any place on the board, but it keeps its direction. If you try to place it outside you get an error.

Change the color of a bug, a flower, and a rock. Which method did you use?
3. I used the setColor() method

4. Move a rock on top of a bug and then move the rock again. What happened to the bug?
4. The bug vanished as though it died. A blank cell remained.

Questions on Page 12
1. What's the role of the instance variable sideLength?
1. It serves as a step limit on one side. If you say your sideLength is 2, and assuming there are no rocks around, the bug will walk in a box of length to. Furthermore, it will walk two steps on each side and then turn, and then another two steps, and then turn again, etc. For this reason the class is called BoxBug, it walks in a box shape so to speak.

2. What is the role of the instance variable steps?
2. The steps serve as a count to know how many steps the bug can take until he must turn due to the sideLength variable.

3. Why is the turn method called twice when steps becomes equal to sideLength?
3. The turn method is called twice when steps is equal to sideLength because the BoxBug again is made to walk in a box, and each point in a box is 90 degrees. Since the turn method turns the bug 45 degrees it must be called twice to make the bug turn 90 degrees to complete the box pattern. Also the BoxBug is made to turn 90 degrees not only in the box pattern. If it encounters a rock it will also call the turn method twice.

4. Why can the move method be called in the BoxBug class when there is no move method in the BoxBug code?
4. It can be called because the move method is inherited from the Bug class. Since it didn't have to be changed it wasn't overriden in the BoxBug class and that's the only reason why it isn't in the BoxBug code.

5. After a BoxBug is constructed, will the size of its square pattern always be the same? Why or why not?
5. It won't be the same given that other objects are on the grid. If the BoxBug cannot move, and still hasn't completed all the steps on one side, it will still turn and break the pattern.

6. Can the path a BoxBug travels ever change? Why or why not?
As was mentioned earlier, it will not change unless other objects exist on the grid, which will affect it's turning.

7. When will the value of steps be zero?
7. The value of steps will be zero whenever the BoxBug turns, and at first when it's constructed.

Exercises Page 13-15

1. Write a class CircleBug  that is identical to BoxBug,  except that in the act()  method the turn() method is called once instead of twice. How is its behavior different from a BoxBug?
1. 
/**
 * Write a description of class CircleBug here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class CircleBug extends BoxBug
{
    /**
     * Constructor for objects of class CircleBug
     */
    public CircleBug(int length)
    {
        super(length);
    }

    public void act()
    {
        if(steps < sideLength && canMove() )
        {
            move();
            steps++;
        }
        else
        {
            turn();
            steps = 0;
        }
    }
    }


2. Write a class SpiralBug  that drops flowers in a spiral pattern.
2. /**
 * Write a description of class CircleBug here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class SpiralBug extends BoxBug
{
    /**
     * Constructor for objects of class CircleBug
     */
    public SpiralBug(int length)
    {
        super(length);
    }

    public void act()
    {
        if(steps < sideLength && canMove() )
        {
            move();
            steps++;
        }
        else
        {
            turn();
            steps = 0;
            sideLength++;
        }
    }
    }

Hint: Imitate BoxBug,  but adjust the side length when the bug turns. You may want to change the world to an UnboundedGrid  to see the spiral pattern more clearly.

3. Write a class ZBug  to implement bugs that move in a “Z” pattern, starting in the top left corner. After completing one “Z” pattern, a ZBug  should stop moving.

In any step, if a ZBug  can’t move and is still attempting to complete its “Z” pattern, the ZBug  does not move and should not turn to start a new side. Supply the length of the “Z” as a parameter in the constructor. The following image shows a “Z” pattern of length 4.

Hint: Notice that a ZBug  needs to be facing east before beginning its “Z” pattern.  

/**
 * Write a description of class CircleBug here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class ZBug extends BoxBug
{
    /**
     * Constructor for objects of class CircleBug
     */
    public ZBug(int length)
    {
        super(length);
        turn();
        turn();
    }

    public void break()
    {
        //didn't know how to implement, but this method is simply supposed to make the bug break all his operations
    }
   
    public void act()
    {
        boolean first = true;
        boolean stop = false;
        if(stop || !canMove())
        {
            break();
        }
        if(steps < sideLength )
        {
            move();
            steps++;
        }
        else if(first)
        {
            turn();
            turn();
            turn();
            steps = 0;
            first = false;
        }
        else if(!first)
        {
            turn();
            turn();
            turn();
            turn();
            turn();
            steps = 0;
            stop = true;
        }
    }
    }

4. Write a class DancingBug  that “dances” by making different turns before each move. The DancingBug  constructor has an integer array as parameter. The integer entries in the array represent how many times the bug turns before it moves.
4. 

For example, an array entry of 5 represents a turn of 225 degrees (recall one turn is 45 degrees). When a dancing bug acts, it should turn the number of times given by the current array entry, then act like a Bug.  In the next move, it should use the next entry in the array. After carrying out the last turn in the array, it should start again with the initial array value so that the dancing bug continually repeats the same turning pattern.

import java.util.Random;
/**
 * Write a description of class DancingBug here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class DancingBug extends Bug
{
    private int[] turns;
    /**
     * Constructor for objects of class DancingBug
     */
    public DancingBug(int length)
    {
        turns = new int[length];
        Random R = new Random();
        for(int i = 0; i<turns.length; i++)
        {
            turns[i] = R.nextInt(10);
        }
    }

    /**
     * An example of a method - replace this comment with your own
     *
     * @param  y   a sample parameter for a method
     * @return     the sum of x and y
     */
    public void act()
    {
        int z = 0;
        if(z = turn.length)
           z = 0;
        if(canMove() )
        {
          while(turn[z] > 0)
          {
              turn();
              turn[z]--;
            }
          move();
        }
        else
        {
          while(turn[z] > 0)
              turn();
              turn[z]--;
        }
    }
}

The DancingBugRunner  class should create an array and pass it as a parameter to the DancingBug  constructor.

5. Study the code for the BoxBugRunner  class. Summarize the steps you would use to add another BoxBug  actor to the grid.
5. To add another BoxBug to the grid would take two steps. First we must initialize the BoxBug with the parameters it takes. Then we would have to add it to the grid. After that, the BoxBug that we have created will appear on the grid.