home *** CD-ROM | disk | FTP | other *** search
/ PSION CD 2 / PsionCDVol2.iso / Programs / 876 / hugs.sis / Queens.hs < prev    next >
Encoding:
Text File  |  2000-09-21  |  858 b   |  24 lines

  1. -- This N-Queens program is based on a small variation of the 8-queens
  2. -- program from Bird and Wadler's book.
  3. --
  4. -- Be warned: printing out the complete list of solutions (all 92 of them)
  5. -- by evaluating "q 8" takes well over 1 million reductions and uses nearly
  6. -- 2.5 million cells... it may take some time to execute on slower systems! :-)
  7.  
  8. module Queens where
  9. import Gofer
  10.  
  11. queens number_of_queens  = qu number_of_queens where
  12.     qu 0          = [[]]
  13.     qu (m+1)      = [ p++[n] | p<-qu m, n<-[1..number_of_queens], safe p n ]
  14.  
  15. safe p n          = all not [ check (i,j) (m,n) | (i,j) <- zip [1..] p ]
  16.                     where m = 1 + length p
  17.  
  18. check (i,j) (m,n) = j==n || (i+j==m+n) || (i-j==m-n)
  19.  
  20. -- Use q 5 to see the list of solutions for 5 queens.
  21. -- Use q 8 to see the list of solutions for 8 queens ....
  22. q = putStr . layn . map show . queens
  23.  
  24.