Business Programming

Course announcements for INFS1609 and INFS2609

Business Programming random header image

Lab Week 11 – Wumpus

Posted by on October 2nd, 2012 · Labs

Download the Wumpus game shown in lectures.

Examine the code try to follow how it works. Make the following changes to the game:

  1. Rearrange the rooms so that are in a 4×5 grid.
  2. Make it so that the wumpus needs to be shot more than once (you choose how many times) to be killed. Each time it is shot it runs to a random neighbouring room (not the one the player is in).
  3. Add a new ‘hazard’ – a Trader who gives the player more arrows. Consider:
    • What ‘warning’ sound is heard if the trader is nearby?
    • What happens when the player enters the trader’s room?
    • Where does the trader fit in the sequence of hazards?
    • What should happen if the player shoots the trader?
  4. Give the player more ‘lives’. So if they die (by pit or wumpus) they reappear in a random room.

 

Lab Week 10 – Scrabble

Posted by on September 23rd, 2012 · Labs

Consider the game of Scrabble.

  1. List all the data involved in representing the game. Be thorough.
  2. How might this data be divided into abstract chunks? What idea does each chunk represent?
  3. Draw a flow chart of the game play. Break it up into methods of different levels of detail.
  4. How do these methods associate with the chunks of data above.
  5. Design a collection of classes representing these chunks. What fields and methods do they have?
  6. How many objects of each class will you need to create? How will they connect to each other?
  7. Write the main method of your game. It should:
    1. Create the objects.
    2. Start the game.
  8. Write method signatures for the other methods you will use. Do not write the code, just decide on what the necessary chunks are at each level of detail.
  9. Write “pseudocode” comments in each method describing the steps it should take and the other methods that it should call.
  10. Challenge: Write the complete game.

 

Assignment 3

Posted by on September 20th, 2012 · Assignments

DUE DATE: Sunday 14th Oct, 23:59:59

Change Log

  • Sample Solution has been updated as of Sept 25th 17:30. If you downloaded the sample earlier than this, grab the latest copy

In this assignment you will be implementing a simple job queue.

Topics covered

This assignment covers the following ideas:

  • OO design: Abstraction and encapsulation
  • Implementing a class with fields, constructors and accessor methods,
  • Handling collections of objects with ArrayLists,
  • Implementing state using fields and mutator methods,
  • Using the null object to represent “nothing”.

The task

You need to implement two classes Job and JobQueue.

The Job class

The Job class is a simple data structure containing:

  • The job name (a String)
  • The duration of the job in seconds (a positive integer).

You need to implement a class called Job with appropriate fields to store this data.

You also need to implement:

  • A constructor: Job(String name, int duration) which initialises the fields to the given values.
  • Accessor methods: getName() and getDuration(). which return the field values.
  • run() method which prints “JOB COMPLETE: ” followed by the name of the job.
    E.g. The code:

    Job job = new Job("Wash the car.", 100);
    job.run();

    should print:

    JOB COMPLETE: Wash the car.

The JobQueue class

The JobQueue class implements a queue of jobs. When you create the queue it is initially empty. You can add jobs to the end of the queue. You can also add run time to the queue. When you run the queue, any available run time is used to execute jobs in the order they are added. As each job is completed, it is moved to the complete jobs list.

So for example, starting with an empty queue:

  1. Add a job “A” that takes 20 seconds.
  2. Add a job “B” that takes 10 seconds.
  3. Add a job “C” that also takes 10 seconds.
  4. Add 25 seconds to the clock.
  5. Run the queue:
    1. Job A is completed. 5 seconds remain on the clock.
    2. Job B is now the current job.
    3. There is not enough time to complete this job, so the queue stops.
  6. Add another 20 seconds to the clock, making the total 25.
  7. Run the queue:
    1. Job B is completed. 15 seconds remain on the clock.
    2. Job C is completed. 5 seconds remain on the clock.
    3. The jobQueue is now empty, so it stops with 5 seconds left on the clock

