Quantcast
Channel: Java, Database, Web And Mobile Apps - cs2it
Viewing all 191 articles
Browse latest View live

Moving shapes in JavaFX with Multi threading

$
0
0

Multithreading and JavaFX

Create an object-oriented JavaFX GUI that shows two shapes or images moving around a GUI. Each shape will have its thread to move it around the GUI. You must use threads – not AnimationTimelines or JavaFx Paths- this is a threading homework that happens to use JavaFx- not just a JavaFx homework.

You must have two separately distinct activities. Two flashing texts are only one different activity. I have provided an example of how to move an image in a circle and flashing text using threads. You may choose one of these, but your second activity must be different from shooting and moving in a circle. Do not directly copy the examples- you may use the algorithm with other things. Try moving in an up-down, side to side, zig-zag, etc. Be sure to shut down all threads when the Application closes. (Hint: interrupt() method on Thread class)

Your program should consist of multiple classes. Put thread Runnable classes in a different class from Application and pass shared information in the constructor.

Order Now:


Buy now

C++ - Game of Dungeons and Dragons complete implementation with header files

$
0
0
Buy now

1.0 Overview

 In the popular role-playing, the game of Dungeons and Dragons players move from room to room in a dungeon where they encounter creatures, treasure, and various obstacles. The underlying functionality of such a computer game lies in the gaming engine. This Statement of Work presents the requirements for a "Scenario Mapping and Player Movement" class for a gaming engine.

2.0 Requirements

 The student shall define, develop, document, prototype, test, and modify as required the software system.

 2.1 Functional Requirements

 2.1.1 The software shall be capable of representing the layout for a role-playing game scenario as a graph implemented as an adjacency matrix. The scenario will typically be an inside location such as a dungeon or castle divided into some rooms. For this implementation, it will be assumed that the number of rooms will be 20.

 2.1.2 The scenario graph shall be implemented as a class called GameGraph (defined in files GameGraph.h andGameGraph.cpp).

 2.1.2.1 The GameGraph class shall contain the following private variables.

 2.1.2.1.1 A stream object called m_InFile which shall reference the data file defining the game scenario.

 2.1.2.1.2 A 2D array of chars called m_cAdjMatrix which shall be a 20x20 matrix used to determine the links between rooms in the script. Data stored in the adjacency matrix will not only indicate where there are doors from the current room to other rooms, i.e., links but also will define the direction of the relationship. In other words, the adjacency matrix will be able to store definitions of up to 6 doors and stairways in a room. This means a room can have, up to 4 doors located on the North, South, East, or West walls, as well as stairways, going up or down.

 2.1.2.1.3 An array called m_Rms of 20 Room structures as defined in 2.1.3 below.

 2.1.2.1.4 An int called m_iLocation which shall determine the index into the m_Rms array giving the current location of the gaming party.

 2.1.2.2 The GameGraph class shall contain the following public functions.

 2.1.2.2.1 GameGraph() and ~GameGraph() - Default constructor and destructor.

 2.1.2.2.2 bool LoadGame(char *fileName) - This feature shall take a single argument which is a character array giving the name of the graph data file. It shall open the file, read all data, and build the graph.

 2.1.2.2.3 bool doCommand(char *cmd) - This function shall take a single argument which is a character array giving a command string the user has input from the keyboard. It shall parse and execute the command. This function always returns false unless the command is QUIT. (Details are given below)

 2.1.2.2.4 void PrintAll() - This function shall print all information in each Room structure and all the links in the graph. This feature is to be used primarily during development and testing to make sure all data have been read and stored correctly.

 2.1.2.3 The GameGraph class shall contain the following private functions.

 2.1.2.3.1 void getNextLine(char *line, int lineLen) - This utility function reads lines from the graph definition data file. The instructor will provide it.

 2.1.2.3.2 void setLink(int roomIdx, int linkIdx, char dCode) - This utility function takes an index of a "link from" Room and a "link to" Room and sets the appropriate code in the AdjMatrix to define a link and its type (North, South, East, West, Up or Down) in the adjacency matrix.

 2.1.2.3.3 void describeRoom(int roomIdx) - This utility function takes an index of a Room in the m_Rms array and prints a complete description of the room, its contents and its exits. See details below.

 2.1.3 Rooms in the scenario shall be represented by a Room structure (defined in a GameGraph.h file). The Room structure shall contain the following fields:

 2.1.3.1 A character array called m_sRoomName which shall be capable of storing room names of up to 63 characters in length. For example: "Banquet Hall".

 2.1.3.2 A character array called m_sRoomDesc which shall be capable of storing room descriptions of up to 127 characters in length. For example: "There is a long oak table filled with plates of food. Wood benches line the walls. Burning torches are mounted on the walls."

 2.1.3.3 A character array called m_sItemName which shall be capable of storing the name of a single item of up to 31 characters in length. For example: "Golden sword".

 2.1.3.4 A character array called m_sCreatureName which shall be capable of storing the name of a single creature of up to 63 characters in length. For example: "Mountain troll".

 2.1.4 Data defining a gaming scenario shall be read from a data file named gamelayout.txt. A sample data file for development and testing will be provided.

 2.1.5 A command line interface shall be included in the software which meets the following criteria:

 2.1.5.1 When the game is started the user shall be placed in the room which was first defined in the data file.

 2.1.5.2 When a user enters a room a description of the site shall be given which includes the name of the place, a brief description of the room, the item found in the room, the creature found in the chamber, and the number of doors and stairways and where they are located. This information will be presented in a narrative style. For example:

You are in the Banquet Hall.

There is a long oak table filled with plates of food. Wood benches line the walls. Burning torches are mounted on the walls.

