我想像在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]);
}
}
答案 0 :(得分:1)
如果您输入的内容(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))))