You need to implement:

  • The JobQueue class with appropriate fields.
  • A constructor with no parameters than initialises the pending and completed queues to empty and the clock to zero.
  • Accessor methods:
    • getPendingJobs() which returns the list of jobs that have not been completed (including the current job)
    • getCompletedJobs() which returns the list of jobs that have been completed.
    • getCurrentJob() which returns the job at the front of the pending queue, or null if the queue is empty.
    • getClockTime() which returns the amount of time left on the clock (as an integer)
    • getTotalDuration() which returns the total duration of all the pending jobs.
  • Mutator methods:
    • addJob(Job job) which adds a Job to the end of the Queue.
    • addTime(int seconds) which adds the specified number of seconds to the clock.
    • runOne() which runs the first job on the queue if there is enough time on the clock.
    • runAll() which runs all the jobs on the queue in order until it runs out of time.

Sample solution

We are not providing a skeleton solution for this assignment as we will be testing that you are able to write your own method signatures following the description above. However it is important that you follow the specification as closely as possible. To help in this, we have provided a sample solution as a BlueJ project with the source code removed. Please check carefully to make sure your program works exactly the sameas the sample solution.

Submission

  • From within your assignment 3 BlueJ project, select Project -> Create Jar File…
  • In the Dialog Box that appears:
    1. Set “Main Class” to none
    2. Ensure “Include Source” is checked
    3. Leave “Include Bluej project files” unchecked
    4. Press “Continue”
    5. Save the filename as “Assignment3.jar”
  • Open a web browser and go to the give web site
  • Log-in with you Z-Pass
  • Either enter “COMP1400″ in for the course and press “Search for Assignments”.
  • Select “Assignment3″ from the next drop down menu and press “Upload my Assignment”
  • Accept the student declaration
  • Press “Choose File” and select the “Assignment3.jar” file that you saved in step 4
  • Press “Submit my Files”
  • Wait for the page to completely load. Then carefully read the output. If the assignment is successful you should see the following lines:
    ================================================
    Checking your submission... 

    Checking for JobQueue.java
    JobQueue.java Compiled Sucessfully

    All files are OK
    ================================================
    If the page doesn’t load properly, that is OK just submit the assignment file again.
    If you don’t get the above output check the output to see what went wrong and resubmit.

Submission notes:

You can submit as many times as you wish, even after the deadline. Only your last submission will be marked.
Make sure you name everything the as instructed, including the classes and the submission file or the submission will not work.
If you have any problems with submission, email the class account. Include exact details of any error messages you get.

 

Lab Week 9 – Classes

Posted by on September 16th, 2012 · Labs

Classes

Consider a database of student records for the university. What kind of data would be associated with each student?

  • Download the Lab9 BlueJ project. It defines a new class Student which contains some student information
  • Create students a number of students in BlueJ. Use the Inspector to examine their fields.
  • Use the getName() method to access the student’s name.
  • Write your own accessor methods to get the address and year enrolled.
  • Add a field to record the student’s gender. Update the constructor to initialise this value appropriately using a parameter. Add an accessor method.
  • Add a field to record the student’s age. Update the constructor to initialise the age to the default value of 18.
  • Add a second constructor that allows you to specify an age other than the default.
  • Add a static final constant to the class for the default age, to avoid using 18 as a magic number in your code.

Consider designing a class representing a car in a database for a used car lot.

  • What kinds of data would be recorded about each car?
  • What are the types of this data?
  • Write a Car class representing an entry in this database. Give it:
    1. Fields recording the above data.
    2. A public constructor.
    3. Public accessor methods to read the data.

 

Lab Week 8 – Objects

