Shuffle An Array
June 30, 2020
Today’s exercise comes to us from Leetcode via Reddit:
Given an array consisting of 2n elements in the form
[x1,x2,…,xn,y1,y2,…,yn], return the array in the form [x1,y1,x2,y2,…,xn,yn].
The Reddit poster claims to be new to Scheme and functional programming, and was thinking of a solution using length and list-ref, but couldn’t solve the problem.
Your task is to show the student how to solve the problem. When you are
finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Sample output:
Another version using generators
A quick naive implementation in Haskell:
Here’s a solution in Python.
Output:
A python implementation
A pythhon implementation
A C implementation
Clojure:
Test:
Though checks can be added to ensure that input is a sequence that has even amount of elements:
Test: