Search code examples
listclojure

How do I replicate items from a list in Clojure?


I've tried this for so many nights that I've finally given up on myself. Seems like an extremely simple problem, but I guess I'm just not fully understanding Clojure as well as I should be (I partially attribute that to my almost sole experience with imperative languages). The problem is from hackerrank.com

Here is the problem:

Problem Statement


 Given a list repeat each element of the list n times. The input and output 
portions will be handled automatically by the grader.

Input Format 
    First line has integer S where S is the number of times you need to repeat 
elements. After this there are X lines, each containing an integer. These are the 
X elements of the array.

Output Format 
    Repeat each element of the original list S times. So you have to return 
list/vector/array of S*X integers. The relative positions of the values should be 
same as the original list provided as input.

Constraints 
0<=X<=10 
1<=S<=100

So, given:

2
1
2
3

Output:

1
1
2
2
3
3

I've tried:

(fn list-replicate [num list]
    (println (reduce 
        (fn [element seq] (dotimes [n num] (conj seq element)))
        []
        list))
)

But that just gives me an exception. I've tried so many other solutions, and this probably isn't one of my better ones, but it was the quickest one I could come up with to post something here.


Solution

  • (defn list-replicate [num list]
      (mapcat (partial repeat num) list))
    

    (doseq [x (list-replicate 2 [1 2 3])]
      (println x))
    
    ;; output:
    1
    1 
    2
    2
    3 
    3