2013-05-12 35 views
6

Tôi đang làm việc trong Common Lisp, cố gắng làm cho trò chơi quét mìn Windows.Làm thế nào để in danh sách dưới dạng ma trận trong Common Lisp

tôi có một danh sách (1 1 1 2 2 2 3 3 3) và muốn in mà như ma trận

(1 1 1 
2 2 2 
3 3 3) 

Làm thế nào để làm điều đó?

Sửa

Tôi vào đầu

(format t "Input width:") 
(setf width (read)) 
(format t "Input height:") 
(setf height (read))  
(format t "How many mines:") 
(setf brMina (read)) 

(defun matrica (i j) 
    (cond ((= 0 i) '()) 
    (t (append (vrsta j) (matrica (1- i) j))))) 


(setf minefield (matrica width height)) 

(defun stampaj() 
     (format t "~%~a" minefield)) 
+0

Bạn nên đăng một số mã bạn đã thử. –

Trả lời

4

Một ví dụ khác, bằng cách sử dụng khá-in for fun:

(defun print-list-as-matrix 
    (list elements-per-row 
    &optional (cell-width (1+ (truncate (log (apply #'max list) 10))))) 
    (let ((*print-right-margin* (* elements-per-row (1+ cell-width))) 
     (*print-miser-width* nil) 
     (*print-pretty* t) 
     (format-string (format nil "~~<[email protected]{~~~ad~~^ ~~}[email protected]:>~%" cell-width))) 
    (format t format-string list))) 

Hoạt động như thế này:

CL-USER> (print-list-as-matrix (loop for i from 1 to 9 collect i) 3) 
1 2 3 
4 5 6 
7 8 9 
NIL 
CL-USER> (print-list-as-matrix (loop for i from 1 to 25 collect i) 5) 
1 2 3 4 5 
6 7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 
21 22 23 24 25 
NIL 
CL-USER> (print-list-as-matrix (loop for i from 1 to 16 collect i) 2) 
1 2 
3 4 
5 6 
7 8 
9 10 
11 12 
13 14 
15 16 
2

Như thế này:

(defun print-list-as-grid (list rows cols) 
    (assert (= (length list) (* rows cols)) 
    (loop for row from 0 below rows do 
    (loop for col from 0 below cols do 
     (princ (car list)) 
     (prinC#\space) 
     (setf list (cdr list))) 
    (prinC#\newline))) 

* (print-list-as-grid '(a b c d e f g h i) 3 3) 
A B C 
D E F 
G H I 

NIL 
+1

Cảm ơn bạn nó đang hoạt động. Hàng đầu tiên là (defun print-list-as-grid (liệt kê các hàng cols) – kosta

Các vấn đề liên quan