cs1132 fall 2010 assignment 1 1 rock paper scissors … · 1.3 rock-paper-scissors-lizard-spock the...

6
CS1132 Fall 2010 Assignment 1 Adhere to the Code of Academic Integrity. You may discuss background issues and general solution strategies with others and seek help from course staff, but the homework you submit must be the work of just you. When submitting your assignment, be careful to follow the instructions summarized in Section 4 of this document. 1 Rock Paper Scissors Lizard Spock Rock paper scissors is a classic children’s game. In it, two players count aloud to three, swinging their hand in a fist each time. When both players say three the two players ”throw” one of three gestures 1. Rock: a clenched fist 2. Scissors: index and middle fingers extended and separated 3. Paper: an open hand. Each gesture ”beats” one of the others: rock crushes scissors, scissors cuts paper, and paper covers rock. If both players pick the same gesture it is a draw and they must throw again. 1.1 Simulating a game of rock-paper-scissors Your first task is to implement a script rockPaperScissors.m that will simulate a single game against a com- puter opponent that randomly picks their throw. If the user picks the same throw as the computer prompt the user to rethrow and generate a new throw for the computer. When generating throws, make sure each possibility has equal chance of occurring. Example Output: >> rockPaperScissors Please pick your throw: (1 - Rock, 2 - Scissors, 3 - Paper): 2 Computer threw Paper, you win! >> rockPaperScissors Please pick your throw: (1 - Rock, 2 - Scissors, 3 - Paper): 1 Tie! Please throw again: (1 - Rock, 2 - Scissors, 3 - Paper): 3 Computer threw Rock, you win! 1.2 Basic Statistics One problem with rock-paper-scissors is how often ties occur. In this section you will simulate 10 5 games of rock-paper-scissors between two players. You must write a function rpsTurn() and a script rpsTest.m. The function rpsTurn() must be its own m-file, and should simulate one game of rock-paper-scissors between two computer players who randomly choose their throws: function [winner, ties] = rpsTurn() % winner: integer indicating which player won % ties: the number of times the two players picked the same throw % This function simulates one game of rock-paper-scissors The script rpsTest.m should simulate 10 5 games of rock-paper-scissors and keep track of how many times player1 wins, how many times player2 wins, and how many ties occur. Note: One game of rock-paper- scissors ends when one player wins, not when there is a tie. Present the final results in a visually pleasing way. Make sure to include the number of simulated games, how many times each player won and how many ties occurred. 1

Upload: hanguyet

Post on 29-Apr-2018

216 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: CS1132 Fall 2010 Assignment 1 1 Rock Paper Scissors … · 1.3 Rock-Paper-Scissors-Lizard-Spock The number of ties can be mitigated by introducing two new throws: lizard and spock

CS1132 Fall 2010 Assignment 1Adhere to the Code of Academic Integrity. You may discuss background issues and general solution strategies with

others and seek help from course staff, but the homework you submit must be the work of just you. When submitting

your assignment, be careful to follow the instructions summarized in Section 4 of this document.

1 Rock Paper Scissors Lizard Spock

Rock paper scissors is a classic children’s game. In it, two players count aloud to three, swinging their handin a fist each time. When both players say three the two players ”throw” one of three gestures

1. Rock: a clenched fist

2. Scissors: index and middle fingers extended and separated

3. Paper: an open hand.

Each gesture ”beats” one of the others: rock crushes scissors, scissors cuts paper, and paper covers rock. Ifboth players pick the same gesture it is a draw and they must throw again.

1.1 Simulating a game of rock-paper-scissors

Your first task is to implement a script rockPaperScissors.m that will simulate a single game against a com-puter opponent that randomly picks their throw. If the user picks the same throw as the computer promptthe user to rethrow and generate a new throw for the computer. When generating throws, make sure eachpossibility has equal chance of occurring.

Example Output:

>> rockPaperScissors

Please pick your throw: (1 - Rock, 2 - Scissors, 3 - Paper): 2

Computer threw Paper, you win!

>> rockPaperScissors

Please pick your throw: (1 - Rock, 2 - Scissors, 3 - Paper): 1

Tie! Please throw again: (1 - Rock, 2 - Scissors, 3 - Paper): 3

Computer threw Rock, you win!

