Comment detail

マルバツゲーム (Nested Flatten)
配列を複製しまくりで効率が悪いけど。
 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import Data.Array
import Data.Maybe
import Control.Monad
import System.Random

type Pos = (Int, Int)
type OX = Bool
type Board = Array Pos (Maybe OX)
type View = OX -> Bool
type Strategy m = Board -> View -> m Pos
type Player m = (Strategy m, View)

emptyBoard :: Board
emptyBoard = array ((0,0), (2,2)) [(p, Nothing) | p<-ps]
  where ps = [(x,y) | x<-[0..2], y<-[0..2]]

availablePos :: Board -> [Pos]
availablePos b = [p | (p, Nothing) <- assocs b]

win :: Board -> View -> Bool
win b v = any (all (fromMaybe False . fmap v . (b!))) xss
  where
    xss = [ [(x,y) | y<-[0..2]] | x<-[0..2] ] ++
          [ [(x,y) | x<-[0..2]] | y<-[0..2] ] ++
          [ [(0,0), (1,1), (2,2)], [(0,2), (1,1), (2,0)] ]

play :: Monad m => Strategy m -> Strategy m -> m (Maybe Bool)
play s1 s2 = go emptyBoard (s1, id) (s2, not)
  where
    go b p1@(s,v) p2
        | null ps = return Nothing
        | otherwise = do
            pos <- s b v
            let m = Just (v True)
                b' = b // [(pos, m)]
            if win b' v
              then return m
              else go b' p2 p1
      where ps = availablePos b

randStrategy :: Strategy IO
randStrategy b v = do
  let ps = availablePos b
  i <- getStdRandom (randomR (0, length ps - 1))
  when (i<0) $ putStrLn $ show ps
  return (ps!!i)

main :: IO ()
main = do
  let n = 10000
  xs <- replicateM n (play randStrategy randStrategy)
  let a = sum [1 | Just True <- xs]
      b = sum [1 | Just False <- xs]
      c = n - (a + b)
  putStrLn $ "player1 won: " ++ show a
  putStrLn $ "player2 won: " ++ show b
  putStrLn $ "draw: "  ++ show c
  putStrLn $ "total: " ++ show n
直線に3個揃っているかの判定を整数計算ですませる方法。

縦3本、横3本、斜め2本、計8本の直線に素数
2,3,5,7,11,13,17,19
を対応させる。
各マスには通っている直線の素数の積を対応させる。つまり
  2*7*17      2*11        2*13*19
  3*7         3*11*17*19  3*13
  5*7*19      5*11        5*13*17
のように整数を配置する。
  ○(または×)が置いてあるマスの場所の整数すべての積をとって
それが (2*3*5*7*11*13*17*19)^2 を
割り切ったらどの直線でも3個揃っていない、
割り切れなかったらどこかの直線で3個揃っている、
と判定できる。

コードはさかいさんの #6209 の判定関数のインタフェースをお借りしてます。
1
2
3
4
5
6
7
8
9
judgeTable :: Array Pos Integer
judgeTable = array ((0,0), (2,2)) [
  ((0,0), 2*7*17), ((0,1), 2*11      ), ((0,2), 2*13*19),
  ((1,0), 3*7   ), ((1,1), 3*11*17*19), ((1,2), 3*13   ),
  ((2,0), 5*7*19), ((2,1), 5*11      ), ((2,2), 5*13*17)]

win :: Board -> View -> Bool
win b v = (2*3*5*7*11*13*17*19)^2 `mod` pr /= 0 where
  pr = product [judgeTable!p | (p, ox) <- assocs b, ox == Just (v True)]

Index

Feed

Other

Link

Pathtraq

loading...