summaryrefslogtreecommitdiff
path: root/prolog/problems/denotational_semantics/prog_8puzzle_3/common.py
blob: b88e54428c64d7d1d8e77dd3b533d2468fe9c5c3 (plain)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from operator import itemgetter
import socket

import prolog.engine
import prolog.util
from server.hints import Hint, HintPopup

id = 173
number = 40
visible = True
facts = 'denotational_semantics_aux__predicates'

solution = '''\
prog_8puzzle(R0 --> R) -->
    [begin],
     { findblank(R0,C0) },
     instructs173(((R0,C0) --> (R,_C))),
    [end].

instructs173((R0,C0) --> (R,C)) -->
  instr173((R0,C0) --> (R,C)).
instructs173((R0,C0) --> (R,C)) -->
  instr173((R0,C0) --> (R1,C1)), instructs173((R1,C1) --> (R,C)).

instr173((R0,C0) --> (R,C)) -->
  [left], {Pos is (C0-1) mod 3,
            (Pos>0, C is C0-1, swap(R0,C0,C,R)
           ;
             Pos=0, C=C0, R=R0)}.
instr173((R0,C0) --> (R,C)) -->
  [right], {Pos is (C0-1) mod 3,
             (Pos<2, C is C0+1, swap(R0,C0,C,R)
            ;
              Pos=2, C=C0, R=R0)}.
instr173((R0,C0) --> (R,C)) -->
  [up], { (C0>3, C is C0-3, swap(R0,C0,C,R)
         ;
           C0=<3, C=C0, R=R0)}.
instr173((R0,C0) --> (R,C)) -->
  [down], { (C0=<6, C is C0+3, swap(R0,C0,C,R)
           ;
             C0>6, C=C0, R=R0)}.
'''

test_cases = [
    ('findall(W, (W = [_], prog_8puzzle(_, W, [])), Words), Words == []',
        [{}]),
    ('prog_8puzzle([1,2,3,4,5,6,7,8,0]-->Out, [begin,down,right,left,end], []), Out == [1,2,3,4,5,6,7,0,8]',
        [{}]),
    ('prog_8puzzle([1,2,3,4,5,6,7,8,0]-->Out, [begin,up,up,left,left,end], []), Out == [0,1,2,4,5,3,7,8,6]',
        [{}]),
    ('prog_8puzzle([1,2,3,4,5,6,7,8,0]-->Out, [begin,left,up,right,up,left,down,down,right,end], []), \
      Out == [1,6,2,4,5,3,7,8,0]',
        [{}]),
]

def test(code, aux_code):
    n_correct = 0
    engine_id = None
    try:
        engine_id, output = prolog.engine.create(code=code+aux_code, timeout=1.0)
        if engine_id is not None and 'error' not in map(itemgetter(0), output):
            # Engine successfully created, and no syntax error in program.
            for query, answers in test_cases:
                if prolog.engine.check_answers(engine_id, query=query, answers=answers, timeout=1.0):
                    n_correct += 1
    except socket.timeout:
        pass
    finally:
        if engine_id:
            prolog.engine.destroy(engine_id)

    hints = [{'id': 'test_results', 'args': {'passed': n_correct, 'total': len(test_cases)}}]
    return n_correct, len(test_cases), hints