我想像在java中一样在clojure中填充2d数组
我提供了java的例子。我想在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]);
}
}
如果您的输入(lines
(有效(它包含正确的行数,并且每行包含正确的字符数(,则可以使用
(vec (map #(clojure.string/split % #"") (drop 2 lines)))
如果您的输入如下所示lines
,则需要过滤掉!
:
(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))))
如果你真的想在从标准输入中读取它时解析它:
(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))))