Transpose and cast and max

1 view
Skip to first unread message

Base

unread,
Jul 30, 2010, 10:03:17 AM7/30/10
to Clojure
Hi All

I have a vector in the following format:

[
["M" "3.4" "5.6"] ["L" "4.2" "6.6"] ["L" "4.9" "7.9"] ["L" "1.1"
"2.4"]["L" "5.4" "4.5"]
]

I would like to create a vector that contains the max values of each
of the second and third values from this vector

in this case it would be: [5.4, 7.9]

The method to do this that i have seen would be to
1. Transpose the vector using (apply map vector v)
2. Discard the vector of Ms and Ls
3 Cast all of the remaining numbers to Float
4 Apply Max to each of the vectors.

There *has* to be a more elegant way to do this than I have been
trying.

Any thoughts are appreciated as usual!

Base

****
(def v [["M" "3.4" "5.6"] ["L" "4.2" "6.6"] ["L" "4.9" "7.9"] ["L"
"1.1" "2.4"]["L" "5.4" "4.5"]])
(def v2 (rest (apply map vector v)))
(def f1 (map #(Float/parseFloat %) (first v2))
(def f2 (map #(Float/parseFloat %) (fnext v2))
(apply max f1)
(apply max f2)

Steve Purcell

unread,
Jul 30, 2010, 10:14:52 AM7/30/10
to clo...@googlegroups.com
On 30 Jul 2010, at 15:03, Base wrote:

> Hi All
>
> I have a vector in the following format:
>
> [
> ["M" "3.4" "5.6"] ["L" "4.2" "6.6"] ["L" "4.9" "7.9"] ["L" "1.1"
> "2.4"]["L" "5.4" "4.5"]
> ]
>
> I would like to create a vector that contains the max values of each
> of the second and third values from this vector
>
> in this case it would be: [5.4, 7.9]
>
> The method to do this that i have seen would be to
> 1. Transpose the vector using (apply map vector v)
> 2. Discard the vector of Ms and Ls
> 3 Cast all of the remaining numbers to Float
> 4 Apply Max to each of the vectors.
>
> There *has* to be a more elegant way to do this than I have been
> trying.


Here's my first take:

(def v [["M" "3.4" "5.6"] ["L" "4.2" "6.6"] ["L" "4.9" "7.9"] ["L" "1.1" "2.4"]["L" "5.4" "4.5"]])

(->> v
(map rest)
(apply map (fn [& vals]
(apply max (map #(Float/parseFloat %) vals)))))

=> (5.4 7.9)


-Steve

Base

unread,
Jul 30, 2010, 10:25:41 AM7/30/10
to Clojure
Awsome!

Thanks much steve!

Luka Stojanovic

unread,
Jul 30, 2010, 10:25:50 AM7/30/10
to clo...@googlegroups.com

My take:

(def v [["M" "3.4" "5.6"] ["L" "4.2" "6.6"] ["L" "4.9" "7.9"] ["L" "1.1"
"2.4"]["L" "5.4" "4.5"]])

(defn my-max [acc l]
(let [fs (map #(Float/parseFloat %) (next l))]
(map max acc fs)))

(reduce my-max [0 0] v)

Reply all
Reply to author
Forward
0 new messages