CPSC 427 Problem Set 1 to 8 solutions

$140.00

Original Work ?

Download Details:

  • Name: PSs-abzvky.zip
  • Type: zip
  • Size: 5.51 MB

Category: Tags: , You will Instantly receive a download link upon Payment||Click Original Work Button for Custom work

Description

5/5 - (1 vote)

CPSC 427 Problem Set 1

1 Assignment Goals
1. Learn how to prepare and build C++ code on the Zoo.
2. Learn how to customize and use tools.cpp and tools.hpp in your own code.
3. Learn good practices for labeling every code file with appropriate date, authorship,
and acknowledgments of any code fragments taken from elsewhere.
4. Learn conventions used in this course regarding the form of the main program, use of
banner() and bye() from the tools library, compiler switches, include guards, and so
forth.
5. Learn simple uses of C++ strings.
6. Learn how to do simple C++ I/O with validity check.
7. Learn how to use C library time functions from within C++.
8. Learn how to report a fatal error by calling the Fatal() function in tools.
9. Learn how to test and submit your code on the Zoo.
2 Problem
You are to write a program called aboutme that, when run, prompts the user to enter their
first name, last name, and year of birth. The program then prints out the first name, last
name, and age, which we take to be the difference between the current year and the year
of birth. Here’s what a sample run for me might look like:
—————————————————————
Michael J. Fischer
CPSC 427/527
Sun Sep 2 2018 21:24:11
—————————————————————
Please enter your first name: Michael
Please enter your last name: Fischer
Please enter the year of your birth: 1942
Michael Fischer becomes 76 years old in 2018.
—————————————————————
Normal termination.
The lines before the first prompt are printed by banner(). The lines after the age line are
printed by bye().
2 Problem Set 1
3 Programming Notes
1. Copy the tools files from /c/cs427/code/tools/ into your working directory. Customize them by editing in your own name in place of the generic “Ima Goetting
Closeau”. Be sure to submit your tools files along with your code and other required
files. Read Chapter 1 of the “Exploring C++” textbook for more information about
tools, but be warned that my version of tools differs somewhat from what is in the
textbook.
2. You should create a file main.cpp with a main function exactly as follows:
int main() {
banner();
run();
bye();
}
Your own code will go into main.cpp. Needed declarations should be placed before
the function main(). You will need to define the function run(), which should be
placed after the function main.
1
3. You must use the standard C++ iostreams facility for your I/O. To use it, one must
#include the header file iostream. tools.hpp already does this for you, so all
you need in main.cpp is the statement #include “tools.hpp”. The standard input
stream is cin; the standard output stream is cout. The input operator is >>; the
output operator is <<. Further information and examples are in the textbook.
4. There are two ways to store a string in C++ . First is as a char array as one does in C.
The other is to use the standard string library. To use it, you must #include the
header file string in your code. (Again, tools.hpp already does this for you.) This
makes string available as a new type, which you can then use to declare variables
and parameters.
A variable of type string acts just like one would expect. You can store a string
literal of any length into it. You can copy one string to another using the assignment
operator. You can print it using the << operator and read a whitespace-delimited string into it using the >> operator. A string manages its own storage so that you do
not have to worry about allocating storage. You must use string variables to store
the first and last names to be read in.
5. Compute the current year by using the standard C library functions time() and
localtime(). time() reads the clock and returns a value of type time_t that is the
number of seconds since the beginning of year 1970. To find the year from a time_t
value, use localtime() to create a struct tm broken-down data structure. This
contains an int field called tm_year that sounds like it ought to be the year (like
2018), but it actually contains the year minus 1900. To use these functions in C++,
you would #include the header file ctime. (This is the C++ version of the C header
file time.h and is also included by tools.hpp.)
1This is the style we will use in the course.
Handout #2—September 3, 2018 3
6. Use the sample Makefile from lecture 2, modified if necessary.
7. Submit this assignment following the submission instructions from lecture 2.
4 Grading Rubric
Your assignment will be graded according to the scale given in Figure 1 (see below).
# Pts. Item
1. 1 All source code is contained in the single file main.cpp.
2. 1 The source code is an ascii or utf-8 text file (not a .doc file).
3. 1 Code is neatly indented according to the style for this course.
4. 2 main.cpp contains required authorship information.
5. 1 main.cpp #includes the tools header file.
6. 1 main() calls banner() and bye().
7. 1 Each function is preceded by a comment that describes briefly what it
does.
8. 1 Program uses C++ I/O operators << and >> with standand streams cout
and cin.
9. 1 Program uses good() to check for input errors and takes appropriate
action in case of error.
10. 2 Program correctly computes the current year using time() and
localtime() functions.
11. 1 A well-formed Makefile or makefile is submitted that specifies compiler
options -O1 -g -Wall -std=c++17.
12. 1 Running make results in an executable file aboutme and generates no
errors or warnings.
13. 4 A file named aboutme.out contains the output from at least two test runs
of the program, one with correct input and one where a non-number was
entered instead of a valid year. The inputs typed for each test run should
also be included so the test output can be replicated.
14. 2 All required files are submitted on Canvas as described in lecture 2.
20 Total points.
Figure 1: Grading rubric.

CPSC 427 Problem Set 2

