Appending an element at nth index - clojure

I'm working on a function, which takes a vector (possibly nested vector) as input along with some quantity y and index n. Essentially the function would append y after the nth element in the vector and adjoin the remaining elements. So far I have the following written, which isn't not working as planned:
(defn funcs [x y n]
(concat (take (- n 1) x) (concat (take-last (- (count x) n) y))))

If you want to return a vector as the final value, you'll have to concatenate your vectors using into (in time linear in the size of the right operand) or core.rrb-vector's catvec (logarithmic time, but the resulting vector will be somewhat slower overall).
As for the actual implementation, assuming you want to go with core.rrb-vector:
(require '[clojure.core.rrb-vector :as fv])
(defn append-after-nth [x y n]
(fv/catvec (fv/subvec x 0 n) y (fv/subvec x n)))

Related

Clojure / core.matrix / initialize 2d array

In clojure a 2-d array can be initialized with a value like so:
(defn vec2d
"Return an x by y vector with all entries equal to val."
[x y val]
(vec (repeat y (vec (repeat x val)))))
Is there maybe a core.matrix built-in feature that would do the job?
You can use new-matrix and fill:
(require '[clojure.core.matrix :as matrix])
(defn vec2d
"Return an x by y vector with all entries equal to val."
[x y val]
(matrix/fill (matrix/new-matrix y x) val))
If you need the result to be a regular 2D Clojure vector, you can call to-nested-vectors on the result. At that point, though, you're probably better off just using the original solution from your question.

Clojure using let variable declaration within its own instantiation?

In the language of Clojure I am trying to pass a variable that I am defining within a let as a parameter to a function within the same let. The variable itself represents a list of vectors representing edges in a graph. The function I want to pass it to uses the list to make sure that it does not generate the same value within the list.
The function in whole
(defn random-WS
([n k] (random-WS (- n 1) k (reg-ring-lattice n k)))
([n k graph]
(cond (= n -1) graph
:else
(let [rem-list (for [j (range (count (graph n))) :when (< (rand) 0.5)]
[n (nth (seq (graph n)) j)])
add-list (for [j (range (count rem-list))]
(random-WSE graph n add-list))
new-graph (reduce add-edge (reduce rem-edge graph rem-list) add-list)]
(random-WS (- n 1) k new-graph)))))
The actual problem statement is seen here
add-list (for [j (range (count rem-list))]
(random-WSE graph n add-list))
Again for clarity, the function random-WSE generates a random edge for my graph based on some rules. Given the current graph, current node n, and current list of edges to add add-list it will generate one more edge to add to the list based on some rules.
The only real idea I have is to first let add-list () to first define it before then redefining it. Though this still has somewhat the same issue, though add-list is now defined, it will be () through out the for statement. Thus the function random-WSE will not take into account the edges already in the list.
Is there a way to "evaluate" add-list at some defined point within its own definition so that it can be used, within its definition? So I would first "evaluate" it to () before the for and then "evaluate" after each iteration of the for.
If you're interested the function is used to create a random Watts-Stogatz graph.
From what I get of your description of this algorithm, add-list grows (accumulates) during the problematic for loop. Accumulation (for a very broad acceptation of accumulation) is a strong sign you should use reduce:
(reduce (fn [add-list j] (conj add-list (random-WSE graph n add-list))) [] (range (count rem-list))
Basically you're chaining results in your let, in the sense that the result of the first computation (resulting in rem-list) is the sole input for your second computation (your trouble point) which again is the sole input for your third computation, which is finally the sole input to your final computation step (your recursion step). If this chaining sounds familiar, that's because it is: think about reformulating your let construction in terms of the threading macro ->.
I.e. something along the lines of
(defn- rem-list [graph n]
...)
(defn- add-list [remlist n]
...)
(defn- new-graph [addlist]
...)
(defn random-ws
([n k] ...)
([graph n k] ;; <- note the moved parameter
(cond (= n -1) graph
:else
(-> graph
(rem-list n)
(add-list n)
(new-graph)
(random-ws (dec n) k))))
You can then formulate add-list as a simple recursive function (maybe introduce an accumulator variable) or use the reduce variant that cgrand explained.

Finding the "middle element" from a vector in Clojure

Simple newbie question in Clojure...
If I have an odd number of elements in a Clojure vector, how can I extract the "middle" value? I've been looking at this for a while and can't work out how to do it!
Some examples:
(middle-value [0]) should return [0]
(middle-value [0 1 2]) should return [1]
(middle-value [0 1 :abc 3 4]) should return [:abc]
(middle-value [0 1 2 "test" 4 5 6]) should return ["test"]
How about calculating the middle index and accessing by it?
(defn middle-value [vect]
(when-not (empty? vect)
(vect (quot (count vect) 2))))
A somewhat inefficient but fun implementation (works with sequence abstraction instead of concrete vector):
(defn middle [[fst & rst]]
(if-not rst fst
(recur (butlast rst))))
Returns nil in case of even amount of elements.
Less fun but more efficient:
(nth v (quot (count v) 2))
where v is the vector.
Get the number of items in the vector, halve it, floor the result and get the item at that index. Assuming a vector v:
(get v (floor (/ (count v) 2)))
Unfortunately floor isn't in clojure.core, you'll need to pull in another library for that or go directly to java.lang.Math.floor.
This code, of course, doesn't do anything about even-counted vectors, but I'm assuming you can handle those already.

Cleaning up Clojure function

Coming from imperative programming languages, I am trying to wrap my head around Clojure in hopes of using it for its multi-threading capability.
One of the problems from 4Clojure is to write a function that generates a list of Fibonacci numbers of length N, for N > 1. I wrote a function, but given my limited background, I would like some input on whether or not this is the best Clojure way of doing things. The code is as follows:
(fn fib [x] (cond
(= x 2) '(1 1)
:else (reverse (conj (reverse (fib (dec x))) (+ (last (fib (dec x))) (-> (fib (dec x)) reverse rest first))))
))
The most idiomatic "functional" way would probably be to create an infinite lazy sequence of fibonacci numbers and then extract the first n values, i.e.:
(take n some-infinite-fibonacci-sequence)
The following link has some very interesting ways of generating fibonnaci sequences along those lines:
http://en.wikibooks.org/wiki/Clojure_Programming/Examples/Lazy_Fibonacci
Finally here is another fun implementation to consider:
(defn fib [n]
(let [next-fib-pair (fn [[a b]] [b (+ a b)])
fib-pairs (iterate next-fib-pair [1 1])
all-fibs (map first fib-pairs)]
(take n all-fibs)))
(fib 6)
=> (1 1 2 3 5 8)
It's not as concise as it could be, but demonstrates quite nicely the use of Clojure's destructuring, lazy sequences and higher order functions to solve the problem.
Here is a version of Fibonacci that I like very much (I took the implementation from the clojure wikibook: http://en.wikibooks.org/wiki/Clojure_Programming)
(def fib-seq (lazy-cat [0 1] (map + (rest fib-seq) fib-seq)))
It works like this: Imagine you already have the infinite sequence of Fibonacci numbers. If you take the tail of the sequence and add it element-wise to the original sequence you get the (tail of the tail of the) Fibonacci sequence
0 1 1 2 3 5 8 ...
1 1 2 3 5 8 ...
-----------------
1 2 3 5 8 13 ...
thus you can use this to calculate the sequence. You need two initial elements [0 1] (or [1 1] depending on where you start the sequence) and then you just map over the two sequences adding the elements. Note that you need lazy sequences here.
I think this is the most elegant and (at least for me) mind stretching implementation.
Edit: The fib function is
(defn fib [n] (nth fib-seq n))
Here's one way of doing it that gives you a bit of exposure to lazy sequences, although it's certainly not really an optimal way of computing the Fibonacci sequence.
Given the definition of the Fibonacci sequence, we can see that it's built up by repeatedly applying the same rule to the base case of '(1 1). The Clojure function iterate sounds like it would be good for this:
user> (doc iterate)
-------------------------
clojure.core/iterate
([f x])
Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of side-effects
So for our function we'd want something that takes the values we've computed so far, sums the two most recent, and returns a list of the new value and all the old values.
(fn [[x y & _ :as all]] (cons (+ x y) all))
The argument list here just means that x and y will be bound to the first two values from the list passed as the function's argument, a list containing all arguments after the first two will be bound to _, and the original list passed as an argument to the function can be referred to via all.
Now, iterate will return an infinite sequence of intermediate values, so for our case we'll want to wrap it in something that'll just return the value we're interested in; lazy evaluation will stop the entire infinite sequence being evaluated.
(defn fib [n]
(nth (iterate (fn [[x y & _ :as all]] (cons (+ x y) all)) '(1 1)) (- n 2)))
Note also that this returns the result in the opposite order to your implementation; it's a simple matter to fix this with reverse of course.
Edit: or indeed, as amalloy says, by using vectors:
(defn fib [n]
(nth (iterate (fn [all]
(conj all (->> all (take-last 2) (apply +)))) [1 1])
(- n 2)))
See Christophe Grand's Fibonacci solution in Programming Clojure by Stu Halloway. It is the most elegant solution I have seen.
(defn fibo [] (map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))
(take 10 (fibo))
Also see
How can I generate the Fibonacci sequence using Clojure?

Different solutions for Clojure implementation of problem

Here is a problem Statement :
Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
The solution is long,
(defn large [x y]
(if (> x y) x y))
(defn large-3 [x y z]
(if(> (large x y) z) (large x y) z))
(defn small [x y]
(if (< x y) x y))
(defn small-3 [x y z]
(if (< (small x y) z ) (small x y) z))
(defn second-largest [x y z]
(let [greatest (large-3 x y z)
smallest (small-3 x y z)]
(first (filter #(and (> greatest %) (< smallest %)) [x y z]))))
(defn square [a]
(* a a)
)
(defn sum-of-square [x y z]
(+ (square (large-3 x y z)) (square (second-largest x y z))))
Just wanted to know what different/succinct ways this problem can be solved in Clojure.
(defn foo [& xs]
(let [big-xs (take 2 (sort-by - xs))]
(reduce + (map * big-xs big-xs))))
; why only 3? how about N
(defn sum-of-squares [& nums]
(reduce + (map #(* % %) (drop 1 (sort nums)))))
or if you want "the sum of the greatest two numbers:
(defn sum-of-squares [& nums]
(reduce + (map #(* % %) (take 2 (reverse (sort nums))))))
(take 2 (reverse (sort nums))) fromMichał Marczyk's answer.
(See a sequence version of the problem together with a lazy solution in my second update to this answer below.)
(defn square [n]
(* n n))
;; generalises easily to larger numbers of arguments
(defn sum-of-larger-squares [x y z]
(apply + (map square (take 2 (reverse (sort [x y z]))))))
;; shorter; generalises easily if you want
;; 'the sum of the squares of all numbers but n smallest'
(defn sum-of-larger-squares [x y z]
(apply + (map square (drop 1 (sort [x y z])))))
Update:
To expand on the comments from the above, the first version's straighforward generalisation is to this:
(defn sum-of-larger-squares [n & xs]
(apply + (map square (take n (reverse (sort xs))))))
The second version straightforwardly generalises to the version Arthur posted in the meantime:
(defn sum-of-larger-squares [n & xs]
(apply + (map square (drop n (sort xs)))))
Also, I've seen exactly the same problem being solved in Scheme, possibly even on SO... It included some fun solutions, like one which calculated the some of all three squares, then subtracted the smallest square (that's very straightforward to express with Scheme primitives). That's 'unefficient' in that it calculates the one extra square, but it's certainly very readable. Can't seem to find the link now, unfortunately.
Update 2:
In response to Arthur Ulfeldt's comment on the question, a lazy solution to a (hopefully fun) different version of the problem. Code first, explanation below:
(use 'clojure.contrib.seq-utils) ; recently renamed to clojure.contrib.seq
(defn moving-sum-of-smaller-squares [pred n nums]
(map first
(reductions (fn [[current-sum [x :as current-xs]] y]
(if (pred y x)
(let [z (peek current-xs)]
[(+ current-sum (- (* z z)) (* y y))
(vec (sort-by identity pred (conj (pop current-xs) y)))])
[current-sum
current-xs]))
(let [initial-xs (vec (sort-by identity pred (take n nums)))
initial-sum (reduce + (map #(* % %) initial-xs))]
[initial-sum initial-xs])
(drop n nums))))
The clojure.contrib.seq-utils (or c.c.seq) lib is there for the reductions function. iterate could be used instead, but not without some added complexity (unless one would be willing to calculate the length of the seq of numbers to be processed at the start, which would be at odds with the goal of remaining as lazy as possible).
Explanation with example of use:
user> (moving-sum-of-smaller-squares < 2 [9 3 2 1 0 5 3])
(90 13 5 1 1 1)
;; and to prove laziness...
user> (take 2 (moving-sum-of-smaller-squares < 2 (iterate inc 0)))
(1 1)
;; also, 'smaller' means pred-smaller here -- with
;; a different ordering, a different result is obtained
user> (take 10 (moving-sum-of-smaller-squares > 2 (iterate inc 0)))
(1 5 13 25 41 61 85 113 145 181)
Generally, (moving-sum-of-smaller-squares pred n & nums) generates a lazy seq of sums of squares of the n pred-smallest numbers in increasingly long initial fragments of the original seq of numbers, where 'pred-smallest' means smallest with regard to the ordering induced by the predicate pred. With pred = >, the sum of n greatest squares is calculated.
This function uses the trick I mentioned above when describing the Scheme solution which summed three squares, then subtracted the smallest one, and so is able to adjust the running sum by the correct amount without recalculating it at each step.
On the other hand, it does perform a lot of sorting; I find it's not really worthwhile to try and optimise this part, as the seqs being sorted are always n elements long and there's a maximum of one sorting operation at each step (none if the sum doesn't require adjustment).