There is a golden sword in the room.
There is a Mountain troll in the chamber.
There is a door in the North wall.
There is a door in the South wall.
There is a door in the East wall.
There is a stairway going down.

 2.1.5.3 After printing the description of the room as described in 2.1.5.2 the user shall be prompted to enter a command. For example: What do you want to do?

 2.1.5.4 The user shall be allowed to enter commands from the keyboard. The command is to be parsed and executed. Commands must meet the following criteria:

 2.1.5.4.1 Valid first words of the command shall be GO, TAKE, FIGHT and QUIT.

 2.1.5.4.2 If the command is GO then valid second words of the command shall be NORTH, SOUTH, EAST, WEST, UP, or DOWN. Indicating a desire to go to the north, south, east, or west doors, or up or down a stairway.

 2.1.5.4.3 If the command is TAKE or FIGHT print a message to inform the user that this command has not been implemented yet.

 2.1.5.4.4 If the command is QUIT exit the program.

 2.1.5.4.5 If any other command is issued or a direction other than those listed in section 2.1.5.4.1 is given then print a message to inform the user that this command is not understood.

 2.1.6 Movement from one room to another, printing of room descriptions, inputting and parsing of commands shall continue until the user enters the command QUIT.

 2.1.7 This program must be capable of being tested using a text file of commands and I/O redirection. Therefore, no other commands requiring input from the keyboard will be allowed except for the single cin.getline(line, 128, '\n'); function calls in the "player movement" loop. (Note: You must use this form of the cin stream reference in order to get a full line including spaces. The '\n' is the character to terminate the input. In this case the Enter key.

3.0 Deliverables

 These products shall be delivered electronically via e-mail as specified below to the instructor.

3.1 Software Design Document

The student shall provide a software development plan for instructor approval NLT (Not Later Than)

3.2 Software Test Plan

The student shall provide a test plan for complete verification and validation of the software for instructor approval NLT Thursday, April 17.

3.3 Gaming Module Source Code File(s)

The student shall provide source files for a fully tested game program via e-mail NLT Thursday, April 24 (last day of class).

Note: No data from the previous three programming assignments are to be included in this project.

4.0 Period of Performance

 The period of performance of this assignment is 28 days from the date of appointment. No deliverables will be accepted after the final exam.

Excerpts from
Software Requirements Specification (SRS)

Programming Assignment 4

 2.1 System Organization
 2.1.1 All data shall be stored internally as a graph which will be implemented as an Adjacency Matrix.
 2.1.2 The data structure defining each room shall contain the following fields. The data structure
MAY NOT CONTAIN ANY OTHER FIELDS.
char m_sRoomName[32]; // Name of the room.
char m_sRoomDesc[128]; // Description of the room.
char m_sItemName[32]; // Name of a single item in the room.
char m_sCreatureName[64]; // Name of a single creature in the room.
 2.1.3 If a valid GO command is given then the software should do the following:
Check the adjacency matrix to determine if there is a door or stairway leading in the direction requested. If not print a message, such as "You can't go in that direction."
If a valid direction is given check the adjacency matrix to locate the room that is linked via this direction and move the player to the appropriate room, give the description of this room, and wait for the user to input the next command.
 2.1.4 The format of the data file shall be as follows:
# Lines beginning with a '#' character will be ignored as comments
# Blank lines will also be ignored
# It is assumed that the file will be valid and contain data on
#    20 rooms for the gaming scenario.
# Data on each room consists of the following on separate lines
#    Room name: Maximum of 32 characters (spaces are allowed)
#    Room Description: Maximum of 128 characters  (spaces are allowed)
#    Room item: Maximum of 32 characters (spaces are allowed)
#    Room creature: Maximum of 64 characters (spaces are allowed)
# The next six lines will define links to other rooms given in the
#    order North, South, East, West, Up, and Down.
# Each of the six lines will contain a number giving the index in the
#    array of rooms to which there is a link.  If the value is -1 then
#    there is no link in that direction.
# In the example below, in the Entrance Hall (room index 0) there is a
# door to the north leading to room 1, one to the south leading to
# room 5, no door east or west, a stairway going up to room 14, but
# no stairway going down.
Entrance Hall
Tapestries hang on the walls.  A chandelier hangs from the ceiling.
Leather bag
Troll guard
1
5
-1
-1
14
-1
# etc. for the remaining rooms

 2.1.5 The class definition (header) file for the game class shall be the following:

//---------------------------------------------------------------
// File: GameGraph.h
// Purpose: Header file for a D&D game class
// Programming Language: C++
// Author: Dr. Rick Coleman
//---------------------------------------------------------------
#ifndef GAMEGRAPH_H
#define GAMEGRAPH_H
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>

using namespace std;

#define NUMROOMS 20

struct Room
{
     char m_sRoomName[64];
     char m_sRoomDesc[128];
     char m_sItemName[32];
     char m_sCreatureName[64];
};

class GameGraph
{
     private:
        ifstream m_InFile;                       // File to read from
        char m_cAdjMatrix[NUMROOMS][NUMROOMS];
        Room m_Rms[NUMROOMS];
        int m_iLocation;                         // Index of current room location
     public:
        GameGraph();                             // Class constructor
        ~GameGraph();                            // Class destructor
        bool LoadGame(char *filename);           // Read game file, build scenario
                                                 // and describe first room.
        bool doCommand(char *cmd);               // Execute a command
        void PrintAll();
     private:
        void getNextLine(char *line, int lineLen);
        void setLink(int roomIdx, int linkIdx, char dCode);
        void describeRoom(int roomIdx);

};

#endif

Sample Files Included in the Downloadable Zip File

Snippets.txt -- Contains several code samples and functions you can use.
Function: bool GameGraph:: LoadGame(char *filename) -- This snippet is an outline of how to read the gamelayout.dat file and parse it. This does not include code on how to insert the data that is read into the graph data structures.

Function: int GetNextLine(char *line, int lineLen) -- Pass in a pointer to a character array, which must be at least 128 characters in length, and the total length of the line which can be read into the array (127 for a 128 character array). The function reads the next line from the data file into the array line. It skips any blank lines or comment lines (those starting with '#'). It also removes the newline character from the end of the line. The function would return TRUE if a successful read was completed or FALSE if the end of file was reached.

gamelayout.txt -- A sample game layout data file. Note that this file contains comment lines. See the description of the function GetNextLine() above that can read the lines and skip the comments.
cmd.txt -- A sample command script similar to the one that will be used to test your program. To use this file copy it into the same directory as your compiled executable then from the command line issue the commandprog4 < cmdscript.txt where prog4 is the name of your executable.

If you run the sample executable with this script the last four responses to "What do you want to do?" will be (1) FIGHT not implemented yet, (2) I don't know how to TRY, (3) "You can't move that way from here.", and (4) "Fare well adventurer." in reply to the QUIT command.

GameMain.cpp -- A file with main which you can use for the final running of your game. Note: This file doesNOT contains all the automatic testing code which you must add for use during development.
GameGraph.h -- Header file for the GameGraph class.

Prog4.txt -- A demonstration of the programming assignment. This is an executable file with the .exe extension changed to .txt to get around some firewalls. To run the program change the .txt back to .exe. Place this in the same directory as the gamelayout.dat file and run it.

Graph Representation

In this programming assignment you will implement the graph as an adjacency matrix (see your lecture notes for details). One problem you will encounter is that in addition to keeping all of the links from room to other rooms, you must also keep which door or stairway links to a specific room. For example: Given that room has doors on the North, and East walls, and a stairway leading down, you must not only have a way of indicating links from this room to three others, but also which room the North and East doors, and the stairway link to. Some possible ways of doing this are given below.

Coding Data into the Adjacency Matrix

In an adjacency matrix one way of storing the information on which door/stairway links to a specific room would be to assign values to each cell in the matrix to indicate the door for this link. For example: '\0' = no link, 'N' = link via North door, 'S' = link via South door, 'E' = link via East door, 'W' = link via West door, 'U' = link via Stairway up, 'D' = link via Stairway down.
The example below shows one row out of the 20x20 adjacency matrix. In this example, the adjacency matrix is implemented as a 2D array of chars. The links from the room represented by this row indicates a door to the North('N') into room 1, a door to the East('E') into room 8, a stairway up('U') into room 14, and a stairway down('D') into room 16.

File I/O

To open the data file use the following lines of code in the GameGraph:: LoadGame() function. This will safely open the data file whose name is stored in a character array called filename and passed into the function as the only argument. The ifstream reference m_InFile is part of the GameGraph member variables. A complete outline of the LoadGame() function can be found in the snippets.txt file in the downloadable zip file.

    m_InFile.open(filename, ifstream::in);
    if(!m_InFile.is_open())
    {
        // m_InFile.is_open() returns false if the file could not be found or
        //    if for some other reason the open failed.
        return false;
    }

The following function can be used to read lines from the opened file. It takes two arguments: a character array and the length of the array. The array should be at least 128 characters long. It will return the next line read from the file skipping any comment lines (those starting with '#') and blank lines. If the line is returned empty, then the end of the file has been reached. This function is included in the snippets.txt file that is included in the downloadable zip file.

//-------------------------------------------
// GetNextLine()
// Read the next line from the file.
//-------------------------------------------
void GameGraph::getNextLine(char *line, int lineLen)
{
    int    done = false;

    while(!done)
    {
        m_InFile.getline(line, lineLen);
   
        if(m_InFile.good())    // If a line was successfully read
        {
           if(strlen(line) == 0)  // Skip any blank lines
                continue;
            else if(line[0] == '#')  // Skip any comment lines
                continue;
            else done = true;    // Got a valid data line so return
                                 // with this line
        }
        else
        {
            strcpy(line, "");
            return;
        }
    } // end while
}

I/O Redirection

This program will be graded by compiling your source files with a driver file containing main(). It will be very similar to the sample driver file provided. Your program will then be tested with I/O redirection using this driver and a test gamelayout.txt file. The way this is done is that the instructor will prepare a text file containing a list of commands (see the example below) and run your program, from a command line, using the following command:

your program name < cmd.txt

What will happen is that each time the driver program comes to the input line to ask the user to enter a command at the keyboard, the operating system will read a line from the text file instead of from the keyboard. This will allow the rapid, thorough testing and grading of each program. The file contains commands that will test moving to every room in the "dungeon" and test for attempts to move in directions in which there is not a door. It also tests for commands such as TAKE and FIGHT that will not be implemented yet and non-existant commands. Note: this sample list of commands is NOT the one that the instructor will use to test your program.

Sample Commands File

GO EAST
GO EAST
GO UP
GO WEST
GO SOUTH
GO WEST
GO SOUTH
GO NORTH
GO EAST
GO NORTH
GO WEST
GO UP
GO EAST
GO WEST
GO DOWN
GO EAST
GO SOUTH
GO DOWN
GO EAST
GO SOUTH
GO SOUTH
GO WEST
GO WEST
GO NORTH
GO EAST
GO WEST
GO NORTH
GO NORTH
TAKE SWORD
FIGHT TROLL
TRY THIS
GO WEST
QUIT

Using sscanf()

The function sscanf() found in the header file stdlib.h can be used to parse the command lines entered by the user. Suppose the user has entered a command at the keyboard, and you have stored it in a character array called command. Suppose also that there is two character arrays called cmd1 and cmd2. To copy the first word out of command intocmd1 use this command:

sscanf(command, "%s", cmd1);

You can now test cmd1 using strcmp() found in string.h to determine what the command is. If it is a command for which there is a second word (example: GO) then you can read both words using this command:

sscanf(command, "%s %s", cmd1, cmd2);

Now you can check cmd2 to determine the rest of the command which must then be executed. Note: You cannot assume that every command will have two words. The QUIT command is only one word. You will get an error if you try to read the one-word command using sscanf(command, "%s %s", cmd1, cmd2);

Making commands all caps
You cannot depend on the user always entering commands in all capitol letters. Since strcmp() is case sensitive you want to be able to convert all commands entered to all caps. The following function will do that. It takes a single argument, a character array. You need to include ctype.h in order to have access to the toupper() function.

//--------------------------------------
// makeUpper()
// Converts input line to all upper case
//--------------------------------------
void makeUpper(char *line)
{
char *temp;

temp = line;
while(*temp != '\0')
{
*temp = toupper(*temp);
temp++;
}
}

Just for Fun

If you enjoy writing game playing programs, this assignment will get you started. After completing it, you might want to expand it. Here are some things to think about:

How would you modify the data structure defining each room (node in the graph) to allow adding additional special items (like a "jeweled sword") to a room?

How would you modify the data structure defining each room (node in the graph) to allow adding more special creatures (like a "basilisk") to a room?

How would you add a data structure to define an adventuring character. In D&D style, the character would have to have a name, race (human, dwarf, elf, etc.), alignment (good, evil, or neutral) scores for strength, constitution, charisma, etc., weapons, equipment, experience points, and other items?
How would you program the execution of commands like Taking SWORD, or FIGHT TROLL?
Do not add any of these modifications to the program you turn in or it may not compile with the instructor's test program. As a result, you will get no credit for this assignment.

Buy now

Lock Up Tite user authentication program in Java GUI

$
0
0
Buy now

Objective 

You work for a company called Lock Up Tite. They want you to write a front end program to grant authentication access to programs using a user name and password. Requirements Write a program that creates a loop and has three options for the user to select.

Option 1 allows the user to add a user name and password, which is then stored into a file.

Option 2 allows the user to enter a user name and password up to three times. For a given attempt, the user will be notified if the attempt is successful or unsuccessful.

Option 3 will exit the loop and end the program Main Menu Requirements: When the program starts, present the user with a menu offering the three options described above. After the user chooses either option 1 or 2, the program should go back to the main menu. The final option will end the program.

Option 1 Requirements:

This option prompts the user for their user name and password and stores them in a file named passwords.txt. The program should not overwrite what's already in the file; it should append the new user name and password to the end of the file.

Option 2 Requirements: 

This option uses the passwords.txt file to verify the user is entering a valid user name and password. It begins by asking the user for a user name and password within a loop that runs up to three times. If the password is correct, an appropriate message will be printed, the loop will end, and the program will go back to the main menu. If the user is unable to provide a user name and password that matches any of the combinations in the file, an appropriate message will be printed and the user will be allowed to try again. If the user fails after three attempts, the loop should end and the program should go back to the main menu.

Technical Requirements: 


1. Create a Java program named LockUpTite.java.

2. Create a procedure for each major task in the program. Call the procedures based on the option selected by the user.

3. After completing the tasks of Option 1 or 2, re-display the menu and allow the user to pick another option. Option 3 will exit the program.

4. Make sure your program is adequately commented, uses consistent naming conventions for variable and module names, and uses appropriate indentation and line spacing to enhance the readability of the code.

Instructions Follow these instructions as you build your program: 


1. Create the LockUpTite.java class and create a main() method.

2. In the main() method, create a try-catch block. Within the try block, get the path to theplayers.txt file. While you can do this many different ways, the easiest approach is to put all your files in the same folder and use Path filePath = Paths.get("players.txt"); If you use an IDE that keeps .java and .class files in a separate folder, then use the following approach: Path filePath = Paths.get("players.txt").toAbsolutePath();

3. You may want to declare this variable outside of the main() method but within the class so that the other functions you build can use it.

4. For the function that responds to Option 2, you should do the following:
(a) Ask the user for a username and password.
(b) Create a Boolean variable to indicate a successful login, and set it to false.
(c) Open the players.txt file by creating a BufferedReader object. Call theFiles.newBufferedReader() method and pass it the BufferedReader reader = Files.newBufferedReader(filePath); NOTE: If you are using Java 7, this technique will not work. Instead, you must send two arguments, aPath and a Charset. So if you are using
Java 7, you will need to do the following:

import java.nio.charset.Charset; Create your Path object as outlined above. Then when you create the BufferedReader: BufferedReader reader = Files.newBufferedReader(filePath, Charset.forName("UTF-8"));

1. Create a String named line, and assign it to reader.readLine(), where reader is the name of theBufferedReader object you created in step 4.

2. Create a while loop that will continue as long as line is not NULL and a match has not been found.
(a) Within the loop, use the line object’s split() method to break the String into two pieces, both of which should be stored in a String array.
(b) Check the name and password for a match. The user name taken from the file will be stored in the first element of the array; the password will be in the second. If both match, set Boolean to true.
(c) Assign line to the next line of text in the file by calling reader.readLine().

3. Below the while loop, check the Boolean variable. If it is true, then a match was found. If not, bump a counter to give the user a second chance unless the value of the counter has exceeded three increments.

4. Within the catch block, print out the Exception object’s error message.

Output Screenshots:








Order Now and get your work!


Buy now

Connect-K in Java Data Structures Compelete Source code

$
0
0
Buy now

Introduction:

In the game of Connect-K, red and blue pieces are dropped into an N-by-N table. The
the table stands up vertically so that pieces drop down to the bottom-most empty slots in their column. For example, consider the following two configurations:-

Legal Position -

.......
..................R
.....RB....
BRB...
RBBR..-

Illegal Position -

............................Bad
 - ..BR......
R....
RBBR..

In these pictures, each '.' represents an empty slot, each 'R' represents a slot filled with a red piece, and each 'B' represents a slot filled with a blue piece. The left configuration is legal, but the right one is not. This is because one of the pieces in the third column (marked with the arrow) has not fallen down to the empty slot below it.
A player wins if they can place at least K pieces of their colour in a row, either horizontally,
vertically, or diagonally. The four possible orientations are shown below:

- Four in a row -

RRRRRRRRRRRRRRRR
In the "Legal Position" diagram at the beginning of the problem statement, both players had lined up two pieces in a row, but not three.
You have a tricky plan to ensure victory with Connect-K! When your opponent is not looking, you are going to rotate the board 90 degrees clockwise onto its side. Gravity will then cause the pieces to fall down into a new position as shown below:

- Start -

........................R......RB....BRB...RBBR..- Rotate -
.......R......BB..... BRRR...RBB..................- Gravity -
.....................R......BB.....BRR....RBBR... Unfortunately, you only have time to rotate once before your opponent will notice.All that remains is picking the right time to make your move. Given a board position, you should determine which player (or players!) will have K pieces in a row after you rotate the board clockwise and gravity takes effect in the new direction.
NotesYou can rotate the board only once.Assume that gravity only takes effect after the board has been rotated completely. Only check for winners after gravity has finished taking effect.

Input

The first line of the input gives the number of test cases, T. T test cases follow, each beginning with a line containing the integers N and K. The next N lines will each be exactly N characters long, showing the initial position of the board, using the same format as the diagrams above.
The initial position in each test case will be a legal position that can occur during a game of Connect-K. In particular, neither player will have already formed K pieces in a row.

Output

For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1), and y is one of "Red", "Blue", "Neither", or "Both". Here, y indicates which player or players will have K pieces in a row after you rotate the board.