This short assignment is designed to deepen your understanding of C++ I/O and of character
representations.
1 Assignment Goals
1. Learn how to use command line arguments.
2. Learn how to open a file and read its contents.
3. Learn how characters are represented by bytes in the computer.
4. Learn the difference between a character and its ASCII code.
5. Learn how to obtain the ASCII code of a character stored in a variable of type char.
6. Learn how to print the character whose ASCII code is stored in a variable of type int.
7. Learn how to print an int as a decimal number.
8. Learn how to print an int as a hex number.
9. Learn how to test if a char is printable.
10. Learn how to use the output manipulators dec, hex, setw(), and setfill() to control
the printed form of numbers.
11. Learn precisely what in>>val does to the istream in when val has type int.
12. Learn how to use in.get(ch) to read a single character from in.
13. Learn precisely what out<>x. If a number is successfully read into x, then x should be printed in
decimal on a line by itself.
If the attempt to read x fails, then the next character should be read from the stream using
in.get(ch), where ch has type char, and a one-line “Skipping. . . ” message should be printed.
Depending on the character read, the message might look like either of the following:
Skipping char: 116 0x74 ’t’
Skipping char: 0 0x00
2 Problem Set 2
In each case, the ASCII code of ch is printed first in decimal, right-justified in a 3-character field
without zero-fill, and then again in hex, prefixed by “0x”, followed by a right-justified 0-filled hex
number in a 2-character field. If ch is printable as defined by isprint()1
, then it should also be
printed as a character, enclosed in single quotes as shown.
For example, if file data.in contains the text:
Score was 35to21.
the output should be:
—————————————————————
Ima Goetting Closeau
CPSC 427/527
Tue Oct 4 2016 11:18:06
—————————————————————
Skipping char: 83 0x53 ’S’
Skipping char: 99 0x63 ’c’
Skipping char: 111 0x6f ’o’
Skipping char: 114 0x72 ’r’
Skipping char: 101 0x65 ’e’
Skipping char: 119 0x77 ’w’
Skipping char: 97 0x61 ’a’
Skipping char: 115 0x73 ’s’
35
Skipping char: 116 0x74 ’t’
Skipping char: 111 0x6f ’o’
21
Skipping char: 46 0x2e ’.’
Loop exit
—————————————————————
Normal termination.
Be sure you understand why there is no “Skipping” line for the spaces following “Score” and “was”.
What happened to those characters?
3 Programming Notes
This program is very short and may be put entirely in the run() function in main.cpp.
You must read x using the stream extract operator >>. You may not use stringstream or
getline() or other methods to read the line as a string or to read individual digits that comprise
a decimal number. You must let the stream do your decimal to binary conversion. Do not call
atoi() or strtol() or any other means of manually converting a string to an int.
To obtain the ASCII code of a character stored in a char variable ch, cast ch to an int.
Similarly, to print a character whose ASCII code is stored in an int variable x, cast x to a char
before printing.
1
See https://www.cplusplus.com/reference/cctype/isprint/.
Grading Rubric
Your assignment will be graded according to the scale given in Figure 1 (see below).
# Pts. Item
1. 1 All relevant standards from PS1 are followed regarding submission, identification of authorship on all files, and so forth.
2. 1 A well-formed Makefile or makefile is submitted that specifies compiler
options -O1 -g -Wall -std=c++17.
3. 1 Running make successfully compiles and links the project and results in an
executable file readint.
4. 1 Your program gives a usage comment and terminates if the wrong number of
command line arguments are given. It gives a descriptive error comment if the
specified input file does not open.
5. 4 All instructions given in sections 2 and 3 are carefully followed.
6. 4 Your program correctly extracts all of the integers in the file.
7. 4 Your program prints a correct “Skipping. . . ” message following each failed
attempt to read an integer.
8. 2 The “Skipping. . . ” message exactly follows the examples and instructions, including spacing and when to print leading 0’s and when not to.
9. 2 Your program correctly handles end-of-file, regardless of whether the EOF is
immediately preceded by whitespace, a digit, or another character.
20 Total points.
Figure 1: Grading rubric.

CPSC 427 Problem Set 3

