Wednesday, August 19, 2015

Bridge Hands

The bridge hands problem on programming praxis in Common Lisp.

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. (defvar deck
  2.   (loop for n from 0 to 51
  3.      collect n))
  4.  
  5.  
  6. (defun shuffle (deck &optional results)
  7.   (if (not deck)
  8.       results
  9.       (let* ((num-cards (length deck))
  10.          (card (nth (random num-cards) deck)))
  11.     (shuffle (remove card deck) (cons card results)))))
  12.  
  13.  
  14.  
  15. (defun deal (shuffled-deck)
  16.   (loop for i from 0 to 3
  17.        for deck = shuffled-deck then (subseq deck 13)
  18.        for hand = (subseq deck 0 13)
  19.      collect hand))
  20.  
  21. (defconstant empty-hand
  22.   (list (list) (list) (list) (list)))
  23.  
  24. (defun add-to-hand (my-hand card)
  25.   (let ((suit (floor card 13)))
  26.     (setf (nth suit my-hand) (cons card (nth suit my-hand)))
  27.     my-hand))
  28.  
  29. (defun build-hand (card-list)
  30.   (let ((my-hand (copy-tree empty-hand)))
  31.     (loop for card in card-list do
  32.      (setf my-hand (add-to-hand my-hand card))
  33.        finally (return my-hand))))
  34.  
  35. (defun shuffle-deal-build ()
  36.   (loop for card-list in (deal (shuffle deck))
  37.        collect (build-hand card-list)))
  38.  
  39. (defun translate-card (card)
  40.   (let ((card-strings
  41.      #("2" "3" "4" "5" "6" "7" "8" "9" "10" "J" "Q" "K" "A")))
  42.     (aref card-strings (rem card 13))))
  43.  
  44. (defun print-suit (card-list suit)
  45.   (let ((sorted (sort card-list #'>))
  46.     (suit-strings #("C: " "D: " "H: " "S: ")))
  47.     (format t "~a" (aref suit-strings suit))
  48.     (loop for card in sorted do
  49.      (format t "~a " (translate-card card)))))
  50.  
  51. (defun print-hand (my-hand)
  52.   (loop for suit from 3 downto 0 do
  53.        (progn
  54.      (print-suit (nth suit my-hand) suit)
  55.      (format t "~%"))))
  56.  
  57. (defun print-all-hands (shuffled-deck)
  58.   (loop
  59.      for hand in shuffled-deck
  60.      for tag in '("NORTH" "EAST" "SOUTH" "WEST")
  61.      do
  62.        (progn
  63.      (format t "~a~%" tag)
  64.      (print-hand hand)
  65.      (format t "~%"))))

No comments:

Post a Comment