Project Three: Simple World
Due: Nov. 17, 2024
I. Motivation
1. To give you experience in using arrays, pointers, structs, enums, and different I/O streams and
writing program that takes arguments.
2. To let you have fun with an application that is extremely captivating.
II. Introduction
The simple world program we will write for this project simulates a number of creatures running
around in a simple square world. The world is an m-by-n two-dimensional grid of squares (The
number m represents the height of the grid and the number n represents the width of the grid.).
Each creature lives in one of the squares, faces in one of the major compass directions (north,
east, south, or west) and belongs to a particular species, which determines how that creature
behaves.
la ho
fl
fl ho Figure 1. A 4-by-4 grid, which contains five creatures. Two creatures belong to the species
flytrap (whose short name is “fl”), two belong to the species hop (whose short name is “ho”), and
one belongs to the species landmine (whose short name is “la”). The direction of each creature
is represented by the direction of the arrow.
Figure 1 shows a 4-by-4 grid populated by five creatures. Two of them belong to the species
flytrap (whose short name is “fl”), two belong to the species hop (whose short name is “ho”), and
one belongs to the species landmine (whose short name is “la”). The direction of each creature is
represented by the direction of the arrow. For example, the flytrap at the top row is facing east
and the flytrap at the bottom row is facing west.
Table 1. The list of instructions and their explanations.
hop
The creature moves forward as long as the square it is facing is empty. If
moving forward would put the creature outside the boundaries of the grid or
would cause it to land on top of another creature, the hop instruction does
nothing.
left The creature turns left 90 degrees to face in a new direction.
right The creature turns right 90 degrees to face in a new direction.
infect
If the square immediately in front of this creature is occupied by a creature of
a different species (an “enemy”), that enemy creature is infected to become
the same as the infecting species. When a creature is infected, it keeps its
position and orientation, but changes its internal species indicator and begins
executing the same program as the infecting creature, starting at step 1. If the
square immediately in front of this creature is empty, outside the grid, or
occupied by a creature of the same species, the infect instruction does
nothing.
ifempty n
If the square in front of the creature is inside the grid boundary and
unoccupied, jump to step n of the program; otherwise, go on with the next
instruction in sequence.
ifwall n
If the creature is facing the border of the grid (which we imagine as
consisting of a huge wall) jump to step n of the program; otherwise, go on
with the next instruction in sequence.
ifsame n
If the square the creature is facing is occupied by a creature of the same
species, jump to step n; otherwise, go on with the next instruction.
ifenemy n
If the square the creature is facing is occupied by a creature of an enemy
species, jump to step n; otherwise, go on with the next instruction.
go n This instruction always jumps to step n, independent of any condition.
Each species has an associated program which controls how each creature of that species
behaves. Programs are composed of a sequence of instructions. The instructions that can be
part of a program are listed in Table 1. There are nine legal instructions in total. The last five
instructions have an additional integer argument.
Program is an attribute associated with species. Creatures of the same species have the same
program. However, different species have different programs.
For example, the program of the species flytrap is composed of the following five instructions:
ifenemy 4
left
go 1
infect
go 1
The meaning of each instruction for this example is commented below:
(step 1) ifenemy 4 # If there is an enemy ahead, go to step 4
(step 2) left # Turn left
(step 3) go 1 # Go to step 1
(step 4) infect # Infect the adjacent creature
(step 5) go 1 # Go to step 1
We will simulate the behaviors of all the creatures for a user specified number of rounds. In each
round, creatures take their turns one by one, starting from the first creature. After the first
creature finishes its turn, the second creature begins its turn. So on and so forth. One round ends
with the last creature finishing its turn. Then the next round begins with the first creature taking
its turn. Note that during the simulation, a creature may infect another creature so that the
infected one changes its species. However, the simulation order of the infected creature does not
change.
Each creature also maintains a variable called program counter which stores the index of the
instruction it is going to execute. On each turn of a creature, it executes a number of instructions
of its program, starting from the step indicated by the program counter. A program ordinarily
continues with each new instruction in sequence, although this order can be changed by certain
instructions in the program such as the if*** instructions. In each turn, a creature can execute
any number of if*** or go instructions without relinquishing this turn. Its turn ends only when
the creature executes one of the instructions: hop, left, right, or infect. After its turn ends, the
creature updates the program counter to point to the next instruction, which will be executed at
the beginning of its next turn.
Note that each creature maintains its own program counter, so that two different creatures
belonging to the same species can have different program counters. The indices of the
instructions start from one, i.e., the first instruction of each program is “step 1”. At the very
beginning of the simulation process, the program counters of all the creatures are set to their first
instructions.
III. Available Types
In completing this project, you will have the following types available to you. They are defined
in the file world_type.h.
const unsigned int MAXSPECIES = 10; // Max number of species in the
// world
const unsigned int MAXPROGRAM = 40; // Max size of a species program
const unsigned int MAXCREATURES = 50; // Max number of creatures in
// the world
const unsigned int MAXHEIGHT = 20; // Max height of the grid
const unsigned int MAXWIDTH = 20; // Max width of the grid
struct point_t
{
int r;
int c;
};
/*
// Type: point_t
// ------------
// This type is used to represent a point in the grid.
// Its component r corresponds to the row number; its component
// c corresponds to the column number.
*/
enum direction_t { EAST, SOUTH, WEST, NORTH };
/*
// Type: direction_t
// ----------------
// This type is used to represent direction, which can take on
// one of the four values: East, South, West, and North.
*/
const std::string directName[] = {"east", "south", "west", "north"};
// An array of strings representing the direction name.
const std::string directShortName[] = {"e", "s", "w", "n"};
// An array of strings representing the short names for directions.
enum opcode_t {HOP, LEFT, RIGHT, INFECT, IFEMPTY, IFENEMY,
IFSAME, IFWALL, GO};
/*
// Type: opcode_t
// -------------
// The type opcode_t is an enumeration of all of the legal
// command names.
*/
const std::string opName[] = {"hop", "left", "right", "infect",
"ifempty", "ifenemy", "ifsame", "ifwall", "go"};
// An array of strings representing the command name.
struct instruction_t
{
opcode_t op;
unsigned int address;
};
/*
// Type: instruction_t
// ------------------
// The type instruction_t is used to represent an instruction
// and consists of a pair of an operation code and an integer.
// For some operation code, the integer stores the address of
// the instruction it jumps to. The address is optional.
*/
struct species_t
{
std::string name;
unsigned int programSize;
instruction_t program[MAXPROGRAM];
};
/*
// Type: species_t
// ------------------
// The type species_t is used to represent a species
// and consists of a string, an unsigned int, and an array
// of instruction_t. The string gives the name of the
// species. The unsigned int gives the number of instructions
// in the program of the species. The array stores all the
// instructions in the program according to their sequence.
*/
struct creature_t
{
point_t location;
direction_t direction;
species_t *species;
unsigned int programID;
};
/*
// Type: creature_t
// ------------------
// The type creature_t is used to represent a creature.
// It consists of a point_t, a direction_t, a pointer to
// species_t and an unsigned int. The point_t gives the location of
// the species. The direction_t gives the direction of the species.
// The pointer to species_t points to the species the creature belongs
// to. The programID gives the index of the instruction to be
// executed in the instruction_t array of the species.
*/
struct grid_t
{
unsigned int height;
unsigned int width;
creature_t *squares[MAXHEIGHT][MAXWIDTH];
};
/*
// Type: grid_t
// ------------------
// The type grid_t consists of the height and the width of the grid
// and a two-dimensional array of pointers to creature_t. If there is
// a creature at the point (r, c) in the grid, then squares[r][c]
// stores a pointer to that creature. If point (r, c) is not occupied
// by any creature, then squares[r][c] is a NULL pointer.
*/
struct world_t
{
unsigned int numSpecies;
species_t species[MAXSPECIES];
unsigned int numCreatures;
creature_t creatures[MAXCREATURES];
grid_t grid;
};
/*
// Type: world_t
// --------------
// This type consists of two unsigned ints, an array of species_t,
// an array of creature_t, and a grid_t object. The first unsigned
// int numSpecies specifies the number of species in the creature
// world. The second unsigned int numCreatures specifies the number
// of creatures in the world. All the species are stored in the array
// species and all the creatures are stored in the array creatures.
// The grid is given in the object grid.
*/
IV. File Input
All the species, the programs for all the species, and the initial layout of the creature world are
stored in files and these files will be read by your program to set up the simulation environment.
Note: when you read files, you must use input file stream ifstream. Otherwise, since the
files are read-only on our online judge, you may fail to read the files.
As we described before, each species has an associated program. The program for each species is
stored in a separate file whose name is just the name of that species. For example, the program
for the species flytrap is stored in a file called flytrap.
A file describing a program contains all the instructions of that program in order. Each line lists
just one instruction. The first line lists the first instruction; the second line lists the second
instruction; so on and so forth. Each instruction is one of the nine legal instructions described in
Table 1. The program ends with the end of file or a blank line. Comments may appear after the
blank line or at the end of each instruction line. For example, the program file for the flytrap
species looks like:
ifenemy 4 If there is an enemy, go to step 4.
left If no enemy, turn left.
go 1
infect
go 1
The flytrap sits in one place and spins.
It infects anything which comes in front.
Flytraps do well when they clump.
Note that in writing functions for reading these program files, you should handle the comments
correctly, which means that you should ignore these comments when setting up the program for a
species.
Since there are many species, we stored all of their program files in a directory.
To help you get all the species and their program files, we also have a file telling the directory
where the program files are stored and listing all the species. We call this file a species summary.
The first line of this file shows the directory where all of the program files are stored. The next
lines list all the species, with one species per line. For example, the following is a species
summary file:
creatures
flytrap
hop
landmine
From this file, we can learn that the program files are stored in the directory called creatures
located relative to the current working directory (i.e., where the program locates). We have three
species to simulate, which are flytrap, hop, and landmine. By first reading the species summary
file, you will know where to find the program file for each species.
Finally, there is a file describing the initial state of the creature world. We call it a world file. The
first line of this file gives the height of the two-dimensional grid (i.e., the number of rows) and
the second line gives the width of the grid (i.e., the number of columns). The remaining lines of
this file describe all the creatures to simulate and their initial directions and locations, with one
creature per line. Each of these lines has the following format:
<species> <initial-direction> <initial-row> <initial-column>
where <species> is one of the species from the species summary file,
<initial-direction> describes the initial direction and is one of the strings “east”,
“south”, “west”, and “north”. <initial-row> describes the initial row location of the
creature. We use the convention that the top-most row of the grid is row 0 and the row
number increases from top to bottom. <initial-column> describes the initial column
location of the creature. We use the convention that the left-most column of the grid is column
0 and the column number increases from left to right. An example of a world file looks like:
4
4
hop east 2 0
flytrap east 2 2
It says that the size of the grid is 4-by-4 and there are two creatures in the world. The first
creature belongs to the species hop. It faces east and lives at point (2, 0) initially. The second
creature belongs to the species flytrap. It faces east and lives at point (2, 2) initially.
In the simulation, the order on the creatures to simulate is important. This order is
determined by the order that these creatures appear in the world file.
V. Program Arguments
Your program will obtain the names of the species summary file and the world file via program
arguments. Additionally, your program will be told the number of rounds to simulate and
whether it should print the simulation result verbosely or not.
The expected order of arguments is:
<species-summary> <world-file> <rounds> [v|verbose]
The first three arguments are mandatory. They give the name of the species summary file, the
name of the world file, and the number of simulation rounds, respectively. The fourth argument
is optional. If the fourth argument is the string “v” or the string “verbose”, your program should
print the simulation result verbosely, which will be explained later. Otherwise, if it is omitted or
is any other string, your program should print the result concisely, which will also be explained
later. If there are more than four arguments, your program should just read the first four and
ignore the remaining.
Suppose that you program is called p3. It may be invoked by typing in a terminal:
./p3 species world 10 v
Then your program should read the species summary from the file called “species” and the world
file from the file called “world”. The number of simulation rounds is 10. Your program should
print the simulation information verbosely.
VI. Error Checking and Error Message
Your program should check for errors before it starts to simulate the moves of the creatures. If
any error happens, your program should issue an error message and then exit. If there are no
errors happening, then the initial state of the creature world is legal and your program can start
simulating the creature world.
We require you to do the following error checking and print the error message in exactly the
same way as described below. Note that some of the output error message has two lines and each
error message should be ended with a newline character. All error messages should be sent to
the standard output stream cout; none to the standard error stream cerr.
1. Check whether the number of arguments is less than three. If it is less than three, then one of
the mandatory arguments is missing. You should print the following error message:
Error: Missing arguments!
Usage: ./p3 <species-summary> <world-file> <rounds> [v|verbose]
2. Check whether the value <rounds> supplied by the user is negative. If it is negative, you
should print the following error message:
Error: Number of simulation rounds is negative!
3. Check whether file open is successful. If opening species summary file, world file, or any
species program file fails (for example, the file to be opened does not exist), print the following
error message:
Error: Cannot open file <filename>!
where <filename> should be replaced with the name of the file that fails to be opened. If that
file is not in the same directory as your program, you need to include its path in the
<filename>. As you may know, there are multiple ways to specify a path. For us, the path
name should be specified in the most basic way, i.e., “<dir>/<filename>” (not
“./<dir>/<filename>”, “<dir>//filename”, etc.). Once you find a file that cannot be
opened, issue the above error message and terminate your program.
4. Check whether the number of species listed in the species summary file exceeds the maximal
number of species MAXSPECIES. If so, print the following error message:
Error: Too many species!
Maximal number of species is <MAXSPECIES>.
where <MAXSPECIES> should be replaced with the maximal number of species set by your
program.
5. Check whether the number of instructions for a species exceeds the maximal size of a species
program MAXPROGRAM. If so, print the following error message:
Error: Too many instructions for species <SPECIES_NAME>!
Maximal number of instructions is <MAXPROGRAM>.
where <SPECIES_NAME> should be replaced with the name of the species whose program has
more instructions than the maximal number allowed and <MAXPROGRAM> should be replaced
with the maximal size of a species program set by your program.
6. Check whether the species program file contains illegal instructions. We only allow nine
instructions as listed in Table 1. Your program needs to check whether the instruction name is
one of the nine legal instruction names listed in the string array opName (which is defined in
Section III). If an instruction name is not recognized, you should print the following error
message:
Error: Instruction <UNKNOWN_INSTRUCTION> is not recognized!
where <UNKNOWN_INSTRUCTION> should be replaced with the name of the unrecognized
instruction. You can assume that for any recognized instruction, it is given in the correct format.
Thus, you don’t need to check whether an integer is appended after the instruction name or not.
If there are multiple unrecognized instruction names, you only need to print out the first one and
then terminate the program.
7. Check whether the number of creatures listed in the world file exceeds the maximal number of
creatures MAXCREATURES. If so, print the following error message:
Error: Too many creatures!
Maximal number of creatures is <MAXCREATURES>.
where <MAXCREATURES> should be replaced with the maximal number of creatures allowed
by your program.
8. Check whether each creature in the world file belongs to one of the species listed in the
species summary file. If the species for a creature is not recognized, print the following error
message:
Error: Species <UNKNOWN_SPECIES> not found!
where <UNKNOWN_SPECIES> should be replaced with the unrecognized species. If there are
multiple unrecognized species, you only need to print out the first one and then terminate the
program.
9. Check whether the direction string for each creature in the world file is one of the strings in
the array directName (which is defined in Section III). If the direction string is not recognized,
print the following error message:
Error: Direction <UNKNOWN_DIRECTION> is not recognized!
where <UNKNOWN_DIRECTION> should be replaced with the unrecognized direction name. If
there are multiple unrecognized direction names, you only need to print out the first one and then
terminate the program.
10. Check whether the grid height given by the world file is legal. A legal grid height is at least
ONE and less than or equal to a maximal value MAXHEIGHT. If the grid height is illegal, print
the following error message:
Error: The grid height is illegal!
11. Check whether the grid width given by the world file is legal. A legal grid width is at least
ONE and less than or equal to a maximal value MAXWIDTH. If the grid width is illegal, print the
following error message:
Error: The grid width is illegal!
12. Check whether each creature is inside the boundary of the grid. If any creature is outside the
boundary, print the following error message:
Error: Creature (<SPECIES> <DIR> <R> <C>) is out of bound!
The grid size is <HEIGHT>-by-<WIDTH>.
where <SPECIES> should be replaced with the species the creature belongs to, <DIR> be
replaced with the direction the creature is facing, <R> be replaced with the row location of the
creature, <C> be replaced with the column location of the creature, <HEIGHT> be replaced with
the height of the grid, and <WIDTH> be replaced with the width of the grid. Here, we use the
four-tuple (<SPECIES> <DIR> <R> <C>) to identify the creature. For example, if given
the following world file:
3
3
flytrap east 0 0
hop south 3 2
food west 2 1
then Creature (hop south 3 2) is outside the boundary. Then, the error message should be:
Error: Creature (hop south 3 2) is out of bound!
The grid size is 3-by-3.
If there are multiple creatures outside the boundary, you only need to print out the first one and
then terminate the program.
13. Check whether each square in the grid is occupied by at most one creature. If any square is
occupied by more than one creature, print the following error message:
Error: Creature (<SP1> <DIR1> <R> <C>) overlaps with creature
(<SP2> <DIR2> <R> <C>)!
where (<R> <C>) identifies the square which is occupied by more than one creature, the first
four-tuple (<SP1> <DIR1> <R> <C>) identifies the second creature in order that
occupies the square, and the second four-tuple (<SP2> <DIR2> <R> <C>) identifies the
first creature in order that occupies the square. Once you find two creatures occupying the
same square, you issue the above error message and then terminate the program.
Since you may implement the error checking in different order and in the case that there is
more than one error, the first error message printed out may be different. Therefore, we
will only test your error checking using test cases containing just one error.
You can also assume that except the above errors, there are no other errors.
You can assume that the species program file is non-empty and a file without errors 5 and
6 above could be executed for infinite rounds.
VII. Simulation Output
Once all of the above error checkings on the initial state of the creature world are passed, you
can start simulating the creature world. You should print to the standard output the simulation
information, either in a verbose mode or in a concise mode, depending on whether an
additional argument “v” or “verbose” is provided by the user.
In the verbose mode, you first print the initial state of the world. In doing so, you begin with
printing the string “Initial state” followed by a newline. Then you graphically show the
layout of the initial grid using just characters. Each square takes a four-character field in your
terminal. Adjacent squares on the same row are separated by one space. If a square in the grid is
not occupied by any creature, the field for that square is filled with FOUR “_”. If a square is
occupied by a creature, then the first two characters of the field for that square are the first two
letters of the name of the species the creature belongs to. (We assume that all the species names
contain at least two characters and no two species names have the identical first two characters.)
The third character in the field is a “_” and the fourth character is the first character of the
direction the creature faces, i.e., “e” for “east”, “s” for “south”, “w” for “west”, and “n” for
“north”.
For example, suppose a world file looks like
4
4
hop east 2 0
flytrap east 2 2
Then the layout of the initial grid is printed as
____ ____ ____ ____
____ ____ ____ ____
ho_e ____ fl_e ____
____ ____ ____ ____
Note that there is a space at the end of each line.
After printing the initial layout, we begin the simulation from the first round to the last round
specified by the user. In the i-th simulation round, you first print “Round <i>” followed by the
newline. For example, in the first round, you should first print
Round 1
During each simulation round, you simulate the moves of all the creatures in turn. When starting
simulating a creature, you announce that this creature takes action by printing
Creature (<SPECIES> <DIR> <R> <C>) takes action:
followed by a newline. In the above output, the four-tuple (<SPECIES> <DIR> <R> <C>)
shows the state of the creature right before it takes the action, where <SPECIES> should be
replaced with the species the creature belongs to, <DIR> be replaced with the direction the
creature is facing, <R> be replaced with the row location of the creature, and <C> be replaced
with the column location of the creature.
After this, you print the sequence of instructions that the creature executes for its turn. This
sequence may include any number of if*** and go instructions and end with one of the hop, left,
right, and infect instruction. You should print the sequence of instructions the creature executes
in order, with one instruction per line. The output format for an instruction is:
Instruction <INSTR_NO>: <INSTR_NAME> [GOTO_STEP]
where <INSTR_NO> should be replaced with the number of that instruction in the program (the
number starts from 1), <INSTR_NAME> should be replaced with the name of the instruction,
and [GOTO_STEP] is the number in an if*** or a go instruction and is optional.
After printing the last instruction of the creature under consideration, you should print the
updated layout of the grid, using the same rule as you print the initial layout.
Now let’s look at an example. Suppose that the program for the species hop is
hop
go 1
and the program for the species flytrap is
ifenemy 4 If there is an enemy, go to step 4.
left If no enemy, turn left.
go 1
infect
go 1
Then, given the following world file
4
4
hop east 2 0
flytrap east 2 2
the simulation information for the first round is printed as
Round 1
Creature (hop east 2 0) takes action:
Instruction 1: hop
____ ____ ____ ____
____ ____ ____ ____
____ ho_e fl_e ____
____ ____ ____ ____
Creature (flytrap east 2 2) takes action:
Instruction 1: ifenemy 4
Instruction 2: left
____ ____ ____ ____
____ ____ ____ ____
____ ho_e fl_n ____
____ ____ ____ ____
The simulation information for the second round is printed as
Round 2
Creature (hop east 2 1) takes action:
Instruction 2: go 1
Instruction 1: hop
____ ____ ____ ____
____ ____ ____ ____
____ ho_e fl_n ____
____ ____ ____ ____
Creature (flytrap north 2 2) takes action:
Instruction 3: go 1
Instruction 1: ifenemy 4
Instruction 2: left
____ ____ ____ ____
____ ____ ____ ____
____ ho_e fl_w ____
____ ____ ____ ____
In the concise mode, you print the initial state of the world in the same way as in the verbose
mode. When printing the simulation information for the i-th round, you first print “Round <i>”
followed by the newline. Then you print the final action of each creature in turn, with one
creature per line. The format is:
Creature (<SPECIES> <DIR> <R> <C>) takes action: <LAST_INSTR>
Same as in the verbose mode, the four-tuple (<SPECIES> <DIR> <R> <C>) shows the
state of the creature right before it takes the action. <LAST_INSTR> should be replaced with
the last instruction the creature executes for its turn, which is one of the hop, left, right, and
infect instruction.
After printing the final actions for all the creatures, you print the updated layout at the end of
this round.
For the same world file as above:
4
4
hop east 2 0
flytrap east 2 2
In the concise mode, the simulation information for the first round is printed as
Round 1
Creature (hop east 2 0) takes action: hop
Creature (flytrap east 2 2) takes action: left
____ ____ ____ ____
____ ____ ____ ____
____ ho_e fl_n ____
____ ____ ____ ____
The simulation information for the second round is printed as
Round 2
Creature (hop east 2 1) takes action: hop
Creature (flytrap north 2 2) takes action: left
____ ____ ____ ____
____ ____ ____ ____
____ ho_e fl_w ____
____ ____ ____ ____
There are no blank lines in the output for both the verbose and concise mode.
VIII. Source Code Files and Compiling
There is a source code file located in the Project-3-Related-Files.zip from our
Canvas Resources:
world_type.h: The header file that defines a number of types for you to use.
You should copy this file into your working directory. DO NOT modify it!
You need to write three other source code files. The first file is named as simulation.h,
which contains the declarations for all the functions you write, just like the p2.h in our project
two. The second file is named as simulation.cpp, which contains all the implementations of
those functions declared in the simulation.h. The third file is named as p3.cpp, which
contains only the main function. After you have written these files, you can type the following
command in the terminal to compile the program:
g++ -Wall -o p3 p3.cpp simulation.cpp
This will generate a program called p3 in your working directory. In order to ensure that the
online judge compiles your program successfully, you should name you source code files exactly
like how they are specified above.
IX. Implementation Requirements and Restrictions
1. When writing your code, you may use the following standard header files: <iostream>,
<fstream>, <sstream>, <iomanip>, <string>, <cstdlib>, and <cassert>. No
other header files can be included.
2. You may not define any global variables yourself. You can only use the global constant ints
and string arrays defined in world_type.h.
3. Pass large structs by reference rather than value. Where appropriate, pass const references /
pointers-to-const. Do not pass lots of little arguments when you can pass an appropriate, larger
structure instead.
4. All required output should be sent to the standard output stream; none to the standard error
stream.
5. You should strive not to duplicate identical or nearly‐identical code, and instead collect such
code into a single function that can be called from various places. Each function should do a
single job, though the definition of "job" is obviously open to interpretation. Most students write
too few functions that are too large.
X. Hints and Tips
1. This project will take you longer than project 2 did, so start early!
2. Do this project in stages. First, be able to read the species summary file. Second, be able to
read the programs for all the species. Third, be able to read the world file. Write some diagnostic
code that can print out the species summary, the program for each species, and the creatures, to
make sure that you are reading them correctly. Implement the error checking and test it with
different illegal inputs. Once you can read the structures in, implement the simple moves such as
left and right. Once you have that working, implement moves such as hop and infect. Finally,
implement if*** and go instructions.
3. Take advantage of the fact that enumerations are sequentially numbered from 0 to N‐1.
4. Use the right methods of input file stream to read file. In some cases, you may first use the
getline() function to read the entire line of a file and then use an input string stream to
extract the content from that line.
5. The hop instruction will only cause the creature to move forward when the square it is facing
is empty. If moving forward would put the creature outside the boundaries of the grid or would
cause it to land on top of another creature, the hop instruction does nothing. However, although
the hop action is not executed successfully, you should update the program counter so that it
points to the next instruction after this hop instruction. The similar situation also applies to the
infect instruction. If there is no enemy to infect, the infect operation does nothing. However, you
should update the program counter to its next instruction.
6. As a hint, you probably need to write the following eight functions or some variations of them.
However, these are not the only functions you have to write. You probably need to write more
functions for different jobs.
bool initWorld(world_t &world, const string &speciesFile,
const string &creaturesFile);
// MODIFIES: world
//
// EFFECTS: Initialize "world" given the species summary file
// "speciesFile" and the world description file
// "creaturesFile". This initializes all the components of
// "world". Returns true if initialization is successful.
void simulateCreature(creature_t &creature, grid_t &grid, bool
verbose);
// REQUIRES: creature is inside the grid.
//
// MODIFIES: creature, grid, cout.
//
// EFFECTS: Simulate one turn of "creature" and update the creature,
// the infected creature, and the grid if necessary.
// The creature programID is always updated. The function
// also prints to the stdout the procedure. If verbose is
// true, it prints more information.
void printGrid(const grid_t &grid);
// MODIFIES: cout.
//
// EFFECTS: print a grid representation of the creature world.
point_t adjacentPoint(point_t pt, direction_t dir);
// EFFECTS: Returns a point that results from moving one square
// in the direction "dir" from the point "pt".
direction_t leftFrom(direction_t dir);
// EFFECTS: Returns the direction that results from turning
// left from the given direction "dir".
direction_t rightFrom(direction_t dir);
// EFFECTS: Returns the direction that results from turning
// right from the given direction "dir".
instruction_t getInstruction(const creature_t &creature);
// EFFECTS: Returns the current instruction of "creature".
creature_t *getCreature(const grid_t &grid, point_t location);
// REQUIRES: location is inside the grid.
//
// EFFECTS: Returns a pointer to the creature at "location" in "grid".
XI. Testing
We provide you with a few test cases in the directory called tests, which can be found inside
Project-3-Related-Files.zip from our Canvas Resources.
Inside the tests directory, there is an example species summary file called species and two
subdirectories called creatures and world-tests. The creatures directory contains a
number of species program files. The world-tests directory contains five world files and the
files recording the correct outputs.
The first world file is called outside-world, which describes an illegal world with one
creature located outside the boundary of the grid.
To run this test case, type the following commands:
./p3 species world-tests/outside-world 5 > outside-world.out
Then the output of your program is redirected to a file named outside-world.out. The
correct output is recorded in the file outside-world.answer in the directory world tests. You can use the diff command to check whether the file outside-world.out is
same as the file outside-world.answer.
The second world file is called overlap-world, which describes an illegal world with two
creatures located at the same square in the grid. You can run this test case using a similar
command as shown above and compare your output with the correct output recorded in the file
overlap-world.answer.
The next three world files world1, world2, and world3 are legal world files. You can run
these test cases in the similar way. The number of simulation rounds for world1, world2, and
world3 are 5, 20, and 40, respectively. For these test cases, we provide you with both the
verbose and the concise output files. The verbose output files are these files named as
*-verbose.answer and the concise output files are these files named as
*-concise.answer.
These are the minimal amount of tests you should run to check your program. Those programs
that do not pass these tests are not likely to receive much credit. You should also write other
different test cases yourself to test your program extensively. In doing so, you need to write your
own legal/illegal species summary files, legal/illegal world files, and species program files.
Indeed, it will be very interesting to create new species yourself and observe what kind of
species will finally dominate the SIMPLE WORLD given different initial layout!
XII. Submitting and Due Date
You should submit your source code files simulation.h, simulation.cpp, and p3.cpp.
These files should be submitted via the online judgment system. See announcement from the
TAs for details about submission. The due date is 11:59 pm on Nov. 17, 2024.
XIII. Grading
Your program will be graded along three criteria:
1. Functional Correctness
2. Implementation Constraints
3. General Style
Functional Correctness is determined by running a variety of test cases against your program,
checking against our reference solution. We will grade Implementation Constraints to see if you
have met all of the implementation requirements and restrictions. General Style refers to the ease
with which TAs can read and understand your program, and the cleanliness and elegance of your
code. For example, significant code duplication will lead to General Style deductions.
相关推荐
【202503】Wan:开放且先进的大规模视频生成模型【1.3B、14B】【支持对无限长度视频进行稳定的Inference】【Wan中的主要计算开销来自注意力机制】
wan: Open and Advanced Large-Scale Video Generative ModelsWan:开放且先进的大规模视频生成模型Wan Team, Alibaba Group Wan 团队,Alibaba GroupThis report presents Wan, a comprehensive and open suite of video foundation models designed to push the boundaries of video generation
Java Thread Pools — Deep Dive
Java线程池核心原理摘要 线程池作用:解决线程创建开销大、资源耗尽问题,通过复用固定线程、控制并发量、任务队列解耦任务提交与执行。Java提供Executor框架(Java 5+)实现。 核心类层次: Executor → ExecutorService → ThreadPoolExecutor(核心)/ScheduledThreadPoolExecutor(定时) ForkJoinPool:工作窃取,支持并行流和CompletableFuture ThreadPoolExecutor关键参数: core
【信息科学与工程学】计算机科学与技术——第七十七篇 系统架构设计02
编号类型模型配方企业资本运作的方法/规则/条件/依据及所有的步骤(风险处理/异常处理/危机应对关联知识法律法规和裁决依据由发起人(通常是知名投资人、投行或产业资本)先设立一个只有现金、无实际业务的特殊目的收购公司(SPAC),通过IPO募集资金并在交易所上市。然后在规定时间内(通常24个月)寻找一家非上市公司进行合并(De-SPAC),使目标公司迅速实现上市,规避传统IPO的复杂流程和不确定性。1.:在开曼或特拉华注册空壳公司,注入少量种子资金。2.
PointWorld: 动作条件的全场景3D点flow 预测(用同一种3D物理空间模态来表示状态和动作)
PointWorld: Scaling 3D World Models for In-The-Wild Robotic Manipulation
医学图像分割评价指标详解:从Dice到MSD的实战解析
本文深入解析医学图像分割的核心评价指标,从最常用的Dice相似系数到衡量边界精度的MSD(最大对称表面距离),通过实战案例与代码演示,系统阐述各指标的计算原理、应用场景及临床意义,帮助读者全面评估模型性能。
某讯天御滑块验证码逆向实战:从参数解析到环境对抗
本文详细解析了某讯天御滑块验证码的逆向工程实战技巧,从关键参数解析到浏览器环境模拟对抗。重点介绍了collect、eks等参数的逆向思路,以及如何通过puppeteer等工具补全环境检测,帮助开发者有效突破验证码防护。文章还提供了常见错误解决方案和性能优化建议,是验证码逆向领域的实用指南。
Delta lake第一稿个人翻译和注释(第四章)
亚马逊S3等云对象存储是全球规模最大、最具成本效益的存储系统之一,因此成为存储大型数据仓库和数据湖的理想之选。遗憾的是,它们作为键值存储的实现使得实现ACID事务和高性能变得困难:元数据操作(如列出对象)成本高昂**(解释:对象存储在云上面list操作费用是get操作的10倍,并且抽取类似元数据次数多了,费用很贵;所以整体思想是减少list操作,有个元数据管理文件,然后从文件抽取必要文件然后采取 get操作),一致性保证也有限。
ArcGIS标注(二分式、三分式、条件分类标注、上下标、牵引线、文字格式化…)
ArcGIS中的各种标注方法、可能遇到的问题和细节。
机器人-模仿学习-双臂【2023-04】:ACT【80M参数;CVAE-Transformer架构;ResNet18编码四路视觉;4层编码器融合视觉状态;7层解码器并行预测100步动作;时序集成平滑】
Meta。
【实战分享】构建企业级RAG(Retrieval-Augmented Generation)知识库的全面实践
大模型指的是训练参数量极其庞大的深度学习模型,如GPT-3、GPT-4等。这些模型能够通过海量的数据学习,具备强大的语言理解和生成能力。在问答系统中,大模型能够理解用户提出的问题,并生成相关的回答。"""添加文档向量"""pass"""相似度检索"""pass"""获取页面分段"""passMilvus是一个开源的向量数据库,专为高效的向量存储和检索设计。Milvus支持多种索引方式(如IVF、HNSW等),并提供高效的查询和检索功能。索引构建:Milvus通过创建索引加速查询速度。
8位可控加减法电路设计
一、设计要求 利用Logisim平台中现有运算部件构建一个8位可控加减法器,可支持八位加减法,利用已经封装全加器和逻辑门进行连接,要求实现相应的输出,判断是否溢出。 二、方案设计 实验原理: [A]补+[B]补 = [A+B]补(mod2^n+1) 公式1 [A-B]补 = [A]补+[-B]补(mod2^n+1) 公式2 FA为全加器,利用全加器实现加减法,难点在于实验减法,对输入的[Y]补各位取反加一即为[-Y]补,利用公式2,就可以将减法转化为加法再利用全加
Deep Agents 框架-基础篇
DeepAgents是LangChain生态中的高级API,构建于LangChain核心智能体模块和LangGraph运行时之上,旨在简化复杂智能体的开发。它提供任务规划、文件系统管理、子智能体生成等内置功能,适用于长期运行的多步骤任务。然而,DeepAgents并非独立框架,仍需依赖LangChain和LangGraph,学习成本较高。文档详细介绍了其核心能力、与LangChain/LangGraph的差异、配置方法及最佳实践,强调其在处理复杂任务时的优势,但也指出工程化选择需谨慎考虑其依赖关系和实际需求
小红书x-mini签名逆向实战:Frida动态Hook与算法还原
在移动App协议分析中,请求签名机制是保障接口安全的核心技术,其本质是客户端对请求参数、时间戳、设备指纹等要素进行加密认证的过程。理解签名原理需掌握Native层加密流程、JNI调用机制及密钥动态派生逻辑。Frida作为主流动态插桩工具,能绕过符号剥离、字符串加密和控制流混淆等反分析手段,在函数执行瞬间捕获寄存器状态、内存数据与调用上下文,实现签名算法的完整还原。该技术广泛应用于合规内容监测、API自动化调用与竞品协议研究等工程场景。本文聚焦小红书x-mini签名这一典型样本,详解从JNI_OnLoad定位
Python+Agent入门笔记(六):记忆和状态,从“一次性问答”到“能用助手”
滑动窗口的缺点很明显:被扔掉的信息就真没了。如果用户第一轮说“我不吃辣”,隔了二十轮让他推荐餐厅,模型已经忘了。定期把旧的对话压缩成一段总结,作为一条特殊的消息插进去。"""把除 system 和最近 keep_recent 条以外的消息,压缩成一条摘要。返回新的 messages 列表。"""# 把旧消息拼成纯文本,让模型总结content = f"[工具结果]把除 system 和最近 keep_recent 条以外的消息,压缩成一条摘要。返回新的 messages 列表。
HFSS新手避坑指南:从零搭建T形波导功分器(含参数扫描与优化实战)
本文为HFSS新手提供T形波导功分器设计的详细指南,涵盖基础设置、建模技巧、参数扫描与优化实战。重点解析内场分析中的常见陷阱,如单位设置、波端口定义和布尔运算错误,并分享优化设计的关键步骤,帮助工程师快速掌握HFSS在微波器件设计中的应用。
无人机——电机篇(一)
1. 电机的定义 电机俗称“马达”,是无人机的动力来源,无人机通过改变电机的转速来改变无人机的飞行状态。即改变每个电机的速度,使得无人机能够盘旋空中,上升或下降,或向各个方向移动。2. 电机的分类 电机分为:“无刷电机”和“有刷电机” - 无刷电机:是采用半导体开关器件来实现电子换向,具有可靠性高、低干扰、低噪声低、寿命长等优点。一般应用在稍大型的飞行器,载重大,可以有更广泛的用途。 - 有刷电机:是内含电刷装置的将电能转换成机械能(电动机)或将机械能转换成电能(发电机)的旋转电机。有刷电机是所有电机的基
循环嵌套(多层 for 循环)
表:order(订单表,order_id, user_id)、user(用户表,user_id, user_name)✅ 优化:先查所有订单,拿到所有 user_id 批量 in 查询,内存 join。✅ 优化:先把优惠券转 HashMap,单层循环查找(hash 查找 O (1))SQL 只有 2 次,O (1) 数据库查询,内存遍历 O (n)。需求:查询所有订单列表,同时带出每个订单对应的用户名称。需求:订单列表、优惠券列表,把订单匹配对应的优惠券名称。复杂度:O (M+N),非常快。
Data-Structures-and-Algorithm-Analysis-in-Java.pdf
作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...
【数据结构-5】单链表的实现
单链表,具体来说是单向的、不带头的、不循环的链表。链表由一个一个节点组成,每个节点分为数据域和指针域,数据域存放数据,指针域存放下一节点的地址。这样,就可以根据指针域中的地址找到下一个节点,节点就串起来了构成了单链表。
jdk-8u144-linux-x64.tar.gz.
该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包
efm32 入门.pdf
本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。
C++ 入门笔记(十七):list 入门 —— 为什么 list 不能 sort?
第17课:用大白话讲清 list 的双向链表结构、哨兵头、push_back 四步、迭代器封装、merge 与 splice 的区别,以及 vector 排序为什么常比 list 快。
pscad IEEE标准系统搭建说明
pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。
C# 数据结构和特殊类型
.NET Core(现称.NET)提供丰富数据结构,优化性能与开发效率。日常开发首选List<T>和Dictionary<TKey,TValue>;高性能场景推荐Span<T>与Memory<T>减少内存分配;并发环境使用ConcurrentDictionary等线程安全集合;避免非泛型集合如ArrayList。
软件商店常见问题标准处理流程
从底层软件源来看,/etc/apt/sources.list配置错误、源地址失效、公网与内网离线源混用、ARM64与x86_64架构源串用,以及DNS解析异常、系统代理配置错误,都会导致商店无法获取应用数据;打开该应用,确认可正常运行;软件商店作为系统内置的图形化软件分发与安装入口(UKUI桌面配套组件,底层依赖APT软件源),承担着应用软件的浏览、搜索、下载、安装、升级与卸载等核心功能,是终端软件部署与管理的关键通道。覆盖软件商店启动、页面加载、应用下载、安装、卸载、搜索、自身更新等全部业务场景。
【AI 开发从入门到进阶 · 10】收官篇:LoRA 微调、模型评估、推理加速与生产部署全链路
本文系统梳理了大模型微调与生产落地的全流程,从决策是否微调、优选LoRA技术方案,到代码实现、效果评估、推理加速与FastAPI服务封装,最终构建可迭代的生产级AI系统。强调“逐级升级”原则,倡导以数据闭环驱动优化,避免技术冲动。全系列贯穿工程化思维,提供可复用模板与实战建议,助力开发者从模型训练迈向稳定可用的AI服务部署。
ARIA规范
ARIA用来补充原生HTML缺失的语义,原则:优先原生标签,ARIA仅做补充。 ARIA角色role:定义组件身份,分为地标角色、构件角色、文档角色;构件角色用于自定义弹窗、tab、下拉菜单等复杂组件; ARIA状态与属性:以aria-开头,描述组件实时状态;常用:aria-label、aria-labelledby、aria-describedby、aria-hidden、aria-expanded、aria-selected、aria-modal、aria-live; 常用场景:图标按钮用aria-l
LangGraph(03):状态归约、并行更新与消息管理
并行节点写入报错?历史消息无法清理?本文拆解 LangGraph 状态归约与消息增删改机制,带你精确控制复杂工作流状态。
LangGraph 的分离思想总结
LangGraph 的分离思想,本质上是对"高内聚、低耦合"这一经典工程原则在 LLM 应用领域的落地。它通过状态与逻辑分离、节点职责分离、控制流与执行分离、计算与持久化分离、编排与实现分离五个层面,把一个难以维护的"大黑盒"拆解成一组可组合、可测试、可观测的部件。理解这套分离思想,比记住 API 更重要——因为当你面对新的智能体场景时,真正指导你做出合理拆分的,正是这些分离原则。
ArrayList 与 LinkedList 的区别:原理、性能与选型指南
ArrayList是默认选择,LinkedList只在特定场景(已知节点位置的频繁增删、需要双端操作)才有优势。理解底层结构,才能在实际开发中做出合理选型。
742



被折叠的 条评论
为什么被折叠?