Limits

1 ≤ T ≤ 100.3 ≤ K ≤ N. Small dataset 3 ≤ N ≤ 7.Large dataset
3 ≤ N ≤ 50.

Example

You can search the Internet for another algorithm that has not been taught in class, and present, subject to the approval of the lecturer. Whatever the algorithm chose, the group will have to find (or implement) a Java implementation and show it, run it and discuss the code of such algorithm in a PowerPoint presentation in front of the class at the end of the course. Submission

Code Screenshots:



Order Now:

Buy now

Car Racing Java API Level 2.2 complete implementation with source code

$
0
0
Buy now

Major Coursework #2

In this coursework, you are required to implement an Android Game App, create an installable apk that can be installed on an Android phone (API level 2.2) and write a report that describes the design and justifies improvements.

The GameYou are required to develop Java code to implement an Android app inspired by the traditional top-down racing game. The code MUST extend the code base provided for the practical in week 7 of Spring term.

The OOP Design

You are required to develop an OOP design before starting implementation. This should be discussed and signed off in your practical session in week 8 of spring term. This will be marked in that week’s practical sign off sheet. You must include an electronic version (e.g. scan handwritten work) in an appendix of the submitted report.
You can later change the design. You must, however, justify your changes in the final report

Your game should:


  • Have functionality to start individual games on a screen using a separate welcome or start screen. The welcome screen must function using the Android library buttons.
  • Display the current score while playing. You define scoring mechanisms.
  • Have a Car that the user controls. 
    • Controlled by touches on the screen and/or sensors within the phone.
  • Have a Track
    • The player will lose a “life” or energy if the car drives off the track. (Try different retro racing games for inspiration.)
    • The track cannot be straight. I.e. it must have corners or change shape while the player drives through the track
  • Have Opponent cars or other vehicles
    • Must have more than one opponent on screen at some point in the gameplay. 
    • This can be opponents that the player is racing against (functioning as A.I. players), or slow driving cars that need to be overtaken, e.g. for extra points.
  • At least three game levels with different tracks and/or types of opponents with different behaviours.
  • Higher marks available for creation of new levels (e.g. levels stored online, in files or easy to reuse data structures within the game)
    • Marks are given for the complexity of the solution. 
      • Using online levels receives higher marks than storing them in a local file.
      • Using appropriate OOP design receives higher marks than one that does not.
  • Research and improve memory and speed efficiency of the game. This process, including tests to verify claims, must be described and justified in the report
  • There are 20% (capped) marks available for
  • Creating an online high score list. This must be hand coded, i.e. without using high score list libraries such as Google Play Services. You can, however, base the server-side code on the code provided in week 3 and 4 of spring term (worth max. 15%). Researching and improving multithreading of the game. This should be described and justified in the report (worth max. 15%)

