Write an F# function shuffle xs that takes an even-length list, cuts it into two
ID: 669025 • Letter: W
Question
Write an F# function shuffle xs that takes an even-length list, cuts it into two equal-sized pieces, and then interleaves the pieces (On a deck of cards, this is called a perfect out-shuffle).
> shuffle [1;2;3;4;5;6;7;8];;
val it : int list = [1; 5; 2; 6; 3; 7; 4; 8]
Write an F# function countshuffles n that counts how many calls to shuffle on a deck of n distinct "cards" it takes to put the deck back into its original order:
> countshuffles 4;;
val it : int = 2
(To see that this result is correct, note that shuffle [1;2;3;4] = [1;3;2;4], and shuffle [1;3;2;4] = [1;2;3;4].) What is countshuffles 52?
Hint: Define an auxiliary function countaux(deck, target) that takes two lists and returns the number of shuffles it takes to make deck equal to target.
Explanation / Answer
let shuffle l : =
let list_1 = []
let y = l.Length/2;
for i = 0 to y-1 do
list_1 = List.append list_1 (List.nth l i);
list_1 = List.append list_1 (List.nth l i+y);
printfn "The list: %A" list_1
shuffle [1;2;3;4;5;6;7;8];;
countshuffle 2 => 0
countshuffle 4 => 2
countshuffle 6 => 6
countshuffle 8 => 8
countshuffle 10 => 12
so there is difference of 2, 4, 2, 4 between two even number
let countshuffles num1 : int32 =
let res = 0;
while (num1 > 2) do
if (num1 % 4 == 0) then res <- res + 4
else res <- res + 2
num1 <- num1 - 2
num1
countshuffles 4;;
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.