ชาวนา กับ หมาป่า มี แพะ และกะหล่ำปีด้วย ตอน 2

มาต่อตอนที่ 2  ดูเงื่อนไขอื่นอีก

        สถานะที่ไม่ปลอดภัย แพะ (goat, g) และกะหล่ำ (cabbage, c) อยู่ฝั่งเดียวกัน

where-goat side และ where-cabb side มีค่าเท่ากัน เขียนด้วย LISP จะได้เป็น

                (equal (where-goat side) (where-cabb side))

ถ้า (where-goat side) และ (where-cabb side) มีค่าเท่ากันจะได้ผลเป็นจริง

 

เมื่อตรวจสอบโดยใช้ cond จะได้

        cond(

                        (equal (where-goat side) (where-wolf side))

                nil )

        (t side)

เหมือนรูปแบบแรก ถ้ามีชาวนาอยู่ด้วยก็ปลอดภัย

        (not

                (equal (farmer-side state) (wolf-side state) )

        )

จะเห็นว่าตรวจสอบสถานะที่ไม่ปลอดภัยง่ายกว่า ถ้าสถานะที่ไม่ปลอดภัย เป็น เท็จ แสดงว่าปลอดภัย J เมื่อรวมกับครั้งที่แล้วจะได้

   (cond (

           (and

                        (equal (where-goat side) (where-wolf side));end equal

                (not

                        (equal (where-farmer side) (where-wolf side));end equal

                );end not

           );end and

        nil);end cond1

            (

            (and      (equal (where-goat side) (where-cabbage side));end equal

                  (not

                        (equal (where-farmer side) (where-goat side));end equal

                );end not

           );end and

        nil);end cond2

           (t side);end cond3

           );end block cond

        ต่อไปก็ทำให้เป็น ฟังก์ชั่นด้วย defun

 

(defun is-safe (side)

;(cond (<cond1><exp1-1>..)(<cond2><exp2-1>..)(<cond3><exp3-1>..))

   (cond (

           (and

                        (equal (where-goat side) (where-wolf side));end equal

                (not

                        (equal (where-farmer side) (where-wolf side));end equal

                );end not

           );end and

        nil);end cond1

            (

            (and      (equal (where-goat side) (where-cabbage side));end equal

                  (not

                        (equal (where-farmer side) (where-goat side));end equal

                );end not

           );end and

        nil);end cond2

           (t side);end cond3

           );end block cond

);end defun is-safe

 

        เมื่อมีการตรวจสอบสถานะปลอดภัย ก็ต้องรู้ว่าแต่ละ item อยู่ฝั่งไหนของแม่น้ำ (มีสถานะเป็นอะไร) ก็ต้องอ่านออกมาจาก list สมมุติให้ list ชื่อ side เก็บตำแหน่ง (ฝั่งไหน) ตามที่กำหนดไว้ตอนต้น (w w w w) และ (f w g c) การอ่านข้อมูลออกจาก list ใน LISP มีหลายวิธี ตัวอย่างนี้จะใช้ nth เช่นอยากรู้ว่า แพะอยู่ฝั่งไหนจะเขียนได้เป็น

        (nth 2 side)

        จากตัวอย่างด้านบนใช้ function where-XXX ก็สร้าง function ให้สอดคล้องกันซะ

 

(defun where-farmer (side)

   (nth 0 side))

 

(defun where-wolf (side)

   (nth 1 side))

 

(defun where-goat (side)

   (nth 2 side))

 

(defun where-cabbage (side)

   (nth 3 side))

อืม ! ยังไม่จบนะ วันนี้แค่นี้ก่อน ลองคิดซิ มีอะไรต้องทำอีกอ่ะ