1 Assignment Goals
1. Produce an application with more than one class, appropriately split into multiple files.
2. Learn how to use a constructor to produce a semantically valid non-trivial data structure.
3. Learn how to use classes and objects to model a physical structure.
4. Learn how to driver program to exercise and test a class.
5. Learn how to code within a prescribed and restricted subset of the language.
2 Think-A-Dot
2.1 Some history
Think-a-Dot is a mathematical toy introduced by E.S.R. Inc. in the 1960’s.
https://www.jaapsch.net/puzzles/images/thinkadot.jpg
It is covered by U.S. patent 3,388,483, issued June 18, 1968 to Joseph A. Weisbecker. (See Fig. 1.)
2 Problem Set 3
Figure 1: U.S. patent 3,388,483, issued June 18, 1968 to Joseph A. Weisbecker.
Figure 2: Looking inside a slightly-modified box.
Handout #5—September 26, 2018 3
Ask some questions:
1. What is the structure of the machine? (See Figure 3.)
2. Starting from the all-yellow pattern, can one drop in marbles so as to make it all blue?
3. If so, can one get back to the all-yellow pattern?
4. How many of the 2
8 = 256 possible patterns can one reach from the initial state (all-yellow)?
5. Given that pattern s2 is reachable from pattern s1, how many marbles are needed? (Call this
the directed distance from s1 to s2.)
6. Is the distance from s1 to s2 always the same as the distance from s2 to s1?
7. What is the largest distance between any pair of states for which the distance is defined?
Figure 3: Structure of the machine.
Binary Counter
Eight balls through hole C will cause gates 7–5–3
to behave like a binary counter and cycle through
all eight possibilities.
Gates to the above and left (1, 2, 4, 6) are not
affected.
4 Problem Set 3
How can you get to a particular pattern?
Starting from all yellow, how can one reach this goal?
Here’s one solution:
−→
−→
−→
Handout #5—September 26, 2018 5
2.2 Further references
Google returns many hits for the search term “think-a-dot”.
1. Some of the early pre-E.S.R. Think-a-Dot history.
2. A realistic Think-a-Dot simulator that you can play with, written Scratch. This shows the
original unmodified dot pattern that appears when the device is tipped to the right.
3. A Think-a-Dot-inspired electronic game from 2002.
4. Some of the mathematical theory behind Think-a-Dot (from Wikipedia, Think-a-Dot).
(a) Schwartz, Benjamin L. (1967), “Mathematical theory of Think-a-Dot”, Mathematics
Magazine, 40 (4): 187193, doi:10.2307/2688674, MR 1571696.
(b) Beidler, John A. (1973), “Think-a-Dot revisited”, Mathematics Magazine, 46: 128136,
doi:10.2307/2687967, MR 0379077.
(c) Gemignani, Michael (1979), “Think-a-Dot: a useful generalization”, Mathematics Magazine, 52 (2): 110112, doi:10.2307/2689850, MR 1572295.
3 Problem
You are to model a Think-a-Dot device and its behavior through a collection of C++ classes. You
are also to write a command tad that allows a user to interact with your simulated Think-a-Dot
device. User inputs are single letters commands. All command letters are case insensitive, so ‘Q’
and ‘q’ for example have the same effect. The commands are:
• ‘A’, ‘B’, ‘C’ simulate the action of the machine when a ball is dropped in hole ‘A’, ‘B’, or ‘C’,
respectively.
• ‘L’, ‘R’ cause the gates to be reset to all point the same way – all to the left or all to the right,
respectively.
• The flip-flops should be colored as shown for the modified box in Figure 2.
• ‘P’ prints the state of the machine using three lines of text, e.g.,
R L R
L L
L L L
• ‘H’ prints a brief version of these instructions.
• ‘Q’ exits the program.
Your program will prompt the user to enter a command letter, check it for validity, and print the
hole at which the ball exits the machine (hole ‘P’ or ‘Q’ as shown in Fig. 3).
4 Programming Notes
You will define and implement three classes: ThinkADot, FlipFlop, and Game. Class
ThinkADot models the Think-A-Dot device. FlipFlop models a single flip-flop within the
Think-a-Dot. Game controls the user-interaction with the Think-A-Dot. It prompts the user to get
command letters (from cin) and to print results (to cout). It interacts with the Think-A-Dot to
determine how the device responds to the various operations that can be performed on it.
6 Problem Set 3
Class Game should have a public function play() that starts the game. play() first creates
a ThinkADot object where the flip-flops are colored as shown in Figure 2. It then enters the
interactive loop that prompts the user for a command letter and performs the corresponding action.
Class FlipFlop models a single flip-flop. The state of a flip-flop is either “left” or “right”
and should be represented by an enum type. (See 08-brackets Token class for an example.) There
should be a print() function that just prints a single letter ‘L’ or ‘R’ according to the current state
of the flip-flop. There should also be a function flip() that flips the state from “left” to “right”
or vice versa and returns the side of the flip-flop (“left” or “right”) the ball is on when leaving the
flip-flop. Thus, if the flip-flop is in the “left”-leaning state initially, the ball will pass to the right,
and the new state will be “right”.
For this class, it is okay to have public functions getState() and setState() to be used
by member functions of class ThinkADot. A superior design would nest the entire FlipFlop
class inside of the ThinkADot class, but for this assignment, FlipFlop should be a separate
class at the same level as the others. (We will get to nested classes later in the course.)
Class ThinkADot models the device. It has a private array (not a vector) of eight FlipFlop
objects that store the current state of each of the eight flip-flops. Its constructor should initialize all of
the flip-flops to the “left” position, the same as the ‘L’ command. It has public functions reset(),
play(), and print() that carry out the actions ‘A’, ‘B’, ‘C’, ‘L’, and ‘R’ (with appropriate
parameters) that can be performed on the device. The flip-flop states must be accessible only from
these required member functions. In particular, there should be no getter or setter functions for the
flip-flops.
The file main.cpp will have the same form as in PS1. The global function run() should only
have two lines – one to instantiate Game and the other to call the Game object’s play() function.
4.1 Computing the next state
The tricky part of this assignment is how to update the state when a ball is dropped through one of
the three holes ‘A’, ‘B’, or ‘C’. Referring to Figure 2, you can see seven channels through which
the ball can pass. If we number them from 0 through 6, starting at the left, then we see that a ball
dropped in hole ‘A’ enters channel 1. After passing through the first flip-flop it moves to either
channel 0 or to channel 2, depending on the state of the flip-flop. If it goes to channel 0, it drops
straight through to the bottom and comes out on the left side. If it goes to channel 2, it encounters
the first flip-flop in the second row. After passing through it, the ball enters channel 1 or 3, etc.
Your code should trace the path of a ball through the machine as described above, flipping each
of the flip-flops encountered on the way, and recording the last channel the ball was in. Clearly that
will be channel 1, 3, 5, or 7. If it’s 1 or 3, the ball exits the machine through hold ‘P’. Otherwise, it
exits through hole ‘Q’. Note that it would be ambiguous where the ball exits if it were coming from
channel 4, but that is not possible.
4.2 No-no’s
There are many ways to implement a Think-a-Dot. For this assignment, you must do it as described
above. Here are a few no-no’s, not because they’re necessarily wrong but because I want you to
learn the particular techniques described above.
1. Don’t use new or delete.
2. Don’t use any Standard Library container functions such as vector.
3. Don’t use a table lookup to find the next state.
Handout #5—September 26, 2018 7
4. Don’t use nested classes.
5. Don’t use language features that have not been presented in lecture or in any of the class
examples. Don’t use prohibited features such as non-const global variables or goto’s.
If you think you need to violate any of these restricts, please ask me for help.
5 Grading Rubric
Your assignment will be graded according to the scale given in Figure 4 (see below).
# Pts. Item
1. 1 All relevant standards from PS1 are followed regarding submission, identification of authorship on all files, and so forth.
2. 1 A well-formed Makefile or makefile is submitted that specifies compiler
options -O1 -g -Wall -std=c++17.
3. 1 Running make successfully compiles and links the project and results in an
executable file tad.
4. 1 tad smoothly interacts with the user. Clean, easily understood user prompts
and help messages are given.
5. 2 Bad user inputs are handled gracefully and do not result in fatal errors.
6. 6 All of the functionality in section 3 is correctly implemented. In particular, each
of the eight command letters works properly in both upper and lower case and
carries out its assigned action correctly.
7. 3 The structure of the program matches the specification and restrictions given in
in section 4. No dynamic storage is used.
8. 1 Each function definition is preceded by a comment that describes clearly what
it does.
9. 4 The program shows good style. All functions are clean and concise. Inline initializations, functions, and const are used where appropriate. Variable names
are appropriate to the context. Programs are consistently indented according to
the course indenting style. Each class has a separate .hpp file and, if needed, a
separate .cpp file.
20 Total points.
Figure 4: Grading rubric.

CPSC 427 Problem Set 4

