I'm going to screw around with visualizing Recamán's Sequence, but want to have a good sequence generator to generate the sequence before I start. I want to use a lazy generator for my actual application, but decided to make a strict version first since it will likely be simpler.
This is what I ended up with. It works (verified against the OEIS), but is quite verbose. I don't technically require seen
, but doing constant linear searching over acc
would likely be unacceptable. I'm just looking for broad suggestions on how this can be improved, because while it's fairly fast (it can find the first million numbers in ~2 seconds on my potato), it's rather ugly.
I know though that I can make use of transients here, but they're easy enough to add afterwards that that's not a big deal.
Any suggestions would be appreciated, because I feel like I'm missing something obvious.
(defn strict-recamans-sequence [max-n]
(let [c-last #(get % (dec (count %)))]
(loop [n 1
seen #{}
acc [0]]
(if (> n max-n)
acc
(let [prev (c-last acc)
back (- prev n)
new-n (if (and (pos? back) (not (seen back)))
back
(+ prev n))]
(recur (inc n) (conj seen new-n) (conj acc new-n)))))))