Output Screenshot:


Order now and get you work in a minute :)


Buy now

HTML, PHP URL registration and lising program Internet Programming Spring 2016 Assignment #5

$
0
0
Buy now

Introduction

Create and run a SQL script with a database named URL and a table named Urltable. The first field of the table should contain an actual URL, and the second, which is named Description, should contain a description of the URL.

Write a PHP script that obtains a URL and its description from a user and stores the information into a database using MySQL. After each new URL is submitted, print the contents of the database in a table.

Requirements:

Store the structure of the tables in a txt file for submission.

Output Screenshots:


Order now!

Buy now

Extra Credit Assignment 1: Rock – Paper – Scissors Java Implementation

$
0
0
Buy now

Problem:

Design and implement an application that plays the Rock-Paper-Scissors game against the computer. When played between two people, each person picks one of three options (usually shown by a hand gesture) at the same time, and a winner is determined. In the game, Rock beats Scissors, Scissors beats Paper, and Paper beats Rock. The program should randomly choose one of the three options (without revealing it) then prompt for the user’s selection. At that point, the program reveals both choices and indicates if the user won, the computer won, or if there was a tie. Continue playing until the user chooses to stop, and then show the number of user wins, losses, and ties.

Objective:


  1. Understand the concept of object-oriented programming.
  2. Understand the use of standard Java classes.
  3. Familiarize with code documentation, compilation, and execution.
  4. Expose to Java syntax, programming styles, and Java classes.

