Share your thoughts in the 2024 State of Clojure Survey!

Welcome! Please see the About page for a little more info on how this works.

0 votes
in Compiler by

I got a text file called "integer.txt", the file contains integers separated by a space.
Am trying to read the integers from the file into an integer array using the following syntax but with no success..I need the integer array for merge sort sorting so please help where possible

(def s ( slurp "integers.txt")) (println s) (def aray(to-array s)) ;;the code above is not working ;;how can i parse for an integer in the file as i add to an integer aray thank

1 Answer

+1 vote
by
selected by
 
Best answer

Here's how I solved this.

If you look at the result of (slurp "integers.txt") that will just be a single string. So need to chop that up.

For that, we'll need some string functions so

(require '[clojure.string :as str])

And let's see what's in there we can use:

(dir str)
blank?
capitalize
ends-with?
escape
includes?
index-of
join
last-index-of
lower-case
re-quote-replacement
replace
replace-first
reverse
split
split-lines
starts-with?
trim
trim-newline
triml
trimr
upper-case
nil

The split-lines sounds quite useful.

(doc str/split-lines)
-------------------------
clojure.string/split-lines
([s])
  Splits s on \n or \r\n.

So (str/split-lines "1\n2\n") should return a sequence of ("1" "2") and we are close to where we need. To figure out how to deal with the array, let's query our repl:

(apropos "array") returns a lot of stuff, but in there i spot clojure.core/int-array.

Call (doc int-array)

clojure.core/int-array
([size-or-seq] [size init-val-or-seq])
  Creates an array of ints

And that first argument "size-or-seq" means we can pass a collection as the contents of the array. After we split the string we have a collection of strings, so if we can turn those into Integers i think we are home free.

A way to turn a collection of one thing into a collection of another thing is using map. And a way to parse an integer from a string is Integer/parseInt.

So putting it all together:

(int-array (map #(Integer/parseInt %) (str/split-lines s)))
by
Thank you very much this was a headache but now its working
...