David
David

Reputation: 924

Recursive function has bad performance

I am learning clojure and I am doing some exercises to practice. Currently I am working on the next problem:

The Elves contact you over a highly secure emergency channel. Back at the North Pole, the Elves are busy misunderstanding White Elephant parties. Each Elf brings a present. They all sit in a circle, numbered starting with position 1. Then, starting with the first Elf, they take turns stealing all the presents from the Elf to their left. An Elf with no presents is removed from the circle and does not take turns.

For example, with five Elves (numbered 1 to 5):

     1

5         2

   4  3

Elf 1 takes Elf 2's present. Elf 2 has no presents and is skipped. Elf 3 takes Elf 4's present. Elf 4 has no presents and is also skipped. Elf 5 takes Elf 1's two presents. Neither Elf 1 nor Elf 2 have any presents, so both are skipped. Elf 3 takes Elf 5's three presents. So, with five Elves, the Elf that sits starting in position 3 gets all the presents.

With the number of Elves given in your puzzle input, which Elf gets all the presents?

My code:

(ns elfos-navidad.core (:gen-class))

(def elfs (range 8977))

(defn remove-elf [elfs] 
  (if (= (count elfs) 1) 
    elfs
    (let [[first second & rest] elfs]
      (recur (concat rest (list first))))))

(defn -main [& args]
  (time (println (+ 1 (first (remove-elf elfs))))))

My Snippets works correctly, but it is so slow. Same problem in nodejs is extremely faster.

PS: I know that the best way to solve this problem is with linked list, but I don't know how to do it with clojure yet

Upvotes: 1

Views: 118

Answers (1)

leetwinski
leetwinski

Reputation: 17859

the problem is that concat is inefficient here. There is a better way to add items to the end of collection, if you use vectors:

(defn remove-elf-v [elfs]
  (let [elfs (vec elfs)]
    (if (= (count elfs) 1) 
      elfs    
      (recur (conj (subvec elfs 2) (first elfs))))))

user> (time (println (+ 1 (first (remove-elf-v elfs)))))
;;=> 1571
;;=> "Elapsed time: 20.128779 msecs"

the old one:

user> (time (println (+ 1 (first (remove-elf elfs)))))
;;=> 1571
;;=> "Elapsed time: 3482.966943 msecs"

Upvotes: 3

Related Questions