Posted by on September 10th, 2012 · Labs
  1. Create an instance of the java.util.Random class in BlueJ using the Tools > Use Library Class… option.
  2. Right click on the object created to see its methods. Try running some of them. What do they do?
  3. Read the Java docs for the Random class.
  4. Which method would you use to:
    • Simulate a fair coin toss?
    • Simulate a (six-sided) dice roll? What about ten-sided? Twenty-sided?
    • Simulate a biased coin that shows heads 67% of the time?
  5. Open the Code Pad and do the following
    • Write a command to construct a Random object with the seed 200 and assign it to a variable.
    • Call nextInt() several times on the object you created.
    • Create a second object with the same seed and call nextInt() on it too. Explain the result.
  6. Write a method rollDice(int number, int nSides) which returns the total result of rolling the number dice with nSides sides.
    So for example rollDice(3, 6) should return the result of rolling 3 six-sided dice (adding to a number between 3 and 18 inclusive).
  7. Write a method selectRandom(String[] names) which returns a randomly selected name from the given array. Each name should be selected with equal probability.
  8. Challenge: Write a method shuffle(String[] names) which takes an array of names are returns a copy of the list with the names randomly rearranged. Each possible should be returned with equal probability
    So for instance, given the code:
    String[] names = {"Malcolm", "Troy", "Sim"};
    String[] shuffled = shuffle(names);

    The following return values should be equally likely: 

    1. {“Malcolm”, “Troy”, “Sim”}
    2. {“Malcolm”, “Sim”, “Troy”}
    3. {“Troy”, “Malcolm”, “Sim”}
    4. {“Troy”, “Sim”, “Malcolm”}
    5. {“Sim”, “Troy”, “Malcolm”}
    6. {“Sim”, “Malcolm”, “Troy”}

Lab Week 7 – Multidimensional Arrays

Posted by on August 23rd, 2012 · Labs

In this tutorial you will be working with 2D arrays to do some image manipulation.

Download the BlueJ project ASCIIArt.zip. Inside you will find a class that contains the method readImage(String url). This method takes the URL for any image on the web and converts it into a 2D array of integers. Each entry in the 2D array represents the brightness of one pixel. The values range from zero (black) to 5 (white). Entries are arranged in width by height order so an array like:

{{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 5, 0, 0, 0, 0, 0, 0, 0}
{0, 5, 5, 5, 0, 0, 0, 0, 0},
{0, 5, 3, 3, 5, 5, 0, 0, 0},
{0, 5, 3, 3, 3, 3, 5, 5, 0},
{0, 5, 3, 3, 5, 5, 0, 0, 0},
{0, 5, 5, 5, 0, 0, 0, 0, 0},
{0, 5, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0}}

represents a grey triangle (the ’3′ pixels) with a white border (the bright ’5′ pixels) pointing to the right on a black background (the ’0′ pixels).

Your tasks:

  1. Write a method to draw an image on the console using ASCII art. That is, each pixel of the image is drawn as a character according to the following table:
    Brightness Character
    0 'X'
    1 '8'
    2 'o'
    3 ':'
    4 '.'
    5 ' '

    So the triangle above would be rendered as:

    XXXXXXXXX
    X XXXXXXX
    X   XXXXX
    X ::  XXX
    X ::::  X
    X ::  XXX
    X   XXXXX
    X XXXXXXX
    XXXXXXXXX


  2. Write a method to invert an image, so that bright pixels are converted to dark and vice versa. It should input an image and return an inverted copy.
  3. Write a method to flip an image horizontally. It should input an image and return a flipped copy.
  4. Challenge: Write a method to rotate an image clockwise. It should input an image and return a rotated copy.

Try these sample images

  1. http://sfpl.org/images/graphics/chicklets/google-small.png
  2. http://a0.twimg.com/profile_images/2258868342/Pokemon_Red_Sprite_normal.jpg

Assignment 2 – The Game of Life

Posted by on August 23rd, 2012 · Assignments

DUE DATE: 11:59pm Friday 14 September.
Assignment Submission now setup

For this assignment you will write a program that implements Conway’s Game of Life. The board is a rectangular array in which a cell is designated as either live or dead. A few simple rules tell you how to create a new generation (i.e. a new board) based on the old one.

  1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overcrowding.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

You can see an animation of the game at this web site. We will not build a graphical display like that one (although that animation is written in Java too). Instead, we will print each generation to the console For example,

..............................
..............................
..............................
..............................
..............................
..............................
..............................
..............................
..***.........................
....*.........................
..*...........................
..............................

You will find a project file for the assignment here. It contains methods for reading in an initial board, like the one above. This is stored in the README.TXT file that is in the project folder. You can change this and experiment with different starting patterns. Try as many arrangements as you can to test your code thoroughly.

Task 1

The project also has the main method that plays that game. You are required to write three methods. This simplest one is to print the board. Note that you MUST print it out exactly as above.

A board is represented as a 2-dimensional boolean array:

