The Fibonacci Sequence and Modelling a Deck of Cards

The Fibonacci Sequence and
Modelling a Deck of Cards
The goal of this lab is to get familiar with writing some basic R
functions. The first exercise is about looping and vectorisation. The
second is more free-form and is about using R to learn about a card
game (poker).
Creating The Fibonacci Sequence
The Fibonacci1 sequence, {fk } = {1, 1, 2, 3, 5, 8, 13, . . .}, is defined by
f1 = 1, f2 = 1, fk+2 = fk+1 + fk .
1. Write an R function which will generate a vector containing the first n
terms of the Fibonacci sequence. The steps in this are as follows:
(a) Create the vector to store the result in.
(b) Initialize the first two elements.
(c) Run a loop with i running from 3 to n, filling in the i-th element.
You should probably consider the cases n = 1 and n = 2 separately.
2. In order to generate fn , the function above has to compute the values
of f1 , f2 , . . . , fn−1 . This is obviously wasteful and it would be better to
compute fn directly. Fortunately there is a formula for doing this (due to
Abraham de Moivre, who discovered the normal distribution).
√
1+ 5
φn − (1 − φ)n
√
fn =
.
,
where φ =
2
5
Write an R function to compute Fibonacci numbers this way.
What is the largest Fibonacci number that R can compute a value for?
1 Named after Leonardo Pisano Fibonacci, 1170–1250. The name is pronounced fee-bohnah-chee.
1
Modelling a Deck of Cards
[ You may find it useful to read the documentation for the R functions sample
and rep when doing this exercise. ]
A standard deck of cards has 52 cards. There are 13 cards each of 4 suits.
Spades = "S",
Clubs = "C" ,
Diamonds = "D",
Hearts = "H"
Each suit contains the face-values
"A",
"2",
...,
"10",
"J",
"Q",
"K".
One way to model a deck of cards is to maintain lookup tables for the suit and
face-value of each card. These will be vectors of length 52 containing the suit
and face-value.
suit = rep(c("S", "C", "D", "H"), each = 13)
face = rep(c("A", 2:10, "J", "Q", "K"), 4)
A single card is then just an index into these arrays, and the entire deck
consists of the set of all possible indices — the vector 1:52.
1. Write a function which, given a vector of cards, will paste together the
names of the cards. For example, the Queen of Hearts should be represented as "Q-H".
2. How would you shuffle the deck of cards?
3. Write a function which will deal a single poker hand (five cards).
4. Write a function which will determine whether a hand contains a “flush”
(all cards are from the same suit).
5. Count the number of flushes that occur in a million poker hands. The
probability of getting a flush can be computed as:
choose(4,1) * choose(13, 5) / choose(52, 5)
This is the number of ways to choose one of the four suits, times the
number of ways to choose 5 cards from that suit, divided by the number
of ways it is possible to 5 cards from 52.
How does what you observe compare with the expected number?
2