Code Screenshots:





Order Now:

Buy now

Extra Credit Assignment 2: Slot Machine in Java with full source code

$
0
0
Buy now

Problem Introduction:

Write an application that simulates a slot machine. The player starts out with M coins. The value of M is an input to the program, and you charge 25 cents per coin. For each play, the player can bet 1 to 4 coins. If the player enters 0 as the number of coins to bet, then the program stops playing. At the end of the game, the program displays the number of coins left and how much the player won or lost in the dollar amount. There are three slots on the machine, and each slot will display one of the three possible pieces: BELL, GRAPE, and CHERRY. When certain combinations appear on the slots, the machine will pay the player. The payoff combinations are these:
The symbol --------- means any piece. If the player bets 4 coins and gets combination 5, for example, the machine pays the player 12 coins.

Code Screenshot:


Order Now:

Buy now

Extra Credit Assignment 3: Loan Calculator Java Implementation Source Code

$
0
0
Buy now

Problem Description

The monthly payments for a given loan are divided into amounts that apply to the principal and to the interest. For example, if you make a monthly payment of $500, only a portion of the $500 goes to the principal and the remainder is the interest payment. The monthly interest is computed by multiplying the monthly interest rate by the unpaid balance. The monthly payment minus the monthly interest is the amount applied to the principal. The following table is the sample loan payment schedule for a one-year loan of $5,000 with a 12 percent annual interest rate. The monthly payment would be $444.24.

Write an application that accepts a loan amount, annual interest rate, and loan period (in number of years) and displays a table with five columns: payment number, the interest and principal paid for that month, the remaining balance after the payment, and the total interest paid to date. Note: The last payment is generally different from the monthly payment, and your application should print out the correct amount for the last payment. Use a formatter to align the output values neatly. If the input values are invalid, then print out an appropriate error message. Decide on the range of valid values for the loan amount, interest rate, and loan period.

Objective

The objectives of this extra credit assignment:
Understand the concept of object-oriented programming.
Understand the concepts of repetition statements.
Understand the use of standard Java classes.
Familiarize with code documentation, compilation, and execution.
Expose to Java syntax, programming styles, and Java classes.

Code Screenshots



Order Now:

Buy now

The Territory: The Memoir of a Friendship in Earliest Iowa Paperback – March 9, 2016

$
0
0

The Territory: 

The Memoir of a Friendship in Earliest Iowa is a lighthearted but serious work of fiction in the form of a memoir by one of a pair of generally serious, sometimes comical pioneer settlers in preterritorial and territorial Iowa. Its inspiration is a number of now little-known local and regional events described by prominent longtime resident Benjamin F. Gue in his 1903 History of Iowa, and the setting and details of events and conditions are thoroughly researched and portrayed accurately from scores of books and journal articles, as well as Internet articles. The readership would be anyone interested in a reliable and informative chronicle of Iowa's pioneer past and foundations of the present state and the many issues, large and small, present at that time, and also anyone who likes a rip-roaring story with frequent passages of more and sometimes less subtle humor. Though the work is not lengthy, it portrays virtually every event of relevance for early pre–Civil War Iowa, as well as recounting the progress and tribulations of its two fictional pioneers and their families, who become involved in just about everything. Highlighted in particular are the opening and development of the land, early towns, the march of the frontier across the territory and new state, and the tenor of the newborn society and its grist of daily conversation. The Territory will provide interesting and reliable context for genealogists, general readers, and students, regardless of age

View on Amazon Now!

The Territory: The Memoir of a Friendship in Earliest Iowa Paperback – March 9, 2016

$
0
0

Bipartite dimension

The Territory: 

The Memoir of a Friendship in Earliest Iowa is a lighthearted but serious work of fiction in the form of a memoir by one of a pair of generally serious, sometimes comical pioneer settlers in preterritorial and territorial Iowa. Its inspiration is a number of now little-known local and regional events described by prominent longtime resident Benjamin F. Gue in his 1903 History of Iowa, and the setting and details of events and conditions are thoroughly researched and portrayed accurately from scores of books and journal articles, as well as Internet articles. The readership would be anyone interested in a reliable and informative chronicle of Iowa's pioneer past and foundations of the present state and the many issues, large and small, present at that time, and also anyone who likes a rip-roaring story with frequent passages of more and sometimes less subtle humor. Though the work is not lengthy, it portrays virtually every event of relevance for early pre–Civil War Iowa, as well as recounting the progress and tribulations of its two fictional pioneers and their families, who become involved in just about everything. Highlighted in particular are the opening and development of the land, early towns, the march of the frontier across the territory and new state, and the tenor of the newborn society and its grist of daily conversation. The Territory will provide interesting and reliable context for genealogists, general readers, and students, regardless of age

