Skip to main content

Generate cyclic list from a list


Given a list (for example, {3, 5}) I would like to make a function genCyclic[n_, list_] which generates a cyclic patterns of list with length n, such that genCyclic[5, {3, 5}] returns {3, 5, 3, 5, 3} or genCyclic[1, {3, 5}] returns {3}.


My current solution is to use ConstantArray to generate the full cycle parts ({3, 5, 3, 5} in the first example) and append the remaining part ({3}) and then Flatten them. I have to say my method seems too ugly.


In my old memory, which is frequently wrong, though, I thought there was a built-in function with this functionality. After spending some time trying to find such a function and failing, I ended up here.



No matter whether there is a built-in function or not, what is the most natural way to implement genCyclic?



Answer



Yes there is something quite strightforward:


 genCyclic[n_, list_] := PadRight[{}, n, list]

Comments