1 Consensus Problem
In this and following assignments, we will be developing a simulator for a distributed consensus algorithm. Consensus is at the heart of maintaining consistency in distributed databases
as well as in cryptocurrencies and blockchain algorithms.
We consider the consensus problem in a simple setting. The players are trying to reach
agreement on a course of action. Each player has a current preference called her choice,
which is the current value stored in her choice register. We assume a simple binary choice,
so the choice value is either 0 or 1. The players communicate with each other, and from
time to time a player may change her choice. The goal is for the players to arrive at a
stage where all players are making the same choice. In this case, we say the players have
reached consensus, and we call the common choice the consensus value. We also require
that the consensus value be stable, meaning that once consensus has been reached, nobody
can subsequently ever change her choice.
We assume the agents communicate using the random-pair communication model. In
this model, a communication round consists of a randomly chosen player (called the sender )
sending a message to another randomly chosen player (called the receiver ). Sender and
receiver must be distinct. For the algorithms considered here, the sender’s message is
always her current choice value. The receiver, depending on the message received, may
change her current choice and her internal state.
A population of players solves the consensus problem if following is true:
1. For all possible initial choices of the players, if the players start in their designated
initial states, the computation eventually reaches consensus with probability 1.
2. Once consensus has been reached, no player can subsequently ever change her choice.
Note that if all players start with the same choice, then that choice is the consensus value,
and no player ever changes her choice.
There are many possible algorithms for reaching consensus. Here are a couple very
simple ones that we will be exploring.
1.1 Fickle
Whenever a fickle player receives a message, she changes her choice, if necessary, to agree
with the sender’s choice. That is, she sets her choice register to the value contained in the
message.
It is easy to see that there is some sequence of message transmissions that causes the
system to reach consensus. Once consensus has been reached, no player will change her
choice since every subsequent message contains the consensus value.
It is also easy to believe that it might take a very large number of random communication
rounds to reach consensus.
2 Problem Set 4
1.2 Follow the Crowd
A follow-the-crowd player has a one-bit state register in which she saves the last message
received. She changes her choice only when she gets two messages in a row that both
disagree with her current choice. Thus, she waits until she gets a sense of the crowd before
deciding to follow. We assume that each player starts with her state register set equal to
her choice.
In greater detail, when a follow-the-crowd player receives a message m, she compares it
with her current state. If it differs, she replaces the current state with m. If it is the same,
she replaces the current choice with m.
It is believable that this might converge to a consensus value faster than fickle since it
is less likely for a player holding the majority choice to change to the minority value.
2 Assignment Goals
1. To learn how to organize a simulation of a large system.
2. To learn about a simple model of asynchronous distributed computing.
3. To learn how to generate uniformly distributed random numbers from a finite interval.
4. To experience a computationally-intensive application where efficiency matters.
3 Problem
In this assignment, you will implement a simulation of a large number of agents attempting
to reach consensus using the fickle algorithm under the random-pair communication model.
The follow-the-crowd algorithm will be used in a later assignment.
You are required to implement two classes and a main program.
• class Agent models an agent running the fickle algorithm. The public interface must
support these functions:
– Agent(int ch) constructs an agent with choice ch.
– void update(int m) performs the update to the agent as specified by algorithm
fickle upon receipt of the message m.
– int choice() const returns the agent’s current choice.
• class Simulator simulates a collection of n agents trying to reach consensus using
the random communication model described in section 1. Its public interface consists
of the following:
– Simulator( int numAgents, int numOne, unsigned int seed ) constructs
a simulator for numAgents agents. The first numOne of these have initial choice 1;
the remainder have initial choice 0. seed is used to initialize the random number
generator random().
– int run( int& rounds ) runs the simulation for as many rounds as it takes
to reach consensus. The number of communication rounds used is stored in the
output parameter rounds. The consensus value is returned.
Handout #6—October 22, 2018 3
To carry out the simulation requires the ability to select a random pair of distinct
agents j and k to serve as sender and receiver in a communication round. Further
details are given in section 4.
To know when consensus is reached requires the simulator to keep track of the number
of agents having each of the two possible choice values. Since the only way an agent
might change its choice is because of update(), you should just update the counts
of agents having a given choice after each communication round. Do not poll every
agent after every round.
• main.cpp implements a command
> consensus numAgents numOne [seed]
that takes two required argumets, numAgents and numOne, and one optional argument,
seed. These three arguments should be converted to numbers and passed to the
Simulator constructor. If seed is omitted, the result of time(0) should be used
instead.
The run() function in main.cpp should instatiate a Simulator with the given parameters and then run it. When Simulator::run() returns, you should print a single
line to cout consisting of five whitespace-separated numbers: The number of agents,
the number of agents initially choosing one, the actual seed used, the number of
communication rounds required to reach consensus, and the final consensus value.
You should test your code using various combinations of parameters. Increasing the
population size numPlayers will cause a big increase in run time as will having numOne be
close to numPlayers/2. You may terminate your experiments once the run time grows to
more than a few seconds. This may come rather quickly with fickle, but that is for you
to find out. As usual, you should submit test input files and the corresponding outputs
produce by your program.
4 Program Notes
I will furnish some test cases on the Zoo in /c/cs427/code/ps4/, and you should test
it with some parameter combinations of your own. However, you might only be able to
duplicate my output if you run your code on the Zoo and your program uses the random
number generator in the same way, namely, at each round, first select the sender and then
select the receiver.
To select a random sender from among n agents, you can use the function
RandomUniform(n), which returns a uniformly-distributed random integer in the range
[0 . . . n − 1].
int RandomUniform( int n ) {
long int usefulMax = RAND_MAX – (RAND_MAX+1)%n;
long int r;
do { r = random(); }
while ( r > usefulMax );
return r % n;
}
4 Problem Set 4
The purpose of this code is to make all numbers in the given range equally likely.1
To make sure you use the same number of calls on the random number generator as I
do when choosing the sender and receiver, you should first chose the sender j from among
the n agents. Now there are only n − 1 eligible receivers, so you should choose a a number
k in the range [0 . . . n − 2] and adjust k to avoid j by incrementing k if k ≥ j.
The submission guidelines are the same as in previous assignments. Submit all files
needed to compile your project along with a Makefile. Include a notes.txt file, a file of
sample inputs and a file of the corresponding outputs.
5 Grading Rubric
Your assignment will be graded according to the scale given in Figure 1 (see below).
# Pts. Item
1. 4 All relevant standards from previous problem sets are followed regarding submission, identification of authorship on all files, and so forth. A
well-formed Makefile or makefile is submitted that specifies compiler
options -O1 -g -Wall -std=c++17. Running make successfully compiles
and links the project and results in an executable file consensus. Each
function definition is preceded by a comment that describes clearly what
it does.
2. 2 Required sample input and output files are submitted.
3. 4 The program shows good style. All functions are clean and concise. Inline
initializations, inline functions, and const are used where appropriate.
Variable names are appropriate to the context. Programs are consistently
indented according to the course indenting style. Each class has a separate
.hpp file and, if needed, a separate .cpp file.
4. 2 Everything is private in all classes except for the specified public interface
and any needed special functions (constructors, destructor, move and
copy constructors and assignments).
5. 8 All of the functionality in section 3 is correctly implemented.
20 Total points.
Figure 1: Grading rubric.
1Note that it is not sufficient to just take random()%n since if n does not divide RAND_MAX + 1, some
numbers will have a greater probability of being chosen than others.
For example, ifrandom() were to produce numbers in the range [0 . . . 9] and we wanted numbers in
the range [0 . . . 3], then reducing each of the numbers in the range [0 . . . , 9] mod 4 gives the sequence
0, 1, 2, 3, 0, 1, 2, 3, 0, 1. We see that 0 and 1 each occur 3 times, whereas 2 and 3 each occur only twice. Thus,
0 and 1 are each generated with probability 0.3 and 2 and 3 are each generated with probability only 0.2. To
be uniformly distributed, all probabilities should be 0.25. In this example, where we pretend RAND_MAX==9
and n = 4, my code computes usefulMax to be 9 – 10%4 = 7. Then whenever random() returns 8 or 9, the
program loops and tries again.