View on Amazon Now!

Simple Trip Planner with file handling in Java complete source

$
0
0

Simple Trip Planner

This assignment is inspired by the problem of planning a European holiday by train, making optimal use of travel time. Your aim is to take each of a number of given train trips, e.g. London to Paris. Your journey must include a number of given trips, but may include additional trips to "link up" the cities in the trips you want to take. For simplicity, we assume that trains run frequently, so that you can focus on scheduling a journey that includes all of your specified trips and minimizes time takes to complete the journey (so you don't have to consider time lost waiting around for departures). The trips in your journey can be scheduled in any order, but your journey always starts in London. The aim is to minimize the total journey time, taking into account travel time and a transfer time in each city (except in London at the start of the journey).

We assume that all cities can be reached by train directly from any other city, and that the travel time between any two cities is the same in either direction (so need only be specified in one direction). This means that the travel times between each pair of cities will be given. Furthermore, we assume the following "triangle inequality" on travel times: for any cities A, B and C, the travel time from A to C is always less than or equal to the travel time from A to B plus the travel time from B to C.

In this assignment, you will implement an A* search procedure for the trip planning problem. In your program design, make use of the Strategy pattern to supply a heuristic to the search procedure, and don't forget to ensure that your heuristic is admissible. Implementing A* is the main requirement for this assignment, so that your program is guaranteed to produce an optimal solution. If your program does not always produce an optimal solution, then it is wrong. Assessment will be based on the design of your program in addition to correctness. You should submit at least a UML class diagram used for the design of your program, i.e. not generated from code afterwards. All input will be a sequence of lines of the following form, and all cities and travel times will be declared before any trip requirements:

Transfer <time> <name>
# Transfer time is <time> minutes in city <name>
Time <time> <name1> <name2>
# Travel time is <time> minutes from city <name1> to city <name2>
Trip <name1> <name2>
# Journey requires a trip from <name1> to <name2>

Create all your Java source files in the default package. Call your main Java file TripPlanner.java. Read input from a file whose name is passed as an argument to the main method in the call to java TripPlanner and print output to System.out. For machine marking, the output will be redirected to a text file that will be compared to the expected output (so do not print out extra spaces, etc.) and remember to close the file. For the purposes of machine marking, problems will be used for which there is only one optimal solution, though in the case of multiple optimal solutions, your program should produce one of them.

To read input from a text file (whose name should be passed as a command line argument to java, e.g. java TripPlanner input.txt), use code such as:

Scanner sc = null;
        try {
            sc = new Scanner(new FileReader(args[0]));
           
            # args[0] is the first command line argument } catch (FileNotFoundException e) {
        } finally {
            if (sc != null) {
                sc.close();
            }
        }

Sample Input: 

For example, the following input has five cities and four required trips as indicated. This means that 10 travel times between cities need to be specified (which can be given in any order). The format and meaning of the input is as follows (comments are for explanation and should not appear in the actual input):


Sample Output:

The above example does not have a unique optimal solution. One valid output corresponding to the above input is as follows. The first line in the output should give the number of nodes n expanded in your search, the number of nodes taken off the queue, which will vary according to the heuristic used. The second line of the output should give the cost of the solution found as an integer, which is the total time taken, and should be the same regardless of the heuristic and the solution path. The remainder of the output should give a sequence of trips that make up an optimal solution. If your program produces a different optimal solution from the one shown (with the same cost) then it is correct.

 order now

Simple Trip Planner with file handling in Java complete source - Buy Now

$
0
0
Buy now

Simple Trip Planner

This assignment is inspired by the problem of planning a European holiday by train, making optimal use of travel time. Your aim is to take each of a number of given train trips, e.g. London to Paris. Your journey must include a number of given trips, but may include additional trips to "link up" the cities in the trips you want to take. For simplicity, we assume that trains run frequently, so that you can focus on scheduling a journey that includes all of your specified trips and minimizes time takes to complete the journey (so you don't have to consider time lost waiting around for departures). The trips in your journey can be scheduled in any order, but your journey always starts in London. The aim is to minimize the total journey time, taking into account travel time and a transfer time in each city (except in London at the start of the journey).

We assume that all cities can be reached by train directly from any other city, and that the travel time between any two cities is the same in either direction (so need only be specified in one direction). This means that the travel times between each pair of cities will be given. Furthermore, we assume the following "triangle inequality" on travel times: for any cities A, B and C, the travel time from A to C is always less than or equal to the travel time from A to B plus the travel time from B to C.

In this assignment, you will implement an A* search procedure for the trip planning problem. In your program design, make use of the Strategy pattern to supply a heuristic to the search procedure, and don't forget to ensure that your heuristic is admissible. Implementing A* is the main requirement for this assignment, so that your program is guaranteed to produce an optimal solution. If your program does not always produce an optimal solution, then it is wrong. Assessment will be based on the design of your program in addition to correctness. You should submit at least a UML class diagram used for the design of your program, i.e. not generated from code afterwards. All input will be a sequence of lines of the following form, and all cities and travel times will be declared before any trip requirements:

Transfer <time> <name>
# Transfer time is <time> minutes in city <name>
Time <time> <name1> <name2>
# Travel time is <time> minutes from city <name1> to city <name2>
Trip <name1> <name2>
# Journey requires a trip from <name1> to <name2>

Create all your Java source files in the default package. Call your main Java file TripPlanner.java. Read input from a file whose name is passed as an argument to the main method in the call to java TripPlanner and print output to System.out. For machine marking, the output will be redirected to a text file that will be compared to the expected output (so do not print out extra spaces, etc.) and remember to close the file. For the purposes of machine marking, problems will be used for which there is only one optimal solution, though in the case of multiple optimal solutions, your program should produce one of them.

To read input from a text file (whose name should be passed as a command line argument to java, e.g. java TripPlanner input.txt), use code such as:

Scanner sc = null;
        try {
            sc = new Scanner(new FileReader(args[0]));
       
            # args[0] is the first command line argument } catch (FileNotFoundException e) {
        } finally {
            if (sc != null) {
                sc.close();
            }
        }

Sample Input: 

For example, the following input has five cities and four required trips as indicated. This means that 10 travel times between cities need to be specified (which can be given in any order). The format and meaning of the input is as follows (comments are for explanation and should not appear in the actual input):


Sample Output:

The above example does not have a unique optimal solution. One valid output corresponding to the above input is as follows. The first line in the output should give the number of nodes n expanded in your search, the number of nodes taken off the queue, which will vary according to the heuristic used. The second line of the output should give the cost of the solution found as an integer, which is the total time taken, and should be the same regardless of the heuristic and the solution path. The remainder of the output should give a sequence of trips that make up an optimal solution. If your program produces a different optimal solution from the one shown (with the same cost) then it is correct.



Buy now

Simple parser-like program for math operations using syntax tree in Java

$
0
0

Requirements:

operators supported: ( ) * / + - ^
trigonometric functions: sine, cosine, tangent, cotangent, secant, cosecant
variables from set of a - z, A - Z, 0 - 9, and _ of arbitrary length


  1. must parse "code-like input" and create tokens from it
  2. must build a syntax tree using PEMDAS (http://www.purplemath.com/modules/orderops.htm) order of operations. Feel free to use code from http://castingrays.blogspot.com/2014/10/mathematical-expression-parsing-and.html for reference
  3. Ability to store variables, and variables must be usable in equations
  4. Numeric values supported is the set of ints and doubles
  5. Ability to support user-defined and evaluation of functionsExample: the user inputs “defn square(x) = x * x”square(5) returns 25
  6. Support for basic graphing: e.g. graph( 3 * X ^ 2 + 7) 
  7. Support for trigonometric functions (implemented in the code – do not reference trig functions of the standard library). e.g. sin(30) outputs 0.5
  8. Please include meaningful/informative comments


Additional examples:

takes in arithmetic expressions of arbitrary length in standard infix notation (e.g. 7 + 8 * 9) and returns the result (output in this example 79)
assignment to variables (e.g. b = 7 + 8 * 9 would assign the value of 79 to variable b)
evaluation with variables (e.g. c = 5 * b would assign 395 to c)
 order now

QuickHull and divide and conquer algorithm

$
0
0

Requirements:

In one place there is a treasure with diamonds. To get someone to treasure should avoid an area with
mines. We want to find, from the starting point, the shortest path to reach the treasure and does not
pass through the minefield. However, it may go scratch the minefield, practically on the mines
around the minefield.

The input will be a file in the following form (without the comments):
Integer coordinates exept the third line that is a single integer representing the number of diamonds.
8 23 //starting point
130 28//coordinates of the treasure
156 // the number of the diamonds
23 108 // the 1st mine
50 99 // 2nd mine
108 107 // 3rd mine
52 54
115 107

Write a code such that:


  1. Finding the shortest path from the initial point and print the following message. The shortest distance is 122.16872656315464 The shortest path is:(8.0,23.0) -->(56.0,23.0) --> (130.0,28.0)
  2. Among the diamonds there is one fake that weighs less than the others (all the other diamonds have exactly the same weight). We have at our disposal a weighing scale (like the one in the image)

Write code that calculates the minimum number of weightings, in order to find the fake diamond. It
must print the following message.

Number of weightings: 5
Instructions
  • Write code in Java 1.7 or 1.8. The only input argument must be the input file.
  • If you use any free code from the internet it should be noted specific.
  • The complexity of a) in the Middle Case it must be O(n logn) and the complexity of b)
  • must be O(n).
  • The source code must have inline comments and extended javadoc comments over every method. You should explain the reasoning of each step and make analysis of complexity.
The weighing scale can be simulated with the following

int scale() {
        Random randomGenerator = new Random();
        int x = randomGenerator.nextInt(100);
        if (x < 34) {
            return 1; // to the left
        } else if (x < 67) {
            return 0; //equal
        } else {
            return -1; // to the right
        }
    }

 order now


Food Ordering System project in Java using Queue Data Structure

$
0
0

Explain how the application works 


  • List the modules involved and briefly describe each of the module. [2 marks]
  • Clearly describe the data organisation or storage patterns that influence the selection of specific data structure in that application. Use animations or illustrations in your explanation to improve understanding. [7 marks]


Pick any one operation in (2) and present the algorithm


  • Find the running time and estimate the efficiency of the algorithm. Explain the steps that drive you to the final answer. [3 marks]
  • Conclusion on the findings (final answer in (3)) [2 marks]

Output Screenshot



Buy now

NP Complete problem and solve it in Map-Reduce and Fan

$
0
0

Requirements

Pick any np-complete problem and solve it in Map-Reduce and Fan. Approximate an NP-Complete solver using Map-Reduce and Fan In algorithms.

Buy now

Representation and manipulation of rational numbers in C++

$
0
0

Requirements

Task is to define a class to represent and manipulate rational numbers (fractions), so that by simply changing the type of n1 and n2 to Rational the program will compute fractional

arithmetic expressions such as these:


1/2 + 1/3 // answer: 5/6
1/3 - 1/4 // answer: 1/12
2/3 * 4/5 // answer: 8/15
3/7 / 2/3 // answer: 9/14

Download the file fractions_0.zip, which contains the calculator code and a skeleton version of the Rational class. The class defines (but doesn't fully implement) appropriate constructors to initialise instances of Rational, extract and insert operators for input and output of Rational values, and of course arithmetic operators to compute the results.

Buy now

Program to emulate calculations performed on the HP-35 calculator

$
0
0

Automatic Testing 

This task is available for automatic testing using the name hp-35. You can run the demo using demo hp-35 and you can test your work using try hp-35 <filename.

Background

The HP-35 was the first scientific hand-held calculator, released in 1972 and an immediate success with engineers and scientists. Amongst other features, it used an unusual way of entering numbers, called RPN. RPN (reverse Polish notation, named for Polish mathematician Jan Lukasiewicz) allows complex calculations to be entered without the use of parentheses. The key difference is that operators are entered after the operands, rather than between them The HP-35 implemented RPN using a stack of 4 registers, referred to as X, Y , Z, and T. The value in the X register is the one shown on the calculator's LED display; the other registers are used for temporary values during calculations. New values are entered into the X register, with existing values "pushed" up the register stack: the old value of X goes into Y, the old value of Y goes into Z, the old value of Z goes into T, and the old value of T is lost. Single-operand functions (such as square root) use and replace the value in the X register; other registers are unchanged. Functions that operate on 2 values (such as the arithmetic operators) use the values in Y and X, with the result going back into X. Values in the Z and T registers are "dropped" down the stack, with Z overwriting the old Y and T overwriting the old Z. The value of T is preserved, providing a simple way to do calculations with repeated values. This scheme allows calculations to be entered without using parentheses. For example, you could compute the compound expression (5 + 4)/(3 - 2) like this:
5 ENTER 4 + 3 ENTER 2 - ÷

Hints

You'll need to define the class HPStack to represent the calculator's operand stack, with operations such as push (push all values up 1 level and store a value into X), pop (drop all values down 1 evel and return the old X value), and peek (return the current X value). The simplest approach is to use an array to store the register values, with the methods manipulating the array elements. The calculator should read and process tokens representing numbers and operator keys, with the current value of the X register displayed after processing each line. It should exit when all lines of input have been processed.

A suitable main function will contain code such as this:

HPStack stack;
        string line;

        while (getline(cin, line)) {
            stringstream expression
            (line
            );
        string token;
            while (expression token) {
                if (isdigit(token[0])) {
                    stack.push(atof(token.data()));
                } else if (token == "+") { // other arithmetic ops similar
                    double x = stack.pop();
                    double y = stack.pop();
                    stack.push(y + x);
                }
            }
            cout << stack.peek();
        }


Level 1: Basic

Implement the arithmetic operations so that the calculator can compute basic expressions:

54 + 3 2 - / // should be 9
3456 + + + // should be 18
1.23 4.5 67 / * // should be 0.0826119

Level 2: Scientific

Implement π (pi) and the functions chs (change the sign of X), 1/x (recip), log (decimal logarithm), ln (natural logarithm), ex (exp), √x (sqrt), sin, cos, tan (and their inverses arcsin, arccos, and arctan), and xy (pow). The function names should be accepted in either upper or lower case. Use the functions in the cmath library to do the actual work! The predefined constant M_PI contains the value of pi.

PI 2 / SIN // should be 1 (or very close)
100 100 * sqrt // should be 100
1E-5 LOG CHS // should be 5
5 EXP LN // should be 5
3 recip 8 pow // should be 2
2 1 arctan cos pow // should be 0.5

Level 3: Memory


Implement STO (store X into memory) and RCL (recall from memory into X, ushing other values up), CLR (set all registers to 0), and CLx (drop the X value).

100 sto 2 * rcl / // should be 2
1 2 clx 3 + // should be 4
1 2 3 4 clr + + + // should be 0


Level 4: Stack Control


Implement x􂁶y (swap X and Y), R↓ (roll the stack down, with each register moved into the register below it and X moved into T), and ENTER↑ (push all values up the stack, preserving X and losing T). (Note that this interpretation of ENTER is not identical to that on the original calculator, where it is also used to separate consecutive numbers).


2 8 swap / // should be 4
1 2 3 4 // should be 4
roll roll // now 2
roll roll // back to 4
2 enter enter enter // 2
+ + + + // 10

Buy now

Count number of word from the .txt file in Java full source code

$
0
0
Buy now

Task

Your task is to write a program, words, that reports information about the number of words read from its standard input. For example, if the file qbf.txt contains the text the quick brown fox jumps over the lazy dog then running the program with is input redirected to come from that file will report 9 words
$ words < qbf.txt

Total: 9

Automatic Testing

This task is available for automatic testing using the name words. You can run the demo using demo words and you can test your work using try words <<filename>>.

Background

Use the following skeleton for the program:
int main (int argc,
        char
        ** argv
       
            ) {
 enum  {

                total, unique
            }
            mode = total;
            for (int c; (c = getopt(argc, argv, "tu")) != -1;) {
                switch (c) {
                    case 't':
                        mode = total;
                        break;
                    case 'u':
                        mode = unique;
                        break;
                }
            }
            argc -= optind;
            argv += optind;
            string word;
            int count = 0;
            while (cin >> word) {
                count += 1;
            }
            switch (mode) {
                case total:
                    cout << "Total: "<< count << endl;
                    break;
                case unique:
                    cout << "Unique: "<< "** missing **"<< endl;
                    break;
            }
        }

The getopt function (#include <unistd.h>) provides a standard way of handling option values in command-line arguments to programs. It analyses the command-line parameters argc and argv, looking for arguments that begin with '-'. It then examines all such arguments for specified option letters, returning individual letters on successive calls and adjusting the variable optind to indicate which arguments it has processed. Consult getopt documentation for details.

In this case, the option processing code is used to optionally modify a variable that determines what output the program should produce. By default, mode is set to total (indicating that it should display the total number of words read). The getopt code looks for the t and u options (which would be specified on the command line as -t or -u) and overwrites the mode variable accordingly. When there are no more options (indicated by getopt returning -1), argc and argv are adjusted to remove the option arguments that getopt has processed.

Level 1: Unique words

Extend the program so that if run with the u option (specified by the command-line argument
-u), it displays the number of unique words. To count unique words, use the STL vector
class to keep track of which words you've already seen. When each word is read, check to see
if it's already in the vector; if it's not, insert it. The number of unique words will then be the
size of the vector.

Level 2: Your Own Vector

Modify your code so that it does not use the STL classes. You'll need to write your own class
to keep track of the list of words. At this level, you can assume that there will be no more that
1000 unique words, so you can use a statically allocated array to store the items.
A minimal STL-compliant class (which will minimise the changes you need to make to your
main program) would have an interface like this:

        template<
        class T

            >
class Vector {

                public
                :
typedef T
                * iterator ;

                Vector() {
                     << code >>
                }

                iterator begin() {
                     << code >>
                }

                iterator end() {
                     << code >>
                }

                int size() {
                     << code >>
                }

                iterator insert(iterator position,
                    const T& item) {  << code >>
                }
                private
                :
                    T items[1000];
                    int used;
            };

Note that, unlike an ordinary class, a template class is defined entirely in a header file, so here won't be any Vector.cpp file. Also, you'll find it easier to define the template methods within the class scope because it avoids the need to specify the scope for each method individually. Note that the insert method returns an iterator (a pointer in the case of Vector) to the newly inserted item.

Level 3: Individual Word Counts

Extend the program so that if run with the i option it displays the counts of individual words in  alphabetical order. For example the command words -i < qbf.txt should result in the output shown.
Your program will need to store two pieces of information for each word. Define a struct called WordInfo that contains a string variable named text for the word's text, and an int variable named count for the number of times it's been seen. Then create a vector of WordInfo instead of a vector of string. When you add a new word, give it a count of 1. When you see a word that's already in the
vector, increment its count. The simplest way to display the result in alphabetic order is to keep the vector in sorted order as words are added, then simply iterate through the vector at the end. To keep the list sorted, iterate through the list until you find a word that's alphabetically after the new word or reach the end of the list, then insert at that position.

Level 4: Large Data Sets

Make sure that your program works correctly (and efficiently!) even if it is run with large data sets. Since you don't know how large the collection of words might become, you'll need to make the vector grow dynamically. A suitable strategy is to allocate space for a small number of items initially, and then check at each insert whether or not there's still enough space. When space runs out, allocate a new block that's twice as large, copy all of the old values into the new space, then delete the old block. You'll also need to make sure that the iterator (pointer) returned by the insert call points into the new block of memory; the previous iterator will be invalid because it points into memory that has been deallocated.

Buy now
Viewing all 191 articles
Browse latest View live