1.2 Basic Statistics

One problem with rock-paper-scissors is how often ties occur. In this section you will simulate 105 games ofrock-paper-scissors between two players. You must write a function rpsTurn() and a script rpsTest.m. Thefunction rpsTurn() must be its own m-file, and should simulate one game of rock-paper-scissors betweentwo computer players who randomly choose their throws:

function [winner, ties] = rpsTurn()

% winner: integer indicating which player won

% ties: the number of times the two players picked the same throw

% This function simulates one game of rock-paper-scissors

The script rpsTest.m should simulate 105 games of rock-paper-scissors and keep track of how many timesplayer1 wins, how many times player2 wins, and how many ties occur. Note: One game of rock-paper-scissors ends when one player wins, not when there is a tie. Present the final results in a visually pleasingway. Make sure to include the number of simulated games, how many times each player won and how manyties occurred.

1

Page 2: CS1132 Fall 2010 Assignment 1 1 Rock Paper Scissors … · 1.3 Rock-Paper-Scissors-Lizard-Spock The number of ties can be mitigated by introducing two new throws: lizard and spock

1.3 Rock-Paper-Scissors-Lizard-Spock

The number of ties can be mitigated by introducing two new throws: lizard and spock. This variant wasinvented by Sam Kass and featured in an episode of The Big Bang Theory. The new rules are as follows

1. Scissors cuts Paper

2. Paper covers Rock

3. Rock crushes Lizard

4. Lizard poisons Spock

5. Spock smashes Scissors

6. Scissors decapitates Lizard

7. Lizard eats Paper

8. Paper disproves Spock

9. Spock vaporizes Rock

10. Rock crushes Scissors

More information can be found at http://bit.ly/98RKUY

Now write a script rpsls.m to simulate rock-paper-scissors-lizard-spock. Just as with rock-paper-scissors, if atie occurs prompt the user for a new throw and generate a new throw for the computer. Your script shouldask the user their choice of throw and tell who wins.

Example Output:

>> rpsls

Please pick your throw: (1 - Rock, 2 - Scissors, 3 - Paper, 4 - Lizard, 5 - Spock): 1

Tie! Please throw again:

(1 - Rock, 2 - Scissors, 3 - Paper, 4 - Lizard, 5 - Spock): 5

Computer threw Rock, you win!

1.4 Lizard Spock Statistics

Now we would like to know how much of an effect the addition of two new throws has had on the num-ber of ties. We will determine this experimentally by writing a function lizardSpock() and a scriptlizardSpockTest.m. The function lizardSpock() should simulate a single game between two computerplayers who randomly choose their throws:

function [winner, ties] = lizardSpock()

% winner: integer indicating which player won

% ties: the number of times the two players picked the same throw

% This function simulates one game of rock-paper-scissors-lizard-spock

Your script lizardSpockTest.m should simulate 105 games of rock-paper-scissors-lizard-spock and keeptrack of the number of times each player wins as well as the number of ties. Present this information in anappealing manner.

2

Page 3: CS1132 Fall 2010 Assignment 1 1 Rock Paper Scissors … · 1.3 Rock-Paper-Scissors-Lizard-Spock The number of ties can be mitigated by introducing two new throws: lizard and spock

2 Sorting Fun!

Sorting a collection of objects has become indispensable for today’s computer programs. From arranging alist of products by price on Amazon.com to ordering flight itineraries by the duration of the flight, sorting iseverywhere. In this exercise we will examine three ways in which sorting can be performed. For simplicitywe will assume we want to arrange an array in ascending order (more specifically in nondescending order).Also we want to experimentally see the performance of these algorithms as the size of the array and thenumber of possible entries changes.

Do not use built-in in function sort.

Do not use the built-in function break.

2.1 Bubble Sort

Bubble sort is a simple sorting algorithm; it works by repeatedly going through the array to be sorted,comparing two adjacent items at a time and swapping them if they are in the wrong order. Specifically, in apass through the array items 1 and 2 are compared and posssibly swapped, then items 2 and 3 are comparedand possibly swapped, and so forth until the end of the array is reached. The pass through the array isrepeated until no swaps occur, which means the array is sorted. The algorithm gets its name from the waysmaller elements ”bubble” to the beginning of the array. Implement this algorithm in the function:

function sortedArray = bubbleSort(A)

% Sort vector A in ascending order using Bubble Sort algorithm

% A: the vector of numbers to be sorted, the length of A is > 0

% sortedArray: the sorted array

The starting positions of the elements in the array greatly influences the number of passes needed to sortthe array. Large elements near the beginning do not cause a problem, as they quickly move towards the end.However, small elements at the end of the array move extremely slowly. This is because each pass throughthe array can only move an element one place to the left, but can move an element all the way to the right.This has led large elements at the beginning of an array and small elements near the end to be known asrabbits and turtles respectively.

2.2 Cocktail Shaker Sort

To solve the problem with the turtles in a bubble sort a variation of bubble sort was developed. The al-gorithm differs from bubble sort in that it sorts in both directions: it alternates between rightward passes(starting at the beginning of the array) and leftward passes (starting at the end of the array). The firstrightward pass will shift the largest element to its correct place at the end (just like in bubble sort), and thefollowing leftward pass will shift the smallest element to its correct place at the beginning. The second setof right and left passes will shift the second largest and second smallest elements to their correct places, andso on. After 2i (i in each direction) passes, the first i and the last i elements in the list are in their correctpositions, and do not need to be checked. By shortening the part of the list that is sorted each time, thenumber of operations can be halved. You must implement this version of the algorithm in the function:

function sortedArray = cocktailShakerSort(A)

% A: the vector of numbers to be sorted

% sortedArray: the sorted array

2.3 Merge Sort

Merge sort is more complicated. The simplest implementation of merge sort uses recursion, but we will use adifferent implementation that does not use recursion. The main idea in merge sort is that given two sorted ar-

3

Page 4: CS1132 Fall 2010 Assignment 1 1 Rock Paper Scissors … · 1.3 Rock-Paper-Scissors-Lizard-Spock The number of ties can be mitigated by introducing two new throws: lizard and spock

rays, we can merge them relatively easily to form one (larger) sorted array. Start by writing a function merge:

function t = merge(v,w)

% Merge sorted vectors v and w to form vector t, which is also sorted.

% v,w: sorted numeric vectors not necessarily of the same length

% t: sorted vector whose length is length(v)+length(w)

Your code should take advantage of the fact that v and w are already sorted.

We begin by considering a vector x with length n where n is a power of 2. Heres the general idea:

1. Set the subvector length m to be 1. (Why? It’s the shortest vector that is sorted.)

2. Divide vector x into subvectors of length m.

3. Merge every two adjacent subvectors. I.e., merge subvectors 1 and 2, 3 and 4, 5 and 6, . . . , so thatthe merged subvector (each of length 2m) is sorted.

4. Double the value of m. (Thats the length of each merged-sorted-subvector)

5. Repeat steps 2 to 4 until < ? >. You should figure this out.

Let’s look at an example. The vector below is of length 8.

3 4 5 2 7 8 9 3

With a subvector length of 1, we have 8 subvectors. Merging subvectors l and 2, 3 and 4, 5 and 6, and 7and 8 gives us the following:

3 4 2 5 7 8 3 9

Now we have four sorted subvectors of length 2. Then we merge subvectors 1 and 2, 3 and 4, giving us twosorted subvectors of length 4:

2 3 4 5 3 7 8 9

Merging these two subvectors gives us the sorted vector of length 8, completing the sorting problem:

2 3 3 4 5 7 8 9

You will generalize this non-recursive algorithm for any positive n value. The key is that the merge stepshould allow for subvectors of different lengths. Consider a vector of length 11:

4 3 1 9 8 7 2 0 6 5 1 3

When the subvector length m is 1, there are 11 subvectors and five merges. There is not a sixth mergebecause there isn’t a right-side subvector to carry out a merge. Therefore the 11th subvector is left alone.

3 4 1 9 7 8 0 2 5 6 1

Now we have five subvectors of length m = 2 and one leftover component, which we’ll call the deficientsubvector. We will do three merges but note that the last merge has a deficient (short) right-side subvector.The result is

1 3 4 9 0 2 7 8 1 5 6

Now we have two subvectors of length m = 4 and one deficient subvector. We can only do one merge sincethe last subvector doesn’t have a right-side partner. So the last subvector is left alone:

0 1 2 3 4 7 8 9 1 5 6

4

Page 5: CS1132 Fall 2010 Assignment 1 1 Rock Paper Scissors … · 1.3 Rock-Paper-Scissors-Lizard-Spock The number of ties can be mitigated by introducing two new throws: lizard and spock

Now m = 8. We have one subvector of length 8 and one deficient subvector. Merge them and we’re done.You must implement this non-recursive algorithm in the function mergeSort. mergeSort must call merge,specified above.

function sortedArray = mergeSort(A)

% Sort vector A using the non-recursive merge sort algorithm as discussed

% A: the vector of numbers to be sorted, the length of A is > 0

% sortedArray: the sorted vector

2.4 Sorting Times

To get an idea of the relative speed of these sorting methods, you will run each of them and compare theirrun times. We are interested in how the speed of the algorithms change as the size of the array and as thenumber of possible entries change. To analyze this, you will write a single script that generates randomarrays and runs each of the three methods on the generated arrays.

To determine how the size of the array affects the runtime, you should use at least three different array sizes:10, 102, 103, . . . For each array size, generate 10 random arrays of numbers and apply each sorting method.Compare the average running time for each array size and for each method. Display the results in a plot,where the x-axis represents the size of the array and the y-axis represents the time. Connect the pointsbelonging to the same method with a line and use colors to differentiate between methods.

To determine how the number of possible entries affects the runtime, fix the array size at 103 and vary thepossible entries: 1 to 10, 1 to 100, 1 to 1000, 1 to 10,000. For each case, generate 10 random arrays ofnumbers and apply each sorting method. Compare the average running time for each set of possible entriesand for each method. Display the results in a plot, where the x-axis represents the number of possible entriesand the y-axis represents the time. Connect the points belonging to the same method with a line and usecolors to differentiate between methods.

To record the time it takes to run a method use tick and toc. Together they provide the functionality ofa stopwatch: tic starts the timer and toc stops it and returns the elapsed time. To exemplify their use,here’s a code snippet measuring the time needed to run bubbleSort on some array A:

tic;

bubbleSort(A); elapsedTime = toc;

Save your script as runtime.m

3 Self-check list

The following is a list of the minimum necessary criteria that your assignment must meet in order to beconsidered satisfactory. Failure to satisfy any of these conditions will result in an immediate request toresubmit your assignment. Save yourself and the graders time and effort by going over it before submittingyour assignment for the first time.Note that, although all of these are necessary, meeting all of them might still not be sufficient to consideryour submission satisfactory. We cannot list everything that could be possibly wrong with any particularassignment!

∆ Comment your code! If any of your functions is not properly commented, regarding function purposeand input/output arguments, you will be asked to resubmit.

∆ Suppress all unnecessary output by placing semicolons (;) appropriately. At the same time, make surethat all output that your program intentionally produces is formatted in a user-friendly way.

5

Page 6: CS1132 Fall 2010 Assignment 1 1 Rock Paper Scissors … · 1.3 Rock-Paper-Scissors-Lizard-Spock The number of ties can be mitigated by introducing two new throws: lizard and spock

∆ Make sure your functions names are exactly the ones we have specified, including case.

∆ Check that the number and order of input and output arguments for each of the functions matchesexactly the specifications we have given.

∆ Test each one of your functions independently, whenever possible, or write short scripts to test them.

∆ Check that your scripts do not crash (i.e., end unexpectedly with an error message) or run into infiniteloops. Check this by running each script several times in a row. Before each test run, you should typethe commands clear all; close all; to delete all variables in the workspace and close all figurewindows.

4 Submission instructions

1. Upload files rockPaperScissors.m, rpsTurn.m, rpsTest.m, rpsls.m, lizardSpock.m, lizardSpockTest.m,bubbleSort.m, cocktailShakerSort.m, merge.m, mergeSort.m and runtime.m to CMS in the sub-mission area corresponding to Assignment 1 in CMS.

2. Please do not make another submission until you have received and read the grader’s comments.

3. Wait for the grader’s comments and be patient.

4. Read the grader’s comments carefully and think for a while.

5. If you are asked to resubmit, fix all the problems and go back to Step 1! Otherwise you are done withthis assignment. Well done!

6