CPSC 427 Problem Set 5

1 Assignment Objective
This problem set continues the development begun in Problem Set 4 of a simulator for a
population of simple agents attempting to reach consensus on a choice value. The PS4
assignment handout describes two different such agent algorithms: fickle and follow the
crowd. In PS4, you implemented a simulator for a collection of fickle agents.
In this assignment, you will add a number of new features to the PS4 consensus program.
Just as in real-life, refactoring code to handle new requirements is easy in places and harder
in others.
2 Assignment Goals
• Learn to use polymorphism.
• Experience the effect of refactoring a big class (Simulator) into two related but
smaller classes.
• Learn how to explore a rich parameter space, and gain insight into the behavior of
random processes.
3 Problem
Here is an overview of the new features and required changes:
1. Agent will become a pure abstract class. Recall that that means all functions are
virtual, and all are abstract except for the virtual destructor. The public Agent
functions are the same as before: update() and choice().
2. Fickle is a new class publicly derived from Agent. It is pretty much the same as the
Agent class from PS4. Crowd is another new class publicly derived from Agent. It
implements the follow-the-crowd algorithm described in the PS4 assignment handout.
3. The Simulator of PS4 did two distinct jobs:
(a) It set up the population of agents to be simulated.
(b) It ran the simulation.
In this assignment, you will separate these two tasks. A new class Population will create and manage the agents. The revised Simulator will take a Population reference
as a parameter and run the simulation, as before, until consensus is reached.
4. Population will maintain the aggregated array of Agent that was previously in
Simulation. However, since Agent is now the base class for two different derived
classes, the array elements will be Agent pointers. Each agent will be created using
either new Fickle( val ) or new Crowd( val ), depending on which kind of agent
2 Problem Set 5
is desired. Here val is the initial choice value for that agent. Population will retain
custody of all of these agents, so its destructor must take care to delete them all.
5. The method for constructing agents is different from PS4. Each agent is randomly
assigned to one of the two concrete agent types, Fickle or Crowd. The initial value
v is randomly chosen from the set {0, 1}. Both of these random choices are biased
according to new command line parameters. probFickle is a real number in the
semi-open interval [0, 1) and specifies the probability that an agent is chosen to be of
type Fickle rather than of type Crowd. probOne similarly is a real number in the
range [0, 1) and specifies the probability that an agent’s initial choice is 1 rather than
0.
6. Population has several public functions in addition to constructors, destructor, and
print:
(a) int size() const returns the number of agents.
(b) void sendMessage(int sender, int receiver) simulates a single communication step from sender to receiver.
(c) bool consensusReached() returns true iff consensus has been reached.
(d) int consensusValue() returns the consensus value if consensus has been
reached; otherwise it returns -1.
7. The Simulator constructor now only takes a single parameter of type Population&.
Its run function has signature void run(). To obtain the results of the simulation,
the caller can call two new public functions: numRounds() and consensusValue().
Since the simulator is doing the simulation, it knows how many rounds it has used.
On the other hand, only Population knows the consensus value, so this is a case
where delegation should be used.
8. main.cpp changes considerably. It takes different command line arguments and it
prints different output than PS4.
(a) The new command line arguments are
numAgents probFickle probOne [seed]
where seed is optional as before. numAgents is again the total number of agents.
probFickle and probCrowd are the probabilities discussed in item 5 above.
(b) All output should go to cout. banner() and bye() should be used as usual.
The output from a run has three parts: The initial parameters, the statistics
of the population after the random generation process, and the results of the
simulation. See sample.out for an example of the new output format.
9. The resulting executable file should be called consensus2 to distinguish it from the
PS4 command name.
An important part of this assignment is to test your program on reasonable test cases,
to submit the test case inputs and corresponding outputs, and to report on what you
observe. For example, you should run your code on extreme cases such as 0 agents, 1 agent,
probabilities of 0.0 and 1.0, and so forth.
Try to gain some insight about the extent to which follow-the-crowd agents do better
than fickle agents. For example, what do you observe with a modest size population (say
1000) with different values for probFickle, say, 0.0, 0.01, 0.5, 0.99, 1.0.
Handout #7—October 31, 2018 3
4 Programming Notes
1. random() is now used in two different parts of the code.
(a) Simulator::run() uses uRandom() as before in order to choose first a sender
and then a receiver for a communication step. uRandom() of course is based on
random().
(b) The Population constructor needs random values when constructing each agent.
First it uses randomness to choose an initial choice value for the agent. Then
it uses it to choose the agent type. In both cases, it chooses a double in the
semi-open interval [0, 1) and compares that number with the desired probability
in order to make its decision. For example, to generate the choice value, test if
the random number is less than the desired probability of choosing 1. If it is,
then choose 1, else choose 0.
2. To choose a random real in [0, 1), you can use my code
double Population::
dRandom() {
return random()/(RAND_MAX+1.0); // result is double in [0,1)
}
By default, the type of “1.0” is double, so the coercion rules force the addition and
then the division to both be performed using double arithmetic. If you change “1.0”
to “1”, it won’t compile without warnings, and it won’t work correctly.
3. In order to duplicate my output, you will need to use the random number generator
in exactly the same way as my program does. In particular, you will need to choose
the sender before the receiver, and you will need to choose the initial consensus value
for an agent before choosing the agent type. Of course, you will also need to start
with the same seed.
4. The submission guidelines are the same as in previous assignments. Submit all files
needed to compile your project along with a Makefile. Include a notes.txt file, a
file of sample inputs and a file of the corresponding outputs.
5. Note that the grading rubric for this assignment puts more emphasis on good design,
good style and good choice of test data than the previous assignments.
4 Problem Set 5
5 Grading Rubric
Your assignment will be graded according to the scale given in Figure 1 (see below).
# Pts. Item
1. 4 All relevant standards from previous problem sets are followed regarding submission, identification of authorship on all files, and so forth. A
well-formed Makefile or makefile is submitted that specifies compiler
options -O1 -g -Wall -std=c++17. Running make successfully compiles
and links the project and results in an executable file consensus2. Each
function definition is preceded by a comment that describes clearly what
it does.
2. 3 Sample input and output files are submitted that show good coverage of
the parameter space, e.g., small inputs, large inputs, edge cases for the
probabilities (e.g., 0.0 and 1.0) as well as reasonable intermediate cases.
3. 5 The program shows good style. All functions are clean and concise. Inline
initializations, inline functions, and const are used where appropriate.
Variable names are appropriate to the context. Programs are consistently
indented according to the course indenting style. Each class has a separate
.hpp file and, if needed, a separate .cpp file. However, it is acceptable
to group the three polymorphic agent classes together in the same .hpp
and .cpp files.
4. 2 Everything is private in all classes except for the specified public interface,
any needed special functions (constructors, destructor, move and copy
constructors and assignments), and functions needed for debugging.
5. 6 All of the functionality in section 3 is correctly implemented.
20 Total points.
Figure 1: Grading rubric.