boolean[][] board = new boolean[numberOfRows][numberOfColumns];

Your print method is called as follows:

public static void printBoard(boolean[][] board)

The method should print each row of the array on separate lines with a ‘.’ representing a false cell and a ‘*’ representing true.

Task 2

The second method you must write is to count the live neighbours of a cell.

public static int countNeighbours(boolean[][] board, int row, int col)

Given a board (i.e. a 2D boolean array) and a row and column position, count the number of immediately surrounding cells that contain the value true. The table below shows the index values of the neighbours of the cell where i is the row number and j is the column number (starting from zero).

i-1, j-1 i-1, j i-1, j+1
i, j-1 i, j i, j+1
i+1, j-1 i+1, j i+1, j+1

Your method should visit each of the surrounding cells and accumulate a count of the cells that contain true, i.e, the cell is live. Note that you do not count the cell itself. If a cell is on the edge of the array (i.e. some of its neighbours are out of bounds), only count the cells that are within the array.

Task 3

The third method you must write is:

public static boolean[][] nextGeneration(boolean[][] board1)

The only parameter to the method is a board (i.e. a 2D boolean array). For each cell in the array (i.e. for each column position in each row), apply the four reproduction rules, given above, to create a new board representing the next generation. To do this, you must declare a new array that is the same size as the old one. As you apply the rules to a cell in the old array, you update the corresponding cell in the new array. That is, you must not change the original array.

WARNING: The Game of Life is a popular programming exercise and you will find many versions of it on the web. While you may use these to get an idea of how to write your own program, your code must be your own. Plagiarism is not allowed and will be heavily penalised.

Submission instructions

You will submit your assignment to the Give automated marked system.

  1. From within your assignment 2 BlueJ project, select Project -> Create Jar File…
  2. In the Dialog Box that appears:
    1. Set “Main Class” to none
    2. Ensure “Include Source” is checked
    3. Leave “Include Bluej project files” unchecked
  3. Press “Continue”
  4. Save the filename as “Assignment2.jar”
  5. Open a web browser and go to the give web site
  6. Log-in with you Z-Pass
  7. Either enter “INFS1609″ in for the course, or select INFS1609/INFS2609 from the drop down menu and press “Search for Assignments”. Note INFS2609 students may need to enter “INFS1609″ instead of selecting INFS2609 if the assignment is not listed
  8. Select “assignment2″ from the next drop down menu and press “Upload my Assignment”
  9. Accept the student declaration
  10. Press “Choose File” and select the “Assignment2.jar” file that you saved in step 4
  11. Press “Submit my Files”
  12. Wait for the page to completely load. Then carefully read the output. If the assignment is successful you should see the following lines:
    ================================================
    Checking your submission...
    
    Checking for Life.java
    Live.java Compiled Sucessfully
    
    All files are OK
    ================================================
  13. If the page doesn’t load properly, that is OK just submit the assignment file again.
  14. If you don’t get the above output check the output to see what went wrong and resubmit.

Submission notes:

  1. You can submit as many times as you wish, even after the deadline. Only your last submission will be marked.
  2. Make sure you name everything the as instructed, including the classes and the submission file or the submission will not work.
  3. If you have any problems with submission, email the class account


Lab Week 6 – More Arrays

Posted by on August 16th, 2012 · Labs

Finish the exercises from last week than attempt the Using Arrays exercises in the example problems below.

Here are some hints about how to do exercise 2 from last week. Suppose we have an array of some fixed length, say 10. Java initialises all the elements to zero. Now let’s assume that we only want to store positive numbers (i.e. greater than 0) in the array. In that case, it’s convenient to treat zero as meaning an array cell is empty. Initially, the array will look like this:

0 0 0 0 0 0 0 0 0 0

Now let’s insert the number 5. All we have to do is look for the first empty position (i.e. contains 0) and replace it with 5:ow let’s insert the number 5. All we have to do is look for the first empty position (i.e. contains 0) and replace it with 5:

5 0 0 0 0 0 0 0 0 0

Now let’s insert 4. It goes before 5, so we have to shift 5 down one place and insert 4 where 5 was:

4 5 0 0 0 0 0 0 0 0

