当前位置:首页 > 开发 > 编程语言 > 编程 > 正文

sudoku slover in Haskell (2)

发表于: 2012-04-19   作者:bookjovi   来源:转载   浏览:
摘要: 继续精简haskell版的sudoku程序,稍微改了一下,这次用了8行,同时性能也提高了很多,对每个空格的所有解不是通过尝试算出来的,而是直接得出。   board = [0,3,4,1,7,0,5,0,0, 0,6,0,0,0,8,3,0,1, 7,0,0,3,0,0,0,0,6, 5,0,0,6,4,0,8,0,7,

继续精简haskell版的sudoku程序,稍微改了一下,这次用了8行,同时性能也提高了很多,对每个空格的所有解不是通过尝试算出来的,而是直接得出。

 

board = [0,3,4,1,7,0,5,0,0,
         0,6,0,0,0,8,3,0,1,
         7,0,0,3,0,0,0,0,6,
         5,0,0,6,4,0,8,0,7,
         0,1,0,9,0,0,0,6,0,
         3,0,6,0,0,2,0,0,4,
         8,0,0,0,0,9,0,0,2,
         1,0,3,7,0,0,0,9,0,
         0,0,9,0,3,1,7,4,0]

newboard xs ys = foldl (\acc x -> merge (break (==0) acc) x) xs ys where merge (f,0:t) x = f ++ [x] ++ t

pointget bd = [1..9] \\ [bd!!(x*9+y) | x<-[0..8], y<-[0..8], x==row||y==col||(f' x, f' y)==(f' row, f' col)] where
                                (row, col) = divMod (length (takeWhile (/=0) bd)) 9
                                f' x = x `div` 3 * 3

nextanswer answer = map (\x->answer++[x]) (pointget $ newboard board answer)

sudoku = (iterate (concatMap $ nextanswer) [[]]) !! length (filter (== 0) board)

divide bd = unfoldr (\x -> if x == [] then Nothing else Just (splitAt 9 x)) bd

main = mapM_ (\x -> putStrLn "answer:" >> mapM_ print (divide $ newboard board x) >> putStrLn "") sudoku

 改天看看能否继续减少代码行数。

sudoku slover in Haskell (2)

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
Question: The Sudoku board could be partially filled, where empty cells are filled with the c
Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicate
一.题目 Valid Sudoku Total Accepted: 29804 Total Submissions: 109584My Submissions Determine
在 Haskell 中是用空格来将函数名与参数分隔的 常用库函数 min 接受两个可比较大小的参数,并返回较
Sudoku Time Limit:10000MS Memory Limit:32768KB 64bit IO Format:%lld & %llu Submit Status Prac
早就见过数独的题了,一看就头疼,也没认真看过,这里遇见了,好似久违的敌人和朋友,终于可以切磋
Description Sudoku is a placement puzzle. The goal is to enter a symbol in each cell of a gri
http://poj.org/problem?id=2676 挺有意思的题目 题意:九宫格数独,给出题目,打出数独的答案 思路
声明:本文采用 BY-NC-SA 协议进行授权。 转载请注明转自: Web Sudoku Deluxe 破解版 Web Sudoku D
一.题目描述 Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号