CPSC 427 Problem Set 6

1 Introduction
This problem set continues the development begun in Problem Set 4 of a simulator for a
population of simple agents attempting to reach consensus on a choice value. The long-rang
goal of this and following assignment(s) is to simulate the blockchain consensus algorithm
used in Bitcoin cryptocurrency, sometimes called Nakamoto consensus, to see how fast consensus is reached under various assumptions about the speed and reliability of the underlying
network and the honesty of the agents participating in the protocol.
2 Blockchain Background
While not strictly needed for this assignment, a general understanding of blockchains and
Nakamoto consensus will help motivate it.
A blockchain is a sequence of records or blocks that are cryptographically protected to
preserve integrity and prevent various kinds of tampering. A blockchain can be extended
only by someone who knows the solution to a difficult cryptographic puzzle that is derived
from the current blockchain. An agent, called a miner, who wants to extend the blockchain
first has to solve the puzzle for that chain. In general, many miners are working in parallel
to solve the puzzle. Any one who succeeds is able to create a new block of transactions and
append it to the end of the chain. The result is a new longer chain that is verifiably valid.
Once a new chain has been produced, the successful miner sends it around the network
to other miners. When a longer (valid) chain is received from another miner, the recipient
discards the old shorter chain and begins trying to solve the puzzle for the longer chain.
Consensus on the new chain is reached when all of the miners have received the new chain
and discarded their old, shorter, chains.
It is possible that two miners will solve the puzzle at nearly the same time and will
each propose longer but different extensions of the current chain. These new chains will
propagate around the network. Because they are equal length, neither will annihilate the
other, so consensus cannot be reached until a yet longer chain is produced by one of the
minors. As this new chain propagates through the network, miners will discard their old
chains and adopt the new one.
Intuitively, consensus will eventually be reached if there is a unique longest chain in
circulation, and no new chains are created before consensus is reached. The purpose of the
puzzles (also called proof of work is to slow down the process of creating new chains, which
in turn will decrease the likelihood of new chains interfering with the consensus process.
In practice, one does not require that consensus on what the current blockchain is.
Rather, one is interested when consensus is reached on a particular block. For example,
suppose a miner extends a length 10 blockchain c to create a new blockchain whose last
(11th) block is b. Intuitively, b is committed if b is the 11th block of every longer blockchain
2 Problem Set 6
still in circulation. Of course, there is always the possibility that some miner still working
on the old chain c will succeed in creating a new length-11 chain with a different 11th block.
However, the chance of that block not being annihilated as it attempts to infect other miners
is vanishing small under suitable circumstances.
3 Problem
This assignment focuses on a particular space-efficient representation of blockchains. At an
abstract level, a blockchain is just a sequence of blocks. A new blockchain is created by
appending a new block to the end of an existing blockchain. The initial blockchain consists
of a single genesis block. All subsequent blockchains begin with the genesis block.
We ignore the cryptography issues of real blockchains and assume that the only properties of interest in a blockchain are its length and the list of blocks that comprise the
chain. Each block has an associated unique identifier, so there is never the possibility of
two identical blocks being created in different parts of the system.
Figure 1 shows a situation with three active blockchains beginning with blocks Bk2,
Bk3, and Bk4, respectively. Four agents ChA, . . . , ChD have three different current choices
for the blockchain. ChA prefers the chain beginning with Bk2, ChB and ChC both prefer
the chain at Bk4, and ChD prefers the chain at Bk3.
ChA ChB
Bk3
Bk2
Bk1
Bk4
ChC ChD
Figure 1: Three active blockchains.
Our blockchain representation has two goals:
1. No block is ever copied.
2. A block is automatically deleted as soon as it becomes inaccessible.
For goal 1, we delete the copy constructor and copy assignment (to prevent accidental
copying), and we use pointers to represent the chain structure as a kind of linked list.
For goal 2, we replace the arrows of Figure 1 with a slight modification of the SPtr
class presented in demo 21a-SmartPointer-v2. Figure 2 shows the smart pointers as white
rectangles inside both the blockchain headers (possessed by the agents) and inside the blocks
Handout #8—November 26, 2018 3
themselves. The dashed white boxes represent the count dynamic extensions in the SPtr
class. Recall that this is a count of the number of SPtr objects having the same target
pointer.
ChA ChB ChC ChD
Bk1
Bk2 Bk4
2
Bk3
2 1
2
Figure 2: Three active blockchains.
Your job is to implement two new classes, Blockchain and Block, to represent
blockchains. In addition to the SPtr data member, each Block will also have two const
fields, a unique identifier and it’s level in the blockchain tree, where the genesis block is
considered to be at level 0. (The genesis block in Figures 1 and 2 is Bk1.)
Class Blockchain contains a single private data member of type SPtr, which implements
the smart pointer to the most recent block in the chain. It should have several public
functions:
1. Blockchain extend() returns a new blockchain created by extending the current
blockchain. The new chain should be stack-allocated and returned by value.
2. print() prints the blocks that comprise a blockchain in order of increasing level. For
example, the output from printing the blockchain ChC in Figure 2 might look like
[0,1] [1,2] [2,4]. Here, the first number of each pair is the block’s level in the
tree and the second number is its UID.
3. operator<<() is the usual inline extension of print(). Other functions that might prove useful include unsigned length(), bool operator==(), and block* tail() (which returns a regular ¸pointer to the last (most recent) block). Class Block should have three private data members: serialNo, level, and SPtr. All three should have the const type qualifier, meaning that they cannot be changed after initialization. The copy constructor and copy assignment should also be deleted since blocks are never supposed to be copied. It should also have a public function blkLevel() that returns the level of the current block. 4 Problem Set 6 Finally, a driver program will need to be written along the lines of class Game in problem set 3 (Think-a-Dot). The driver should create an array bc of 10 blockchains. Each blockchain should be initialized with a copy of the length-0 blockchain that contains only the level-0 genesis block. The driver should support four one-letter commands, some of which take single-digit arguments. Ajk does the assignment bc[j] = bc[k]. Ej extends blockchain bc[j]. P prints the blockchains in array bc[], one per line. Q quits. 4 Teaching Objectives • Make use of a slightly expanded version of the smart pointer class SPtr given in class demo 21a-SmartPointer-v2. • Make use of class Serial from the same demo to assign unique ID’s to new blocks. • Learn how to use smart pointers of class SPtr to manage the job of deleting blocks when they no longer needed. 5 Programming Notes 1. When running your code under valgrind, expect an output line in use at exit: 4 bytes in 1 blocks These four bytes are the ones containing the single instance of class Serial. Since that instance is stored in a static variable, it is never deleted, and that’s okay. 2. Use const wherever possible. In particular, the print() functions are generally const since they are not supposed to change the data that they are printing. 3. Minor modifications to class SPtr are permissible and necessary. For example, the typedef for T will need to be changed. Also, you might find it helpful to define operator->() to behave like the standard -> operator behaves on ordinary C pointers.
You might also want to define a function to return the C pointer target that the SPtr
object manages.
Handout #8—November 26, 2018 5
6 Grading Rubric
Your assignment will be graded according to the scale given in Figure 3 (see below).
# Pts. Item
1. 4 All relevant standards from previous problem sets are followed regarding submission, identification of authorship on all files, and so forth. A
well-formed Makefile or makefile is submitted that specifies compiler
options -O1 -g -Wall -std=c++17. Running make successfully compiles
and links the project and results in an executable file blockchain. Each
function definition is preceded by a comment that describes clearly what
it does.
2. 4 Sample input and output files are submitted that show the program behaves as expected. In particular, you should create a test file that grows
a blockchain structure like the one in Figure 1 and then proceeds to replace some of the blockchains with others. An inaccessible block should
be deleted automatically when the last smart pointer to it is deallocated.
It may be useful to leave the SPtr debugging printout in place that shows
when a block is deleted.
3. 4 The program shows good style. All functions are clean and concise. Inline
initializations, inline functions, and const are used where appropriate.
Variable names are appropriate to the context. Programs are consistently
indented according to the course indenting style. Each class has a separate
.hpp file and, if needed, a separate .cpp file.
4. 4 All of the functionality in section 3 is correctly implemented.
5. 4 Valgrind gives clean output with all storage blocks freed except for the
instantiation of Serial.
20 Total points.
Figure 3: Grading rubric.

CPSC 427 Problem Set 7

1 Introduction
This problem set continues the development begun in Problem Set 4 of a simulator for a
population of simple agents attempting to reach consensus on a choice value. The PS4
assignment handout describes two different such agent algorithms: fickle and follow the
crowd. In PS4, you implemented a simulator for a collection of fickle agents.
In the PS5 assignment, you refactored the PS4 solution to add a number of new features.
In particular, you made Agent into a pure abstract class, you split off a new Population
class from the Simulator class, and you changed the method used for building the initial
population from the command line parameters.
In the PS6 assignment, you implemented new classes Block and Blockchain, and you
imported and perhaps modified demo classes SPtr and Serial.
The goal of this assignment is to simulate the blockchain consensus algorithm used
in Bitcoin cryptocurrency, sometimes called Nakamoto consensus, to see how consensus
gradually evolves.
2 Teaching Objectives
• Gain more experience in refactoring code to adapt it to new requirements.
• Learn how to factor out common code in a polymorphic class hierarchy.
• Find additional uses of delegation in order to keep functions close to the data members
that they need.
• Learn how objects of class Blockchain can be passed around freely in the simulator
without concern about storage management issues.
• Take a step closer to simulating a realistic blockchain consensus algorithm.
3 Problem
Integrate and extend your PS5 and PS6 solutions to result in a simulator for agents that
are attempting to agree on a blockchain rather than on a single bit. In particular, you will
need to do the following:
1. Find everywhere in your code from PS5 involved with reaching consensus on an a
0-1 value of type int. Change the value type instead to Blockchain. In particular,
the abstract virtual function choice() in Agent should now return a value of type
Blockchain rather than of type int.
2 Problem Set 7
2. Add a new abstract virtual function extend() to class Agent() that causes the agent
to extend its current blockchain and to make the extended blockchain its new choice.
This will apply to all agent classes, including Fickle and Crowd.
1
3. Add another agent class, Nakamoto, to model the Nakamoto algorithm’s rule of ignoring a new blockchain received from another agent unless the new chain is longer than
the current one, in which case the longer blockchain replaces the shorter one.
4. Add a new class AgentBase that is publicly derived from Agent and from which the
actual agents Fickle, Crowd, and Nakamoto will be publicly derived. The purpose of
AgentBase is to give a place for the data members and functions that are common to
all agents such as the agent’s current choice and the public functions choice() and
extend(). The reason for not putting these things directly in Agent is that Agent
is a pure abstract class, so it cannot be instantiatied and therefore also cannot have
data members.
5. Change Simulator to randomly decide at each step whether to perform an update()
operation or an extend() operation. It does this by calling dRandom() and comparing
the result to a new command line argument probExtend. In case it decides to simulate
an extend, it chooses an agent at random to perform the extend. Similarly, if it decides
to simulate the sending of a message, it works as in PS4 and PS5 by choosing a random
sender and a distinct random receiver for the simulated sending of a message.
6. Instead of running until consensus is reached, the new simulator will run
for maxRounds, which is a new command line argument that is passed to
Simulator::run() as a parameter. Thus, there is no longer any need for the functions and data members that were formerly involved in trying to determine whether
or not consensus had been reached, and if so, what the consensus value was. Rather,
at the end of the simulation, we’ll simply print out a list of agents with each agent’s
current choice.
7. The code in class Population that creates the population should now make a 3-way
choice between Fickle, Crowd, and Nakamoto. New command line parameters provide
the desired probabilities for each kind of agent. All agents, regardless of type, now all
start with copies of the same initial genesis Blockchain for their initial choice. The
genesis Blockchain contains a smart pointer that points to the genesis Block. The
genesis Block is unique in that its SPtr data member has both target and count set
to nullptr.
8. Population should also have functions extend(int receiver) and
sendMessage(int senter, int receiver) to translate between the simulator’s use of integers to identify agents and the agents themselves, which actually carry
out those operations. The agents in turn delegate some of the work to Blockchain
functions that were defined in PS6.
9. Modify main.cpp to accept the following command line arguments,
numAgents maxRounds probNak probFickle probExtend [seed]
where the arguments have the following meanings:
1This is intended to model what happens when a Bitcoin miner successfully solves the current proof-ofwork puzzle and is therefore allowed to add a set of transactions to the current blockchain.
Handout #9—December 3, 2018 3
numAgents The total number of agents (as before).
maxRounds The total number of simulation rounds to perform.
probNak The probability of selecting a Nakamoto agent when building the population.
probFickle The probability of selecting a Fickle agent when building the population.
probExtend The probability that the simulator chooses to simulate an extend() operation rather than a sendMessage() operation.
[seed] Optional seed for the random number generator (as before).
The probability of selecting a Crowd agent is 1.0 − probNak − probFickle. It is an
error if the result does not lie in the closed interval [0.0, 1.0].
10. Modify Population to have two print functions, one which prints the statistics as
in PS5 (but I’m now calling it printStats()), and one that prints out each agent’s
choice of blockchain, one per line (which is what I’m now calling print()). Naturally,
print() delegates the printing of an agent’s current choice to Blockchain::print().
A sample call on your simulator is given on the Zoo in /c/cs427/code/ps7/sample.sh,
along with the output from a run on my machine. To give a better idea of what the
simulator is doing, I have added print statements to the simulator to show what operation
is being performed at each step of the simulation. I’ve also added a print statement to
Population::extend() to print each new blockchain when it is first produced.
4 Programming Notes
1. There should be no public data members and no use of friend classes or functions.
2. Dynamic memory (allocated by new) should only be used in the following places:
(a) Within the furnished classes SPtr and Serial;
(b) For creating objects of type Block;
(c) For creating objects of type Agent and for creating the array of agents.
All Blockchain objects should be stack allocated.
3. The only delete statements outside of class SPtr should be to delete objects created
in case 2c above. You should not explicitly delete any blocks. They should be deleted
automatically by the SPtr objects that manage them.
4 Problem Set 7
5 Grading Rubric
Your assignment will be graded according to the scale given in Figure 1 (see below).
# Pts. Item
1. 3 All relevant standards from previous problem sets are followed regarding submission, identification of authorship on all files, and so forth. A
well-formed Makefile or makefile is submitted that specifies compiler
options -O1 -g -Wall -std=c++17. Running make successfully compiles
and links the project and results in an executable file blockchain. Each
function definition is preceded by a comment that describes clearly what
it does.
2. 2 Sample input and output files are submitted that show good coverage of
the parameter space, e.g., small inputs, large inputs, edge cases for the
probabilities (e.g., 0.0 and 1.0) as well as reasonable intermediate cases.
This is in addition to the furnished sample file.
3. 3 The program shows good style. All functions are clean and concise. Inline
initializations, inline functions, and const are used where appropriate.
Variable names are appropriate to the context. Programs are consistently
indented according to the course indenting style. Each class has a separate
.hpp file and, if needed, a separate .cpp file. However, it is acceptable
to group the three polymorphic agent classes together in the same .hpp
and .cpp files.
4. 2 The restrictions in section 4 are all obeyed.
5. 10 All of the functionality in section 3 is correctly implemented.
20 Total points.
Figure 1: Grading rubric.

CPSC 427 Problem Set 8

1 Introduction
This 10-point assignment is required for graduate students and anyone else registered under
CPSC 527. It is optional for students registered under CPSC 427. For those students,
points earned on this assignment will offset points lost on previous homework assignments,
but they will not apply against points lost on exams, nor will they permit anyone to earn
more than 100% of the possible homework points.
The due date for this assignment is the same as that for homework assignment 7. However, they are separate assignments and should be submitted separately.
2 Problem
The goal of this assignment is to modify your solution to homework assignment 7 to gather
and print additional information about the progress of the simulation.
An inventory of blockchains is a pr´ecis of the current set of choices of all of the agents
in the population. A sample inventory from a real simulation run with 10 agents is:
Inventory: 5 active blockchain(s):
1 copies of [0,1] [1,46] [2,123] [3,255]
1 copies of [0,1] [1,46] [2,123] [3,271]
6 copies of [0,1] [1,46] [2,123]
1 copies of [0,1] [1,46] [2,160]
1 copies of [0,1] [1,46] [2,236]
We see that all of the agents agree on the level-0 and level-1 blocks of each chain and
eight agents agree on level-2 block [2,123]. However, two different chains have already
been forked from it, so two agents have distinct level-3 blocks, and it is unclear which will
eventually win out.
Thus, an inventory is a compressed version of the current choices of the population
that allows one to relatively quickly find those blocks for which consensus has already been
achieved. However, finding consensus blocks is not a part of this assignment. All that is
required is to create the initial inventory, to maintain it step by step during the simulation,
and to print it when required (in the format shown above).
3 Programming Notes
1. You should create a class Inventory whose sole data member is a std::map.
2 Problem Set 8
2. To maintain the inventory, you should write functions add() and sub that add (insert) and subtract (remove) blockchains from the inventory, respectively. After each
simulation step, if the agent’s new and old choices differ, the new one should be added
and the old one subtracted from the inventory.
3. There should be no occurrences of new in PS8 other than those already present in
PS7. In particular, the map should be composed in Inventory and not be a dynamic
extension. Keeping the use of dynamic storage confined to classes that can manage it
such as SPtr and std::map simplies your code and makes it less likely to have hidden
errors. Remember the motto: “No new’s is good news!”
4. You should define Blockchain::operator<() and Blockchain::operator==(). The
default definitions won’t work properly because they end up comparing the embedded
SPtr’s, which will always differ in their my_id fields, even when one is a copy of
another. For our purposes, it works to compare the serial numbers of the last block
in the chain to which each Blockchain points.
5. The same sample call on your simulator that was provided for PS7 is given again on the
Zoo in /c/cs427/code/ps8/sample.sh, along with the corresponding output. Note
that adding the inventory to your PS7 code will change the serial numbers assigned
to the blocks. This is okay.
4 Grading Rubric
Your assignment will be graded according to the scale given in Figure 1 (see below).
# Pts. Item
1. 1 All relevant standards from previous problem sets are followed regarding submission, identification of authorship on all files, and so forth. A
well-formed Makefile or makefile is submitted that specifies compiler
options -O1 -g -Wall -std=c++17. Running make successfully compiles
and links the project and results in an executable file blockchain. Each
function definition is preceded by a comment that describes clearly what
it does.
2. 1 Sample input and output files are submitted that show good coverage of
the parameter space, e.g., small inputs, large inputs, edge cases for the
probabilities (e.g., 0.0 and 1.0) as well as reasonable intermediate cases.
This is in addition to the furnished sample file.
3. 1 The program shows good style. All functions are clean and concise. Inline
initializations, inline functions, and const are used where appropriate.
Variable names are appropriate to the context. Programs are consistently
indented according to the course indenting style. Each class has a separate
.hpp file and, if needed, a separate .cpp file.
4. 2 The guidelines in section 3 are followed.
5. 5 All of the functionality in section 2 is correctly implemented.
10 Total points.
Figure 1: Grading rubric.