Now let’s insert 3. It goes before 4, so we have to shift 4 and 5 down one place and insert 3 where 5 was:

3 4 5 0 0 0 0 0 0 0

Inserting 6 is easier because it is larger than any of the existing entries, so it will go into the next empty spot:

3 4 5 6 0 0 0 0 0 0

What happens when the array fills up? What should you do?

Extra Practice Weeks 1 – 4

Posted by on August 13th, 2012 · Uncategorized

These are additional practice questions to be done in your spare time, covering content up to Week 4 (Arrays). They are not compulsory, however the more you practice programming, the better you get. You should be able to answer all these questions by the end of the week.

For these questions create a new BlueJ project, and a new Java Class. All can be done in the same class file

Basic Output

1. Write a method that prints the string “Hello World” 8 times. The output should be:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

2. Write a method that prints your name, age and favourite number, using integers for the numbers. For example:

My name is Fred, I am 18 years old, my favourite number is 2.

Simple Calculations

1. Write a method, which takes one parameter n and returns the number squared.

2. Write a method, which takes three parameters a, b and c to calculate the area of a triangle using Heron’s formula: area = sqrt(s(s-a)(s-b)(s-c)). Where s is the “semi-perimeter” given by s = (a+b+c)/2. The sqrt can be calculated by Math.sqrt()

3. Write a method that performs a calculation that you learnt in high school mathematics. The method should take as parameters any variables of the calculations and return the result of the calculation.

4. Write a method that takes a 4 digit number and then prints the number of units, tens, hundreds and thousands. For example:

Number: 1234
4 units
3 tens
2 hundreds
1 thousands

Using conditions

1. Write a method that takes in one parameter year and prints “This is a leap year”, if the year is a leap year or “This is not a leap year” if it is not. Recall that years are leap years if they are divisible by 4. Except years divisible by 100 are not leap years unless they are also divisible by 400.
HINT: the code x % y returns the remainder when x is divided by y

2. Write a method that takes three integers and prints them out in increasing order.

3. Write a method which takes in three real numbers a, b and c representing the coefficients of a quadratic equation ax2 + bx + c and uses the quadratic formula to determine one solution of the equation ax2 + bx + c = 0. Use an if statement to ensure that the program works correctly for all numeric input.

4. Write a method that takes a single integer, n between 0 and 9 and prints out the word for that number. For example

Number: 0
zero
Number: 1
one
Number: 9
nine

Using Loops

1. Write a method, which takes two parameters n and pow and returns the value of npow

2. Write a method with a while loop that prints out the numbers from 1 to 10 and their squares.

3. Change your method in question 1 to use a for loop.

4. Modify your method in question 2 so that is prints “Number is even”, if the number (or its square) is even. Otherwise print “Number is odd”.

5. Write a method that takes one parameter n and outputs an n x n square of asterisks. For example

Square: 5
*****
*****
*****
*****
*****

6. Write a method that takes one parameter n and outputs an n x n triangle. For example

Triangle: 5
    *
   **
  ***
 ****
*****

7. Write a method, which takes one parameter, a positive integer n and prints all the factors of n. For example:

n: 1001
The factors of 1001 are:
1
7
11
13
77
91
143
1001

Using Arrays

1. Write the method, void stars(int[] values) which, for each element of values prints out the number of asterisks corresponding to the integer. For example:

 values: {3, 2, 1, 5, 5, 3, 1, 0, 2}
***
**
*
*****
*****
***
*

**

2. Write the method, boolean isIncreasing (int[] values) which returns true if the values in the array are in increasing order. It should return false otherwise

Lab Week 5 – Algorithms

Posted by on August 9th, 2012 · Labs

If you did not finish all the exercises from last week’s lab, try to finish them off this week. If you have already completed those exercises, try these ones.

Exercise 1. Write a method that accepts two arguments, an integer and an array of integers. Assume that the numbers in the array are sorted in ascending order. Your method should return a new array that is one element longer than the first array and with the first argument inserted into the array, in the correct position.

Exercise 2. Now suppose that we want to insert the number into the same array, rather than creating a new one. Assume that the array is long enough to accommodate the extra element. What would you have to do? What complications arise in this version and how would you handle them?