I want to fill 2d array in clojure like we do in java
I have provided the example of java. I want to do like this in Clojure
Scanner sc=new Scanner(System.in);
Scanner sc1=new Scanner(System.in);
int row=sc.nextInt();
int col=sc.nextInt();
realMatrix=new String[row][col];
String[] in=new String[row];
for(int k=0;k<row;k++) {
in[k]=sc1.nextLine();
}
for(int i=0;i<row;i++) {
char[] charArry=in[i].toCharArray();
for(int j=0;j<col;j++) {
realMatrix[i][j]=Character.toString(charArry[j]);
}
}
If your input (lines
) is valid (it contains the correct number of rows and each row contains the correct number of characters), it can be parsed with
(vec (map #(clojure.string/split % #"") (drop 2 lines)))
If your input looks like lines
below, you'll want to filter out the !
s:
(def lines
["3"
"5"
"abcde!!!"
"FGHIJ!!!"
"klmno!!!"
"!!!!!!!!"
"!!!!!!!!"])
(defn split-row [row n-cols]
(vec (take n-cols (clojure.string/split row #""))))
(defn parse-matrix [lines]
(let [n-rows (Integer. (first lines))
n-cols (Integer. (second lines))
matrix-lines (take n-rows (drop 2 lines))]
(vec (map #(split-row % n-cols) matrix-lines))))
If you really want to parse it as it is read from standard input:
(defn parse-matrix-stdin []
(let [n-rows (Integer. (read-line))
n-cols (Integer. (read-line))
matrix-lines (take n-rows (repeatedly read-line))]
(vec (map #(split-row % n-cols) matrix-lines))))