chustar
chustar

Reputation: 12465

How do I write a program to find the tiles that are completely enclosed?

I am trying to write a prolog program that can find the tiles that are completely surrounded by b or w in a 2D-array.

For example, given a dataset like this:

[
    [b, w, +, +],
    [w, +, w, b],
    [+, w, b, +],
    [+, +, +, b],
]

It would return another Variable containing:

[
    [-, -, -, -],
    [-, w, -, -],
    [-, -, -, b],
    [-, -, -, -],
]

That is, it replaced all the + which were completely surrounded with b with a b, and the same for those surrounded by a w, and replaced everything else with a -.

Can anyone give any ideas on how to build a program to do this?

Upvotes: 4

Views: 342

Answers (2)

CapelliC
CapelliC

Reputation: 60024

With this rep/2 predicate

rep(L0, L1) :-
    rep(b, L0, L1) ;
    rep(w, L0, L1).

rep(E, [E|Ps], [-|Rs]) :-
    rep1(E, Ps, Rs).
rep(E, [X|Ps], [-|Rs]) :-
    E \= X,
    rep(Ps, Rs).

rep1(E, [+|Ps], [E|Rs]) :-
    rep2(E, Ps, Rs).

rep2(E, [+|Ps], [E|Rs]) :-
    rep2(E, Ps, Rs).
rep2(E, [E|Ps], [-|Rs]) :-
    dash(Ps, Rs).

dash([], []).
dash([_|Ps], [-|Rs]) :- dash(Ps, Rs).

that performs this way

?- rep([b,+,b,b],L).
L = [-, b, -, -] ;
false.

?- rep([b,+,+,+,+,+,b,+,b],L).
L = [-, b, b, b, b, b, -, -, -] .

?- rep([w,+,+,+,+,+,w,+,b],L).
L = [-, w, w, w, w, w, -, -, -] .

?- rep([b,+,+,+,+,+,w,+,b],L).
false.

?- rep([b,+,+,+,+,+,+,b],L).
L = [-, b, b, b, b, b, b, -] .

?- rep([b,+,+,+,+,+,+,+,b],L).
L = [-, b, b, b, b, b, b, b, -] .

?- rep([b,+,+,w,+,+,w,+,b],L).
L = [-, -, -, -, w, w, -, -, -] .

and a transposition predicate to enable rep/2 to work on columns

transpose_col_row([], []).
transpose_col_row([U], B) :- gen(U, B).
transpose_col_row([H|T], R) :- transpose_col_row(T, TC), splash(H, TC, R).

gen([H|T], [[H]|RT]) :- gen(T,RT).
gen([], []).

splash([], [], []).
splash([H|T], [R|K], [[H|R]|U]) :-
    splash(T,K,U).

you could combine them to solve your problem. HTH

Upvotes: 0

Scott Hunter
Scott Hunter

Reputation: 49838

This might help: it takes the representation you gave, and gives back a list whose elements are each of the form [ColumnIndex, RowIndex, Value]. You can then use member to find an element at a particular row/column.

encodearray( A, AA ) :- ( A, 0, 0, AA ).
encodearray( [], _, _, [] ).
encodearray( [[]|A], _, R, AA ) :- R1 is R+1, encodeArray( A, 0, R1, AA ).
encodearray( [[A|B]|X], C, R, [[C,R,A]|AA] ) :- C1 is C+1, encodeArray( [B|X], C1, R, AA ).

Upvotes: 1

Related Questions